idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
12,400
def get_innings if @innings . length == 0 inn_count = get_num_innings ( 1 .. get_num_innings ) . each do | inn | inning = Inning . new inning . load_from_id ( @gid , inn ) @innings << inning end end @innings end
Returns an array of Inning objects that represent each inning of the game
12,401
def get_atbats atbats = [ ] innings = get_innings innings . each do | inning | inning . top_atbats . each do | atbat | atbats << atbat end inning . bottom_atbats . each do | atbat | atbats << atbat end end atbats end
Returns an array of AtBat objects that represent each atbat of the game
12,402
def init ( element ) @xml_doc = element self . away_team_runs = element . attributes [ "away_team_runs" ] self . away_team_hits = element . attributes [ "away_team_hits" ] self . away_team_errors = element . attributes [ "away_team_errors" ] self . home_team_runs = element . attributes [ "home_team_runs" ] self . home_...
Initialize this instance from an XML element containing linescore data .
12,403
def get_player if ! self . player player = Player . new player . init ( ) self . player = player end self . player end
Looks up the player record using the players . xml file for the player in this appearance
12,404
def load_from_id ( gid , inning ) @top_atbats = [ ] @bottom_atbats = [ ] @gid = gid begin @xml_data = GamedayFetcher . fetch_inningx ( gid , inning ) @xml_doc = REXML :: Document . new ( @xml_data ) if @xml_doc . root @num = @xml_doc . root . attributes [ "num" ] @away_team = @xml_doc . root . attributes [ "away_team" ...
loads an Inning object given a game id and an inning number
12,405
def init ( element , gid ) self . gid = gid self . team_name = element . attributes [ 'name' ] self . id = element . attributes [ 'id' ] self . type = element . attributes [ 'type' ] self . players = [ ] self . coaches = [ ] self . set_players ( element ) self . set_coaches ( element ) end
type = home or away
12,406
def set_user_in_warden ( scope , resource ) scope = Devise :: Mapping . find_scope! ( scope ) warden . set_user ( resource , scope : scope , store : false ) end
extracted and simplified from Devise
12,407
def import_team_for_month ( team_abbrev , year , month ) start_date = Date . new ( year . to_i , month . to_i ) end_date = ( start_date >> 1 ) - 1 ( ( start_date ) .. ( end_date ) ) . each do | dt | puts year . to_s + '/' + month . to_s + '/' + dt . day team = Team . new ( 'det' ) games = team . games_for_date ( year ,...
player team game atbat pitch pitch type game type umpire
12,408
def install_ssh_components ( container , host ) case host [ 'platform' ] when / / , / / container . exec ( %w( apt-get update ) ) container . exec ( %w( apt-get install -y openssh-server openssh-client ) ) when / / container . exec ( %w( apt-get update ) ) container . exec ( %w( apt-get install -y openssh-server openss...
This sideloads sshd after a container starts
12,409
def fix_ssh ( container , host = nil ) @logger . debug ( "Fixing ssh on container #{container.id}" ) container . exec ( [ 'sed' , '-ri' , 's/^#?PermitRootLogin .*/PermitRootLogin yes/' , '/etc/ssh/sshd_config' ] ) container . exec ( [ 'sed' , '-ri' , 's/^#?PasswordAuthentication .*/PasswordAuthentication yes/' , '/etc/...
a puppet run may have changed the ssh config which would keep us out of the container . This is a best effort to fix it . Optionally pass in a host object to to determine which ssh restart command we should try .
12,410
def find_container ( host ) id = host [ 'docker_container_id' ] name = host [ 'docker_container_name' ] return unless id || name containers = :: Docker :: Container . all if id @logger . debug ( "Looking for an existing container with ID #{id}" ) container = containers . select { | c | c . id == id } . first end if nam...
return the existing container if we re not provisioning and docker_container_name is set
12,411
def load_from_id ( gid ) @gid = gid @rosters = [ ] @umpires = { } @xml_data = GamedayFetcher . fetch_players ( gid ) @xml_doc = REXML :: Document . new ( @xml_data ) if @xml_doc . root self . set_rosters self . set_umpires end end
Loads the players XML from the MLB gameday server and parses it using REXML
12,412
def update_rosters ( game , away_id , home_id ) game_id = find_or_create_game ( game , nil , nil ) gameday_info = GamedayUtil . parse_gameday_id ( 'gid_' + game . gid ) active_date = "#{gameday_info['year']}/#{gameday_info['month']}/#{gameday_info['day']}" away_res = @db . query ( "select id from rosters where team_id ...
Used to set game_id and home_or_away flag
12,413
def update_umpire_ids_for_games ump_id_hp = nil ump_id_1b = nil ump_id_2b = nil ump_id_3b = nil res = @db . query ( "select id, umpire_hp_id, umpire_1b_id, umpire_2b_id, umpire_3b_id from games" ) res . each do | row | game_id = row [ 0 ] umpire_hp_id = row [ 'umpire_hp_id' ] umpire_1b_id = row [ 'umpire_1b_id' ] umpir...
Update the game records to point to the first instance of the specific umpires originally new umpire records were being inserted for every game which is what caused this problem
12,414
def load_from_id ( gid ) @gid = gid @xml_data = GamedayFetcher . fetch_eventlog ( gid ) @xml_doc = REXML :: Document . new ( @xml_data ) if @xml_doc . root set_teams set_events end end
Loads the eventLog XML from the MLB gameday server and parses it using REXML
12,415
def set_teams @xml_doc . elements . each ( "game/team[@home_team='false']" ) do | element | @away_team = element . attributes [ "name" ] end @xml_doc . elements . each ( "game/team[@home_team='true']" ) do | element | @home_team = element . attributes [ "name" ] end end
Sets the team names for the teams involved in this game
12,416
def call ( env ) req = Rack :: Request . new ( env ) resp = Rack :: Response . new return resp . finish if ! req . post? resp . write process ( req . body . read ) resp . finish end
Entry point for Rack
12,417
def buffer ( msg , opts ) buffer_size = write_to_buffer ( msg , opts ) unless buffer_size . nil? process_buffer ( buffer_size ) end end
this should always be running synchronously within this thread
12,418
def flush ( ) if defined? @@request and ! @@request . nil? request_messages = [ ] @lock . synchronize do request_messages = @messages @buffer . truncate ( 0 ) @messages = [ ] end return if request_messages . empty? real = { e : 'ls' , ls : request_messages , } . to_json @@request . body = real @response = Net :: HTTP ....
this should be running synchronously if
12,419
def run response = Response . new request ( :search , @queue ) results = @queue . collect do result = { :matches => [ ] , :fields => [ ] , :attributes => { } , :attribute_names => [ ] , :words => { } } result [ :status ] = response . next_int case result [ :status ] when Statuses [ :warning ] result [ :warning ] = resp...
Run all the queries currently in the queue . This will return an array of results hashes .
12,420
def query ( search , index = '*' , comments = '' ) @queue . clear @queue << query_message ( search , index , comments ) self . run . first end
Query the Sphinx daemon - defaulting to all indices but you can specify a specific one if you wish . The search parameter should be a string following Sphinx s expectations .
12,421
def update ( index , attributes , values_by_doc ) response = Response . new request ( :update , update_message ( index , attributes , values_by_doc ) ) response . next_int end
Update attributes - first parameter is the relevant index second is an array of attributes to be updated and the third is a hash where the keys are the document ids and the values are arrays with the attribute values - in the same order as the second parameter .
12,422
def query_message ( search , index , comments = '' ) message = Message . new message . append_ints @offset , @limit , MatchModes [ @match_mode ] message . append_int RankModes [ @rank_mode ] message . append_string @rank_expr if @rank_mode == :expr message . append_int SortModes [ @sort_mode ] message . append_string @...
Generation of the message to send to Sphinx for a search .
12,423
def excerpts_message ( options ) message = Message . new message . append [ 0 , excerpt_flags ( options ) ] . pack ( 'N2' ) message . append_string options [ :index ] message . append_string options [ :words ] message . append_string options [ :before_match ] message . append_string options [ :after_match ] message . a...
Generation of the message to send to Sphinx for an excerpts request .
12,424
def update_message ( index , attributes , values_by_doc ) message = Message . new message . append_string index message . append_array attributes message . append_int values_by_doc . length values_by_doc . each do | key , values | message . append_64bit_int key message . append_ints * values end message . to_s end
Generation of the message to send to Sphinx to update attributes of a document .
12,425
def keywords_message ( query , index , return_hits ) message = Message . new message . append_string query message . append_string index message . append_int return_hits ? 1 : 0 message . to_s end
Generates the simple message to send to the daemon for a keywords request .
12,426
def errors reference_factories . inject ( factory . errors ) do | memo , f | Validation :: ErrorCollection . combine ( memo , f . errors ) end end
Any validation errors that are present on the OpenAPI document
12,427
def register_reference ( given_reference , factory , context ) reference = Reference . new ( given_reference ) ReferenceResolver . new ( reference , factory , context ) . tap do | resolver | next if resolver . in_root_source? reference_register . register ( resolver . reference_factory ) end end
Used to register a reference with the underlying document and return a reference resolver to access the object referenced
12,428
def data_at_pointer ( json_pointer ) return data if json_pointer . empty? data . dig ( * json_pointer ) if data . respond_to? ( :dig ) end
Access the data in a source at a particular pointer
12,429
def pages @pages ||= begin from = @page - ( @size / 2 ) . ceil from = 1 if from < 1 upto = from + @size - 1 if upto > pages_count from -= ( upto - pages_count ) from = 1 if from < 1 upto = pages_count end ( from .. upto ) . to_a end end
Number of pages to display .
12,430
def run ( max_reviewers = 3 , file_blacklist = [ ] , user_blacklist = [ ] ) files = select_files ( file_blacklist ) return if files . empty? authors = { } compose_urls ( files ) . each do | url | result = parse_blame ( url ) authors . merge! ( result ) { | _ , m , n | m + n } end reviewers = find_reviewers ( authors , ...
Mention potential reviewers .
12,431
def push ( node ) node = Node ( node ) @head ||= node if @tail @tail . next = node node . prev = @tail end @tail = node @length += 1 self end
Pushes new nodes to the end of the list .
12,432
def unshift ( node ) node = Node ( node ) @tail ||= node node . next = @head @head . prev = node if @head @head = node @length += 1 self end
Pushes new nodes on top of the list .
12,433
def insert ( to_add , after : nil , before : nil ) if after && before || ! after && ! before raise ArgumentError , 'either :after or :before keys should be passed' end matcher = after || before matcher_proc = if matcher . is_a? ( Proc ) __to_matcher ( & matcher ) else __to_matcher ( matcher ) end node = each_node . fin...
Inserts after or before first matched node . data from the the list by passed block or value .
12,434
def insert_after_node ( data , node ) Node ( data ) . tap do | new_node | new_node . prev = node new_node . next = node . next if node . next node . next . prev = new_node else @tail = new_node end node . next = new_node @length += 1 end end
Inserts data after first matched node . data .
12,435
def insert_before_node ( data , node ) Node ( data ) . tap do | new_node | new_node . next = node new_node . prev = node . prev if node . prev node . prev . next = new_node else @head = new_node end node . prev = new_node @length += 1 end end
Inserts data before first matched node . data .
12,436
def delete ( val = nil , & block ) if val . respond_to? ( :to_node ) node = val . to_node __unlink_node ( node ) return node . data end each_node . find ( & __to_matcher ( val , & block ) ) . tap do | node_to_delete | return unless node_to_delete __unlink_node ( node_to_delete ) end . data end
Removes first matched node . data from the the list by passed block or value .
12,437
def delete_all ( val = nil , & block ) each_node . select ( & __to_matcher ( val , & block ) ) . each do | node_to_delete | next unless node_to_delete __unlink_node ( node_to_delete ) end . map ( & :data ) end
Removes all matched data . data from the the list by passed block or value .
12,438
def regenerate store . delete_session ( self . session_id ) self . session_id = Merb :: SessionMixin . rand_uuid store . store_session ( self . session_id , self ) end
Regenerate the session ID .
12,439
def collect_methods list = @context . method_list unless @options . show_all list = list . find_all { | m | m . visibility == :public || m . visibility == :protected || m . force_documentation } end @methods = list . collect { | m | HtmlMethod . new ( m , self , @options ) } end
Create a list of HtmlMethod objects for each method in the corresponding context object . If the
12,440
def markup_code ( tokens ) src = "" tokens . each do | t | next unless t style = case t when RubyToken :: TkCONSTANT then "ruby-constant" when RubyToken :: TkKW then "ruby-keyword kw" when RubyToken :: TkIVAR then "ruby-ivar" when RubyToken :: TkOp then "ruby-operator" when RubyToken :: TkId then "ruby-identifier" when...
Given a sequence of source tokens mark up the source code to make it look purty .
12,441
def net_smtp smtp = Net :: SMTP . new ( config [ :host ] , config [ :port ] . to_i ) if config [ :tls ] if smtp . respond_to? ( :enable_starttls ) smtp . enable_starttls elsif smtp . respond_to? ( :enable_tls ) && smtp . respond_to? ( :use_tls? ) smtp . enable_tls ( OpenSSL :: SSL :: VERIFY_NONE ) else raise 'Unable to...
Sends the mail using SMTP .
12,442
def process_queue begin while blk = Merb :: Dispatcher . work_queue . pop Thread . pass blk . call break if Merb :: Dispatcher . work_queue . empty? && Merb . exiting end rescue Exception => e Merb . logger . warn! %Q!Worker Thread Crashed with Exception:\n#{Merb.exception(e)}\nRestarting Worker Thread! retry end end
Creates a new worker thread that loops over the work queue .
12,443
def handle @start = env [ "merb.request_start" ] = Time . now Merb . logger . info { "Started request handling: #{start.to_s}" } find_route! return rack_response if handled? klass = controller Merb . logger . debug { "Routed to: #{klass::_filter_params(params).inspect}" } unless klass < Controller raise NotFound , "Con...
Handles request routing and action dispatch .
12,444
def dispatch_action ( klass , action_name , status = 200 ) @env [ "merb.status" ] = status @env [ "merb.action_name" ] = action_name if Dispatcher . use_mutex @@mutex . synchronize { klass . call ( env ) } else klass . call ( env ) end end
Setup the controller and call the chosen action
12,445
def dispatch_exception ( exception ) if ( exception . is_a? ( Merb :: ControllerExceptions :: Base ) && ! exception . is_a? ( Merb :: ControllerExceptions :: ServerError ) ) Merb . logger . info ( Merb . exception ( exception ) ) else Merb . logger . error ( Merb . exception ( exception ) ) end exceptions = env [ "merb...
Re - route the current request to the Exception controller if it is available and try to render the exception nicely .
12,446
def render_chunked ( & blk ) must_support_streaming! headers [ 'Transfer-Encoding' ] = 'chunked' Proc . new { | response | @response = response response . send_status_no_connection_close ( '' ) response . send_header blk . call response . write ( "0\r\n\r\n" ) } end
Renders the block given as a parameter using chunked encoding .
12,447
def render_then_call ( str , & blk ) Proc . new do | response | response . write ( str ) blk . call end end
Renders the passed in string then calls the block outside the mutex and after the string has been returned to the client .
12,448
def send_file ( file , opts = { } ) opts . update ( Merb :: Const :: DEFAULT_SEND_FILE_OPTIONS . merge ( opts ) ) disposition = opts [ :disposition ] . dup || 'attachment' disposition << %(; filename="#{opts[:filename] ? opts[:filename] : File.basename(file)}") headers . update ( 'Content-Type' => opts [ :type ] . stri...
Sends a file over HTTP . When given a path to a file it will set the right headers so that the static file is served directly .
12,449
def send_data ( data , opts = { } ) opts . update ( Merb :: Const :: DEFAULT_SEND_FILE_OPTIONS . merge ( opts ) ) disposition = opts [ :disposition ] . dup || 'attachment' disposition << %(; filename="#{opts[:filename]}") if opts [ :filename ] headers . update ( 'Content-Type' => opts [ :type ] . strip , 'Content-Dispo...
Send binary data over HTTP to the user as a file download . May set content type apparent file name and specify whether to show data inline or download as an attachment .
12,450
def stream_file ( opts = { } , & stream ) opts . update ( Merb :: Const :: DEFAULT_SEND_FILE_OPTIONS . merge ( opts ) ) disposition = opts [ :disposition ] . dup || 'attachment' disposition << %(; filename="#{opts[:filename]}") headers . update ( 'Content-Type' => opts [ :type ] . strip , 'Content-Disposition' => dispo...
Streams a file over HTTP .
12,451
def set_cookie ( name , value , expires ) options = expires . is_a? ( Hash ) ? expires : { :expires => expires } cookies . set_cookie ( name , value , options ) end
Sets a cookie to be included in the response .
12,452
def handle_redirect_messages ( url , opts = { } ) opts = opts . dup [ :notice , :error , :success ] . each do | message_key | if opts [ message_key ] opts [ :message ] ||= { } opts [ :message ] [ message_key ] = opts [ message_key ] end end if opts [ :message ] notice = Merb :: Parse . escape ( [ Marshal . dump ( opts ...
Process a redirect url with options appending messages onto the url as query params
12,453
def _call_filters ( filter_set ) ( filter_set || [ ] ) . each do | filter , rule | if _call_filter_for_action? ( rule , action_name ) && _filter_condition_met? ( rule ) case filter when Symbol , String if rule . key? ( :with ) args = rule [ :with ] send ( filter , * args ) else send ( filter ) end when Proc then self ....
Calls a filter chain .
12,454
def absolute_url ( * args ) options = extract_options_from_args! ( args ) || { } protocol = options . delete ( :protocol ) host = options . delete ( :host ) raise ArgumentError , "The :protocol option must be specified" unless protocol raise ArgumentError , "The :host option must be specified" unless host args << optio...
Returns the absolute url including the passed protocol and host .
12,455
def capture ( * args , & block ) ret = nil captured = send ( "capture_#{@_engine}" , * args ) do | * args | ret = yield * args end captured . empty? ? ret . to_s : captured end
Calls the capture method for the selected template engine .
12,456
def notify_of_exceptions if Merb :: Plugins . config [ :exceptions ] [ :environments ] . include? ( Merb . env ) begin request = self . request details = { } details [ 'exceptions' ] = request . exceptions details [ 'params' ] = params details [ 'params' ] = self . class . _filter_params ( params ) details [ 'environme...
if you need to handle the render yourself for some reason you can call this method directly . It sends notifications without any rendering logic . Note though that if you are sending lots of notifications this could delay sending a response back to the user so try to avoid using it where possible .
12,457
def writable? ( key , parameters = { } , conditions = { } ) case key when String , Numeric , Symbol ! conditions . has_key? ( :expire_in ) else nil end end
Creates directory for cached files unless it exists . File caching does not support expiration time .
12,458
def read ( key , parameters = { } ) if exists? ( key , parameters ) read_file ( pathify ( key , parameters ) ) end end
Reads cached template from disk if it exists .
12,459
def write ( key , data = nil , parameters = { } , conditions = { } ) if writable? ( key , parameters , conditions ) if File . file? ( path = pathify ( key , parameters ) ) write_file ( path , data ) else create_path ( path ) && write_file ( path , data ) end end end
Writes cached template to disk creating cache directory if it does not exist .
12,460
def fetch ( key , parameters = { } , conditions = { } , & blk ) read ( key , parameters ) || ( writable? ( key , parameters , conditions ) && write ( key , value = blk . call , parameters , conditions ) && value ) end
Fetches cached data by key if it exists . If it does not uses passed block to get new cached value and writes it using given key .
12,461
def read_file ( path ) data = nil File . open ( path , "r" ) do | file | file . flock ( File :: LOCK_EX ) data = file . read file . flock ( File :: LOCK_UN ) end data end
Reads file content . Access to the file uses file locking .
12,462
def write_file ( path , data ) File . open ( path , "w+" ) do | file | file . flock ( File :: LOCK_EX ) file . write ( data ) file . flock ( File :: LOCK_UN ) end true end
Writes file content . Access to the file uses file locking .
12,463
def write ( key , data = nil , parameters = { } , conditions = { } ) @stores . capture_first { | s | s . write ( key , data , parameters , conditions ) } end
persists the data so that it can be retrieved by the key & parameters . returns nil if it is unable to persist the data . returns true if successful .
12,464
def write_all ( key , data = nil , parameters = { } , conditions = { } ) @stores . map { | s | s . write_all ( key , data , parameters , conditions ) } . all? end
persists the data to all context stores . returns nil if none of the stores were able to persist the data . returns true if at least one write was successful .
12,465
def fetch ( key , parameters = { } , conditions = { } , & blk ) read ( key , parameters ) || @stores . capture_first { | s | s . fetch ( key , parameters , conditions , & blk ) } || blk . call end
tries to read the data from the store . If that fails it calls the block parameter and persists the result . If it cannot be fetched the block call is returned .
12,466
def delete ( key , parameters = { } ) @stores . map { | s | s . delete ( key , parameters ) } . any? end
deletes the entry for the key & parameter from the store .
12,467
def user = ( user ) session [ :user ] = nil && return if user . nil? session [ :user ] = store_user ( user ) @user = session [ :user ] ? user : session [ :user ] end
This method will store the user provided into the session and set the user as the currently logged in user
12,468
def authenticate! ( request , params , * rest ) opts = rest . last . kind_of? ( Hash ) ? rest . pop : { } rest = rest . flatten strategies = if rest . empty? if request . session [ :authentication_strategies ] request . session [ :authentication_strategies ] else Merb :: Authentication . default_strategy_order end else...
The workhorse of the framework . The authentiate! method is where the work is done . authenticate! will try each strategy in order either passed in or in the default_strategy_order .
12,469
def extract_headers ( controller_defaults = { } ) defaults = @_cookie_defaults . merge ( controller_defaults ) cookies = [ ] self . each do | name , value | next unless @_options_lookup [ name ] options = defaults . merge ( @_options_lookup [ name ] ) if ( expiry = options [ "expires" ] ) . respond_to? ( :gmtime ) opti...
Generate any necessary headers .
12,470
def read ( key , parameters = { } ) begin @memcached . get ( normalize ( key , parameters ) ) rescue Memcached :: NotFound , Memcached :: Stored nil end end
Reads key from the cache .
12,471
def write ( key , data = nil , parameters = { } , conditions = { } ) if writable? ( key , parameters , conditions ) begin @memcached . set ( normalize ( key , parameters ) , data , expire_time ( conditions ) ) true rescue nil end end end
Writes data to the cache using key parameters and conditions .
12,472
def extract_required_files ( files , options = { } ) return [ ] if files . nil? || files . empty? seen = [ ] files . inject ( [ ] ) do | extracted , req_js | include_files , include_options = if req_js . last . is_a? ( Hash ) [ req_js [ 0 .. - 2 ] , options . merge ( req_js . last ) ] else [ req_js , options ] end seen...
Helper method to filter out duplicate files .
12,473
def reap_expired_sessions @timestamps . each do | session_id , stamp | delete_session ( session_id ) if ( stamp + @session_ttl ) < Time . now end GC . start end
Deletes any sessions that have reached their maximum validity .
12,474
def to_cookie unless self . empty? data = self . serialize value = Merb :: Parse . escape "#{data}--#{generate_digest(data)}" if value . size > MAX msg = "Cookies have limit of 4K. Session contents: #{data.inspect}" Merb . logger . error! ( msg ) raise CookieOverflow , msg end value end end
Create the raw cookie string ; includes an HMAC keyed message digest .
12,475
def secure_compare ( a , b ) if a . length == b . length a_bytes = a . unpack ( 'C*' ) b_bytes = b . unpack ( 'C*' ) result = 0 for i in 0 .. ( a_bytes . length - 1 ) result |= a_bytes [ i ] ^ b_bytes [ i ] end result == 0 else false end end
Securely compare two digests using a constant time algorithm . This avoids leaking information about the calculated HMAC
12,476
def unmarshal ( cookie ) if cookie . blank? { } else data , digest = Merb :: Parse . unescape ( cookie ) . split ( '--' ) return { } if data . blank? || digest . blank? unless secure_compare ( generate_digest ( data ) , digest ) clear unless Merb :: Config [ :ignore_tampered_cookies ] raise TamperedWithCookie , "Maybe ...
Unmarshal cookie data to a hash and verify its integrity .
12,477
def controller unless params [ :controller ] raise ControllerExceptions :: NotFound , "Route matched, but route did not specify a controller.\n" + "Did you forgot to add :controller => \"people\" or :controller " + "segment to route definition?\nHere is what's specified:\n" + route . inspect end path = [ params [ :name...
Returns the controller object for initialization and dispatching the request .
12,478
def body_params @body_params ||= begin if content_type && content_type . match ( Merb :: Const :: FORM_URL_ENCODED_REGEXP ) Merb :: Parse . query ( raw_post ) end end end
Parameters passed in the body of the request . Ajax calls from prototype . js and other libraries pass content this way .
12,479
def ensure_authenticated ( * strategies ) session . authenticate! ( request , params , * strategies ) unless session . authenticated? auth = session . authentication if auth . halted? self . headers . merge! ( auth . headers ) self . status = auth . status throw :halt , auth . body end session . user end
This is the main method to use as a before filter . You can call it with options and strategies to use . It will check if a user is logged in and failing that will run through either specified .
12,480
def callback ( event , buffer = nil , start = nil , the_end = nil ) return if ! start . nil? && start == the_end if @callbacks . has_key? event @callbacks [ event ] . call ( buffer , start , the_end ) end end
Issues a callback .
12,481
def content_type = ( type ) unless Merb . available_mime_types . has_key? ( type ) raise Merb :: ControllerExceptions :: NotAcceptable . new ( "Unknown content_type for response: #{type}" ) end @_content_type = type mime = Merb . available_mime_types [ type ] headers [ "Content-Type" ] = mime [ :content_type ] mime [ :...
Sets the content type of the current response to a value based on a passed in key . The Content - Type header will be set to the first registered header for the mime - type .
12,482
def render_mail ( options = @method ) @_missing_templates = false options = { :action => { :html => options , :text => options } } if ! options . is_a? ( Hash ) opts_hash = { } opts = options . dup actions = opts . delete ( :action ) if opts [ :action ] . is_a? ( Hash ) templates = opts . delete ( :template ) if opts [...
Allows you to render various types of things into the text and HTML parts of an email If you include just text the email will be sent as plain - text . If you include HTML the email will be sent as a multi - part email .
12,483
def check_lgtm ( image_url : nil , https_image_only : false ) return unless status_report [ :errors ] . length . zero? && status_report [ :warnings ] . length . zero? image_url ||= fetch_image_url ( https_image_only : https_image_only ) markdown ( markdown_template ( image_url ) ) end
Check status report say lgtm if no violations Generates a markdown of a lgtm image .
12,484
def each unless block_given? return self . enum_for ( :each ) else while @parser . has_next? event = @parser . pull if event . start_element? and strip_ns ( event [ 0 ] ) == 'record' yield build_record end end end end
Loop through the MARC records in the XML document
12,485
def build_record record = MARC :: Record . new data_field = nil control_field = nil subfield = nil text = '' attrs = nil if Module . constants . index ( 'Nokogiri' ) and @parser . is_a? ( Nokogiri :: XML :: Reader ) datafield = nil cursor = nil open_elements = [ ] @parser . each do | node | if node . value? && cursor i...
will accept parse events until a record has been built up
12,486
def validate_response ( response ) case response when * SERVER_ERRORS raise :: Lgtm :: Errors :: UnexpectedError when * CLIENT_ERRORS raise :: Lgtm :: Errors :: UnexpectedError end end
validate_response is response validating
12,487
def reindex @tags = { } self . each_with_index do | field , i | @tags [ field . tag ] ||= [ ] @tags [ field . tag ] << i end @clean = true end
Rebuild the HashWithChecksumAttribute with the current values of the fields Array
12,488
def fields ( filter = nil ) unless filter @fields . clean = false unless @fields . frozen? return @fields end @fields . reindex unless @fields . clean flds = [ ] if filter . is_a? ( String ) && @fields . tags [ filter ] @fields . tags [ filter ] . each do | idx | flds << @fields [ idx ] end elsif filter . is_a? ( Array...
Provides a backwards compatible means to access the FieldMap . No argument returns the FieldMap array in entirety . Providing a string array or range of tags will return an array of fields in the order they appear in the record .
12,489
def create upload_meta = prepare_to_upload response = upload_to_aws_s3 ( upload_meta ) notify_ribose_file_upload_endpoint ( response , upload_meta . fields . key ) end
Initialize the file uploader
12,490
def request ( options = { } ) parsable = extract_config_option ( :parse ) != false options [ :query ] = extract_config_option ( :query ) || { } response = agent . call ( http_method , api_endpoint , data , options ) parsable == true ? response . data : response end
Initialize a Request
12,491
def to_hash field_hash = { @tag => { 'ind1' => @indicator1 , 'ind2' => @indicator2 , 'subfields' => [ ] } } self . each do | subfield | field_hash [ @tag ] [ 'subfields' ] << { subfield . code => subfield . value } end field_hash end
Turn the variable field and subfields into a hash for MARC - in - JSON
12,492
def call ( obj , args , ctx ) cache_key = [ CacheQL :: Railtie . config . global_key , obj . cache_key , ctx . field . name ] CacheQL :: Railtie . config . cache . fetch ( cache_key , expires_in : CacheQL :: Railtie . config . expires_range . sample . minutes ) do @resolver_func . call ( obj , args , ctx ) end end
Resolve function level caching!
12,493
def call ( input , options = { } ) handler = handler_steps ( options ) . map ( & method ( :step ) ) . reduce ( :>> ) handler . call ( input ) rescue StepError => err raise TransactionFailedError . new ( self , err ) end
Call the transaction
12,494
def create_table ( name ) if ! db . tables . include? ( name . to_sym ) db . create_table name do String :name , :size => 15 Float :freq index :freq end end end
create a name table
12,495
def cleanup_surname ( name ) if name . length > 4 name . gsub! ( / \w / ) { | s | "Mc#{$1.capitalize}" } name . gsub! ( / \w / ) { | s | "Mac#{$1.capitalize}" } name . gsub! ( / \w / ) { | s | "Mac#{$1.capitalize}" } name . gsub! ( / \w / ) { | s | "O'sh#{$1}" } name . gsub! ( / \w / ) { | s | "Van#{$1.capitalize}" } n...
apply some simple regexps to clean up surnames
12,496
def each_word ( data , & block ) return enum_for ( :each_word , data ) unless block unless data . respond_to? ( :each_byte ) raise ( ArgumentError , "the data to hexdump must define #each_byte" ) end if @word_size > 1 word = 0 count = 0 init_shift = if @endian == :big ( ( @word_size - 1 ) * 8 ) else 0 end shift = init_...
Creates a new Hexdump dumper .
12,497
def each ( data ) return enum_for ( :each , data ) unless block_given? index = 0 count = 0 numeric = [ ] printable = [ ] each_word ( data ) do | word | numeric << format_numeric ( word ) printable << format_printable ( word ) count += 1 if count >= @width yield index , numeric , printable numeric . clear printable . cl...
Iterates over the hexdump .
12,498
def dump ( data , output = $stdout ) unless output . respond_to? ( :<< ) raise ( ArgumentError , "output must support the #<< method" ) end bytes_segment_width = ( ( @width * @format_width ) + @width ) line_format = "%.8x %-#{bytes_segment_width}s |%s|\n" index = 0 count = 0 numeric = '' printable = '' each_word ( dat...
Dumps the hexdump .
12,499
def format_printable ( word ) if @word_size == 1 PRINTABLE [ word ] elsif ( RUBY_VERSION > '1.9.' && ( word >= - 2 && word <= 0x7fffffff ) ) begin word . chr ( Encoding :: UTF_8 ) rescue RangeError UNPRINTABLE end else UNPRINTABLE end end
Converts a word into a printable String .