idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
15,200
def options Dotenv . load seq_config = ENV . keys . select { | key | key =~ / / } . inject ( { } ) do | config , key | new_key = key . gsub ( / / , '' ) . downcase config [ new_key ] = ENV [ key ] config end db_config = ENV . keys . select { | key | key =~ / / } . inject ( { } ) do | config , key | new_key = key . down...
Any environment variables in the . env file are loaded and then any environment variable starting with SEQUELIZER_ will be used as an option for the database
15,201
def cvar ( cvar_name ) response = command ( cvar_name ) match = / \s \s / . match response match = match [ 1 ] if / \D / . match match return match else return match . to_i end end
Convenience method to scrape input from cvar output and return that data . Returns integers as a numeric type if possible .
15,202
def command ( command ) if ! @authed raise NetworkException . new ( "You must authenticate the connection successfully before sending commands." ) end @packet = Packet :: Source . new @packet . command ( command ) @socket . print @packet . to_s rpacket = build_response_packet if rpacket . command_type != Packet :: Sour...
Sends a RCon command to the server . May be used multiple times after an authentication is successful .
15,203
def auth ( password ) establish_connection @packet = Packet :: Source . new @packet . auth ( password ) @socket . print @packet . to_s rpacket = nil 2 . times { rpacket = build_response_packet } if rpacket . command_type != Packet :: Source :: RESPONSE_AUTH raise NetworkException . new ( "error authenticating: #{rpacke...
Requests authentication from the RCon server given a password . Is only expected to be used once .
15,204
def add_cell ( object , args , type = nil , block = nil ) @cells << FormatCell . new ( object , args , type , block ) end
Create a new cell with the class FormatCell Add the object in
15,205
def content_columns model_name ( @object ) . constantize . content_columns . collect { | c | c . name . to_sym } . compact rescue [ ] end
Return each column in the model s database table
15,206
def model_have_column? ( column ) model_name ( @object ) . constantize . content_columns . each do | model_column | return true if model_column . name == column . to_s end false end
Return true if the column is in the model s database table
15,207
def format_options_to_cell ( ask , options = @column_options ) options . each do | key , value | if only_cell_option? ( key ) if ask . is_a? Hash ask . merge! ( key => value ) else ask = [ ask ] unless ask . is_a? Array ( ask . last . is_a? Hash and ask . last . has_key? :html ) ? ask . last [ :html ] . merge! ( key =>...
Format ask to send options to cell
15,208
def dictionary_meaning if @dictionary_meaning . nil? @dictionary = Dictionary . new ( @word ) meanings = @dictionary . meanings if meanings . is_a? Array and not meanings . empty? @dictionary_meanings = meanings @dictionary_meaning = @dictionary . meaning end end @dictionary_meaning end
Gives dictionary meaning for the word
15,209
def urban_meaning if @urban_meaning . nil? @urban = Urban . new ( @word ) meanings = @urban . meanings if meanings . is_a? ( Array ) and not meanings . empty? @urban_meanings = meanings @urban_meaning = @urban . meaning end end @urban_meaning end
Fetches the first meaning from Urban Dictionary for the word .
15,210
def ask ( * args ) options = args . last . kind_of? ( Hash ) ? args . pop : { } prompts = args . flatten . compact if block_given? logger . warn "You passed a block to #ask, but this functionality is not available in adhearsion-asr. If you're looking for the block validator functionality, you should avoid using it in f...
Prompts for input handling playback of prompts DTMF grammar construction and execution
15,211
def menu ( * args , & block ) raise ArgumentError , "You must specify a block to build the menu" unless block options = args . last . kind_of? ( Hash ) ? args . pop : { } prompts = args . flatten . compact menu_builder = MenuBuilder . new ( options , & block ) output_document = prompts . empty? ? nil : output_formatter...
Creates and manages a multiple choice menu driven by DTMF handling playback of prompts invalid input retries and timeouts and final failures .
15,212
def spatial_join ( other , buffer = 0 , table_alias = 'features' , other_alias = 'other_features' , geom = 'geom_lowres' ) scope = features_scope ( self ) . select ( "#{geom} AS geom" ) . select ( :spatial_model_id ) other_scope = features_scope ( other ) other_scope = other_scope . select ( "ST_Union(#{geom}) AS geom"...
Returns a scope that includes the features for this record as the table_alias and the features for other as other_alias Performs a spatial intersection between the two sets of features within the buffer distance given in meters
15,213
def chain_enrichments! ( agg ) chain . keys . each do | e | enrichment = enrichment_cache ( e ) if enrichment . is_a? Audumbla :: FieldEnrichment agg = do_field_enrichment ( agg , enrichment , chain [ e ] ) else agg = do_basic_enrichment ( agg , enrichment , chain [ e ] ) end end end
Given an aggregation take each enrichment specified by the chain given in our instantiation and apply that enrichment with the given options modifying the aggregation in - place .
15,214
def deep_sym ( obj ) if obj . is_a? Hash return obj . inject ( { } ) do | memo , ( k , v ) | memo [ k . to_sym ] = deep_sym ( v ) memo end elsif obj . is_a? Array return obj . inject ( [ ] ) do | memo , el | memo << deep_sym ( el ) memo end elsif obj . respond_to? :to_sym return obj . to_sym else return nil end end
Transform the given hash recursively by turning all of its string keys and values into symbols .
15,215
def add meter = nil Meter . uncached { meter = Meter . find_by_name_and_created_on ( name , created_on ) } meter ||= Meter . new ( name : name , created_on : created_on ) meter . value += value return meter . save end
Instance methods Create an object for this name + date in the db if one does not already exist . Add the value from this object to the one in the DB . Returns the result of the ActiveRecord save operation .
15,216
def post_update raise StateError . new 'device access_token prohibited' if @session . device? post_data = @data . dup post_data [ 'tags' ] = post_data . delete 'name' grok_self_from post 'tag/permissions/update' , post_data self end
POST the tag s +
15,217
def post_update post_data = @data . dup case @session . type when :application post_data [ 'deviceIds' ] = post_data . delete 'deviceId' when :device post_data . delete 'deviceId' end post_data . delete 'tags' post_data . delete 'lastSeen' grok_self_from post 'device/update' , post_data self end
POST the device s +
15,218
def meanings url = PREFIX + CGI :: escape ( @word ) @doc ||= Nokogiri :: HTML ( open ( url ) ) nodes = @doc . css ( '.meaning' ) results = nodes . map ( & :text ) . map ( & :strip ) . reject ( & :empty? ) @meaning = results . first results end
Fetches and gives meanings for the word from Urban Dictionary
15,219
def define ( name , opts = { } , & block ) klass = opts . fetch ( :class , DPLA :: MAP :: Aggregation ) parser = opts . fetch ( :parser , Krikri :: XmlParser ) parser_args = opts . fetch ( :parser_args , nil ) map = Krikri :: Mapping . new ( klass , parser , * parser_args ) map . instance_eval ( & block ) if block_give...
Creates mappings and passes DSL methods through to them then adds them to a global registry .
15,220
def run ( activity_uri = nil ) records . each do | rec | next if rec . nil? begin process_record ( rec , activity_uri ) rescue => e Krikri :: Logger . log :error , "Error harvesting record:\n" "#{rec.content}\n\twith message:\n" "#{e.message}" next end end true end
Run the harvest .
15,221
def find_by_activity ( activity_uri , include_invalidated = false ) raise ArgumentError , 'activity_uri must be an RDF::URI' unless activity_uri . respond_to? :to_term query = SPARQL_CLIENT . select ( :record ) . where ( [ :record , [ RDF :: PROV . wasGeneratedBy , '|' , RDF :: DPLA . wasRevisedBy ] , activity_uri . to...
Finds all entities generated or revised by the activity whose URI is given .
15,222
def ct_increment ( increment = 1 ) params = { ct : { } } params [ :ct ] [ :increment ] = increment @requester . put ( url : "#{@api_url}/state" , params : params ) end
color temperature commands
15,223
def change_catalog catalog , id , valuehash catalog_exists? catalog if @report . at_css ( "#{catalog}" ) . at ( "[@id='#{id}']" ) valuehash . each do | key , value | @report . at_css ( "#{catalog}" ) . at ( "[@id='#{id}']" ) [ "#{key}" ] = value end else cat = @report . at_css ( "#{catalog}" ) newentry = Nokogiri :: XM...
Change a catalog
15,224
def get_catalog_value catalog , id , key catalog_exists? catalog if @report . at_css ( "#{catalog}" ) . at ( "[@id='#{id}']" ) @report . at_css ( "#{catalog}" ) . at ( "[@id='#{id}']" ) [ "#{key}" ] else return false end end
get an attribute from a catalog entry
15,225
def link_to_current_page_by_provider ( provider ) provider = Krikri :: Provider . find ( provider ) if provider . is_a? String return link_to_provider_page ( provider ) if params [ :controller ] == 'krikri/providers' params [ :provider ] = provider . id params [ :session_provider ] = provider . id link_to provider_name...
Link to the current page changing the session provider the given value .
15,226
def meter_description ( name ) content_tag ( :p ) do concat content_tag ( :b , name ) concat ' - ' concat t ( name , scope : :meter_cat ) end end
Constructs a single meter description
15,227
def meter_descriptions ( meters ) content_tag ( :ul ) do meters . keys . sort . each do | name | concat content_tag ( :li , meter_description ( name ) ) end end end
Constructs a list of meter descriptions
15,228
def meter_form ( date , days , names , all_names ) render partial : 'form' , locals : { date : date , days : days , names : names , all_names : all_names } end
Renders the _form partial with locals
15,229
def truncate_between ( str , after = 30 ) str = '' if str . nil? str . length > after ? "#{str[0..(after / 2) - 2]}...#{str[(str.length - ((after / 2) - 2))..str.length]}" : str end
adds ... in between like if you have to long names in apple finder so you can i . e see the beginning and the suffix
15,230
def post path , params = { } , other_headers = { } r = @hc . post BASE_URL % path , params . to_json , headers ( other_headers ) raise GeotriggerError . new r . body unless r . status == 200 h = JSON . parse r . body raise_error h [ 'error' ] if h [ 'error' ] h end
POST an API request to the given path with optional params and headers . Returns a normal Ruby + Hash + of the response data .
15,231
def raise_error error ge = GeotriggerError . new error [ 'message' ] ge . code = error [ 'code' ] ge . headers = error [ 'headers' ] ge . message = error [ 'message' ] ge . parameters = error [ 'parameters' ] jj error raise ge end
Creates and raises a + GeotriggerError + from an API error response .
15,232
def coord_values ( s ) coords = s . split ( / / ) return [ nil , nil ] if coords . size != 2 coords . map! { | c | c . to_f . to_s == c ? c : nil } return [ nil , nil ] unless coords [ 0 ] && coords [ 1 ] [ coords [ 0 ] , coords [ 1 ] ] end
Given a String s return an array of two elements split on a comma and any whitespace around the comma .
15,233
def example_pending ( example , message , deprecated_pending_location = nil ) immediately_dump_pending ( example . description , message , example . location ) mark_error_state_pending increment end
third param is optional because earlier versions of rspec sent only two args
15,234
def make_request ( method , body = nil , headers = { } ) validate_subject ldp_connection . send ( method ) do | request | request . url rdf_subject request . headers = headers if headers request . body = body end end
Lightly wraps Faraday to manage requests of various types their bodies and headers .
15,235
def show if params [ :set_session ] session [ :current_provider ] = params [ :id ] redirect_to :back , provider : params [ :id ] elsif params [ :clear_session ] session . delete :current_provider redirect_to providers_path end @current_provider = Krikri :: Provider . find ( params [ :id ] ) end
Renders the show view for the provider given by id .
15,236
def remove_unlikely_elements! search ( '*' ) . each do | element | idclass = "#{element['class']}#{element['id']}" if idclass =~ UNLIKELY_IDENTIFIERS && ! REMOVAL_WHITELIST . include? ( element . name ) element . remove end end end
Removes unlikely elements from the document . These are elements who have classes that seem to indicate they are comments headers footers nav etc
15,237
def score! mark_scorable_elements! scorable_elements . each do | element | points = 1 points += element . text . split ( ',' ) . length points += [ element . text . length / 100 , 3 ] . min scores [ element . path ] = points scores [ element . parent . path ] += points scores [ element . parent . parent . path ] += poi...
Scores the document elements based on an algorithm to find elements which hold page content .
15,238
def distill! ( options = { } ) remove_irrelevant_elements! remove_unlikely_elements! score! clean_top_scoring_elements! ( options ) unless options . delete ( :clean ) == false top_scoring_elements . map ( & :inner_html ) . join ( "\n" ) end
Distills the document down to just its content .
15,239
def clean_top_scoring_elements! ( options = { } ) keep_images = ! ! options [ :images ] top_scoring_elements . each do | element | element . search ( "*" ) . each do | node | if cleanable? ( node , keep_images ) debugger if node . to_s =~ / / node . remove end end end end
Attempts to clean the top scoring node from non - page content items such as advertisements widgets etc
15,240
def unique_question_codes codes = @survey . versions . map ( & :question_codes ) . flatten . uniq codes . map do | code | session_fields . include? ( code ) ? "answer_#{code}" : code end end
It could be possible that an answer code equals a session field . We add answer_ in that case so that we get uniqe question codes for sure
15,241
def records ( opts = { } ) opts = @opts . merge ( opts ) request_with_sets ( opts ) do | set_opts | client . list_records ( set_opts ) . full . lazy . flat_map do | rec | begin @record_class . build ( mint_id ( get_identifier ( rec ) ) , record_xml ( rec ) ) rescue => e Krikri :: Logger . log ( :error , e . message ) n...
Sends ListRecords requests lazily .
15,242
def get_record ( identifier , opts = { } ) opts [ :identifier ] = identifier opts = @opts . merge ( opts ) @record_class . build ( mint_id ( identifier ) , record_xml ( client . get_record ( opts ) . record ) ) end
Gets a single record with the given identifier from the OAI endpoint
15,243
def concat_enum ( enum_enum ) Enumerator . new do | yielder | enum_enum . each do | enum | enum . each { | i | yielder << i } end end end
Concatinates two enumerators
15,244
def request_with_sets ( opts , & block ) sets = Array ( opts . delete ( :set ) ) if opts [ :skip_set ] sets = self . sets ( & :spec ) if sets . empty? skips = Array ( opts . delete ( :skip_set ) ) sets . reject! { | s | skips . include? s } end sets = [ nil ] if sets . empty? set_enums = sets . lazy . map do | set | se...
Runs the request in the given block against the sets specified in opts . Results are concatenated into a single enumerator .
15,245
def post_update opts = { } post_data = @data . dup post_data [ 'triggerIds' ] = post_data . delete 'triggerId' post_data . delete 'tags' if circle? post_data [ 'condition' ] [ 'geo' ] . delete 'geojson' post_data [ 'condition' ] [ 'geo' ] . delete 'esrijson' end grok_self_from post 'trigger/update' , post_data . merge ...
POST the trigger s +
15,246
def fix_options ( passed_options ) return passed_options unless passed_options . nil? || passed_options . is_a? ( Hash ) sequelizer_options = db_config . merge ( OptionsHash . new ( passed_options || { } ) . to_hash ) if sequelizer_options [ :adapter ] =~ / / sequelizer_options [ :adapter ] = 'postgres' paths = %w( sea...
If passed a hash scans hash for certain options and sets up hash to be fed to Sequel . connect
15,247
def after_connect ( search_path ) Proc . new do | conn | search_path . split ( ',' ) . map ( & :strip ) . each do | schema | conn . execute ( "CREATE SCHEMA IF NOT EXISTS #{schema}" ) end conn . execute ( "SET search_path TO #{search_path}" ) end end
Returns a proc that should be executed after Sequel connects to the datebase .
15,248
def run_once ( binding ) @ivars . clear before = binding . instance_variables binding . instance_eval ( & @block ) ( binding . instance_variables - before ) . each do | ivar | @ivars [ ivar ] = binding . instance_variable_get ( ivar ) end end
This runs the block and stores any new instance variables that were set .
15,249
def setup ( test_class ) block = self test_class . setup { block . run ( self ) } test_class . teardown { block . teardown_transaction } end
Ensure the block is setup to run first and that the test run is wrapped in a database transaction .
15,250
def set_ivar ( binding , ivar , value ) if value . class . respond_to? ( :find ) value = value . class . find ( value . id ) end super ( binding , ivar , value ) end
reload any AR instances
15,251
def experts ( q , options = { } ) options = set_window_or_default ( options ) result = handle_response ( get ( "/experts.json" , :query => { :q => q } . merge ( options ) ) ) Topsy :: Page . new ( result , Topsy :: Author ) end
Returns list of authors that talk about the query . The list is sorted by frequency of posts and the influence of authors .
15,252
def link_posts ( url , options = { } ) linkposts = handle_response ( get ( "/linkposts.json" , :query => { :url => url } . merge ( options ) ) ) Topsy :: Page . new ( linkposts , Topsy :: Linkpost ) end
Returns list of URLs posted by an author
15,253
def related ( url , options = { } ) response = handle_response ( get ( "/related.json" , :query => { :url => url } . merge ( options ) ) ) Topsy :: Page . new ( response , Topsy :: LinkSearchResult ) end
Returns list of URLs related to a given URL
15,254
def search ( q , options = { } ) if q . is_a? ( Hash ) options = q q = "site:#{options.delete(:site)}" if options [ :site ] else q += " site:#{options.delete(:site)}" if options [ :site ] end options = set_window_or_default ( options ) results = handle_response ( get ( "/search.json" , :query => { :q => q } . merge ( o...
Returns list of results for a query .
15,255
def search_count ( q ) counts = handle_response ( get ( "/searchcount.json" , :query => { :q => q } ) ) Topsy :: SearchCounts . new ( counts ) end
Returns count of results for a search query .
15,256
def search_histogram ( q , count_method = 'target' , slice = 86400 , period = 30 ) response = handle_response ( get ( "/searchhistogram.json" , :query => { :q => q , :slice => slice , :period => period , :count_method => count_method } ) ) Topsy :: SearchHistogram . new ( response ) end
Returns mention count data for the given query
15,257
def stats ( url , options = { } ) query = { :url => url } query . merge! ( options ) response = handle_response ( get ( "/stats.json" , :query => query ) ) Topsy :: Stats . new ( response ) end
Returns counts of tweets for a URL
15,258
def tags ( url , options = { } ) response = handle_response ( get ( "/tags.json" , :query => { :url => url } . merge ( options ) ) ) Topsy :: Page . new ( response , Topsy :: Tag ) end
Returns list of tags for a URL .
15,259
def trending ( options = { } ) response = handle_response ( get ( "/trending.json" , :query => options ) ) Topsy :: Page . new ( response , Topsy :: Trend ) end
Returns list of trending terms
15,260
def url_info ( url ) response = handle_response ( get ( "/urlinfo.json" , :query => { :url => url } ) ) Topsy :: UrlInfo . new ( response ) end
Returns info about a URL
15,261
def extract_header_value ( response , key ) response . headers [ key ] . class == Array ? response . headers [ key ] . first . to_i : response . headers [ key ] . to_i end
extracts the header key
15,262
def poll_again ( fiber , connection , request_options , stop_at ) http = connection . send ( :get , request_options ) http . errback { fiber . resume ( * handle_error ( "POLL" , http . error ) ) } http . callback do code , body , headers = http . response_header . status , http . response , http . response_header if co...
Repeatedly make long - polling request until receive data hit error or timeout Treat terminating and reconnecting errors as an empty poll result
15,263
def beautify_headers ( headers ) headers . inject ( { } ) { | out , ( key , value ) | out [ key . gsub ( / / , '_' ) . downcase . to_sym ] = value ; out } end
Beautify response header keys so that in same form as RestClient
15,264
def tags ( options = { } ) do_query ( nil , @agent . mode == :http ? @agent . self_href : @agent . identity , options ) do | result | if result . kind_of? ( Hash ) yield ( result . size == 1 ? result . values . first [ 'tags' ] : [ ] ) else yield result end end end
Retrieve current agent tags and give result to block
15,265
def query_tags ( tags , options = { } ) tags = ensure_flat_array_value ( tags ) unless tags . nil? || tags . empty? do_query ( tags , nil , options ) { | result | yield result } end
Queries a list of servers in the current deployment which have one or more of the given tags .
15,266
def add_tags ( new_tags , options = { } ) new_tags = ensure_flat_array_value ( new_tags ) unless new_tags . nil? || new_tags . empty? do_update ( new_tags , [ ] , options ) { | raw_response | yield raw_response if block_given? } end
Add given tags to agent
15,267
def remove_tags ( old_tags , options = { } ) old_tags = ensure_flat_array_value ( old_tags ) unless old_tags . nil? || old_tags . empty? do_update ( [ ] , old_tags , options ) { | raw_response | yield raw_response if block_given? } end
Remove given tags from agent
15,268
def do_query ( tags = nil , hrefs = nil , options = { } ) raw = options [ :raw ] timeout = options [ :timeout ] request_options = { } request_options [ :timeout ] = timeout if timeout agent_check payload = { :agent_identity => @agent . identity } payload [ :tags ] = ensure_flat_array_value ( tags ) unless tags . nil? |...
Runs a tag query with an optional list of tags .
15,269
def do_update ( new_tags , old_tags , options = { } , & block ) agent_check raise ArgumentError . new ( "Cannot add and remove tags in same update" ) if new_tags . any? && old_tags . any? tags = @agent . tags tags += new_tags tags -= old_tags tags . uniq! if new_tags . any? request = RightScale :: RetryableRequest . ne...
Runs a tag update with a list of new or old tags
15,270
def init ( agent , agent_name , options = { } ) @agent = agent @trace_level = options [ :trace_level ] || { } notify_init ( agent_name , options ) reset_stats true end
Initialize error tracker
15,271
def log ( component , description , exception = nil , packet = nil , trace = nil ) if exception . nil? Log . error ( description ) elsif exception . is_a? ( String ) Log . error ( description , exception ) else trace = ( @trace_level && @trace_level [ exception . class ] ) || trace || :trace Log . error ( description ,...
Log error and optionally track in stats Errbit notification is left to the callback configured in the stats tracker Logging works even if init was never called
15,272
def track ( component , exception , packet = nil ) if @exception_stats component = component . class . name . split ( "::" ) . last . snake_case unless component . is_a? ( String ) @exception_stats . track ( component , exception , packet ) end true end
Track error in stats
15,273
def notify ( exception , packet = nil , agent = nil , component = nil ) if @notify_enabled if packet && packet . is_a? ( Packet ) action = packet . type . split ( "/" ) . last if packet . respond_to? ( :type ) params = packet . respond_to? ( :payload ) && packet . payload uuid = packet . respond_to? ( :token ) && packe...
Notify Errbit of error if notification enabled
15,274
def notify_callback Proc . new do | exception , packet , agent , component | notify ( exception , packet , agent , component ) end end
Create proc for making callback to notifier
15,275
def notify_init ( agent_name , options ) if options [ :airbrake_endpoint ] && options [ :airbrake_api_key ] unless require_succeeds? ( "airbrake-ruby" ) raise RuntimeError , "airbrake-ruby gem missing - required if airbrake options used in ErrorTracker" end @cgi_data = { :process => $0 , :pid => Process . pid , :agent_...
Configure Airbrake for exception notification
15,276
def filter ( params ) if @filter_params filtered_params = { } params . each { | k , p | filtered_params [ k ] = @filter_params . include? ( k . to_s ) ? FILTERED_PARAM_VALUE : p } filtered_params end end
Apply parameter filter
15,277
def message_received ( & callback ) if block_given? @message_received_callbacks << callback else @message_received_callbacks . each { | c | c . call } if @check_interval > 0 now = Time . now if ( now - @last_received ) > MIN_RESTART_INACTIVITY_TIMER_INTERVAL @last_received = now restart_inactivity_timer end end end tru...
Update the time this agent last received a request or response message and restart the inactivity timer thus deferring the next connectivity check Also forward this message receipt notification to any callbacks that have registered
15,278
def check ( id = nil , max_ping_timeouts = MAX_PING_TIMEOUTS ) unless @terminating || @ping_timer || ( id && ! @sender . agent . client . connected? ( id ) ) @ping_id = id @ping_timer = EM :: Timer . new ( PING_TIMEOUT ) do if @ping_id begin @ping_stats . update ( "timeout" ) @ping_timer = nil @ping_timeouts [ @ping_id...
Check whether broker connection is usable by pinging a router via that broker Attempt to reconnect if ping does not respond in PING_TIMEOUT seconds and if have reached timeout limit Ignore request if already checking a connection
15,279
def restart_inactivity_timer @inactivity_timer . cancel if @inactivity_timer @inactivity_timer = EM :: Timer . new ( @check_interval ) do begin check ( id = nil , max_ping_timeouts = 1 ) rescue Exception => e ErrorTracker . log ( self , "Failed connectivity check" , e ) end end true end
Start timer that waits for inactive messaging period to end before checking connectivity
15,280
def serviced_by ( token ) if @cache [ token ] @cache [ token ] = Time . now . to_i @lru . push ( @lru . delete ( token ) ) @identity end end
Determine whether request has already been serviced
15,281
def stats if ( s = size ) > 0 now = Time . now . to_i { "local total" => s , "local max age" => RightSupport :: Stats . elapsed ( now - @cache [ @lru . first ] ) } end end
Get local cache statistics
15,282
def control ( options ) AgentConfig . cfg_dir = options [ :cfg_dir ] AgentConfig . pid_dir = options [ :pid_dir ] list_configured_agents if options [ :list ] action = options . delete ( :action ) fail ( "No action specified on the command line." , print_usage = true ) unless action if action == 'kill' && ( options [ :p...
Parse arguments and execute request
15,283
def kill_process ( sig = 'TERM' ) content = IO . read ( @options [ :pid_file ] ) pid = content . to_i fail ( "Invalid pid file content #{content.inspect}" ) if pid == 0 begin Process . kill ( sig , pid ) rescue Errno :: ESRCH => e fail ( "Could not find process with pid #{pid}" ) rescue Errno :: EPERM => e fail ( "You ...
Kill process defined in pid file
15,284
def stop_agent ( agent_name ) res = false if ( pid_file = AgentConfig . pid_file ( agent_name ) ) name = human_readable_name ( agent_name , pid_file . identity ) if ( pid = pid_file . read_pid [ :pid ] ) begin Process . kill ( 'TERM' , pid ) res = true puts "#{name} stopped" rescue Errno :: ESRCH puts "#{name} not runn...
Stop agent process
15,285
def list_configured_agents agents = AgentConfig . cfg_agents if agents . empty? puts "Found no configured agents" else puts "Configured agents:" agents . each { | a | puts " - #{a}" } end exit end
List all configured agents
15,286
def configure_agent ( action , options ) agent_type = options [ :agent_type ] agent_name = options [ :agent_name ] if agent_name != agent_type && ( cfg = AgentConfig . load_cfg ( agent_type ) ) base_id = ( options [ :base_id ] || AgentIdentity . parse ( cfg [ :identity ] ) . base_id . to_s ) . to_i unless ( identity = ...
Determine configuration settings for this agent and persist them if needed Reuse existing agent identity when possible
15,287
def configure_proxy ( proxy_setting , exceptions ) ENV [ 'HTTP_PROXY' ] = proxy_setting ENV [ 'http_proxy' ] = proxy_setting ENV [ 'HTTPS_PROXY' ] = proxy_setting ENV [ 'https_proxy' ] = proxy_setting ENV [ 'NO_PROXY' ] = exceptions ENV [ 'no_proxy' ] = exceptions true end
Enable the use of an HTTP proxy for this process and its subprocesses
15,288
def cascade_serializers ( action , packet , serializers , id = nil ) errors = [ ] serializers . map do | serializer | obj = nil begin obj = serializer == SecureSerializer ? serializer . send ( action , packet , id ) : serializer . send ( action , packet ) rescue RightSupport :: Net :: NoResult , SocketError => e raise ...
Apply serializers in order until one succeeds
15,289
def method_missing ( m , * args ) res = @targets . inject ( [ ] ) { | res , t | res << t . send ( m , * args ) } res [ 0 ] end
Forward any method invocation to targets
15,290
def respond_to? ( m , * args ) super ( m , * args ) || @targets . all? { | t | t . respond_to? ( m , * args ) } end
Determine whether this object or ALL of its targets responds to the named method .
15,291
def status ( reason = false ) case @status_code when SUCCESS then 'success' when ERROR then 'error' + ( reason ? " (#{truncated_error})" : "" ) when CONTINUE then 'continue' when RETRY then 'retry' + ( reason ? " (#{@content})" : "" ) when NON_DELIVERY then 'non-delivery' + ( reason ? " (#{@content})" : "" ) when MULTI...
User friendly result status
15,292
def truncated_error e = @content . is_a? ( String ) ? @content : @content . inspect e = e [ 0 , MAX_ERROR_SIZE - 3 ] + "..." if e . size > ( MAX_ERROR_SIZE - 3 ) e end
Limited length error string
15,293
def listen ( socket_port , & block ) raise ArgumentError , 'Missing listener block' unless block_given? raise Exceptions :: Application , 'Already listening' if listening begin @conn = EM . start_server ( '127.0.0.1' , socket_port , ServerInputHandler , block ) rescue Exception => e raise Exceptions :: IO , 'Listen por...
Open command socket and wait for input on it This can only be called again after stop_listening was called
15,294
def reply ( conn , data , close_after_writing = true ) conn . send_data ( CommandSerializer . dump ( data ) ) conn . close_connection_after_writing if close_after_writing true end
Write given data to socket must be listening
15,295
def manage ( options ) AgentConfig . cfg_dir = options [ :cfg_dir ] level = options [ :level ] command = { :name => ( level ? 'set_log_level' : 'get_log_level' ) } command [ :level ] = level . to_sym if level agent_names = if options [ :agent_name ] [ options [ :agent_name ] ] else AgentConfig . cfg_agents end fail ( "...
Handle log level request
15,296
def request_log_level ( agent_name , command , options ) res = false config_options = AgentConfig . agent_options ( agent_name ) unless config_options . empty? || ( listen_port = config_options [ :listen_port ] ) . nil? fail ( "Could not retrieve #{agent_name} agent listen port" ) unless listen_port client = CommandCli...
Send log level request to agent
15,297
def parse_common ( opts , options ) opts . on ( "--test" ) do options [ :user ] = 'test' options [ :pass ] = 'testing' options [ :vhost ] = '/right_net' options [ :test ] = true options [ :pid_dir ] = Dir . tmpdir options [ :base_id ] = "#{rand(1000000)}" options [ :options ] [ :log_dir ] = Dir . tmpdir end opts . on (...
Parse common options between rad and rnac
15,298
def resolve_identity ( options ) options [ :agent_type ] = agent_type ( options [ :agent_type ] , options [ :agent_name ] ) if options [ :base_id ] base_id = options [ :base_id ] . to_i if base_id . abs . to_s != options [ :base_id ] puts "** Identity needs to be a positive integer" exit ( 1 ) end token = if options [ ...
Generate agent identity from options Build identity from base_id token prefix and agent name
15,299
def agent_type ( type , name ) unless type if name =~ / / type = Regexp . last_match ( 1 ) else type = name || "instance" end end type end
Determine agent type