idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
23,400
def compile ( template ) v8_context do | context | template = template . read if template . respond_to? ( :read ) compiled_handlebars = context . eval ( "Handlebars.precompile(#{template.to_json})" ) "Handlebars.template(#{compiled_handlebars});" end end
Compile a Handlerbars template for client - side use with JST
23,401
def render ( template , vars = { } ) v8_context do | context | unless Handlebarer . configuration . nil? helpers = handlebars_helpers context . eval ( helpers . join ( "\n" ) ) if helpers . any? end context . eval ( "var fn = Handlebars.compile(#{template.to_json})" ) context . eval ( "fn(#{vars.to_hbs.to_json})" ) end end
Compile and evaluate a Handlerbars template for server - side rendering
23,402
def divide ( src_file , dst_dir ) FileUtils . mkdir_p ( dst_dir ) unless File . exist? ( dst_dir ) src_content = YAML . load_file ( src_file ) filenames = [ ] case src_content when Hash src_content . each do | key , value | filename = "#{dst_dir}/#{key}.yml" File . open ( filename , "wb" ) do | f | f . write ( { key => value } . to_yaml ) end filenames << filename end when Array src_content . each_with_index do | element , index | filename = "#{dst_dir}/#{index}.yml" File . open ( filename , "wb" ) do | f | f . write ( [ element ] . to_yaml ) end filenames << filename end else raise "Unknown type" end filenames end
divide yaml file
23,403
def players_unplay_role! ( extending_ticker ) roles . keys . each do | rolekey | :: DCI :: Multiplayer ( @_players [ rolekey ] ) . each do | roleplayer | roleplayer . __unplay_last_role! if extending_ticker [ "#{roleplayer.object_id}_#{rolekey}" ] end end end
Disassociates every role from the playing object .
23,404
def on_change ( modified , added , deleted ) ( modified + added ) . uniq . each do | path | if file = Ichiban :: ProjectFile . from_abs ( path ) begin @loader . change ( file ) file . update rescue Exception => exc Ichiban . logger . exception ( exc ) end end end deleted . each do | path | Ichiban :: Deleter . new . delete_dest ( path ) end ( modified + added + deleted ) . uniq . each do | path | begin Ichiban :: Dependencies . propagate ( path ) rescue => exc Ichiban . logger . exception ( exc ) end end end
The test suite calls this method directly to bypass the Listen gem for certain tests .
23,405
def all events = Event . get ( "/eventlist" , :query => { "id" => @@id , "account" => @@account } ) event_sales = Event . get ( "/eventsales" , :query => { "id" => @@id , "account" => @@account } ) parsed_event = [ ] events . parsed_response [ "document" ] [ "event" ] . each do | event | parsed_event << Event . new ( @id , @account , event ) end return parsed_event end
Returns all the account s events from brownpapersticker
23,406
def find ( event_id ) event = Event . get ( "/eventlist" , :query => { "id" => @@id , "account" => @@account , "event_id" => event_id } ) event_sales = Event . get ( "/eventsales" , :query => { "id" => @@id , "account" => @@account , "event_id" => event_id } ) @attributes = event . parsed_response [ "document" ] [ "event" ] return self end
This method get an event from brownpapersticker . The event should belong to the account .
23,407
def init! @lookups ||= { } @aliases ||= { } r = Aggregations :: TermsAggregation . new ( from : '2015-09-01 00:00:00Z' , to : '2015-09-02 00:00:00Z' , term : "memoryAddress" ) . results addresses = r . map { | x | x [ "key" ] } addresses . each do | address | r = Query . new ( from : '2015-09-01 10:00:00Z' , to : '2015-09-30 11:00:00Z' , memory_addresses : address , limit : 1 ) . results signal_name = remove_cruft ( r . first [ "_source" ] [ "signalName" ] . to_s ) @lookups [ signal_name ] = address end aliases = OpenStruct . new fetch_yaml 'signal_aliases' aliases . each_pair do | key , value | @aliases [ key . to_s ] = @lookups [ value ] @lookups [ key . to_s ] = @lookups [ value ] end end
Separate out initialization for testing purposes
23,408
def remove_cruft ( signal ) parts = signal . split ( "." ) [ parts [ 0 .. - 3 ] . join ( '.' ) , parts . pop ] . join ( '.' ) end
This will go away once we get the correct signals in the DB
23,409
def render_copy from_source_path source_path = "#{ActiveCopy.content_path}/#{from_source_path}.md" if File . exists? source_path raw_source = IO . read source_path source = raw_source . split ( "---\n" ) [ 2 ] template = ActiveCopy :: Markdown . new template . render ( source ) . html_safe else raise ArgumentError . new "#{source_path} does not exist." end end
Render a given relative content path to Markdown .
23,410
def sudo! ( * args ) on roles ( :all ) do | host | key = "#{host.user}@#{host.hostname}" SSHKit :: Sudo . password_cache [ key ] = "#{fetch(:password)}\n" end sudo ( * args ) end
sudo! executes sudo command and provides password input .
23,411
def define_actions unless @action_defined hash = YAML . load ( File . read ( @file_path ) ) hash . each do | k , v | v . each do | key , value | @app . class . define_action! ( value [ "request" ] , value [ "response" ] ) end end @action_defined = true end end
defines actions for each request in yaml file .
23,412
def save mongo_handle date_collection = self [ "date" ] if self [ "time" ] < @@cut_off_time date_collection = ( Time . parse ( self [ "date" ] ) - 86400 ) . strftime "%F" end clxns = [ "events" , self [ "type" ] , self [ "subtype" ] , date_collection ] clxns . each do | c | if c mongo_handle . db . collection ( c ) . update ( { "serial" => self [ "serial" ] } , self , { :upsert => true } ) end end end
Save the event to Mongo via mongo_handle
23,413
def shift ( severity , shift = 0 , & block ) severity = ZTK :: Logger . const_get ( severity . to_s . upcase ) add ( severity , nil , nil , shift , & block ) end
Specialized logging . Logs messages in the same format except has the option to shift the caller_at position to exposed the proper calling method .
23,414
def add ( severity , message = nil , progname = nil , shift = 0 , & block ) return if ( @level > severity ) message = block . call if message . nil? && block_given? return if message . nil? called_by = parse_caller ( caller [ 1 + shift ] ) message = [ message . chomp , progname ] . flatten . compact . join ( ": " ) message = "%19s.%06d|%05d|%5s|%s%s\n" % [ Time . now . utc . strftime ( "%Y-%m-%d|%H:%M:%S" ) , Time . now . utc . usec , Process . pid , SEVERITIES [ severity ] , called_by , message ] @logdev . write ( ZTK :: ANSI . uncolor ( message ) ) @logdev . respond_to? ( :flush ) and @logdev . flush true end
Writes a log message if the current log level is at or below the supplied severity .
23,415
def set_log_level ( level = nil ) defined? ( Rails ) and ( default = ( Rails . env . production? ? "INFO" : "DEBUG" ) ) or ( default = "INFO" ) log_level = ( ENV [ 'LOG_LEVEL' ] || level || default ) self . level = ZTK :: Logger . const_get ( log_level . to_s . upcase ) end
Sets the log level .
23,416
def pop ( size = 1 , timeout : nil ) raise ArgumentError , 'size must be positive' unless size . positive? if timeout . nil? return self . connection . rpop ( @key ) if size == 1 return shift_pop_script ( keys : @key , argv : [ - size , - 1 , 1 ] ) else raise ArgumentError , 'timeout is only supported if size == 1' unless size == 1 return self . connection . brpop ( @key , timeout : timeout ) &. last end end
Pops an item from the list optionally blocking to wait until the list is non - empty
23,417
def shift ( size = 1 , timeout : nil ) raise ArgumentError , 'size must be positive' unless size . positive? if timeout . nil? return self . connection . lpop ( @key ) if size == 1 return shift_pop_script ( keys : @key , argv : [ 0 , size - 1 , 0 ] ) else raise ArgumentError , 'timeout is only supported if size == 1' unless size == 1 return self . connection . blpop ( @key , timeout : timeout ) &. last end end
Shifts an item from the list optionally blocking to wait until the list is non - empty
23,418
def popshift ( list , timeout : nil ) raise ArgumentError , 'list must respond to #key' unless list . respond_to? ( :key ) if timeout . nil? return self . connection . rpoplpush ( @key , list . key ) else return self . connection . brpoplpush ( @key , list . key , timeout : timeout ) end end
Pops an element from this list and shifts it onto the given list .
23,419
def connect ( transport : :tcp , address : '127.0.0.1' , port : 5555 ) endpoint = "#{ transport }://#{ address }" endpoint << ":#{ port }" if %i( tcp pgm epgm ) . include? transport @socket . method ( __callee__ ) . call ( endpoint ) == 0 end
Connects the socket to the given address .
23,420
def pop ( non_block = false ) handle_interrupt do @mutex . synchronize do while true if @que . empty? if non_block raise ThreadError , "queue empty" else begin @num_waiting += 1 @cond . wait @mutex ensure @num_waiting -= 1 end end else return @que . shift end end end end end
Retrieves data from the queue . If the queue is empty the calling thread is suspended until data is pushed onto the queue . If + non_block + is true the thread isn t suspended and an exception is raised .
23,421
def pop_up_to ( num_to_pop = 1 , opts = { } ) case opts when TrueClass , FalseClass non_bock = opts when Hash timeout = opts . fetch ( :timeout , nil ) non_block = opts . fetch ( :non_block , false ) end handle_interrupt do @mutex . synchronize do while true if @que . empty? if non_block raise ThreadError , "queue empty" else begin @num_waiting += 1 @cond . wait ( @mutex , timeout ) return nil if @que . empty? ensure @num_waiting -= 1 end end else return @que . shift ( num_to_pop ) end end end end end
Retrieves data from the queue and returns array of contents . If + num_to_pop + are available in the queue then multiple elements are returned in array response If the queue is empty the calling thread is suspended until data is pushed onto the queue . If + non_block + is true the thread isn t suspended and an exception is raised .
23,422
def raw_get ( option ) value = options_storage [ option ] Confo . callable_without_arguments? ( value ) ? value . call : value end
Internal method to get an option . If value is callable without arguments it will be called and result will be returned .
23,423
def public_set ( option , value ) method = "#{option}=" respond_to? ( method ) ? send ( method , value ) : raw_set ( option , value ) end
Method to set an option . If there is an option accessor defined then it will be used . In other cases + raw_set + will be used .
23,424
def set? ( arg , * rest_args ) if arg . kind_of? ( Hash ) arg . each { | k , v | set ( k , v ) unless set? ( k ) } nil elsif rest_args . size > 0 set ( arg , rest_args . first ) unless set? ( arg ) true else options_storage . has_key? ( arg ) end end
Checks if option is set . Works similar to set if value passed but sets only uninitialized options .
23,425
def find_or_build_page_part ( attr_name ) key = normalize_page_part_key ( attr_name ) page_parts . detect { | record | record . key . to_s == key } || page_parts . build ( key : key ) end
Find page part by key or build new record
23,426
def poster src = doc . at ( "#img_primary img" ) [ "src" ] rescue nil unless src . nil? if src . match ( / \. / ) return src . match ( / \. / ) [ 1 , 2 ] . join else return src end end src end
Get movie poster address
23,427
def title doc . at ( "//head/meta[@name='title']" ) [ "content" ] . split ( / \( \) / ) [ 0 ] . strip! || doc . at ( "h1.header" ) . children . first . text . strip end
Get movie title
23,428
def director_person begin link = doc . xpath ( "//h4[contains(., 'Director')]/.." ) . at ( 'a[@href^="/name/nm"]' ) profile = link [ 'href' ] . match ( / \/ \/ / ) [ 1 ] rescue nil IMDB :: Person . new ( profile ) unless profile . nil? rescue nil end end
Get Director Person class
23,429
def stub! CiscoMSE :: Endpoints :: Location . any_instance . stub ( :clients ) . and_return ( Stub :: Data :: Location :: CLIENTS ) end
Setup stubbing for all endpoints
23,430
def blog__clean_post_parents post_parents = LatoBlog :: PostParent . all post_parents . map { | pp | pp . destroy if pp . posts . empty? } end
This function cleans all old post parents without any child .
23,431
def blog__get_posts ( order : nil , language : nil , category_permalink : nil , category_permalink_AND : false , category_id : nil , category_id_AND : false , tag_permalink : nil , tag_permalink_AND : false , tag_id : nil , tag_id_AND : false , search : nil , page : nil , per_page : nil ) posts = LatoBlog :: Post . published . joins ( :post_parent ) . where ( 'lato_blog_post_parents.publication_datetime <= ?' , DateTime . now ) order = order && order == 'ASC' ? 'ASC' : 'DESC' posts = _posts_filter_by_order ( posts , order ) posts = _posts_filter_by_language ( posts , language ) if category_permalink || category_id posts = posts . joins ( :categories ) posts = _posts_filter_by_category_permalink ( posts , category_permalink , category_permalink_AND ) posts = _posts_filter_category_id ( posts , category_id , category_id_AND ) end if tag_permalink || tag_id posts = posts . joins ( :tags ) posts = _posts_filter_by_tag_permalink ( posts , tag_permalink , tag_permalink_AND ) posts = _posts_filter_tag_id ( posts , tag_id , tag_id_AND ) end posts = _posts_filter_search ( posts , search ) posts = posts . uniq ( & :id ) total = posts . length page = page &. to_i || 1 per_page = per_page &. to_i || 20 posts = core__paginate_array ( posts , per_page , page ) { posts : posts && ! posts . empty? ? posts . map ( & :serialize ) : [ ] , page : page , per_page : per_page , order : order , total : total } end
This function returns an object with the list of posts with some filters .
23,432
def blog__get_post ( id : nil , permalink : nil ) return { } unless id || permalink if id post = LatoBlog :: Post . find_by ( id : id . to_i , meta_status : 'published' ) else post = LatoBlog :: Post . find_by ( meta_permalink : permalink , meta_status : 'published' ) end post . serialize end
This function returns a single post searched by id or permalink .
23,433
def commit! ( message ) date = Time . now @status_add . each { | name , body | json = Article . new ( name , body , date ) . to_json zcard = @redis . zcard name @redis . zadd name , zcard + 1 , json @redis . sadd KEY_SET , name @summary_redis . update MarkdownBody . new ( name , body , date ) . summary } @remove_add . each { | name , latest_rank | @redis . zremrange ( name , 0 , latest_rank ) } @redis . set MODIFIED_DATE , date . to_s end
message is not used .
23,434
def make_query_string ( params ) clean_params ( params ) . collect do | k , v | CGI . escape ( k ) + '=' + CGI . escape ( v ) end . join ( '&' ) end
Convert params to query string
23,435
def do_http ( uri , request ) http = Net :: HTTP . new ( uri . host , uri . port ) http . use_ssl = true request [ 'User-Agent' ] = 'SlackRubyAPIWrapper' begin http . request ( request ) rescue OpenSSL :: SSL :: SSLError => e raise Slack :: Error , 'SSL error connecting to Slack.' end end
Handle http requests
23,436
def find_coming n = 10 , start_time = nil start_time = Time . now if start_time . nil? feeds = [ ] channel . feed_list . each do | feed | feed . dates . item_list . each do | item | if item . type_attr == "standalone" feeds << { :time => Time . parse ( item . start . text! ) , :feed => feed } elsif item . type_attr == "recurrent" moments = parse_recurrent_date_item ( item , n , start_time ) moments . each do | moment | feeds << { :time => moment , :feed => feed } end elsif item . type_attr == "permanent" start = Time . parse ( item . start . text! ) if start > start_time feeds << { :time => start , :feed => feed } else feeds << { :time => start_time , :feed => feed } end else raise DTD :: InvalidValueError , "the \"#{item.type_attr}\" is not valid for a date item type attribute" end end end feeds = feeds . delete_if { | x | x [ :time ] < start_time } feeds . sort! { | x , y | x [ :time ] <=> y [ :time ] } return feeds [ 0 .. n - 1 ] end
Returns the next n events from the moment specified in the second optional argument .
23,437
def find_between start_time , end_time feeds = [ ] channel . feed_list . each do | feed | feed . dates . item_list . each do | item | if item . type_attr == "standalone" feed_start_time = Time . parse ( item . start . text! ) if feed_start_time . between? ( start_time , end_time ) feeds << { :time => feed_start_time , :feed => feed } end elsif item . type_attr == "recurrent" moments = parse_recurrent_date_item ( item , end_time , start_time ) moments . each do | moment | if moment . between? ( start_time , end_time ) feeds << { :time => moment , :feed => feed } end end elsif item . type_attr == "permanent" start = Time . parse ( item . start . text! ) unless start > end_time if start > start_time feeds << { :time => start , :feed => feed } else feeds << { :time => start_time , :feed => feed } end end else raise DTD :: InvalidValueError , "the \"#{item.type_attr}\" is not valid for a date item type attribute" end end end feeds . sort! { | x , y | x [ :time ] <=> y [ :time ] } end
Returns all events starting after the time specified by the first parameter and before the time specified by the second parameter which accept regular Time objects .
23,438
def check_permission_to_route route_provider = RouteProvider . new ( self . class ) if route_provider . verifiable_routes_list . include? ( current_action ) if logged_user . nil? raise UserNotLoggedInException . new ( current_route , nil ) end is_permitted = AccessProvider . action_permitted_for_user? ( current_route , logged_user ) is_permitted ? allow_route : deny_route elsif route_provider . non_verifiable_routes_list . include? ( current_action ) allow_route else deny_route end end
Check access to route and we expected the existing of current_user helper
23,439
def fetch requests = instantiate_modules . select ( & :fetch? ) . map ( & :requests ) . flatten total , done = requests . size , 0 update_progress ( total , done ) before_fetch backend . new ( requests ) . run do update_progress ( total , done += 1 ) end after_fetch true rescue => e error ( e ) raise e end
Begin fetching . Will run synchronous fetches first and async fetches afterwards . Updates progress when each module finishes its fetch .
23,440
def instantiate_modules mods = Array ( modules ) mods = load! ( mods ) if callback? ( :load ) Array ( mods ) . map do | klass | init! ( klass ) || klass . new ( fetchable ) end end
Array of instantiated fetch modules .
23,441
def update_progress ( total , done ) percentage = total . zero? ? 100 : ( ( done . to_f / total ) * 100 ) . to_i progress ( percentage ) end
Updates progress with a percentage calculated from + total + and + done + .
23,442
def generate_session_key self . check_for_client_session raise "Missing Administrator Secret" unless KalturaFu . config . administrator_secret @@session_key = @@client . session_service . start ( KalturaFu . config . administrator_secret , '' , Kaltura :: Constants :: SessionType :: ADMIN ) @@client . ks = @@session_key rescue Kaltura :: APIError => e puts e . message end
Generates a Kaltura ks and adds it to the KalturaFu client object .
23,443
def from_xml ( data ) procs . inject ( XML :: Node . from ( data ) [ tag ] ) { | d , p | p . call ( d ) rescue d } end
Creates a new instance of Attr to be used as a template for converting XML to objects and from objects to XML
23,444
def mash ( h ) h . merge! @options @options . clear h . each { | k , v | self [ k ] = v } end
merge takes in a set of values and overwrites the previous values . mash does this in reverse .
23,445
def content_for route parts = route . split ( "/" ) . delete_if & :empty? content = parts . inject ( self ) do | page , part | page . children [ part . to_sym ] if page end content end
Walks the tree based on a url and returns the requested page Will return nil if the page does not exist
23,446
def won_rewards ( options = { } ) response = connection . get do | req | req . url "won_rewards" , options end return_error_or_body ( response ) end
Get a list of all won rewards for the authenticating client .
23,447
def generate_password if ( self . password . nil? ) self . password = Digest :: SHA1 . hexdigest ( self . username + self . enterprise_id ) else self . password = Digest :: SHA1 . hexdigest ( self . password + self . enterprise_id ) end end
Check or Generate client password
23,448
def kong_requests kong_config = Octo . get_config :kong if kong_config [ :enabled ] url = '/consumers/' payload = { username : self . username , custom_id : self . enterprise_id } process_kong_request ( url , :PUT , payload ) create_keyauth ( self . username , self . apikey ) end end
Perform Kong Operations after creating client
23,449
def option ( name , * args , & block ) __proxy_options__ . option ( name , * args , & block ) NsOptions :: ProxyMethod . new ( self , name , 'an option' ) . define ( $stdout , caller ) end
pass thru namespace methods to the proxied NAMESPACE handler
23,450
def method_missing ( meth , * args , & block ) if ( po = __proxy_options__ ) && po . respond_to? ( meth . to_s ) po . send ( meth . to_s , * args , & block ) else super end end
for everything else send to the proxied NAMESPACE handler at this point it really just enables dynamic options writers
23,451
def configure ( env = :default , & block ) environment = config_attributes [ env . to_sym ] Builder . new ( environment , & block ) end
Add or merge environment configuration
23,452
def build_configuration ( env = nil ) result = config_attributes [ :default ] result . deep_merge! ( config_attributes [ env . to_sym ] ) if env Entity . create ( result ) end
Build configuration object
23,453
def initializePageObject ( pageObject ) @pageObject = pageObject pathDepth = @pathComponents . length - 1 rootLinkPath = "../" * pathDepth setPageObjectInstanceVar ( "@fileName" , @fileName ) setPageObjectInstanceVar ( "@baseDir" , File . dirname ( @fileName ) ) setPageObjectInstanceVar ( "@baseFileName" , File . basename ( @fileName ) ) setPageObjectInstanceVar ( "@pathDepth" , pathDepth ) setPageObjectInstanceVar ( "@pathComponents" , @pathComponents ) setPageObjectInstanceVar ( "@rootLinkPath" , rootLinkPath ) setPageObjectInstanceVar ( "@baseUrl" , rootLinkPath ) setPageObjectInstanceVar ( "@site" , @site ) @initialInstanceVariables = Set . new ( @pageObject . instance_variables ) pageObject . postInitialize end
The absolute name of the source file initialise the page object which is the object that owns the defined instance variables and the object in whose context the Ruby components are evaluated Three special instance variable values are set -
23,454
def startNewComponent ( component , startComment = nil ) component . parentPage = self @currentComponent = component @components << component if startComment component . processStartComment ( startComment ) end end
Add a newly started page component to this page Also process the start comment unless it was a static HTML component in which case there is not start comment .
23,455
def writeRegeneratedFile ( outFile , makeBackup , checkNoChanges ) puts "writeRegeneratedFile, #{outFile}, makeBackup = #{makeBackup}, checkNoChanges = #{checkNoChanges}" if makeBackup backupFileName = makeBackupFile ( outFile ) end File . open ( outFile , "w" ) do | f | for component in @components do f . write ( component . output ) end end puts " wrote regenerated page to #{outFile}" if checkNoChanges if ! makeBackup raise Exception . new ( "writeRegeneratedFile #{outFile}: checkNoChanges specified, but no backup was made" ) end checkAndEnsureOutputFileUnchanged ( outFile , backupFileName ) end end
Write the output of the page components to the output file ( optionally checking that there are no differences between the new output and the existing output .
23,456
def readFileLines puts "Reading source file #{@fileName} ..." lineNumber = 0 File . open ( @fileName ) . each_line do | line | line . chomp! lineNumber += 1 commentLineMatch = COMMENT_LINE_REGEX . match ( line ) if commentLineMatch parsedCommandLine = ParsedRegenerateCommentLine . new ( line , commentLineMatch ) if parsedCommandLine . isRegenerateCommentLine parsedCommandLine . checkIsValid processCommandLine ( parsedCommandLine , lineNumber ) else processTextLine ( line , lineNumber ) end else processTextLine ( line , lineNumber ) end end finishAtEndOfSourceFile end
Read in and parse lines from source file
23,457
def regenerateToOutputFile ( outFile , checkNoChanges = false ) executeRubyComponents @pageObject . process writeRegeneratedFile ( outFile , checkNoChanges , checkNoChanges ) end
Regenerate from the source file into the output file
23,458
def executeRubyComponents fileDir = File . dirname ( @fileName ) Dir . chdir ( fileDir ) do for rubyComponent in @rubyComponents rubyCode = rubyComponent . text @pageObject . instance_eval ( rubyCode , @fileName , rubyComponent . lineNumber ) end end end
Execute the Ruby components which consist of Ruby code to be evaluated in the context of the page object
23,459
def erb ( templateFileName ) @binding = binding fullTemplateFilePath = relative_path ( @rootLinkPath + templateFileName ) File . open ( fullTemplateFilePath , "r" ) do | input | templateText = input . read template = ERB . new ( templateText , nil , nil ) template . filename = templateFileName result = template . result ( @binding ) end end
Method to render an ERB template file in the context of this object
23,460
def add_tracks @tracks = [ ] doc = Nokogiri :: XML ( @gpx_data ) doc . css ( 'xmlns|trk' ) . each do | trk | track = Track . new trk . css ( 'xmlns|trkpt' ) . each do | trkpt | track . add_point ( lat : trkpt . attributes [ 'lat' ] . text . to_f , lon : trkpt . attributes [ 'lon' ] . text . to_f , elevation : trkpt . at_css ( 'xmlns|ele' ) . text . to_f , time : Time . parse ( trkpt . at_css ( 'xmlns|time' ) . text ) ) end @tracks << track end @intersegments = [ ] @tracks . each_with_index do | track , i | next if i == 0 this_track = track prev_track = @tracks [ i - 1 ] inter_track = Track . new inter_track . add_point ( lat : prev_track . end_location [ 0 ] , lon : prev_track . end_location [ 1 ] , elevation : prev_track . end_location [ 2 ] , time : prev_track . end_time ) inter_track . add_point ( lat : this_track . start_location [ 0 ] , lon : this_track . start_location [ 1 ] , elevation : this_track . start_location [ 2 ] , time : this_track . start_time ) @intersegments << inter_track end @tracks_added = true end
extract track data from gpx data
23,461
def at ( time ) add_tracks if ! @tracks_added if time . is_a? ( String ) time = Time . parse ( time ) end time = time . to_i location = nil @tracks . each do | track | location = track . at ( time ) break if location end if ! location case @intersegment_behavior when :interpolate then @intersegments . each do | track | location = track . at ( time ) break if location end when :nearest then points = { } @tracks . each do | t | points [ t . start_time . to_i ] = t . start_location points [ t . end_time . to_i ] = t . end_location end last_diff = Infinity last_time = - 1 points . each do | p_time , p_location | this_diff = ( p_time . to_i - time ) . abs if this_diff > last_diff l = points [ last_time ] location = Track . array_to_hash ( points [ last_time ] ) break else last_diff = this_diff last_time = p_time end end location = Track . array_to_hash ( points [ last_time ] ) end end location end
infer a location from track data and a time
23,462
def clear_permissions ( account_href , client , options = { } ) options = { :dry_run => false } . merge ( options ) current_permissions = get_api_permissions ( account_href ) if options [ :dry_run ] Hash [ current_permissions . map { | p | [ p . href , p . role_title ] } ] else retval = RsUserPolicy :: RightApi :: PermissionUtilities . destroy_permissions ( current_permissions , client ) @permissions . delete ( account_href ) retval end end
Removes all permissions for the user in the specified rightscale account using the supplied client
23,463
def set_api_permissions ( permissions , account_href , client , options = { } ) options = { :dry_run => false } . merge ( options ) existing_api_permissions_response = get_api_permissions ( account_href ) existing_api_permissions = Hash [ existing_api_permissions_response . map { | p | [ p . role_title , p ] } ] if permissions . length == 0 removed = clear_permissions ( account_href , client , options ) @permissions . delete ( account_href ) return removed , { } else permissions_to_remove = ( existing_api_permissions . keys - permissions ) . map { | p | existing_api_permissions [ p ] } remove_response = Hash [ permissions_to_remove . map { | p | [ p . href , p . role_title ] } ] unless options [ :dry_run ] remove_response = RsUserPolicy :: RightApi :: PermissionUtilities . destroy_permissions ( permissions_to_remove , client ) end permissions_to_add = { @href => Hash [ ( permissions - existing_api_permissions . keys ) . map { | p | [ p , nil ] } ] } add_response = { } if options [ :dry_run ] href_idx = 0 add_response = { @href => Hash [ ( permissions - existing_api_permissions . keys ) . map { | p | [ p , ( href_idx += 1 ) ] } ] } else add_response = RsUserPolicy :: RightApi :: PermissionUtilities . create_permissions ( permissions_to_add , client ) end @permissions [ account_href ] = client . permissions . index ( :filter => [ "user_href==#{@href}" ] ) unless options [ :dry_run ] return remove_response , Hash [ add_response [ @href ] . keys . map { | p | [ add_response [ @href ] [ p ] , p ] } ] end end
Removes and adds permissions as appropriate so that the users current permissions reflect the desired set passed in as permissions
23,464
def finish retval = { } @attributes . each do | attr | val = instance_variable_get "@#{attr}" raise ArgumentError , "Missing attribute #{attr}" if val . nil? retval [ attr ] = val end retval end
Return a hash after verifying everything was set correctly
23,465
def run_xpath_handlers ( ctx , handlers , remover ) handlers . each do | h | if ( not ctx . done? ) and ( h . match? ( ctx . stanza ) ) ctx [ 'xpath.handler' ] = h ctx = h . call ( ctx ) raise RuntimeError , "xpath handlers should return a Context" unless ctx . is_a? ( Context ) send remover , h unless ctx . reuse_handler? end end end
runs all handlers calls the remover method if a handler should be removed
23,466
def update_params env , json env [ FORM_HASH ] = json env [ BODY ] = env [ FORM_INPUT ] = StringIO . new ( Rack :: Utils . build_query ( json ) ) end
update all of the parameter - related values in the current request s environment
23,467
def verify_request_method env allowed = ALLOWED_METHODS allowed |= ALLOWED_METHODS_PRIVATE if whitelisted? ( env ) if ! allowed . include? ( env [ METHOD ] ) raise "Request method #{env[METHOD]} not allowed" end end
make sure the request came from a whitelisted ip or uses a publically accessible request method
23,468
def update_options env , options if options [ :method ] and ( ALLOWED_METHODS | ALLOWED_METHODS_PRIVATE ) . include? ( options [ :method ] ) env [ METHOD ] = options [ :method ] end end
updates the options
23,469
def add_csrf_info env env [ CSRF_TOKEN ] = env [ SESSION ] [ :_csrf_token ] = SecureRandom . base64 ( 32 ) . to_s if env [ METHOD ] != 'GET' and whitelisted? ( env ) end
adds csrf info to non - GET requests of whitelisted IPs
23,470
def read_keys self . class . keys . inject Hash . new do | hash , key | hash [ key . name ] = proxy_reader ( key . name ) if readable? ( key . name ) hash end end
Call methods on the object that s being presented and create a flat hash for these mofos .
23,471
def write_keys ( attrs ) attrs . each { | key , value | proxy_writer ( key , value ) if writeable? ( key ) } self end
Update the attrs on zie model .
23,472
def proxy_writer ( key , * args ) meth = "#{key}=" if self . respond_to? meth self . send ( meth , * args ) else object . send ( meth , * args ) end end
Proxy the writer to zie object .
23,473
def table_rows now = ActiveRecord :: Base . default_timezone == :utc ? Time . now . utc : Time . now now = now . to_s ( :db ) fixtures . delete ( 'DEFAULTS' ) rows = Hash . new { | h , table | h [ table ] = [ ] } rows [ table_name ] = fixtures . map do | label , fixture | row = fixture . to_hash if model_class && model_class < ActiveRecord :: Base if model_class . record_timestamps timestamp_column_names . each do | name | row [ name ] = now unless row . key? ( name ) end end row . each do | key , value | row [ key ] = label if value == "$LABEL" end if has_primary_key_column? && ! row . include? ( primary_key_name ) row [ primary_key_name ] = ActiveRecord :: Fixtures . identify ( label ) end reflection_class = if row . include? ( inheritance_column_name ) row [ inheritance_column_name ] . constantize rescue model_class else model_class end reflection_class . reflect_on_all_associations . each do | association | case association . macro when :belongs_to fk_name = ( association . options [ :foreign_key ] || "#{association.name}_id" ) . to_s if association . name . to_s != fk_name && value = row . delete ( association . name . to_s ) if association . options [ :polymorphic ] && value . sub! ( / \s \( \) \) \s / , "" ) row [ association . foreign_type ] = $1 end row [ fk_name ] = ActiveRecord :: Fixtures . identify ( value ) end when :has_and_belongs_to_many if ( targets = row . delete ( association . name . to_s ) ) targets = targets . is_a? ( Array ) ? targets : targets . split ( / \s \s / ) table_name = association . options [ :join_table ] rows [ table_name ] . concat targets . map { | target | { association . foreign_key => row [ primary_key_name ] , association . association_foreign_key => ActiveRecord :: Fixtures . identify ( target ) } } end end end end row end rows end
Return a hash of rows to be inserted . The key is the table the value is a list of rows to insert to that table .
23,474
def use ( mod , opts = { } ) raise ArgumentError , "#{mod} is not a Mimi module" unless mod < Mimi :: Core :: Module mod . configure ( opts ) used_modules << mod unless used_modules . include? ( mod ) true end
Use the given module
23,475
def require_files ( glob , root_path = app_root_path ) Pathname . glob ( root_path . join ( glob ) ) . each do | filename | require filename . expand_path end end
Requires all files that match the glob .
23,476
def valid_user if ( self . username . blank? || self . password_digest . blank? ) && ( self . oauth_provider . blank? || self . oauth_uid . blank? ) errors . add ( :username , " and password OR oauth must be specified" ) end end
This method validates if the user object is valid . A user is valid if username and password exist OR oauth integration exists .
23,477
def issue_token ( kind ) session = Session . new ( user : self , seconds : 3600 ) session . save if kind == :reset_token self . reset_token = session . token elsif kind == :verification_token self . verification_token = session . token end end
This method will generate a reset token that lasts for an hour .
23,478
def lookup_scripts scripts = [ [ 'connect' , 'ELB connect' ] , [ 'disconnect' , 'ELB disconnect' ] ] server = @servers . first server . settings st = ServerTemplate . find ( server . server_template_href ) lookup_scripts_table ( st , scripts ) end
Grab the scripts we plan to excersize
23,479
def log_rotation_checks detect_os app_servers . each do | server | server . settings force_log_rotation ( server ) log_check ( server , "/mnt/log/#{server.apache_str}/access.log.1" ) end end
This is really just a PHP server check . relocate?
23,480
def has_guise? ( value ) value = value . to_s . classify unless guise_options . values . include? ( value ) raise ArgumentError , "no such guise #{value}" end association ( guise_options . association_name ) . reader . any? do | record | ! record . marked_for_destruction? && record [ guise_options . attribute ] == value end end
Checks if the record has a guise record identified by on the specified value .
23,481
def instancify ( technology , rule ) class_name , attributes = send ( "parse_rule_of_type_#{rule.class.name.downcase}" , rule ) Rule . const_get ( "#{class_name}Rule" ) . new ( technology , attributes ) end
Create a class instance for a rule entry
23,482
def find_favicon_urls_in_html ( html ) doc = Nokogiri . parse html candidate_urls = doc . css ( ICON_SELECTORS . join ( "," ) ) . map { | e | e . attr ( 'href' ) } . compact candidate_urls . sort_by! { | href | if href =~ / \. / 0 elsif href =~ / \. / 1 else 2 end } uri = URI final_url candidate_urls . map! do | href | href = URI . encode ( URI . decode ( href . strip ) ) if href =~ / \A \/ \/ / href = "#{uri.scheme}:#{href}" elsif href !~ / \A / href = URI . join ( url_root , href ) . to_s rescue nil end href end . compact . uniq end
Tries to find favicon urls from the html content of query_url
23,483
def final_url return @final_url if ! @final_url . nil? location = final_location ( FaviconParty :: HTTPClient . head ( @query_url ) ) if ! location . nil? if location =~ / \A / @final_url = URI . encode location else uri = URI @query_url root = "#{uri.scheme}://#{uri.host}" @final_url = URI . encode URI . join ( root , location ) . to_s end end if ! @final_url . nil? if %w( 127.0.0.1 localhost ) . any? { | host | @final_url . include? host } @final_url = @query_url end return @final_url end @final_url = @query_url end
Follow redirects from the query url to get to the last url
23,484
def context ( path , & block ) ctx = RouteContext . new ( self , path ) ctx . instance_eval ( & block ) ctx . methods_used . each do | meth | add_route! ( meth , ctx ) end end
Create a context for route nesting .
23,485
def match ( env ) routes [ env [ Rack :: REQUEST_METHOD ] ] . lazy . map { | r | r . match ( env ) } . find { | r | ! r . nil? } end
Tries to match against a Rack environment .
23,486
def insert! ( mirror = @client ) timeline_item = self result = [ ] if file_upload? for file in file_to_upload media = Google :: APIClient :: UploadIO . new ( file . contentUrl , file . content_type ) result << client . execute! ( :api_method => mirror . timeline . insert , :body_object => timeline_item , :media => media , :parameters => { :uploadType => 'multipart' , :alt => 'json' } ) end else result << client . execute ( :api_method => mirror . timeline . insert , :body_object => timeline_item ) end return result . data end
Insert a new Timeline Item in the user s glass .
23,487
def select_defined ( args ) args . select { | k , v | ( ATTRS . include? k ) && ! v . nil? } end
Based on the ATTRS the args are returned that are included in the ATTRS . args with nil values are omitted
23,488
def exportForum ( * args ) options = args . last . is_a? ( Hash ) ? args . pop : { } if args . size == 1 options . merge! ( :forum => args [ 0 ] ) response = post ( 'exports/exportForum' , options ) else puts "#{Kernel.caller.first}: exports.exportForum expects an arguments: forum" end end
Export a forum
23,489
def update_column ( name , value ) name = name . to_s raise ActiveRecordError , "#{name} is marked as readonly" if self . class . readonly_attributes . include? ( name ) raise ActiveRecordError , "can not update on a new record object" unless persisted? updated_count = self . class . update_all ( { name => value } , self . class . primary_key => id ) raw_write_attribute ( name , value ) updated_count == 1 end
Updates a single attribute of an object without calling save .
23,490
def source_path options = { } @source_path ||= if options [ :relative ] File . join collection_path , "#{self.id}.md" else File . join root_path , collection_path , "#{self.id}.md" end end
Return absolute path to Markdown file on this machine .
23,491
def default_action_block proc do begin record = if resource . singular parent_model = resource . parent . model . find ( parent_resource_id ) parent_model . send resource . name else record = model . find ( params [ :id ] ) end record . update ( instance_eval ( & @strong_params ) ) body record . reload rescue ActionController :: ParameterMissing => error body error . message status :bad_request end end end
Sets the default action to update a resource . If the resource is singular updates the parent s associated resource . Otherwise updates the resource directly .
23,492
def deserialize ( response , return_type ) body = response . body return @tempfile if return_type == 'File' return nil if body . nil? || body . empty? return body if return_type == 'String' content_type = response . headers [ 'Content-Type' ] || 'application/json' raise "Content-Type is not supported: #{content_type}" unless json_mime? ( content_type ) begin data = JSON . parse ( "[#{body}]" , :symbolize_names => true ) [ 0 ] rescue JSON :: ParserError => e if %w[ String Date DateTime ] . include? ( return_type ) data = body else raise e end end convert_to_type data , return_type end
Deserialize the response to the given return type .
23,493
def index @sessions = Session . where ( user : @user ) expired = [ ] active = [ ] @sessions . each do | session | if session . expired? expired << session . uuid else active << session end end SessionsCleanupJob . perform_later ( * expired ) render json : active , except : [ :secret ] end
Lists all sessions that belong to the specified or authenticated user .
23,494
def create if ( omniauth_hash = request . env [ "omniauth.auth" ] ) @user = User . from_omniauth_hash ( omniauth_hash ) elsif accept_auth @user = @auth_user else @user = User . find_by_username ( session_params [ :username ] ) if ( @user . nil? || ! @user . authenticate ( session_params [ :password ] ) || ! @user . verified ) raise ApplicationController :: UNAUTHORIZED_ERROR end end @session = Session . new ( user : @user ) if @session . save if omniauth_hash url = Rails . application . config . oauth_landing_page_url url = "#{url}?token=#{@session.token}" render inline : "" , status : 302 , location : url else render json : @session , except : [ :secret ] , status : 201 end else render_errors 400 , @session . full_error_messages end end
This action is essentially the login action . Note that get_user is not triggered for this action because we will look at username first . That would be the normal way to login . The alternative would be with the token based authentication . If the latter doesn t make sense just use the username and password approach .
23,495
def get_session session_id = params [ :id ] if session_id == "current" if @auth_session . nil? raise Repia :: Errors :: NotFound end session_id = @auth_session . id end @session = find_object ( Session , session_id ) authorize_for! ( @session ) if @session . expired? @session . destroy raise Repia :: Errors :: NotFound end end
Get the specified or current session .
23,496
def has_enumeration ( enumeration , mapping , options = { } ) unless mapping . is_a? ( Hash ) mapping_hash = { } mapping . each { | m | mapping_hash [ m ] = m . to_s } mapping = mapping_hash end attribute = options [ :attribute ] || enumeration klass = create_enumeration_mapping_class ( mapping ) attr_enumeration_mapping_classes [ enumeration ] = klass mapping_class_name = enumeration . to_s . camelize const_set ( mapping_class_name , klass ) scoped_class_name = [ self . name , mapping_class_name ] . join ( '::' ) composed_of ( enumeration , :class_name => scoped_class_name , :mapping => [ attribute . to_s , 'raw_value' ] , :converter => :from_sym , :allow_nil => true ) if ActiveRecord :: VERSION :: MAJOR >= 3 && ActiveRecord :: VERSION :: MINOR == 0 :: Arel :: Table . has_enumeration_mappings [ table_name ] [ attribute ] = mapping else unless @aggregate_conditions_override_installed extend HasEnumeration :: AggregateConditionsOverride @aggregate_conditions_override_installed = true end end end
Declares an enumerated attribute called + enumeration + consisting of the symbols defined in + mapping + .
23,497
def depth_first_recurse ( node = nil , depth = 0 , & block ) node = self if node == nil yield node , depth node . children . each do | child | depth_first_recurse ( child , depth + 1 , & block ) end end
helper for recursion into descendents
23,498
def perform ( async = false , & block ) @results = { } @clients . each do | client | @threads << Thread . new do loop do break if @reqs . empty? req = @reqs . shift break if req . nil? client . url = req . uri args = [ "http_#{req.method}" ] if [ :put , :post ] . include? req . method if req . body then if req . body . kind_of? Array then args += req . body else args << req . body end else args << "" end end client . send ( * args ) if block then yield ( req , client . body_str ) else @results [ req . key ] = client . body_str end end end end if async then return true end join ( ) return true if block return @results end
Execute requests . By default will block until complete and return results .
23,499
def collate_results ( results ) ret = [ ] results . size . times do | i | ret << results [ i ] end return ret end
Create ordered array from hash of results