idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
24,700
def check_dates raise "start date (#{start}) is after end date (#{finish})" if @start && @finish && @start > @finish if @round_dates . size > 0 raise "the number of round dates (#{@round_dates.size}) does not match the number of rounds (#{@rounds})" unless @round_dates . size == @rounds raise "the date of the first rou...
Check dates are consistent .
24,701
def check_type ( type ) if type . respond_to? ( :validate! ) type . validate! ( self ) elsif klass = self . class . factory ( type . to_s ) klass . new . validate! ( self ) else raise "invalid type supplied for validation check" end end
Validate against a specific type .
24,702
def tie_break_score ( hash , method , player , rounds ) case method when :score then player . points when :wins then player . results . inject ( 0 ) { | t , r | t + ( r . opponent && r . score == 'W' ? 1 : 0 ) } when :blacks then player . results . inject ( 0 ) { | t , r | t + ( r . opponent && r . colour == 'B' ? 1 : ...
Return a tie break score for a given player and a given tie break method .
24,703
def deployed_by username = nil scm = fetch ( :scm , nil ) if scm if scm . to_sym == :git username = ` ` . chomp username = nil if $? != 0 || username . strip == '' end end username || ` ` . chomp end
get the name of the deploying user currently this only supports git . if reading the git user . name fall back on whoami
24,704
def unload_plugin ( name ) p = get_plugin ( name ) p . unload if p . respond_to? ( :unload ) Capistrano . remove_plugin ( name ) end
given a plugin name as a symbol unload the capnotify plugin this will also unload any kind of capistrano plugin if the plugin supports the unload method it will be called .
24,705
def get_plugin ( name ) raise "Unknown plugin: #{ name }" unless Capistrano :: EXTENSIONS . keys . include? ( name ) self . send ( name ) end
given a plugin name return the plugin .
24,706
def build_template ( template_path ) self . build_components! ERB . new ( File . open ( template_path ) . read , nil , '<>' ) . result ( self . binding ) end
given a path to an ERB template process it with the current binding and return the output .
24,707
def component ( name ) components . each { | c | return c if c . name == name . to_sym } return nil end
fetch a component given the name this is most useful for getting a component directly if you want to make modificatins to it
24,708
def insert_component_before ( name , component ) components . each_with_index do | c , i | if c . name == name components . insert ( i , component ) return end end components << component end
insert the given component before the component with name if no component is found with that name the component will be inserted at the end
24,709
def insert_component_after ( name , component ) components . each_with_index do | c , i | if c . name == name components . insert ( i + 1 , component ) return end end components << component end
insert the given component after the component with name if no component is found with that name the component will be inserted at the end
24,710
def new_edge_key ( u , v ) if @adj [ u ] && @adj [ u ] [ v ] keys = @adj [ u ] [ v ] key = keys . length while keys . include? ( key ) key += 1 end return key else return 0 end end
returns an unused key for edges between nodes u and v .
24,711
def calculated_data @data ||= @raw_data . group_by { | contributor | contributor [ 'login' ] } . map { | login , data | log "user: #{login}" [ login , user_data ( login , data ) ] } . sort_by { | login , data | [ 1000000 / data [ 'contributions' ] , login ] } end
group data calculate contributions sort by contributions
24,712
def start ( redis ) logger . debug { "Scat is starting the Redis cache server..." } unless system ( REDIS_SERVER , REDIS_CONF ) then raise ScatError . new ( "Scat cannot start the Redis cache server." ) end 3 . times do | n | begin redis . ping logger . debug { "Scat started the Redis cache server." } return redis resc...
Starts the Redis server on the default Redis port .
24,713
def query ( q , options = { } , & block ) query = Query :: Results . new ( q , options ) query . process ( self , & block ) end
Query the model RDF graph using a query language
24,714
def populate_with_fake_data ( interval_days = 7 ) if self . enterprise . fakedata? today = Time . now . beginning_of_day ( today - interval_days . days ) . to ( today , 24 . hour ) . each do | ts | Octo :: FunnelData . new ( enterprise_id : self . enterprise_id , funnel_slug : self . name_slug , ts : ts , value : fake_...
Populates a newly created funnel with some fake data
24,715
def data ( ts = Time . now . floor ) args = { enterprise_id : self . enterprise . id , funnel_slug : self . name_slug , ts : ts } res = Octo :: FunnelData . where ( args ) if res . count > 0 res . first elsif self . enterprise . fakedata? args . merge! ( { value : fake_data ( self . funnel . count ) } ) Octo :: FunnelD...
Returns data for a funnel
24,716
def fake_data ( n ) fun = Array . new ( n ) max_dropoff = 100 / n n . times do | i | if i == 0 fun [ i ] = 100.0 else fun [ i ] = fun [ i - 1 ] - rand ( 1 .. max_dropoff ) if fun [ i ] < 0 fun [ i ] = rand ( 0 ... fun [ i ] . abs ) end end end fun end
Generates fake data for funnel
24,717
def handle_error ( err , data = nil ) case determine_error_type ( err ) when :token_revoked on_revoke ( data ) when :rate_limited on_rate_limit ( data ) when :closed on_close ( data ) else on_error ( err , data ) end end
Handle different error cases
24,718
def find_activity ( activity_id ) activity_hash = self . driver . find_activity ( activity_id ) if activity_hash self . run_hook ( :did_find_activity , activity_hash ) Activr :: Activity . from_hash ( activity_hash ) else nil end end
Find an activity
24,719
def find_activities ( limit , options = { } ) options = { :skip => 0 , :before => nil , :after => nil , :entities => { } , :only => [ ] , :except => [ ] , } . merge ( options ) options [ :only ] = [ options [ :only ] ] if ( options [ :only ] && ! options [ :only ] . is_a? ( Array ) ) result = self . driver . find_activ...
Find latest activities
24,720
def count_activities ( options = { } ) options = { :before => nil , :after => nil , :entities => { } , :only => [ ] , :except => [ ] , } . merge ( options ) options [ :only ] = [ options [ :only ] ] if ( options [ :only ] && ! options [ :only ] . is_a? ( Array ) ) self . driver . count_activities ( options ) end
Count number of activities
24,721
def count_duplicate_activities ( activity , after ) entities = { } activity . entities . each do | entity_name , entity | entities [ entity_name . to_sym ] = entity . model_id end self . count_activities ( { :only => activity . class , :entities => entities , :after => after , } ) end
Find number of duplicate activities
24,722
def delete_activities_for_entity_model ( model ) Activr . registry . activity_entities_for_model ( model . class ) . each do | entity_name | self . driver . delete_activities ( :entities => { entity_name => model . id } ) end end
Delete activities referring to given entity model instance
24,723
def find_timeline_entry ( timeline , tl_entry_id ) timeline_entry_hash = self . driver . find_timeline_entry ( timeline . kind , tl_entry_id ) if timeline_entry_hash self . run_hook ( :did_find_timeline_entry , timeline_entry_hash , timeline . class ) Activr :: Timeline :: Entry . from_hash ( timeline_entry_hash , time...
Find a timeline entry
24,724
def find_timeline ( timeline , limit , options = { } ) options = { :skip => 0 , :only => [ ] , } . merge ( options ) options [ :only ] = [ options [ :only ] ] if ( options [ :only ] && ! options [ :only ] . is_a? ( Array ) ) result = self . driver . find_timeline_entries ( timeline . kind , timeline . recipient_id , li...
Find timeline entries by descending timestamp
24,725
def count_timeline ( timeline , options = { } ) options = { :only => [ ] , } . merge ( options ) options [ :only ] = [ options [ :only ] ] if ( options [ :only ] && ! options [ :only ] . is_a? ( Array ) ) self . driver . count_timeline_entries ( timeline . kind , timeline . recipient_id , options ) end
Count number of timeline entries
24,726
def delete_timeline ( timeline , options = { } ) options = { :before => nil , :entities => { } , } . merge ( options ) self . driver . delete_timeline_entries ( timeline . kind , timeline . recipient_id , options ) end
Delete timeline entries
24,727
def delete_timeline_entries_for_entity_model ( model ) Activr . registry . timeline_entities_for_model ( model . class ) . each do | timeline_class , entities | entities . each do | entity_name | self . driver . delete_timeline_entries ( timeline_class . kind , nil , :entities => { entity_name => model . id } ) end end...
Delete timeline entries referring to given entity model instance
24,728
def run_hook ( name , * args ) return if @hooks [ name ] . blank? @hooks [ name ] . each do | hook | args . any? ? hook . call ( * args ) : hook . call end end
Run a hook
24,729
def reformatted! self . class . format_fields . each do | field_name , format_method , options | formatted_value = send ( format_method , get_field ( field_name ) , options ) set_field ( field_name , formatted_value ) end self end
Triger any formatting rules specified with the reformat directive . The attributes are reformatted and mutated in place .
24,730
def to_params attrs = Hash . new instance_variables . each do | ivar | name = ivar [ 1 .. - 1 ] attrs [ name . to_sym ] = instance_variable_get ( ivar ) if respond_to? "#{name}=" end attrs end
Return all the attributes as a params hash .
24,731
def merge_protections ( protections , protected_params ) protected_params . each do | k , v | if protections [ k ] . is_a? ( Hash ) merge_protections ( protections [ k ] , v ) if v else protections [ k ] = v end end protections end
Merge protections for the same params into one so as to allow extension of them in inheriting controllers .
24,732
def media_url begin r = HTTParty . get ( "https://api.soundcloud.com/i1/tracks/#{id}/streams?client_id=#{@CLIENT.client_id}" ) r [ 'http_mp3_128_url' ] rescue Exception => ex raise SoundDrop :: Exception :: FailedRequest . new ( ex ) end end
Track media url
24,733
def for ( klass , options = { } , & blk ) ActiveAdmin . register klass do options = { index : { } , form : { } , filter : { } } . merge options permitted_params = options . delete :permitted_params permit_params ( * ( klass . main_fields + ( permitted_params || [ ] ) ) ) menu options if options . any? actions :all , ex...
for proper work model must have class method mail_fields which return array of field symbols . references write as is like foo_id
24,734
def generate_diff_for_language ( current_language , target_language ) current_langmap = langmap [ current_language ] target_langmap = langmap [ target_language ] diffmap_key = [ current_language , target_language ] diffmap [ diffmap_key ] = current_langmap - target_langmap end
a diffmap shows what is missing between two languages the key is a two - element array the first element is the current language and the second element is the target language
24,735
def make_keymap ( langmap_entry , language ) language . each do | key , value | if value . is_a? Hash make_keymap_for ( langmap_entry , value , [ key . to_sym ] ) else langmap_entry << [ key . to_sym ] end end end
outer method for creating keymap on parent hash
24,736
def make_keymap_for ( langmap_entry , language , key_path ) language . each do | key , value | new_path = Array . new key_path if value . is_a? Hash make_keymap_for ( langmap_entry , value , new_path . push ( key . to_s . to_sym ) ) else langmap_entry << new_path . push ( key . to_s . to_sym ) end end end
recursive helper for creating keymap on children hashes
24,737
def write ( key , value , binary = false ) value = @conn . class . encode_value ( value , binary ) result = @conn . call ( :write , [ key , value ] ) @conn . class . check_fail_abort ( result ) @conn . class . process_result_commit ( result ) end
Write the value to key .
24,738
def add_del_on_list ( key , to_add , to_remove ) result = @conn . call ( :add_del_on_list , [ key , to_add , to_remove ] ) @conn . class . check_fail_abort ( result ) @conn . class . process_result_add_del_on_list ( result ) end
Changes the list stored at the given key i . e . first adds all items in to_add then removes all items in to_remove . Both to_add and to_remove must be lists . Assumes en empty list if no value exists at key .
24,739
def add_on_nr ( key , to_add ) result = @conn . call ( :add_on_nr , [ key , to_add ] ) @conn . class . check_fail_abort ( result ) @conn . class . process_result_add_on_nr ( result ) end
Changes the number stored at the given key i . e . adds some value . Assumes 0 if no value exists at key .
24,740
def has_superclass? ( child , ancestor ) if child . superclass == ancestor true elsif child . superclass . nil? false else has_superclass? ( child . superclass , ancestor ) end end
It seems like there must be a builtin for this but I m not finding it .
24,741
def process_news ( total = 25 ) items . map . with_index do | item , num | @headlines << format_headline ( item , num ) if total_met? ( total ) end . compact || nil end
Handles iteration of each headline
24,742
def find_by_uni ( uni ) entries = search ( base : "ou=People,o=Columbia University, c=US" , filter : Net :: LDAP :: Filter . eq ( "uid" , uni ) ) ( entries . count == 1 ) ? entries . first : nil end
LDAP lookup based on UNI . If record could not be found returns nil .
24,743
def find_by_name ( name ) if name . include? ( ',' ) name = name . split ( ',' ) . map ( & :strip ) . reverse . join ( " " ) end entries = search ( base : "ou=People,o=Columbia University, c=US" , filter : Net :: LDAP :: Filter . eq ( "cn" , name ) ) ( entries . count == 1 ) ? entries . first : nil end
LDAP lookup based on name .
24,744
def rest_action ( options , action = "insert" ) body_object = json_content ( options , action ) inserting_content = { api_method : mirror_api . timeline . send ( action ) , body_object : body_object } end
optional parameter is merged into the content hash before sending . good for specifying more application specific stuff like speakableText parameters .
24,745
def list ( opts = { as_hash : true } ) page_token = nil parameters = { } self . timeline_list = [ ] begin parameters = { } parameters [ 'pageToken' ] = page_token if page_token . present? api_result = google_client . execute ( api_method : mirror_api . timeline . list , parameters : parameters ) if api_result . success...
this method is pretty much extracted directly from the mirror API code samples in ruby
24,746
def to_hbs h = { :model => self . class . name . downcase } self . hbs_attributes . each do | attr | h [ attr ] = self . send ( attr ) ans = h [ attr ] . class . ancestors if h [ attr ] . class . respond_to? ( :hbs_serializable ) || ans . include? ( Enumerable ) || ans . include? ( ActiveModel :: Validations ) h [ attr...
Serialize instance attributes to a Hash based on serializable attributes defined on Model class .
24,747
def hbs_attributes s = self . class . class_variable_get ( :@@serialize ) if s [ :merge ] attrs = s [ :attrs ] + self . attributes . keys else attrs = s [ :attrs ] end attrs . collect { | attr | attr . to_sym } . uniq end
List of Model attributes that should be serialized when called to_hbs on Model instance
24,748
def validate if ( folder1 == nil ) || ( folder1 == "" ) || ! Dir . exists? ( folder1 ) puts "a valid folder path is required as argument 1" exit end if ( folder2 == nil ) || ( folder2 == "" ) || ! Dir . exists? ( folder2 ) puts "a valid folder path is required as argument 2" exit end end
the format to output the results to . csv html or json initialize the class with the folders to be compared Validates the input ensuring the arguments are both valid folders
24,749
def display_results_html output = "<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title></title></head><body>" output . concat ( "<table><thead><tr><td>FileName</td></tr><tr><td>#{@folder1}</td></tr><tr><td>#{@folder2}</td></tr><tr><td>Equal</td></tr></thead>" ) @filehash . each { | key , value | ou...
Prints the results to standard out in the csv format specified .
24,750
def ratings ( str ) all_valid_cjk ( str ) . map do | enc | [ enc , recode ( enc , str ) . codepoints . map do | point | Analects :: Models :: Zi . codepoint_ranges . map . with_index do | range , idx | next 6 - idx if range . include? ( point ) 0 end . inject ( :+ ) end . inject ( :+ ) ] end . sort_by ( & :last ) . rev...
Crude way to guess which encoding it is
24,751
def lookup_totals begin Timeout . timeout ( 4 ) do html = open ( "https://projecteuler.net/recent" ) fragment = Nokogiri :: HTML ( html ) id_col = fragment . css ( '#problems_table td.id_column' ) id_col . first . text . to_i . times { Problem . new } Page . total = Problem . page ( Problem . total - 10 ) end rescue Ti...
Pulls information from the recent page to determine the total number of problems and pages .
24,752
def load_recent return if Page . visited . include? ( 0 ) html = open ( "https://projecteuler.net/recent" ) fragment = Nokogiri :: HTML ( html ) problem_links = fragment . css ( '#problems_table td a' ) i = Problem . total problem_links . each do | link | Problem [ i ] . title = link . text i -= 1 end Page . visited <<...
Loads in all of the problem numbers and titles from the recent page .
24,753
def load_page ( page ) return if Page . visited . include? ( page ) html = open ( "https://projecteuler.net/archives;page=#{page}" ) fragment = Nokogiri :: HTML ( html ) problem_links = fragment . css ( '#problems_table td a' ) i = ( page - 1 ) * Page :: LENGTH + 1 problem_links . each do | link | Problem [ i ] . title...
Loads the problem numbers and titles for an individual page of the archive .
24,754
def load_problem_details ( id ) return unless Problem [ id ] . published . nil? html = open ( "https://projecteuler.net/problem=#{id}" ) fragment = Nokogiri :: HTML ( html ) problem_info = fragment . css ( 'div#problem_info span span' ) details = problem_info . text . split ( ';' ) Problem [ id ] . published = details ...
Loads the details of an individual problem .
24,755
def email_verification_email ( token , root_url ) @token = token @protocol , @host = * root_url . split ( '://' , 2 ) @host . slice! ( - 1 ) if @host [ - 1 ] == ?/ hostname = @host . split ( ':' , 2 ) . first mail to : @token . email , subject : email_verification_subject ( token , hostname , @protocol ) , from : email...
Creates an e - mail containing a verification token for the e - mail address .
24,756
def reset_password_email ( email , token , root_url ) @email , @token , @host , @protocol = email , token @token = token @protocol , @host = * root_url . split ( '://' , 2 ) @host . slice! ( - 1 ) if @host [ - 1 ] == ?/ hostname = @host . split ( ':' , 2 ) . first mail to : email , from : reset_password_from ( token , ...
Creates an e - mail containing a password reset token .
24,757
def load_self_descendants file = ClassFinder . where_is ( self ) path = File . expand_path ( File . dirname ( file ) ) Dir [ "#{path}/**/*.rb" ] . each { | f | load f } end
Find and load all ruby files under the same directory structure of the declared class which is including DescendantsLoader module .
24,758
def check_commit_message_length ( message ) check_label = 'Commit message length' if message . length >= @min_length && message . length <= @max_length Status . report ( check_label , true ) else @errors . push "Commit messages should be between #{@min_length} " "and #{@max_length} characters." Status . report ( check_...
Check message length
24,759
def follow ( * args ) options = args . last . is_a? ( Hash ) ? args . pop : { } target = args . first merge_target_into_options! ( target , options ) response = post ( 'users/follow' , options ) end
Follow a user
24,760
def parse ( file ) pattern = PATTERNS [ File . extname ( file ) ] IO . readlines ( file ) . take_while do | line | line =~ pattern end . map { | line | line [ pattern , 1 ] } end
Determines a file s dependencies based on the file s extension .
24,761
def increment_for ( obj ) ts = Time . now . ceil . to_i if obj . class . ancestors . include? Cequel :: Record args = obj . key_attributes . collect { | k , v | v . to_s } cache_key = generate_key ( ts , obj . class . name , * args ) val = Cequel :: Record . redis . get ( cache_key ) if val . nil? val = 1 else val = va...
Increments the counter for a model .
24,762
def aggregate ( ts = Time . now . floor ) ts = ts . to_i aggr = { } index_key = generate_index_key ( ts , '*' ) counters = Cequel :: Record . redis . keys ( index_key ) counters . each do | cnt | _tmp = cnt . split ( SEPARATOR ) _ts = _tmp [ 2 ] . to_i aggr [ _ts ] = { } unless aggr . has_key? ( _ts ) clazz = _tmp [ 3 ...
Aggregates all the counters available . Aggregation of only time specific events can be done by passing the ts parameter .
24,763
def rank = ( value ) r = value . to_s . downcase . strip if ! RANKS . include? ( r ) raise NameError , "#{r} is not a valid rank." end @rank = r end
Set the rank .
24,764
def name = ( name ) case @rank when 'superfamily' raise NameError , "ICZN superfamily name does not end in 'oidae'." if name [ - 5 , 5 ] != 'oidae' when 'family' raise NameError , "ICZN family name does not end in 'idae'." if name [ - 4 , 4 ] != 'idae' when 'subfamily' raise NameError , "ICZN subfamily name does not en...
Set the name checks for family group restrictions .
24,765
def rollback_active_record_state! remember_transaction_record_state yield rescue Exception IdentityMap . remove ( self ) if IdentityMap . enabled? restore_transaction_record_state raise ensure clear_transaction_record_state end
Reset id and
24,766
def rolledback! ( force_restore_state = false ) run_callbacks :rollback ensure IdentityMap . remove ( self ) if IdentityMap . enabled? restore_transaction_record_state ( force_restore_state ) end
Call the after rollback callbacks . The restore_state argument indicates if the record state should be rolled back to the beginning or just to the last savepoint .
24,767
def start_child @child_thread ||= Thread . new do Open3 . popen3 ( child_env_vars , * ruby_command , context_file ) do | _ , stdout , stderr | @pid = stdout . gets . strip . to_i while ( line = stderr . gets ) print "!! #{line}" end end end end
Sets necessary ivars Starts a child process in a child - watching - thread Reads it s PID from the new process STDOUT and sets it as an instance variable
24,768
def create logger . debug ( "Create new user" ) @user = User . new ( user_params ) if @user . save render json : @user , except : [ :verification_token , :reset_token , :password_digest ] , status : 201 @user . issue_token ( :verification_token ) @user . save user_mailer . email_verification ( @user ) . deliver_later e...
Creates a new user . This action does not require any auth although it is optional .
24,769
def update_user ( update_user_params ) if @user . update_attributes ( update_user_params ) render json : @user , except : [ :password_digest ] else render_errors 400 , @user . errors . full_messages end end
This method normally updates the user using permitted params .
24,770
def update_token ( kind ) @user . issue_token ( kind ) @user . save if kind == :reset_token user_mailer . password_reset ( @user ) . deliver_later else user_mailer . email_verification ( @user ) . deliver_later end render body : '' , status : 204 end
This method updates user with a new reset token . Only used for this operation .
24,771
def add ( bullet , * items ) items . each do | item | @bullet_data << [ bullet . to_s , item ] bullet = "" end end
Prepare a blank slate . Add items to these bullet points .
24,772
def render @key_length , results = get_key_length , [ ] @bullet_data . each do | key , item | results . concat ( render_bullet ( key , item ) ) end @bullet_data = [ ] results end
Render the bullet points as an array of strings .
24,773
def create return false unless new_record? run_callbacks :save do run_callbacks :create do httparty = self . class . post ( self . class . index_path , request_options . merge ( :body => to_json ) ) handle_save_response ( httparty ) end end end
Create a new model on the server
24,774
def update return false if new_record? run_callbacks :save do run_callbacks :update do httparty = self . class . put ( self [ :@url ] , request_options . merge ( :body => to_json ) ) handle_save_response ( httparty ) end end end
Update an existing model on the server
24,775
def destroy return false if new_record? run_callbacks :destroy do httparty = self . class . delete ( self [ :@url ] , request_options ) self . class . handle_critical_response_errors ( httparty ) end true end
Delete an existing model on the server
24,776
def to_hash ( args = { } ) args ||= { } if args [ :nested ] { 'url' => self [ :@url ] || self [ :url ] } else hash = super hash . merge! ( '@version' => self [ '@version' ] ) unless new_record? { self . class . json_name => hash } end end
ActiveSupport caused problems when using as_json so using to_hash
24,777
def retrieve ( url , method = :get , headers = { } , data = nil ) puts "[ActiveHarmony] Retrieving data:" puts "[ActiveHarmony] URL: #{url}" puts "[ActiveHarmony] Method: #{method}" puts "[ActiveHarmony] Headers: #{headers.inspect}" puts "[ActiveHarmony] Data: #{data.inspect}" if data if defined...
Retrieving data from networks
24,778
def list ( object_type ) url = generate_rest_url ( :list , object_type ) result = retrieve ( url . path ) parsed_result = parse_xml ( result ) find_object_in_result ( parsed_result , object_type , :list ) end
Working with REST services
24,779
def show ( object_type , id ) url = generate_rest_url ( :show , object_type , id ) result = retrieve ( url . path ) parsed_result = parse_xml ( result ) find_object_in_result ( parsed_result , object_type , :show ) end
Shows remote object
24,780
def update ( object_type , id , data ) url = generate_rest_url ( :update , object_type , id ) object_name = object_name_for ( object_type , :update ) xml_data = data . to_xml ( :root => object_name , :skip_instruct => true , :dasherize => false ) result = retrieve ( url . path , url . method , { 'Content-type' => 'appl...
Updates remote object
24,781
def create ( object_type , data ) url = generate_rest_url ( :create , object_type ) object_name = object_name_for ( object_type , :create ) xml_data = data . to_xml ( :root => object_name , :skip_instruct => true , :dasherize => false ) result = retrieve ( url . path , url . method , { 'Content-type' => 'application/xm...
Creates a new remote object
24,782
def custom_url_for ( object_type , action ) path = @paths . find do | path | path [ :object_type ] == object_type && path [ :action ] == action end if path ServiceUrl . new ( generate_url ( path [ :path ] ) , path [ :method ] ) end end
Returns custom path
24,783
def object_name_for ( object_type , action ) object_name = @object_names . find do | object_name | object_name [ :object_type ] == object_type object_name [ :action ] == action end object_name = object_name ? object_name [ :new_object_name ] : nil unless object_name object_name = object_type . to_s . gsub ( '-' , '_' )...
Returns custom object name for action
24,784
def get ( path , options = { } ) if options [ :query ] . nil? options . merge! ( { query : { api_key : @key } } ) else options [ :query ] . merge! ( { api_key : @key } ) end response = self . class . get path , options raise LoLBaseError , response . message if response . code != 200 response . body end
Override HTTParty s get method to append the API key and to process errors returned from request
24,785
def login_required setup_client @user = :: TwitterOAuth :: User . new ( @client , session [ :user ] ) if session [ :user ] @rate_limit_status = @client . rate_limit_status redirect '/login' unless user end
Redirects to login unless there is an authenticated user
24,786
def redirect_to_twitter_auth_url request_token = get_request_token session [ :request_token ] = request_token . token session [ :request_token_secret ] = request_token . secret redirect request_token . authorize_url . gsub ( 'authorize' , 'authenticate' ) end
gets the request token and redirects to twitter s OAuth endpoint
24,787
def convert_to ( other ) return self if other . nil? case other when Unit return self if other == self target = other when String target = SIUnits :: Unit . new ( other . to_f ) else raise ArgumentError , "Unknown target units" end end
Comparable units = > Compare with scale of kinds convert to a specified unit string or to the same unit as another Unit
24,788
def add_sources ( urls ) urls . each_with_object ( { } . compare_by_identity ) do | link , pairs | pairs [ root_url ( link ) ] = link end end
Adds root urls as hash keys
24,789
def save_images ( urls , file_path ) urls . each_with_index do | url , i | open ( "#{@topic.gsub(' ', '-')}_#{i}.jpg" , 'wb' ) do | file | file << open ( url ) . read end end end
takes an array of links
24,790
def row row_number if row_number == 0 cells = [ ] if @has_titles @column_titles . each do | title | cells << title ? title : '' end end cells else @engine . generate ( row_number , @columns , @cell_styles , @column_styles , @column_types ) end end
Returns an array of String objects generates by the engine attached to this Sheet s Spreadsheet .
24,791
def each_cell_definition & block if block . arity == 1 @columns . each do | column | yield column end else @columns . each_with_index do | column , i | yield column , i end end end
Calls the passed block for every Element the cell definition attached to columns for this Sheet .
24,792
def render mentions = mentions_erb hashtags = hashtags_erb smileys = smileys_erb clients = clients_erb counters = { tweets : @parsed [ :tweet_count ] , retweets : @parsed [ :retweet_count ] , retweets_percentage : ( @parsed [ :retweet_count ] * 100 / @parsed [ :tweet_count ] . to_f ) . round ( 2 ) , selftweets : @parse...
Initializes a new TemplateRenderer .
24,793
def mentions_erb retdict = { enabled : @config [ :mentions ] [ :enabled ] , top : [ ] , nottop : [ ] } if @config [ :mentions ] [ :enabled ] top = @parsed [ :mentions ] . slice ( 0 , @config [ :mentions ] [ :top ] ) top . each do | mention | retdict [ :top ] << mention [ 1 ] end nottop = @parsed [ :mentions ] . slice (...
Returns an array with the mentions which can be easily used within ERB .
24,794
def hashtags_erb retdict = { enabled : @config [ :hashtags ] [ :enabled ] , top : [ ] , nottop : [ ] } if @config [ :hashtags ] [ :enabled ] top = @parsed [ :hashtags ] . slice ( 0 , @config [ :hashtags ] [ :top ] ) top . each do | hashtag | retdict [ :top ] << hashtag [ 1 ] end nottop = @parsed [ :hashtags ] . slice (...
Returns an array with the hashtags which can be easily used within ERB .
24,795
def smileys_erb retdict = { enabled : @config [ :smileys ] [ :enabled ] , top : [ ] , nottop : [ ] } if @config [ :smileys ] [ :enabled ] top = @parsed [ :smileys ] . slice ( 0 , @config [ :smileys ] [ :top ] ) top . each do | smiley | retdict [ :top ] << smiley [ 1 ] end nottop = @parsed [ :smileys ] . slice ( @config...
Returns an array with the smileys which can be easily used within ERB .
24,796
def clients_erb retdict = { enabled : @config [ :clients ] [ :enabled ] , top : [ ] , nottop : [ ] } if @config [ :clients ] [ :enabled ] top = @parsed [ :clients ] . slice ( 0 , @config [ :clients ] [ :top ] ) top . each do | client | retdict [ :top ] << { name : client [ 1 ] [ :name ] , url : client [ 1 ] [ :url ] , ...
Returns an array with the clients which can be easily used within ERB .
24,797
def list ( * extensions ) all_files . keep_if do | filename | extensions . include? ( Pathname . new ( filename ) . extname ) end all_files . reject! { | file | excluded_file? ( file ) } all_files end
Instantiate a FileFinder with the path to a folder
24,798
def excluded_file? ( file ) full_path = File . expand_path ( file ) options . fetch ( :excluded_files ) { [ ] } . any? do | file_to_exclude | File . fnmatch ( file_to_exclude , full_path ) end end
Check if this file has been excluded
24,799
def full_messages inject ( [ ] ) do | m , kv | att , errors = * kv errors . each { | e | m << "#{e}" } m end end
Returns an array of fully - formatted error messages .