idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
22,300
def sitemap_meta_description return controller . sitemap_meta_data [ :description ] . blank? ? nil : tag ( :meta , { name : :description , content : controller . sitemap_meta_data [ :description ] } , false , false ) end
Generates a description meta tag for use inside HTML header area .
22,301
def sitemap_meta_lastmod return controller . sitemap_meta_data [ :lastmod ] . blank? ? nil : tag ( :meta , { name : "Last-Modified" , content : controller . sitemap_meta_data [ :lastmod ] } , false , false ) end
Generates a Last - Modified meta tag for use inside HTML header area .
22,302
def sitemap_meta_canonical return controller . sitemap_meta_data [ :canonical ] . blank? ? nil : tag ( :link , { rel : :canonical , href : controller . sitemap_meta_data [ :canonical ] } , false , false ) end
Generates a canonical link tag for use inside HTML header area .
22,303
def valid? number raise_on_type_mismatch number num , check = split_number ( number ) self . of ( num ) == check end
Primitive97 validation of provided number
22,304
def check! ( request ) @check_headers . each do | header_name | values = @checks [ header_name ] header = request . send ( header_name ) raise AcceptError unless values . any? { | v | header . accept? ( v ) } end end
Raises an AcceptError if this server is not able to serve an acceptable response .
22,305
def of number raise_on_type_mismatch number digits = convert_number_to_digits ( number ) INVERSE [ digits . reverse_each . with_index . reduce ( 0 ) { | check , ( digit , idx ) | d_row = DIHEDRAL_GROUP_D5 [ check ] d_row [ PERMUTATION [ idx . next % 8 ] [ digit ] ] } ] end
Calculates Verhoeff checksum
22,306
def save_to_file ( path ) fullpath = File . expand_path ( path ) lines = [ ] @content . each_pair do | key , value | k = "lxc.#{key.gsub('_', '.')}" if value . kind_of? ( Array ) lines << value . map { | v | "#{k} = #{v}" } else lines << "#{k} = #{value}" end end File . open ( path , "w" ) do | f | f . write ( lines . ...
Save configuration into file
22,307
def symbolize_keys ( hash ) hash = hash . to_hash if hash . respond_to? ( :symbolize_keys ) hash . symbolize_keys else hash . inject ( { } ) do | new_hash , ( key , value ) | new_hash [ symbolize_key ( key ) ] = value new_hash end end end
Ethon hates on hash with indifferent access for some reason
22,308
def get ( url ) begin response = perform_get ( url ) rescue RestClient :: TooManyRequests => e return nil unless wait_for_quota sleep_until_quota_reset ( e . response ) response = perform_get ( url ) end response end
Performs HTTP queries while respecting the rate limit .
22,309
def matches ( language ) values . select { | v | v = v . match ( / / ) ? $1 : v if @first_level_match v == language || v == '*' || ( language . match ( / / ) && v == $1 ) } . sort { | a , b | a == '*' ? - 1 : ( b == '*' ? 1 : a . length <=> b . length ) } . reverse end
Returns an array of languages from this header that match the given + language + ordered by precedence .
22,310
def convert ( * args ) @options += args if args outputfile = @options . map { | x | x [ :output ] } . compact tmp_file = Tempfile . new ( 'pandoc-conversion' ) @options += [ { output : tmp_file . path } ] if outputfile . empty? @option_string = prepare_options ( @options ) begin run_pandoc IO . binread ( tmp_file ) ens...
Create a new RubyPandoc converter object . The first argument contains the input either as string or as an array of filenames .
22,311
def run_pandoc command = unless @input_files . nil? || @input_files . empty? "#{@@pandoc_path} #{@input_files} #{@option_string}" else "#{@@pandoc_path} #{@option_string}" end output = error = exit_status = nil options = { } options [ :stdin_data ] = @input_string if @input_string output , error , exit_status = Open3 ....
Wrapper to run pandoc in a consistent DRY way
22,312
def prepare_options ( opts = [ ] ) opts . inject ( '' ) do | string , ( option , value ) | string += case when value create_option ( option , value ) when option . respond_to? ( :each_pair ) prepare_options ( option ) else create_option ( option ) end end end
Builds the option string to be passed to pandoc by iterating over the opts passed in . Recursively calls itself in order to handle hash options .
22,313
def create_option ( flag , argument = nil ) return '' unless flag flag = flag . to_s return " #{argument}" if flag == 'extra' set_pandoc_ruby_options ( flag , argument ) if ! argument . nil? "#{format_flag(flag)} #{argument}" else format_flag ( flag ) end end
Takes a flag and optional argument uses it to set any relevant options used by the library and returns string with the option formatted as a command line options . If the option has an argument it is also included .
22,314
def set_pandoc_ruby_options ( flag , argument = nil ) case flag when 't' , 'to' @writer = argument . to_s @binary_output = true if BINARY_WRITERS . keys . include? ( @writer ) end end
Takes an option and optional argument and uses them to set any flags used by RubyPandoc .
22,315
def parse ( scanner , rules , scope = ParserScope . empty ) result = false backtracking ( scanner ) do if scope = parse_children ( scanner , rules , scope . nest ) { | r | result = r } yield scope if block_given? result end end end
Parse each parser in sequence and if they all succeed return the result of applying the semantic action to the captured results .
22,316
def burn ( burn_cards ) return false if burn_cards . is_a? ( Integer ) if burn_cards . is_a? ( Card ) || burn_cards . is_a? ( String ) burn_cards = [ burn_cards ] end burn_cards . map! do | c | c = Card . new ( c ) unless c . class == Card @cards . delete ( c ) end true end
delete an array or a single card from the deck converts a string to a new card if a string is given
22,317
def backend_resources ( * args , & block ) resources ( * args , & block ) additional_resource_route_blocks = Itsf :: Backend :: Configuration . additional_resource_route_blocks if additional_resource_route_blocks . any? resources_name = args . first additional_resource_route_blocks . each do | route_block | resources r...
Using this method instead of resources adds member routes for pages added in the itsf_backend configuration .
22,318
def generate_html FileUtils . rm_rf ( Rails . root . join ( 'tmp/apidocs' ) ) options = [ Rails . root . join ( "app/controllers" ) . to_s , "--op=#{Rails.root.join('tmp/apidocs')}" ] self . store = RDoc :: Store . new @options = load_options @options . parse options @exclude = @options . exclude @last_modified = setup...
generate_html entry point for on fly document generation
22,319
def collect_sources_and_toolchains sources_to_build = { } exclude_files = Set . new exclude_sources . each do | p | if p . include? ( ".." ) Printer . printError "Error: Exclude source file pattern '#{p}' must not include '..'" return nil end Dir . glob ( p ) . each { | f | exclude_files << f } end files = Set . new ad...
returns a hash from all sources to the toolchain that should be used for a source
22,320
def calc_dirs_with_files ( sources ) filemap = { } sources . keys . sort . reverse . each do | o | d = File . dirname ( o ) if filemap . include? ( d ) filemap [ d ] << o else filemap [ d ] = [ o ] end end return filemap end
calcs a map from unique directories to array of sources within this dir
22,321
def arguments ( value ) value = case value when Hash value . map do | key , sub_value | if sub_value == true then key . to_s elsif sub_value then "#{key}=#{sub_value}" end end when false , nil [ ] else Array ( value ) end return value . compact end
Formats a value into an Array of arguments .
22,322
def add ( relation , item ) unless item . respond_to? ( :to_hash ) raise ArgumentError . new ( 'only items that can be converted to hashes with #to_hash are permitted' ) end @relations [ relation ] = @relations . fetch ( relation , [ ] ) << item end
Adds an object to a relation .
22,323
def to_hash @relations . each_with_object ( { } ) do | ( rel , val ) , obj | rel = rel . to_s hashed_val = val . map ( & :to_hash ) if val . length == 1 && ! single_item_arrays? hashed_val = val . first . to_hash end obj [ rel ] = hashed_val end end
Returns a hash corresponding to the object .
22,324
def request ( method , path , options , headers ) headers . merge! ( { 'User-Agent' => user_agent , 'Accept' => 'application/vnd.urbanairship+json; version=3;' , } ) response = connection . send ( method ) do | request | request . url ( "#{endpoint}#{path}/" ) if [ :post , :put ] . member? ( method ) request . body = o...
Perform an HTTP request .
22,325
def follow ( model ) if self . id != model . id && ! self . follows? ( model ) model . before_followed_by ( self ) if model . respond_to? ( 'before_followed_by' ) model . followers . create! ( :ff_type => self . class . name , :ff_id => self . id ) model . inc ( :fferc , 1 ) model . after_followed_by ( self ) if model ...
follow a model
22,326
def unfollow ( model ) if self . id != model . id && self . follows? ( model ) model . before_unfollowed_by ( self ) if model . respond_to? ( 'before_unfollowed_by' ) model . followers . where ( :ff_type => self . class . name , :ff_id => self . id ) . destroy model . inc ( :fferc , - 1 ) model . after_unfollowed_by ( ...
unfollow a model
22,327
def assert_type ( value ) unless @type . nil? || value . is_a? ( @type ) || allow_nil && value . nil? raise TypeError , format ( "Expected %s, got %s" , @type , value . class ) end end
Raises a TypeError if value is not of
22,328
def todo_with_substring ( substring ) issue_todo = @remaining_todos . detect { | t | ! t . content . index ( substring ) . nil? } issue_todo ||= @completed_todos . detect { | t | ! t . content . index ( substring ) . nil? } end
searches the remaining and completed todos for the first todo with the substring in its content
22,329
def create_todo ( todo ) post_params = { :body => todo . post_json , :headers => Logan :: Client . headers . merge ( { 'Content-Type' => 'application/json' } ) } response = Logan :: Client . post "/projects/#{@project_id}/todolists/#{@id}/todos.json" , post_params Logan :: Todo . new response end
create a todo in this todo list via the Basecamp API
22,330
def update_todo ( todo ) put_params = { :body => todo . put_json , :headers => Logan :: Client . headers . merge ( { 'Content-Type' => 'application/json' } ) } response = Logan :: Client . put "/projects/#{@project_id}/todos/#{todo.id}.json" , put_params Logan :: Todo . new response end
update a todo in this todo list via the Basecamp API
22,331
def safety_cone_filter if cone = fetch_cone if cone . type == 'notice' flash . now [ "safetycone_#{notice_type(cone.type)}" ] = cone . message else flash [ "safetycone_#{notice_type(cone.type)}" ] = cone . message end redirect_to safety_redirect if cone . type == 'block' end end
Filter method that does the SafetyCone action based on the configuration .
22,332
def fetch_cone paths = SafetyCone . paths if path = paths [ request_action ] key = request_action elsif cone = paths [ request_method ] key = request_method else return false end path = Path . new ( key , path ) path . fetch %w[ notice block ] . include? ( path . type ) ? path : false end
Fetches a configuration based on current request
22,333
def star_loop selection = '' while true puts "Type the number of the post that you want to learn about" print " (or hit return to view all again, you ego-maniac) >> " selection = $stdin . gets . chomp break if [ '' , 'q' , 'quit' , 'exit' , 'fuckthis' ] . include? ( selection . downcase ) show ( selection ) end disp...
Initializes a new Client .
22,334
def show ( id ) post = @posts [ id . to_i - 1 ] return puts ( "\nMake a valid selection. Pretty please?\n" ) unless post puts post . more display end
Displays all of the star tables and information we have .
22,335
def print_posts ( posts ) table do | t | t . headings = headings posts . each_with_index do | post , i | t << [ { :value => i + 1 , :alignment => :right } , post . service . capitalize , { :value => post . stars_count , :alignment => :center } , post . short_name ] end end end
This does the actual printing of posts .
22,336
def loyalty ( parsed_text = extract_power_toughness ) if parsed_text && ! parsed_text . include? ( '/' ) parsed_text . to_i if parsed_text . to_i > 0 end end
gatherer uses the pt row to display loyalty
22,337
def add_file ( path , ** kwords ) response = connection . send ( :post , "/repos/#{self.Name}/file/#{path}" , query : kwords , query_mangle : false ) hash = JSON . parse ( response . body ) error = Errors :: RepositoryFileError . from_hash ( hash ) raise error if error hash [ 'Report' ] [ 'Added' ] end
Add a previously uploaded file to the Repository .
22,338
def packages ( ** kwords ) response = connection . send ( :get , "/repos/#{self.Name}/packages" , query : kwords , query_mangle : false ) JSON . parse ( response . body ) end
List all packages in the repository
22,339
def edit! ( ** kwords ) response = connection . send ( :put , "/repos/#{self.Name}" , body : JSON . generate ( kwords ) ) hash = JSON . parse ( response . body , symbolize_names : true ) return nil if hash == marshal_dump marshal_load ( hash ) self end
Edit this repository s attributes as per the parameters .
22,340
def parse_authority_response threaded_responses = [ ] end_response = [ ] position_counter = 0 @raw_response . select { | response | response [ 0 ] == "atom:entry" } . map do | response | threaded_responses << Thread . new ( position_counter ) { | local_pos | end_response [ local_pos ] = loc_response_to_qa ( response_to...
Reformats the data received from the LOC service
22,341
def loc_response_to_qa ( data , counter ) json_link = data . links . select { | link | link . first == 'application/json' } if json_link . present? json_link = json_link [ 0 ] [ 1 ] broader , narrower , variants = get_skos_concepts ( json_link . gsub ( '.json' , '' ) ) end count = ActiveFedora :: Base . search_with_con...
Simple conversion from LoC - based struct to QA hash
22,342
def name dirs = File . expand_path ( @uri . path ) . split ( File :: SEPARATOR ) unless dirs . empty? if @scm == :sub_version if dirs [ - 1 ] == 'trunk' dirs . pop elsif ( dirs [ - 2 ] == 'branches' || dirs [ - 2 ] == 'tags' ) dirs . pop dirs . pop end elsif @scm == :git dirs . last . chomp! ( '.git' ) end end return (...
Initializes the remote repository .
22,343
def execute ( thrift_call_group , host_s = nil , port_n = nil , incr = false ) @@host = host_s if ! host_s . nil? @@port = port_n if ! port_n . nil? socket = Thrift :: Socket . new ( @@host , @@port ) transport = Thrift :: BufferedTransport . new ( socket ) transport . open protocol = Thrift :: BinaryProtocol . new ( t...
Initialize a Thrift connection to the specified host and port and execute the provided ThriftCallGroup object .
22,344
def todolists active_response = Logan :: Client . get "/projects/#{@id}/todolists.json" lists_array = active_response . parsed_response . map do | h | Logan :: TodoList . new h . merge ( { :project_id => @id } ) end end
get active todo lists for this project from Basecamp API
22,345
def publish post_params = { :body => { } . to_json , :headers => Logan :: Client . headers . merge ( { 'Content-Type' => 'application/json' } ) } response = Logan :: Client . post "/projects/#{@id}/publish.json" , post_params end
publish this project from Basecamp API
22,346
def completed_todolists completed_response = Logan :: Client . get "/projects/#{@id}/todolists/completed.json" lists_array = completed_response . parsed_response . map do | h | Logan :: TodoList . new h . merge ( { :project_id => @id } ) end end
get completed todo lists for this project from Basecamp API
22,347
def todolist ( list_id ) response = Logan :: Client . get "/projects/#{@id}/todolists/#{list_id}.json" Logan :: TodoList . new response . parsed_response . merge ( { :project_id => @id } ) end
get an individual todo list for this project from Basecamp API
22,348
def create_todolist ( todo_list ) post_params = { :body => todo_list . post_json , :headers => Logan :: Client . headers . merge ( { 'Content-Type' => 'application/json' } ) } response = Logan :: Client . post "/projects/#{@id}/todolists.json" , post_params Logan :: TodoList . new response . merge ( { :project_id => @i...
create a todo list in this project via Basecamp API
22,349
def create_message ( subject , content , subscribers , private ) post_params = { :body => { subject : subject , content : content , subscribers : subscribers , private : private } . to_json , :headers => Logan :: Client . headers . merge ( { 'Content-Type' => 'application/json' } ) } response = Logan :: Client . post "...
create a message via Basecamp API
22,350
def parse ( scanner , rules , scope = ParserScope . empty ) catch ( :rule_failed ) do return expr . parse ( scanner , rules , scope ) end false end
Parse using the rule body and on success return the result on failure return a false value .
22,351
def development_mode = ( flag ) self [ :development_mode ] = flag self . level = Logger :: DEBUG if new_logger new_logger . level = self . level if self . logger . respond_to? ( :level= ) end end
Helps to enable debug logging when in development mode
22,352
def []= ( key , data ) info , _ = read ( key ) info ||= { } if data write ( key , data , info ) else delete ( key , info ) end end
Write data to entry key or updating existing one if it exists .
22,353
def read ( key ) command "find-generic-password" , "-g" , "-l" , key do | info , password_info | [ Utils . parse_info ( info ) , Utils . parse_contents ( password_info ) ] end rescue CommandError => e raise unless e . message =~ ENTRY_MISSING nil end
Read a key from the keychain .
22,354
def write ( key , data , options = { } ) info = Utils . build_info ( key , options ) command "add-generic-password" , "-a" , info [ :account_name ] , "-s" , info [ :service_name ] , "-l" , info [ :label ] , "-D" , info [ :kind ] , "-C" , info [ :type ] , "-T" , "" , "-U" , "-w" , data end
Write data with given key to the keychain or update existing key if it exists .
22,355
def delete ( key , options = { } ) info = Utils . build_info ( key , options ) command "delete-generic-password" , "-a" , info [ :account_name ] , "-s" , info [ :service_name ] , "-l" , info [ :label ] , "-D" , info [ :kind ] , "-C" , info [ :type ] end
Delete the entry matching key and options .
22,356
def variation ( id ) variations . select { | v | v . id . split ( ':' ) . last == id } . first end
Find a variation in this Family by the Font Variation Description
22,357
def load_application_files if %w( development test ) . include? ( env . to_s ) config [ 'autoload_paths' ] . each ( & method ( :autoreload_constants ) ) autoreload_yml end config [ 'autoload_paths' ] . each ( & method ( :require_dependencies ) ) end
Autoloads all app - specific files
22,358
def fetch! obj = ComicVine :: API . get_details_by_url ( self . api_detail_url ) self . methods . each do | m | if m . to_s =~ / \w \d \_ / get_m = $1 . to_sym set_m = m next if get_m . to_s =~ / \_ / || set_m . to_s =~ / / if self . respond_to? ( set_m ) && obj . respond_to? ( get_m ) && ! obj . method ( get_m ) . cal...
Fetches data from ComicVine based on objects api_detail_url and updates self with new values
22,359
def configure_query @query_to_pluck = @records @attributes_to_pluck = [ { name : @query_to_pluck . primary_key . to_sym , sql : "\"#{@query_to_pluck.table_name}\".#{@query_to_pluck.primary_key}" } ] @results = { } @klass_reflections = @query_to_pluck . reflections . with_indifferent_access pluck_reflections = @options ...
In this base implementation we just reset all the query information . Features and subclasses must redefine this method if they are interested in adding some behaviour .
22,360
def build_results @attributes_to_pluck . uniq! { | f | f [ :name ] } names_to_pluck = @attributes_to_pluck . map { | f | f [ :name ] } sql_to_pluck = @attributes_to_pluck . map { | f | f [ :sql ] } pluck_records ( sql_to_pluck ) . each_with_index do | record , index | record = [ record ] unless record . is_a? Array att...
In this base implementation we perform the real pluck execution .
22,361
def signing_key digest = "SHA256" kDate = OpenSSL :: HMAC . digest ( digest , "AWS4" + credentials . aws_secret , request_datestamp ) kRegion = OpenSSL :: HMAC . digest ( digest , kDate , region ) kService = OpenSSL :: HMAC . digest ( digest , kRegion , service ) OpenSSL :: HMAC . digest ( digest , kService , "aws4_req...
Calculate the signing key for task 3 .
22,362
def canonical_headers hash = headers . dup hash [ "host" ] ||= Addressable :: URI . parse ( url ) . host hash = hash . map { | name , value | [ name . downcase , value ] } hash . reject! { | name , value | name == "authorization" } hash . sort end
The canonical headers including the Host .
22,363
def git ( commands = { } ) if commands . is_a? ( Symbol ) run "git #{commands}" else commands . each do | cmd , options | run "git #{cmd} #{options}" end end end
Run a command in git .
22,364
def node_properties result = { } api_nodes . each do | data | next if data [ 'deactivated' ] name = data [ 'certname' ] values = data . dup %w[ deactivated certname ] . each { | key | values . delete ( key ) } result [ name ] = values end result end
get hash of node update properties
22,365
def nodes_update_facts_since ( timestamp ) ts = ( timestamp . is_a? ( String ) ? Time . iso8601 ( ts ) : timestamp ) node_properties . delete_if do | _k , data | ! data [ "facts_timestamp" ] || Time . iso8601 ( data [ "facts_timestamp" ] ) < ts end . keys end
get all nodes that have updated facts
22,366
def single_node_facts ( node ) json = get_json ( "#{@nodes_url}/#{node}/facts" , 10 ) return nil if json . include? ( "error" ) Hash [ json . map { | data | [ data [ "name" ] , data [ "value" ] ] } ] end
get hash of facts for given node name
22,367
def facts json = get_json ( @facts_url , 60 ) result = { } json . each do | fact | data = result [ fact [ "certname" ] ] result [ fact [ "certname" ] ] = data = { } unless data data [ fact [ "name" ] ] = fact [ "value" ] end result end
get all nodes with all facts
22,368
def call ( action , query = { } , & blk ) call! ( action , expand ( query ) ) do | code , data | case code when 200 response = compact ( data ) when 400 ... 500 messages = if data [ "Response" ] Array ( data [ "Response" ] [ "Errors" ] ) . map { | _ , e | e [ "Message" ] } elsif data [ "ErrorResponse" ] Array ( data [ ...
Execute an EC2 command expand the input and compact the output
22,369
def open! raise BadWordnetDataset , "Failed to locate the wordnet database. Please ensure it is installed and that if it resides at a custom path that path is given as an argument when constructing the Words object." if @wordnet_path . nil? @connected = true evocation_path = @data_path + 'evocations.dmp' File . open ( ...
Constructs a new pure ruby connector for use with the words wordnet class .
22,370
def homographs ( term , use_cache = true ) raise NoWordnetConnection , "There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object." unless connected? cache_ensure_from_wordnet ( term , use_cache ) cached_entry_to_homograph_hash ( term ) ...
Locates from a term any relevent homographs and constructs a homographs hash .
22,371
def synset ( synset_id ) raise NoWordnetConnection , "There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object." unless connected? pos = synset_id [ 0 , 1 ] File . open ( @wordnet_path + "data.#{SHORT_TO_POS_FILE_TYPE[pos]}" , "r" ) do ...
Locates from a synset_id a specific synset and constructs a synset hash .
22,372
def evocations ( synset_id ) raise NoWordnetConnection , "There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object." unless connected? if defined? @evocations raw_evocations = @evocations [ synset_id + "s" ] { 'relations' => raw_evocati...
Locates from a synset id any relevent evocations and constructs an evocations hash .
22,373
def create name , password , params = { } params . merge! ( { new_account_username : name , new_account_passcode : password } ) post 'accounts' , params end
Sends a request to create an account using the + accounts + endpoint . Raises a + MissingAPITokenError + error if an API token hasn t been set on the Hey module or Yo instance . Accepts an optional hash of additional parameters to send with the request .
22,374
def when_done ( & block ) call_block = false @job_lock . synchronize do if completed? call_block = true else @when_done_callbacks << block end end yield if call_block end
Execute a given block when the batch has finished processing . If the batch has already finished executing execute immediately .
22,375
def prune ( options = { } ) puts describe_prune ( options ) puts "Fetching latest branches and tags from remotes" @git . fetch_all ( :prune => true ) branches = @git . branches ( :all => true ) branches = branches . select { | x | x =~ options [ :only ] } if options [ :only ] branches = branches . reject { | x | x =~ o...
Prune dead branches from the repository .
22,376
def describe_prune ( options ) statement = [ 'Pruning' ] if options [ :remote ] statement << 'remote' elsif options [ :local ] statement << 'local' end statement << 'branches' if options [ :age ] statement << "older than #{time_ago_in_words(options[:age])}" end if options [ :merged ] statement << "that are fully merged...
Build a plain - English description of a prune command based on the options given .
22,377
def prompt ( p , yes_no = false ) puts loop do print p , ' ' line = STDIN . readline . strip if yes_no return true if line =~ YES return false if line =~ NO else return line end end end
Ask the user a yes - or - no question
22,378
def parse_age ( str ) ord , word = str . split ( / / , 2 ) ord = Integer ( ord ) word . gsub! ( / / , '' ) ago = nil TIME_INTERVALS . each do | pair | mag , term = pair . first , pair . last if term == word ago = Time . at ( Time . now . to_i - ord * mag ) break end end if ago ago else raise ArgumentError , "Cannot par...
Given a natural - language English description of a time duration return a Time in the past that is the same duration from Time . now that is expressed in the string .
22,379
def get_save_params { player : @player , email : @email , password : @password , suppress_errors : @suppress_errors , timeout : @timeout , user_agent : @user_agent , cookie : get_cookie_string , expires : @expires . to_s , proxy_addr : @proxy_addr , proxy_port : @proxy_port } . delete_if { | _k , v | v . nil? } end
Returns params to create existing authenticated client
22,380
def get_club_info ( id = nil ) return unless id . to_i . positive? uri = URI :: HTTP . build ( host : SquashMatrix :: Constants :: SQUASH_MATRIX_URL , path : SquashMatrix :: Constants :: CLUB_PATH . gsub ( ':id' , id . to_s ) ) success_proc = lambda do | res | SquashMatrix :: NokogiriParser . get_club_info ( res . body...
Returns newly created Client
22,381
def get_player_results ( id = nil ) return unless id . to_i . positive? uri = URI :: HTTP . build ( host : SquashMatrix :: Constants :: SQUASH_MATRIX_URL , path : SquashMatrix :: Constants :: PLAYER_RESULTS_PATH . gsub ( ':id' , id . to_s ) , query : SquashMatrix :: Constants :: PLAYER_RSULTS_QUERY ) success_proc = lam...
Returns player results .
22,382
def get_search_results ( query = nil , squash_only : false , racquetball_only : false ) return if query . to_s . empty? uri = URI :: HTTP . build ( host : SquashMatrix :: Constants :: SQUASH_MATRIX_URL , path : SquashMatrix :: Constants :: SEARCH_RESULTS_PATH ) query_params = { Criteria : query , SquashOnly : squash_on...
Returns get_search_results results
22,383
def expects ( * args , & block ) expector = Expector . new ( self , @control , @expectation_builder ) return expector if args . empty? expector . send ( args . shift . to_sym , * args , & block ) end
Begin declaring an expectation for this Mock .
22,384
def file_path self . path = File . join ( Dir . pwd , uri_file_name ) unless path if File . directory? ( path ) self . path = File . join ( self . path , uri_file_name ) end self . path end
return a string with a file path where the file will be saved
22,385
def start ( hash = { } ) set_multi ( hash ) File . delete ( file_path ) if File . exist? ( file_path ) File . open ( file_path , 'wb' ) do | file_obj | Kernel . open ( * [ url , options ] . compact ) do | fin | while ( buf = fin . read ( 8192 ) ) file_obj << buf end end end return file_path end
start the downloading process
22,386
def validate ( record , field_name , bindings = { } ) if validations validations . collect do | validation | unless valid_value? ( validation , record , field_name , bindings ) FieldValidationError . new ( validation , record , field_name , pos , width ) end end . compact elsif record && record [ field_name ] [ ] else ...
return an array of error objects empty array if all validation passes
22,387
def details ( label_id ) details_url = File . join ( LABEL_URL , "#{label_id}.json" ) response = connection . get details_url details = response . parsed . tap { | d | d . delete ( 'success' ) } OpenStruct . new ( details ) end
Get label details
22,388
def connect! ( repository ) repository . subscribe do | aggregate_id , event | route ( event . name , aggregate_id , ** event . data ) end end
Connects to the repository .
22,389
def days_range ws = Date :: DAYS_INTO_WEEK [ @options [ :week_start ] ] ( ws ... ws + number_of_days_per_week ) . map { | d | d % 7 } end
Get the range of days to show
22,390
def row_to_day ( i , j ) starting_wday = @day_start . wday - 1 starting_wday = 6 if starting_wday < 0 base = ( i * 7 ) + j base += Date :: DAYS_INTO_WEEK [ @options [ :week_start ] ] base -= starting_wday base += 1 return nil if base < 1 || base > days_in_month ( @day_start ) base end
Get the month s day corresponding to a row . Nil is returned if none .
22,391
def fetch ( attribute ) family_id , variation_id = @id . split ( ':' ) mass_assign Client . get ( "/families/#{family_id}/#{variation_id}" ) attribute ? instance_variable_get ( "@#{attribute}" ) : self end
Get detailed information about this Family Variation from Typekit
22,392
def method_missing ( m , * array ) endpoint = Scale . descendants ( Scale :: Endpoints :: Endpoint ) . find { | e | e . match? m } return endpoint . new ( self , * array ) . process if endpoint super end
Endpoint helper . If the method is not defined then try looking into the available endpoints .
22,393
def execute_helper ( block , opts ) if_condition = execute_helper_condition ( opts [ :if ] ) unless_condition = ! execute_helper_condition ( opts [ :unless ] , false ) block . call if if_condition && unless_condition end
Execute a helper block if it matches conditions
22,394
def method_missing ( symbol , * args ) ( args . empty? and labeled . has_key? ( symbol ) ) ? labeled [ symbol ] : super end
Return + true + if the node has the same value as + other + i . e . + other + is an instance of the same class and has equal children and attributes and the children are labeled the same .
22,395
def create_snapshot ( options = { } ) response = ProfitBricks . request ( method : :post , path : "/datacenters/#{datacenterId}/volumes/#{id}/create-snapshot" , headers : { 'Content-Type' => 'application/x-www-form-urlencoded' } , expects : 202 , body : URI . encode_www_form ( options ) ) ProfitBricks :: Snapshot . new...
Create volume snapshot .
22,396
def parse_range_params ( params ) params . split ( ';' ) . inject ( { 'q' => '1' } ) do | m , p | k , v = p . split ( '=' , 2 ) m [ k . strip ] = v . strip if v m end end
Parses a string of media type range parameters into a hash of parameters to their respective values .
22,397
def normalize_qvalue ( q ) ( q == 1 || q == 0 ) && q . is_a? ( Float ) ? q . to_i : q end
Converts 1 . 0 and 0 . 0 qvalues to 1 and 0 respectively . Used to maintain consistency across qvalue methods .
22,398
def match_any? ( data = nil , values = [ ] ) unless data . blank? unless values . kind_of? ( Array ) values = [ values ] end values . each do | value | if value . kind_of? ( String ) && ( data . to_s . downcase . eql? ( value . downcase ) || value . eql? ( "all" ) ) return true elsif value . kind_of? ( Symbol ) && ( da...
Matches a single value against an array of Strings Symbols and Regexp s .
22,399
def cached_belongs_to ( * args ) caches = Array ( args [ 1 ] . delete ( :caches ) ) association = belongs_to ( * args ) create_cached_belongs_to_child_callbacks ( caches , association ) create_cached_belongs_to_parent_callbacks ( caches , association ) end
Creates a many to one association between two models . Works exactly as ActiveRecord s belongs_to except that it adds caching to it .