idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
18,300 | def valid? @errors = [ ] @critical_keys . each do | k | any_error = public_send ( k ) . nil? @errors << k if any_error end @errors . size == 0 end | Checks if all of the required run parameters are set . |
18,301 | def run fail_if_invalid partitions = Partitioner . subset ( documents , k ) results = partitions . map . with_index do | part , i | training_samples = Partitioner . exclude_index ( documents , i ) classifier_instance = classifier . call ( ) train ( classifier_instance , training_samples ) part . each do | x | predictio... | Performs k - fold cross - validation and returns a confusion matrix . |
18,302 | def create_post ( publication , opts ) response = @client . post "publications/#{publication['id']}/posts" , build_request_with ( opts ) Medium :: Client . validate response end | Creates a post in a publication on behalf of the authenticated user . |
18,303 | def sign_in_user ( username : , password : , client_id : , client_secret : , scope : 'openid' ) client ( issuer ) . post do | req | req . url "/oauth2/#{auth_server_id}/v1/token" req . headers [ 'Content-Type' ] = 'application/x-www-form-urlencoded' req . headers [ 'Authorization' ] = 'Basic: ' + Base64 . strict_encode... | sign in user to get tokens |
18,304 | def sign_in_client ( client_id : , client_secret : , scope : ) client ( issuer ) . post do | req | req . url "/oauth2/#{auth_server_id}/v1/token" req . headers [ 'Content-Type' ] = 'application/x-www-form-urlencoded' req . headers [ 'Authorization' ] = 'Basic: ' + Base64 . strict_encode64 ( "#{client_id}:#{client_secre... | sign in client to get access_token |
18,305 | def verify_token ( token , issuer : , audience : , client_id : ) header , payload = token . split ( '.' ) . first ( 2 ) . map { | encoded | JSON . parse ( Base64 . decode64 ( encoded ) ) } raise InvalidToken . new ( 'Invalid issuer' ) if payload [ 'iss' ] != issuer raise InvalidToken . new ( 'Invalid audience' ) if pay... | validate the token |
18,306 | def get_jwk ( header , payload ) kid = header [ 'kid' ] return JWKS_CACHE [ kid ] if JWKS_CACHE [ kid ] logger . info ( "[Okta::Jwt] Fetching public key: kid => #{kid} ..." ) if logger jwks_response = client ( payload [ 'iss' ] ) . get do | req | req . url get_metadata ( payload ) [ 'jwks_uri' ] end jwk = JSON . parse ... | extract public key from metadata s jwks_uri using kid |
18,307 | def store ( actual , truth ) key = @keys_for . call ( truth , actual ) if @values . key? ( key ) @values [ key ] += 1 else fail IndexError , "#{key} not found in confusion matrix" end self end | Save the result of classification |
18,308 | def fscore ( beta ) b2 = Float ( beta ** 2 ) ( ( b2 + 1 ) * precision * recall ) / ( b2 * precision + recall ) end | Returns the F - measure of the classifier s precision and recall . |
18,309 | def packet ( code ) @global_variable_name = nil partialruby_packet = partialruby_context . packet ( code ) @all_packets ||= [ ] newpacket = EvalHook :: Packet . new ( partialruby_packet , @global_variable_name ) @all_packets << newpacket newpacket end | Creates a packet of preprocessed ruby code to run it later useful to execute the same code repeatedly and avoid heavy preprocessing of ruby code all the times . |
18,310 | def boot Thread . new do sleep 1 until EM . reactor_running? begin log . info "Loading application..." app_init load_settings Fastr :: Plugin . load ( self ) load_app_classes setup_router setup_watcher log . info "Application loaded successfully." @booting = false plugin_after_boot rescue Exception => e log . error "#{... | This is used to initialize the application . It runs in a thread because startup depends on EventMachine running |
18,311 | def load_app_classes @@load_paths . each do | name , path | log . debug "Loading #{name} classes..." Dir [ "#{self.app_path}/#{path}" ] . each do | f | log . debug "Loading: #{f}" load ( f ) end end end | Loads all application classes . Called on startup . |
18,312 | def setup_watcher this = self Handler . send ( :define_method , :app ) do this end @@load_paths . each do | name , path | Dir [ "#{self.app_path}/#{path}" ] . each do | f | EM . watch_file ( f , Handler ) end end end | Watch for any file changes in the load paths . |
18,313 | def transact ( dbname , data ) data = transmute_data ( data ) RestClient . post ( db_url ( dbname ) + "/" , { "tx-data" => data } , :Accept => 'application/edn' , & HANDLE_RESPONSE ) end | Data can be a ruby data structure or a string representing clojure data |
18,314 | def query ( query , args_or_dbname , params = { } ) query = transmute_data ( query ) args = args_or_dbname . is_a? ( String ) ? [ db_alias ( args_or_dbname ) ] : args_or_dbname args = transmute_data ( args ) get root_url ( "api/query" ) , params . merge ( :q => query , :args => args ) end | Query can be a ruby data structure or a string representing clojure data If the args_or_dbname is a String it will be converted into one arg pointing to that database . |
18,315 | def view ( * names ) if names . length === 1 puts "YOU ARE USING AND OLD VERSION OF CELLS. PLEASE CONSIDER TO UPDATE YOUR CODE" old_cell = "LatoView::CellsV1::#{names.first.capitalize}::Cell" . constantize return old_cell end cell_class = "LatoView::" names . each do | name | cell_class = "#{cell_class}#{name.capitaliz... | This function render a cell set with params . |
18,316 | def view_getSidebarLogo return VIEW_SIDEBARLOGO if defined? VIEW_SIDEBARLOGO dir = "#{Rails.root}/app/assets/images/lato/" if File . exist? ( "#{dir}/sidebar_logo.svg" ) return "lato/sidebar_logo.svg" end if File . exist? ( "#{dir}/sidebar_logo.png" ) return "lato/sidebar_logo.png" end if File . exist? ( "#{dir}/sideba... | This function return the url of sidebar logo . |
18,317 | def view_getLoginLogo return VIEW_LOGINLOGO if defined? VIEW_LOGINLOGO dir = "#{Rails.root}/app/assets/images/lato/" if File . exist? ( "#{dir}/login_logo.svg" ) return "lato/login_logo.svg" end if File . exist? ( "#{dir}/login_logo.png" ) return "lato/login_logo.png" end if File . exist? ( "#{dir}/login_logo.jpg" ) re... | This function return the url of login logo . |
18,318 | def view_getApplicationLogo return VIEW_APPLOGO if defined? VIEW_APPLOGO dir = "#{Rails.root}/app/assets/images/lato/" if File . exist? ( "#{dir}/logo.svg" ) return "lato/logo.svg" end if File . exist? ( "#{dir}/logo.png" ) return "lato/logo.png" end if File . exist? ( "#{dir}/logo.jpg" ) return "lato/logo.jpg" end if ... | This function return the url of application logo . |
18,319 | def dispatch ( env ) return [ 500 , { 'Content-Type' => 'text/plain' } , [ "Server Not Ready" ] ] if @booting begin new_env = plugin_before_dispatch ( env ) plugin_after_dispatch ( new_env , do_dispatch ( new_env ) ) rescue Exception => e bt = e . backtrace . join ( "\n" ) [ 500 , { 'Content-Type' => 'text/plain' } , [... | Convenience wrapper for do_dispatch This is the heart of the server called indirectly by a Rack aware server . |
18,320 | def do_dispatch ( env ) path = env [ 'PATH_INFO' ] ret = dispatch_public ( env , path ) return ret if not ret . nil? log . debug "Checking for routes that match: #{path}" route = router . match ( env ) if route . has_key? :ok dispatch_controller ( route , env ) else [ 404 , { "Content-Type" => "text/plain" } , [ "404 N... | Route instantiate controller return response from controller s action . |
18,321 | def setup_controller ( controller , env , vars ) controller . env = env controller . headers = { } setup_controller_params ( controller , env , vars ) controller . cookies = Fastr :: HTTP . parse_cookies ( env ) controller . app = self end | Sets up a controller for a request . |
18,322 | def setup_controller_params ( controller , env , vars ) if Fastr :: HTTP . method? ( env , :get ) controller . get_params = Fastr :: HTTP . parse_query_string ( env [ 'QUERY_STRING' ] ) controller . params = controller . get_params . merge ( vars ) elsif Fastr :: HTTP . method? ( env , :post ) controller . post_params ... | Populate the parameters based on the HTTP method . |
18,323 | def plugin_before_dispatch ( env ) new_env = env self . plugins . each do | plugin | if plugin . respond_to? :before_dispatch new_env = plugin . send ( :before_dispatch , self , env ) end end new_env end | Runs before_dispatch in all plugins . |
18,324 | def plugin_after_dispatch ( env , response ) new_response = response self . plugins . each do | plugin | if plugin . respond_to? :after_dispatch new_response = plugin . send ( :after_dispatch , self , env , response ) end end new_response end | Runs after_dispatch in all plugins . |
18,325 | def options ( opts ) opts . version = Filepreviews :: VERSION opts . banner = BANNER opts . set_program_name 'Filepreviews.io' opts . on ( '-k' , '--api_key [key]' , String , 'use API key from Filepreviews.io' ) do | api_key | Filepreviews . api_key = api_key end opts . on ( '-s' , '--secret_key [key]' , String , 'use ... | Passes arguments from ARGV and sets metadata flag |
18,326 | def parse opts = OptionParser . new ( & method ( :options ) ) opts . parse! ( @args ) return opts . help if @args . last . nil? file_preview = Filepreviews . generate ( @args . last ) @metadata ? file_preview . metadata ( js : true ) : file_preview end | Parses options sent from command - line |
18,327 | def source_mac @source_mac ||= if self . victim_ip :: ServiceObjects :: NetworkInformation . self_mac ( interface ) else gateway_ip = ServiceObjects :: NetworkInformation . gateway_ip mac = :: Ownlan :: Attack :: Base . new ( self ) . ip_to_mac ( gateway_ip ) end end | Create a new instance . |
18,328 | def die_rolls ( number_of_words ) die_rolls_per_word = 5 total_die_rolls = number_of_words * die_rolls_per_word die_roll_sequence = generate_random_numbers ( total_die_rolls , 6 , 1 ) group_die_rolls ( die_roll_sequence , number_of_words , die_rolls_per_word ) end | Returns an array of strings where each string comprises five numeric characters each one representing one roll of a die . The number of elements in the array equals the number of words specified for the passphrase . |
18,329 | def process_params ( params ) parameters = { url : CGI . unescape ( params . url ) } if params . metadata parameters [ :metadata ] = extract_metadata ( params . metadata ) end parameters end | Returns processed options and url as parameters |
18,330 | def match ( env ) self . routes . each do | info | next unless info [ :methods ] . nil? or info [ :methods ] . include? ( env [ "REQUEST_METHOD" ] . downcase . to_sym ) match = env [ 'PATH_INFO' ] . match ( info [ :regex ] ) if not match . nil? vars = { } info [ :vars ] . each_index do | i | var = info [ :vars ] [ i ] ... | Searches the routes for a match given a Rack env . |
18,331 | def for ( path , * args ) arg = args [ 0 ] log . debug "Adding route, path: #{path}, args: #{args.inspect}" match = get_regex_for_route ( path , arg ) hash = get_to_hash ( arg ) route_info = { :regex => match [ :regex ] , :args => arg , :vars => match [ :vars ] , :hash => hash } route_info [ :methods ] = arg [ :methods... | Adds a route for a path and arguments . |
18,332 | def conf hsh = { :host => host , :port => port , :db => db } . merge parse_query ( query ) hsh [ :password ] = password if password hsh end | Returns a hash suitable for sending to Redis . new . The hash is generated from the host port db and password from the URI as well as any query vars . |
18,333 | def view_getCurrentTemplateName return VIEW_CURRENTTEMPLATENAME if defined? VIEW_CURRENTTEMPLATENAME directory = core_getCacheDirectory if File . exist? "#{directory}/view.yml" config = YAML . load ( File . read ( File . expand_path ( "#{directory}/view.yml" , __FILE__ ) ) ) if ! config || ! config [ 'template' ] retur... | This function return the name of the current theme used for the application . |
18,334 | def songs ( options = { page : 1 } ) songs_url = "/artists/#{@id}/songs/?page=#{options[:page]}" fetch ( songs_url ) [ "response" ] [ "songs" ] . map do | song | Song . new ( artist : Artist . new ( name : song [ "primary_artist" ] [ "name" ] , id : song [ "primary_artist" ] [ "id" ] , type : :primary ) , title : song ... | You seem to be able to load 20 songs at a time for an artist . I haven t found a way to vary the number you get back from the query but you can paginate through in blocks of 20 songs . |
18,335 | def view_getApplicationsAssetsItems return VIEW_APPASSETS if defined? VIEW_APPASSETS assets = [ ] directory = core_getCacheDirectory if File . exist? "#{directory}/view.yml" config = YAML . load ( File . read ( File . expand_path ( "#{directory}/view.yml" , __FILE__ ) ) ) data = getConfigAssets ( config ) data . each d... | This function return an array of url of assets from the main application . |
18,336 | def default_connection ( url = BASE_URL , debug = false ) Faraday . new ( url : url ) do | conn | conn . adapter :typhoeus conn . headers [ :user_agent ] = USER_AGENT conn . headers [ :content_type ] = 'application/json' configure_api_auth_header ( conn . headers ) configure_logger ( conn ) if debug end end | Returns custom Typhoeus connection configuration |
18,337 | def prepare_request ( params ) request = process_params ( params ) request . store ( :sizes , [ extract_size ( params . size ) ] ) if params . size request . store ( :format , params . format ) if params . format request . store ( :data , params . data ) if params . data request . store ( :uploader , params . uploader ... | Returns processed metadata and image attributes params |
18,338 | def fetch ( params , endpoint_path = 'previews' ) options = prepare_request ( params ) response = default_connection ( BASE_URL , params . debug ) . post do | req | req . url ( "/v2/#{endpoint_path}/" ) req . body = JSON . generate ( options ) end parse ( response . body ) end | Returns parsed response from API |
18,339 | def loadalltracks uri = URI ( @service_url + 'loadalltracks' ) http = Net :: HTTP . new ( uri . host , uri . port ) http . use_ssl = true req = Net :: HTTP :: Post . new ( uri . path ) req . set_form_data ( 'u' => 0 , 'xt' => @cookie ) req [ 'Authorization' ] = 'GoogleLogin auth=%s' % @auth res = http . request ( req )... | Web Client API |
18,340 | def mac_addr case RUBY_PLATFORM when / / if ( m = ` ` . match ( / \S / ) ) m [ 1 ] . upcase end when / / devices = Dir [ '/sys/class/net/*/address' ] . reject { | a | a =~ %r{ } } dev = devices . first File . read ( dev ) . chomp . upcase end end | MusicManager Uploader identification |
18,341 | def zscan_each ( key , * args , & block ) data_type_check ( key , ZSet ) return [ ] unless data [ key ] return to_enum ( :zscan_each , key , options ) unless block_given? cursor = 0 loop do cursor , values = zscan ( key , cursor , options ) values . each ( & block ) break if cursor == '0' end end | Originally from redis - rb |
18,342 | def get_all ( selector , separator ) elements = @mechanize_page . search ( selector ) throw_if_empty ( elements , "elements" , selector ) ( elements . map & :text ) . join ( separator ) end | String with the text of all matching elements separated by separator . |
18,343 | def easy_finder ( api , symbol , options , at_index = 0 ) if api . is_a? Class return api if options . length == 0 and symbol == :first options . insert ( at_index , symbol ) if options [ at_index ] . is_a? ( Hash ) api . find ( * options ) else raise TaskMapper :: Exception . new ( "#{Helper.name}::#{this_method} meth... | A helper method for easy finding |
18,344 | def search_by_attribute ( things , options = { } , limit = 1000 ) things . find_all do | thing | options . inject ( true ) do | memo , kv | break unless memo key , value = kv begin memo &= thing . send ( key ) == value rescue NoMethodError memo = false end memo end and ( limit -= 1 ) > 0 end end | Goes through all the things and returns results that match the options attributes hash |
18,345 | def determine_private_dirty_rss ( pid ) total = 0 File . read ( "/proc/#{pid}/smaps" ) . split ( "\n" ) . each do | line | line =~ / \d / if $2 total += $2 . to_i end end if total == 0 return nil else return total end rescue Errno :: EACCES , Errno :: ENOENT return nil end | Returns the private dirty RSS for the given process in KB . |
18,346 | def train ( klass , text ) th = TextHash . new ( text ) th . each { | word , count | @storage . incr_word_count klass , word , count yield word , count if block_given? } @storage . incr_total_word_count klass , th . word_count doccount = ( text . kind_of? Array ) ? text . length : 1 @storage . incr_doc_count klass , do... | text can be either an array of strings or a string klass is a symbol |
18,347 | def unseen ( title ) all = seasons title episodes_per_season = { } episodes_to_remove = [ ] all . each do | season_info | season_num = season_info [ 'season' ] next if season_num == 0 episodes = season_info [ 'episodes' ] 1 . upto ( episodes ) do | episode | episodes_to_remove << { season : season_num , episode : episo... | need to use thetvdb id here since the slug can t be used for unseen |
18,348 | def + ( other_color ) other_color = Colorist :: Color . from ( other_color ) color = self . dup color . r += other_color . r color . g += other_color . g color . b += other_color . b color end | Create a duplicate of this color . Add the individual RGB values of two colors together . You may also use an equivalent numeric or string color representation . |
18,349 | def to_hsv red , green , blue = * [ r , g , b ] . collect { | x | x / 255.0 } max = [ red , green , blue ] . max min = [ red , green , blue ] . min if min == max hue = 0 elsif max == red hue = 60 * ( ( green - blue ) / ( max - min ) ) elsif max == green hue = 60 * ( ( blue - red ) / ( max - min ) ) + 120 elsif max == b... | Returns an array of the hue saturation and value of the color . Hue will range from 0 - 359 hue and saturation will be between 0 and 1 . |
18,350 | def gradient_to ( color , steps = 10 ) color_to = Colorist :: Color . from ( color ) red = color_to . r - r green = color_to . g - g blue = color_to . b - b result = ( 1 .. ( steps - 3 ) ) . to_a . collect do | step | percentage = step . to_f / ( steps - 1 ) Color . from_rgb ( r + ( red * percentage ) , g + ( green * p... | Uses a naive formula to generate a gradient between this color and the given color . Returns the array of colors that make the gradient including this color and the target color . By default will return 10 colors but this can be changed by supplying an optional steps parameter . |
18,351 | def add_table ( name , table ) if table . is_a? Hash tables [ name . to_sym ] = table else raise TypeError , 'Invalid table format' end end | Adds a table to the table store . A valid table must be a Hash with single character string keys and numerical values . A table that is not a Hash will raise a TypeError . The table name will be converted to a Symbol . |
18,352 | def get_pr_arguments_with_xml ( mark , * args ) res = get_pr_arguments_without_xml ( ( ! ! mark ) . to_s , * args ) res [ :file ] = File . expand_path ( res [ :file ] ) res end | Mark should be true or false as a String |
18,353 | def call words = stems_for ( remove_stopwords_in ( @words ) ) score_words ( frequencies_for ( words ) ) scores . key ( scores . values . max ) end | Main method that initiates scoring emotions |
18,354 | def method_missing ( emotion ) return scores [ emotion ] || 0 if scores . keys . include? emotion raise NoMethodError , "#{emotion} is not defined" end | MethodMissing to implement metods that are the names of each emotion that will returen the score of that specific emotion for the text |
18,355 | def ambiguous_score unq_scores = scores . values . uniq scores [ :ambiguous ] = 1 if unq_scores . length == 1 && unq_scores . first . zero? end | Last part of the scoring process If all scores are empty ambiguous is scored as 1 |
18,356 | def score_emotions ( emotion , term , frequency ) return unless SadPanda :: Bank :: EMOTIONS [ emotion ] . include? ( term ) scores [ emotion ] += frequency end | Increments the score of an emotion if the word exist in that emotion bank |
18,357 | def set_emotions ( word , frequency ) SadPanda :: Bank :: EMOTIONS . keys . each do | emotion | score_emotions ( emotion , word , frequency ) end end | Iterates all emotions for word in text |
18,358 | def score_words ( word_frequencies ) word_frequencies . each do | word , frequency | set_emotions ( word , frequency ) end score_emoticons ambiguous_score end | Logic to score all unique words in the text |
18,359 | def parse_file path , matcher File . open ( path ) do | f | f . each do | line | if m = matcher . call ( line ) return m end end end raise "#{path}: found no matching lines." end | Parse the specified file with the provided matcher . |
18,360 | def update_file path , matcher , currentVersion , nextVersion temp_path = "#{path}.autoversion" begin File . open ( path ) do | source | File . open ( temp_path , 'w' ) do | target | source . each do | line | if matcher . call ( line ) target . write line . gsub currentVersion . to_s , nextVersion . to_s else target . ... | Update a file naively matching the specified matcher and replace any matching lines with the new version . |
18,361 | def update_files paths , matcher , currentVersion , nextVersion paths . each do | path | update_file path , matcher , currentVersion , nextVersion end end | Convenience function for update_file to apply to multiple files . |
18,362 | def echo ( options ) which = options [ :id ] ? "with ID #{options[:id].inspect}" : "named #{format_script_name(options[:name])}" scope = options [ :scope ] == :all ? "'all' servers" : "a 'single' server" where = options [ :tags ] ? "on #{scope} with tags #{options[:tags].inspect}" : "locally on this server" using = "" ... | Echo what is being requested |
18,363 | def to_forwarder_options ( options ) result = { } if options [ :tags ] result [ :tags ] = options [ :tags ] result [ :selector ] = options [ :scope ] end if options [ :thread ] result [ :thread ] = options [ :thread ] end if options [ :policy ] result [ :policy ] = options [ :policy ] end if options [ :audit_period ] r... | Map arguments options into forwarder actor compatible options |
18,364 | def render ( template , output = nil ) result = ERB . new ( File . read ( template ) , 0 , '-' ) . result ( binding ) if ! output . nil? File . open ( output , "w" ) do | file | file . write ( result ) end else puts result end end | Create RUYML data from a YAML hash . Underlying hashes will be accessed as instances of this class . Other types are kept untouched and returned as is . Renders RUYML data using the given template . Rendered data is either written to an optional output file path or to stdout . |
18,365 | def add_scout ( scout_description , & block ) config = ScoutConfig . new config . instance_eval ( & block ) scout_description . each do | scout , description | @scouts [ scout ] << { :description => description , :config => config } end end | New instance of a Outpost - based class . |
18,366 | def notify if reports . any? @notifiers . each do | notifier , options | options_copy = Marshal . load ( Marshal . dump ( options ) ) notifier . new ( options_copy ) . notify ( self ) end end end | Runs all notifications associated with an Outpost - based class . |
18,367 | def append_output ( text ) @mutex . synchronize do @buffer << RightScale :: AuditProxy . force_utf8 ( text ) end EM . next_tick do buffer_size = nil @mutex . synchronize do buffer_size = @buffer . size end if buffer_size > MAX_AUDIT_SIZE flush_buffer else reset_timer end end end | Append output to current audit section |
18,368 | def internal_send_audit ( options ) RightScale :: AuditProxy . force_utf8! ( options [ :text ] ) opts = { :audit_id => @audit_id , :category => options [ :category ] , :offset => @size } opts [ :category ] ||= EventCategories :: CATEGORY_NOTIFICATION unless EventCategories :: CATEGORIES . include? ( opts [ :category ] ... | Actually send audits to core agent and log failures |
18,369 | def flush_buffer if @timer @timer . cancel @timer = nil end to_send = nil @mutex . synchronize do unless @buffer . empty? to_send = @buffer @buffer = '' end end if to_send internal_send_audit ( :kind => :output , :text => to_send , :category => EventCategories :: NONE ) end end | Send any buffered output to auditor |
18,370 | def htmlify_except ( nodes ) nodes . reduce ( to_html ) do | output , node | output . gsub ( node . to_html , node . to_xhtml ) end end | Generate an html string for the current document but replace the provided nodes with their xhtml strings . |
18,371 | def run ( options ) check_privileges AgentConfig . root_dir = AgentConfig . right_link_root_dirs if RightScale :: Platform . windows? cleanup_certificates ( options ) reenroller_state = { :reenroll => true } File . open ( STATE_FILE , "w" ) { | f | f . write reenroller_state . to_json } print 'Restarting RightScale ser... | Trigger re - enrollment |
18,372 | def process_running? ( pid ) return false unless pid Process . getpgid ( pid ) != - 1 rescue Errno :: ESRCH false end | Checks whether process with given pid is running |
18,373 | def start ( options ) begin setup_traps @state_serializer = Serializer . new ( :json ) @agent = AgentConfig . agent_options ( 'instance' ) error ( "No instance agent configured" , nil , abort = true ) if @agent . empty? @options = options unless @options [ :time_limit ] if @agent [ :ping_interval ] @options [ :time_lim... | Run daemon or run one agent communication check If running as a daemon store pid in same location as agent except suffix the agent identity with - rchk . |
18,374 | def check begin checker_identity = "#{@agent[:identity]}-rchk" pid_file = PidFile . new ( checker_identity , @agent [ :pid_dir ] ) if @options [ :stop ] pid_data = pid_file . read_pid if pid_data [ :pid ] info ( "Stopping checker daemon" ) if RightScale :: Platform . windows? begin send_command ( { :name => :terminate ... | Perform required checks |
18,375 | def check_communication ( attempt , must_try = false ) attempt += 1 begin if ! must_try && ( time = time_since_last_communication ) < @options [ :time_limit ] @retry_timer . cancel if @retry_timer elapsed = elapsed ( time ) info ( "Passed communication check with activity as recently as #{elapsed} ago" , to_console = !... | Check communication repeatedly if necessary |
18,376 | def time_since_last_communication state_file = @options [ :state_path ] || File . join ( AgentConfig . agent_state_dir , 'state.js' ) state = @state_serializer . load ( File . read ( state_file ) ) if File . file? ( state_file ) state . nil? ? ( @options [ :time_limit ] + 1 ) : ( Time . now . to_i - state [ "last_commu... | Get elapsed time since last communication |
18,377 | def try_communicating ( attempt ) begin send_command ( { :name => "check_connectivity" } , @options [ :verbose ] , COMMAND_IO_TIMEOUT ) do | r | @command_io_failures = 0 res = serialize_operation_result ( r ) rescue nil if res && res . success? info ( "Successful agent communication" + ( attempt > 1 ? " on attempt #{at... | Ask instance agent to try to communicate |
18,378 | def reenroll! unless @reenrolling @reenrolling = true begin info ( "Triggering re-enroll after unsuccessful communication check" , to_console = true ) cmd = "rs_reenroll" cmd += " -v" if @options [ :verbose ] cmd += '&' unless RightScale :: Platform . windows? terminate unless RightScale :: Platform . windows? system (... | Trigger re - enroll This will normally cause the checker to exit |
18,379 | def error ( description , error = nil , abort = false ) if @logging_enabled msg = "[check] #{description}" msg += ", aborting" if abort msg = Log . format ( msg , error , :trace ) if error Log . error ( msg ) end msg = description msg += ": #{error}" if error puts "** #{msg}" if abort terminate exit ( 1 ) end true end | Handle error by logging message and optionally aborting execution |
18,380 | def elapsed ( time ) time = time . to_i if time <= MINUTE "#{time} sec" elsif time <= HOUR minutes = time / MINUTE seconds = time - ( minutes * MINUTE ) "#{minutes} min #{seconds} sec" elsif time <= DAY hours = time / HOUR minutes = ( time - ( hours * HOUR ) ) / MINUTE "#{hours} hr #{minutes} min" else days = time / DA... | Convert elapsed time in seconds to displayable format |
18,381 | def run_recipe_command ( opts ) payload = opts [ :options ] || { } target = { } target [ :tags ] = payload . delete ( :tags ) if payload [ :tags ] target [ :scope ] = payload . delete ( :scope ) if payload [ :scope ] target [ :selector ] = payload . delete ( :selector ) if payload [ :selector ] if ( target [ :tags ] &&... | Run recipe command implementation |
18,382 | def run_right_script_command ( opts ) payload = opts [ :options ] || { } target = { } target [ :tags ] = payload . delete ( :tags ) if payload [ :tags ] target [ :scope ] = payload . delete ( :scope ) if payload [ :scope ] target [ :selector ] = payload . delete ( :selector ) if payload [ :selector ] if ( target [ :tag... | Run RightScript command implementation |
18,383 | def send_retryable_request_command ( opts ) options = opts [ :options ] options [ :timeout ] ||= opts [ :timeout ] send_retryable_request ( opts [ :type ] , opts [ :conn ] , opts [ :payload ] , options ) end | Send a retryable request to a single target with a response expected retrying multiple times at the application layer in case failures or errors occur . |
18,384 | def get_instance_state_agent_command ( opts ) result = RightScale :: InstanceState . value CommandIO . instance . reply ( opts [ :conn ] , JSON . dump ( { :result => result } ) ) rescue Exception => e CommandIO . instance . reply ( opts [ :conn ] , JSON . dump ( { :error => e . message } ) ) end | Get Instance State value for Agent type |
18,385 | def get_instance_state_run_command ( opts ) value = RightScale :: InstanceState . value result = case value when 'booting' "booting#{InstanceState.reboot? ? ':reboot' : ''}" when 'operational' , 'stranded' value when 'decommissioning' , 'decommissioned' decom_reason = "unknown" decom_reason = InstanceState . decommissi... | Get Instance State value for Run type |
18,386 | def get_tags_command ( opts ) AgentTagManager . instance . tags ( opts ) { | tags | CommandIO . instance . reply ( opts [ :conn ] , tags ) } end | Get tags command |
18,387 | def add_tag_command ( opts ) AgentTagManager . instance . add_tags ( opts [ :tag ] , opts ) do | raw_response | reply = @serializer . dump ( raw_response ) rescue raw_response CommandIO . instance . reply ( opts [ :conn ] , reply ) end end | Add given tag |
18,388 | def remove_tag_command ( opts ) AgentTagManager . instance . remove_tags ( opts [ :tag ] , opts ) do | raw_response | reply = @serializer . dump ( raw_response ) rescue raw_response CommandIO . instance . reply ( opts [ :conn ] , reply ) end end | Remove given tag |
18,389 | def query_tags_command ( opts ) AgentTagManager . instance . query_tags_raw ( opts [ :tags ] , opts [ :hrefs ] , opts ) do | raw_response | reply = @serializer . dump ( raw_response ) rescue raw_response CommandIO . instance . reply ( opts [ :conn ] , reply ) end end | Query for instances with given tags |
18,390 | def audit_create_entry_command ( opts ) payload = { :agent_identity => @agent_identity , :summary => opts [ :summary ] , :category => opts [ :category ] || RightScale :: EventCategories :: NONE , :user_email => opts [ :user_email ] , :detail => opts [ :detail ] } send_push ( '/auditor/create_entry' , opts [ :conn ] , p... | Create an audit entry . |
18,391 | def audit_update_status_command ( opts ) AuditCookStub . instance . forward_audit ( :update_status , opts [ :content ] , opts [ :thread_name ] , opts [ :options ] ) CommandIO . instance . reply ( opts [ :conn ] , 'OK' , close_after_writing = false ) end | Update audit summary |
18,392 | def set_inputs_patch_command ( opts ) payload = { :agent_identity => @agent_identity , :patch => opts [ :patch ] } send_push ( "/updater/update_inputs" , opts [ :conn ] , payload ) CommandIO . instance . reply ( opts [ :conn ] , 'OK' ) end | Update inputs patch to be sent back to core after cook process finishes |
18,393 | def send_push ( type , conn , payload = nil , target = nil , options = { } ) payload ||= { } payload [ :agent_identity ] = @agent_identity Sender . instance . send_push ( type , payload , target , options ) CommandIO . instance . reply ( conn , 'OK' ) true end | Helper method to send a request to one or more targets with no response expected See Sender for details |
18,394 | def send_request ( type , conn , payload = nil , target = nil , options = { } ) payload ||= { } payload [ :agent_identity ] = @agent_identity Sender . instance . send_request ( type , payload , target , options ) do | r | reply = @serializer . dump ( r ) rescue '\"Failed to serialize response\"' CommandIO . instance . ... | Helper method to send a request to a single target agent with a response expected The request is retried if the response is not received in a reasonable amount of time The request is timed out if not received in time typically configured to 2 minutes The request is allowed to expire per the agent s configured time - to... |
18,395 | def send_retryable_request ( type , conn , payload = nil , opts = { } ) req = RetryableRequest . new ( type , payload , opts ) callback = Proc . new do | content | result = OperationResult . success ( content ) reply = @serializer . dump ( result ) rescue '\"Failed to serialize response\"' CommandIO . instance . reply ... | Helper method to send a retryable request to a single target with a response expected retrying at the application layer until the request succeeds or the timeout elapses ; default timeout is forever . |
18,396 | def run_request ( type , conn , payload ) payload ||= { } payload [ :agent_identity ] = @agent_identity Sender . instance . send_request ( type , payload ) do | r | r = OperationResult . from_results ( r ) if r && r . success? && r . content . is_a? ( RightScale :: ExecutableBundle ) @scheduler . schedule_bundle ( :bun... | Send scheduling request for recipe or RightScript If it returns with a bundle schedule the bundle for execution |
18,397 | def get_shutdown_request_command ( opts ) shutdown_request = ShutdownRequest . instance CommandIO . instance . reply ( opts [ :conn ] , { :level => shutdown_request . level , :immediately => shutdown_request . immediately? } ) rescue Exception => e CommandIO . instance . reply ( opts [ :conn ] , { :error => e . message... | Get shutdown request command |
18,398 | def set_shutdown_request_command ( opts ) shutdown_request = ShutdownRequest . submit ( opts ) CommandIO . instance . reply ( opts [ :conn ] , { :level => shutdown_request . level , :immediately => shutdown_request . immediately? } ) rescue Exception => e CommandIO . instance . reply ( opts [ :conn ] , { :error => e . ... | Set reboot timeout command |
18,399 | def add_transcoding ( parameters ) response = self . class . resource . post ( "#{id}/transcodings" , parameters ) reload response . code . to_i == 201 end | Adds a transcoding to the video instance and reloads itself to reflect the changed transcodings array . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.