idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
15,000
def run @inputs . each do | inp | inp . start if inp . respond_to? ( :start ) end @outputs . each do | outp | outp . start if outp . respond_to? ( :start ) end intro = introspect if @options [ :introspect ] print intro . to_yaml else @bus = create_bus dbusinputs = LibComponent :: DbusInput . create_dbusinputs_from_intr...
Let s rock! Run the component
15,001
def introspect inputs_h = Hash . new outputs_h = Hash . new @inputs . each { | input | inputs_h . merge! ( input . introspect ) { | key , old , new | old . merge ( new ) } } @outputs . each { | output | outputs_h . merge! ( output . introspect ) { | key , old , new | old . merge ( new ) } } res = Hash . new res [ "inpu...
Parse inputs and outputs to communicate with server
15,002
def quit_server ( status_ , str_ ) $stderr . puts str_ if ( ! @options . nil? ) && ! @options [ :debug ] bus = DBus :: ASessionBus . new server = bus . service ( "org.openplacos.server.internal" ) opos = server . object ( "/plugins" ) opos . introspect opos . default_iface = "org.openplacos.plugins" opos . exit ( statu...
Print an error message and make the server quit
15,003
def make_original_face ( num_edges ) num_edges_check ( num_edges ) vert_ref = Array . new ( num_edges ) { Vertex . new } edge_ref = [ ] ( num_edges ) . times do | vert_id | edge_ref << make_connection ( vert_ref [ vert_id - 1 ] , vert_ref [ vert_id ] ) end face = add_face ( edge_ref ) @vertices += vert_ref @edges += ed...
Makes a face with num_edges edges which will be attached to nothing .
15,004
def add_attached_face ( vertex_array , num_edges ) vertex_array_check ( vertex_array ) num_edges_check ( num_edges ) vertex_line = confirm_vertex_line ( vertex_array ) end_vertices = [ vertex_line . first , vertex_line . last ] new_neighbors = find_neighbors ( vertex_array ) vertices_to_make = num_edges - vertex_array ...
This adds a face that will be attached to the given vertices Make sure the vertices are connected or it will raise an error All new vertices and edges will be created This will automatically make_neighbors with any faces that share a vertex with the new face
15,005
def find_neighbors ( vertex_array ) vertex_array_check ( vertex_array ) neighbors = [ ] vertex_array . each do | vertex | @faces . each do | face | neighbors << face if face . vertices . include? ( vertex ) end end neighbors . uniq end
Return all faces containing the given vertices
15,006
def find_face_neighbors ( face ) raise "not a face" unless face . is_a? ( Face ) neighbors = find_neighbors ( face . vertices ) neighbors - [ face ] end
Return all neighbors of the given faces Neighbor is defined as sharing a vertex not necessarily sharing an edge .
15,007
def check_proper_status ( hsh ) proper = hsh [ :proper ] proper_f = hsh [ :proper_f ] status = 'invalid' status = proper != proper_f ? 'formatted' : 'unchanged' if proper && proper_f hsh [ :proper_status ] = status if status . present? hsh end
COMPARE ORIGINAL AND FORMATTED PROPER
15,008
def dress ( value , handler = DressHelper . new ) error = nil candidates . each do | c | success , uped = handler . just_try do c . dress ( value , handler ) end return uped if success error ||= uped end handler . failed! ( self , value , error ) end
Invoke dress on each candidate type in turn . Return the value returned by the first one that does not fail . Fail with an TypeError if no candidate succeeds at tranforming value .
15,009
def define_features @fvs . each do | vector , label | vector . each do | term , value | @features . add ( term ) end end end
For training data points we make sure all the features are added to the feature list
15,010
def add_integration ( namespace , body , opts = { } ) data , _status_code , _headers = add_integration_with_http_info ( namespace , body , opts ) return data end
Add an integration
15,011
def delete_integration ( namespace , integration_id , integration_type , opts = { } ) delete_integration_with_http_info ( namespace , integration_id , integration_type , opts ) return nil end
Delete an integration
15,012
def get_integration ( namespace , integration_type , integration_id , opts = { } ) data , _status_code , _headers = get_integration_with_http_info ( namespace , integration_type , integration_id , opts ) return data end
Get details of a given integration
15,013
def replace_integration ( namespace , integration_id , integration_type , body , opts = { } ) data , _status_code , _headers = replace_integration_with_http_info ( namespace , integration_id , integration_type , body , opts ) return data end
Replace an integration
15,014
def repo_root return git_directory_path if inside_bare_repo? if inside_git_directory? File . expand_path ( '..' , git_directory_path ) elsif inside_work_tree? execute ( git_cmd ( 'rev-parse' , '--show-toplevel' ) ) else raise 'not in git directory or work tree!?' end end
Returns the absolute path to the root of the current git directory
15,015
def parse_results ( solr_data , options = { } ) results = { :docs => [ ] , :total => 0 } configuration = { :format => :objects } results . update ( :spellcheck => solr_data . data [ 'spellcheck' ] ) unless solr_data . nil? results . update ( :facets => { 'facet_fields' => [ ] } ) if options [ :facets ] unless solr_data...
Parses the data returned from Solr
15,016
def reorder ( things , ids ) ordered_things = [ ] ids . each do | id | thing = things . find { | t | t . id . to_s == id . to_s } ordered_things |= [ thing ] if thing end ordered_things end
Reorders the instances keeping the order returned from Solr
15,017
def add_scores ( results , solr_data ) with_score = [ ] solr_data . hits . each do | doc | with_score . push ( [ doc [ "score" ] , results . find { | record | scorable_record? ( record , doc ) } ] ) end with_score . each do | score , object | class << object ; attr_accessor :solr_score ; end object . solr_score = score...
Adds the score to each one of the instances found
15,018
def check_web_status ( hsh ) status = 'invalid' if hsh [ :web_neg ] &. include? ( 'error' ) if hsh [ :url ] && hsh [ :url_f ] && status . nil? status = hsh [ :url ] != hsh [ :url_f ] ? 'formatted' : 'unchanged' end hsh [ :web_status ] = status if status . present? hsh end
COMPARE ORIGINAL AND FORMATTED URL
15,019
def extract_path ( url_hash ) path_parts = url_hash [ :url_f ] . split ( '//' ) . last . split ( '/' ) [ 1 .. - 1 ] path = "/#{path_parts.join('/')}" if path &. length > 2 url_hash [ :url_path ] = path url_hash [ :url_f ] = url_hash [ :url_f ] . gsub ( url_hash [ :url_path ] , '' ) end url_hash end
Supporting Methods Below
15,020
def pack_element ( height , content = nil , & block ) return if @column_packer . nil? if block_given? @column_packer . add ( height . to_i , capture ( & block ) ) else @column_packer . add ( height . to_i , content ) end end
Packs a single element with a given height into a column .
15,021
def u_students_extension ( data ) db_extensions = { "name" => "u_students_extension" , "recordFound" => false , "_field" => [ ] } data . each do | key , value | db_extensions [ "_field" ] << { "name" => "#{key}" , "type" => "String" , "value" => "#{value}" } end db_extensions end
prepare data to update student database extensions
15,022
def u_studentsuserfields ( data ) db_extensions = { "name" => "u_studentsuserfields" , "recordFound" => false , "_field" => [ ] } data . each do | key , value | db_extensions [ "_field" ] << { "name" => "#{key}" , "type" => "String" , "value" => "#{value}" } end db_extensions end
prepare data to built - in database extensions
15,023
def strip_bang ( k ) if k . is_a? Symbol k . to_s [ 0 ... - 1 ] . to_sym else k . to_s [ 0 ... - 1 ] end end
strip a ! from the end of a + String + or + Symbol +
15,024
def camelize ( s ) if s . is_a? ( Symbol ) s . to_s . split ( '_' ) . map ( & :capitalize ) . join . to_sym else s . split ( '_' ) . map ( & :capitalize ) . join end end
camel - case a + String +
15,025
def camel_keys ( h ) Hash [ h . map { | k , v | [ camelize ( k . to_s ) , v ] } ] end
camel - case the keys of a + Hash +
15,026
def apply_namespace ( qname , apply_prefix , apply_uri ) local_part , prefix , uri = qname if ! prefix prefix = apply_prefix uri = apply_uri end [ local_part , prefix , uri ] . compact end
given an exploded qname apply a given namespace and uri if the qname has no namespace already
15,027
def camelize_qname ( qname ) local_part , prefix , uri = qname [ camelize ( local_part ) , prefix , uri ] . compact end
given an exploded qname camelize the local_part
15,028
def with_error_check ( client , * response_msg_keys ) raise "no block" if ! block_given? begin response = yield hash_response = response . to_hash statuses = hash_response . fetch_in ( * response_msg_keys ) if statuses . is_a? ( Array ) all_statuses = statuses else all_statuses = [ statuses ] end errors = all_statuses ...
check the response codes of an Exchange Web Services request . the supplied block makes a SOAP request and the response is parsed out and checked
15,029
def single_error_check ( client , status ) begin response_class = status [ :response_class ] rescue raise "no response_class found: #{status.inspect}" if ! response_class end if status [ :response_class ] == "Error" return "#{status[:response_code]} - #{status[:message_text]}" elsif status [ :response_class ] == "Warni...
check the status of the response of a single part of a multi - part request
15,030
def fetch_on ( arg , & bl ) unless arg . respond_to? ( :fetch ) raise ArgumentError , "Object responding to `fetch` expected" end arg . fetch ( name ) do arg . fetch ( name . to_s , & bl ) end end
Fetch the attribute on arg which is expected to be a Hash object .
15,031
def sentences ( total ) list = [ ] total . times do word_count = rand ( word_count_range_in_a_sentence ) sentence_len = word_count . times . inject ( 0 ) { | sum | sum + rand ( char_count_range_in_a_word ) } sentence_key = bsearch ( sentence_map_keys , sentence_len ) unless sentence_key sentence_key = sentence_map . ke...
return rondom sentences from word resource
15,032
def set_property ( property , value ) cmd = [ "SET" , self . class . object_name , id , property , value ] . compact . join ( " " ) Skyper :: Skype . send_command ( cmd ) end
Invokes SET command for a given object with id property and value
15,033
def subtype ( super_type , constraints = nil , name = nil , metadata = nil , & bl ) super_type = type ( super_type ) constraints = constraints ( constraints , & bl ) name = name ( name ) meta = metadata ( metadata ) SubType . new ( super_type , constraints , name , metadata ) end
Sub and union
15,034
def tuple ( heading , name = nil , metadata = nil ) heading = heading ( heading ) name = name ( name ) meta = metadata ( metadata ) TupleType . new ( heading , name , meta ) end
Tuples and relations
15,035
def image ( size , options = { } ) domain = options [ :domain ] || 'http://placehold.it' src = "#{domain}/#{size}" hex = %w( a b c d e f 0 1 2 3 4 5 6 7 8 9 ) background_color = options [ :background_color ] color = options [ :color ] if options [ :random_color ] background_color = hex . shuffle [ 0 ... 6 ] . join colo...
Get a placeholder image using placehold . it by default
15,036
def save raise ArgumentError . new ( "Account is missing." ) unless account account . require_secret hash = { } hash [ "settings" ] = to_hash hash [ "secret" ] = account . secret RippleRest . post "v1/accounts/#{account.address}/settings" , hash end
Save the account settings
15,037
def submit @account . require_secret hash = { } hash [ "payment" ] = self . to_hash hash [ "secret" ] = @account . secret hash [ "client_resource_id" ] = client_resource_id = RippleRest . next_uuid source_account = self . to_hash [ :source_account ] RippleRest . post ( "v1/accounts/#{source_account}/payments" , hash ) ...
Submits a payment
15,038
def read_items ( client , items ) return [ ] if ! items items . map do | item_class , items_of_class | items_of_class = [ items_of_class ] if ! items_of_class . is_a? ( Array ) items_of_class . map do | item | Item . new ( client , item_class , item ) end end . flatten end
return a list of Item objects given a hash formed from an Items element
15,039
def read_get_item_response_messages ( client , get_item_response_messages ) get_item_response_messages = [ get_item_response_messages ] if ! get_item_response_messages . is_a? ( Array ) items = get_item_response_messages . map do | girm | read_items ( client , girm [ :items ] ) end . flatten end
return a list of Item objects from a list of GetItemResponseMessages
15,040
def most_similar ( value , threshold = 0.5 ) @white ||= Text :: WhiteSimilarity . new result = @map . max_by { | str , _ | @white . similarity ( value , str ) } return result [ 1 ] if @white . similarity ( value , result . first ) > threshold nil end
Performs White Similarity comparison against the keys and gives the value of the closest match .
15,041
def index ( options = { } , & block ) respond_with ( collection , options , & block ) if stale? ( collection , last_modified : collection . maximum ( :updated_at ) ) end
index action this set a collection of objects to an instance variable which can be accessed from the view using the collection helper method . The instance variable name is a pluralization of the model name defined in the restful macro .
15,042
def create ( options = { } , & block ) object = get_resource_ivar || create_resource options [ :location ] = collection_path if object . errors . empty? respond_with_dual ( object , options , & block ) end
create action creates a new object off the received params and sets an instance variable if record is saved then a redirect to index action is made .
15,043
def enumerate_records ( xml ) doc = Nokogiri :: XML ( xml ) doc . root . add_namespace_definition ( 'nmbib' , PRIMO_NS ) doc . xpath ( '//sear:DOC' ) . lazy . map do | record | identifier = record . xpath ( './nmbib:PrimoNMBib/nmbib:record/' 'nmbib:control/nmbib:recordid' ) . first . text record = record . dup record ....
Extract a page s worth of records from a Primo XML search result .
15,044
def sortable_fields_for ( model ) if model . respond_to? ( :sortable_fields ) model . sortable_fields . map ( & :to_sym ) elsif model . respond_to? ( :column_names ) model . column_names . map ( & :to_sym ) else [ ] end end
Overridable method for available sortable fields
15,045
def filterable_fields_for ( model ) if model . respond_to? ( :filterable_fields ) model . filterable_fields . map ( & :to_sym ) elsif model . respond_to? ( :column_names ) model . column_names . map ( & :to_sym ) else [ ] end end
Overridable method for available filterable fields
15,046
def status_report ( checkers ) format , format_length = status_report_format ( checkers ) header = status_report_header ( format ) length = [ format_length , header . length ] . max separator = ( '-' * length ) + "\n" result = separator + header + separator checkers . each { | checker | result << checker . to_s ( forma...
Constructs a text status report
15,047
def status_report_format ( checkers ) name_max = status_report_format_max_length ( checkers , :name ) value_max = status_report_format_max_length ( checkers , :value ) status_max = status_report_format_max_length ( checkers , :status ) format = "%#{name_max}s | %#{value_max}s | %#{status_max}s\n" length = name_max + 3 ...
Generate a format string to justify all values
15,048
def status_report_header ( format = StatusCat :: Checkers :: Base :: FORMAT ) name = I18n . t ( :name , scope : :status_cat ) value = I18n . t ( :value , scope : :status_cat ) status = I18n . t ( :status , scope : :status_cat ) return format ( format , name , value , status ) end
Generate a header string
15,049
def extract_month_from_xml_element ( element ) month = element . xpath ( 'date/month' ) . text . to_i year = element . xpath ( 'date/year' ) . text . to_i [ year , month ] end
Extracts the year and month from the given XML element .
15,050
def extract_date_from_xml_element ( element ) day = element . xpath ( 'date/day' ) . text . to_i year , month = extract_month_from_xml_element ( element ) Date . new ( year , month , day ) end
Extracts the date from the given XML element .
15,051
def extract_datetime_from_xml_element ( element ) date = extract_date_from_xml_element ( element ) hour = element . xpath ( 'time/hour' ) . text . to_i minute = element . xpath ( 'time/minute' ) . text . to_i offset = Time . now . strftime ( '%:z' ) Time . new ( date . year , date . month , date . day , hour , minute ,...
Extracts the date and time from the given XML element .
15,052
def extract_transmitted_bytes_from_xml_element ( element ) bytes_received = element . xpath ( 'rx' ) . text . to_i * 1024 bytes_sent = element . xpath ( 'tx' ) . text . to_i * 1024 [ bytes_received , bytes_sent ] end
Extracts the bytes received and sent from the given XML element .
15,053
def tandem_navigation_tag ( active_page , pages_collection = nil , html_options = { } ) html_options , pages_collection = pages_collection , nil if pages_collection . is_a? ( Hash ) html_options [ :class ] ||= 'nav' page_groups = ( pages_collection || Page . all ) . inject ( { } ) do | groups , page | if groups [ page ...
todo ... document this
15,054
def get ( path , params = { } ) uri = path if params . count > 0 uri += "?#{URI.encode_www_form(params)}" end headers = { } request ( 'GET' , uri , nil , headers ) do | resp | if params [ :fetch_all ] == true && resp . body . has_key? ( 'pagination' ) && resp . body [ 'pagination' ] [ 'next_uri' ] != nil params [ :star...
HTTP GET method
15,055
def put ( path , params ) headers = { } request ( 'PUT' , path , params . to_json , headers ) do | resp | yield ( resp ) if block_given? end end
HTTP PUT method
15,056
def post ( path , params ) headers = { } request ( 'POST' , path , params . to_json , headers ) do | resp | yield ( resp ) if block_given? end end
HTTP POST method
15,057
def delete ( path , params ) headers = { } request ( 'DELETE' , path , nil , headers ) do | resp | yield ( resp ) if block_given? end end
HTTP DELETE method
15,058
def charts_slug_get ( slug , opts = { } ) data , _status_code , _headers = charts_slug_get_with_http_info ( slug , opts ) return data end
Chart A Chart is chosen by Pollster editors . One example is \ Obama job approval - Democrats \ . It is always based upon a single Question . Users should strongly consider basing their analysis on Questions instead . Charts are derived data ; Pollster editors publish them and change them as editorial priorities change...
15,059
def polls_slug_get ( slug , opts = { } ) data , _status_code , _headers = polls_slug_get_with_http_info ( slug , opts ) return data end
Poll A Poll on Pollster is a collection of questions and responses published by a reputable survey house . This endpoint provides raw data from the survey house plus Pollster - provided metadata about each question . Pollster editors don t include every question when they enter Polls and they don t necessarily enter ev...
15,060
def exchange_rate url = "/currencyconverter/convert/?Amount=1&From=#{from_currency.to_s.upcase}&To=#{to_currency.to_s.upcase}" uri = URI . parse ( 'https://www.xe.com' ) request = Net :: HTTP . new ( uri . host , uri . port ) request . use_ssl = true response = request . get ( url ) doc = Nokogiri :: HTML ( response . ...
Returns the Float value of rate or nil
15,061
def log ( priority , msg ) @logger . tagged ( Time . now . to_s , Process . pid , to_s ) do @logger . send ( priority , msg ) end end
Log a message tagged for application - wide consistency
15,062
def to_WGS84 if @type == :ie @a = 6377340.189 @b = 6356034.447 else @a = 6377563.396 @b = 6356256.909 end @eSquared = ( ( @a * @a ) - ( @b * @b ) ) / ( @a * @a ) @phi = deg_to_rad ( @latitude ) @lambda = deg_to_rad ( @longitude ) @v = @a / ( Math . sqrt ( 1 - @eSquared * sin_pow_2 ( @phi ) ) ) @H = 0 @x = ( @v + @H ) *...
Takes OSGB36 or TM75 Latitude and Longitude coords and returns WGS84 Latitude and Longitude
15,063
def populate_timespan ( timespan ) return timespan unless ( timespan . begin . empty? || timespan . end . empty? ) && ! timespan . providedLabel . empty? parsed = parse_labels ( timespan . providedLabel ) return timespan if parsed . empty? parsed . each do | date | begin_date , end_date = span_from_date ( date ) timesp...
Populates a timespan with a begin and end date .
15,064
def span_from_date ( date ) return [ nil , nil ] if date . nil? if date . is_a? ( Date ) return [ date , date ] if date . precision == :day return [ date , ( date . succ - 1 ) ] end [ ( date . respond_to? ( :first ) ? date . first : date . from ) , ( date . respond_to? ( :last ) ? date . last : date . to ) ] end
Converts an EDTF date to a begin and end date .
15,065
def reduce_to_largest_span ( timespan ) timespan . begin = timespan . begin . sort . first timespan . end = timespan . end . sort . last timespan end
Reduces a timespan with multiple begin or end dates to a single earliest begin date and a single latest end date .
15,066
def run if block_given? update_attribute ( :end_time , nil ) if ended? Krikri :: Logger . log ( :info , "Activity #{agent.constantize}-#{id} is running" ) set_start_time begin yield agent_instance , rdf_subject rescue => e Krikri :: Logger . log ( :error , "Error performing Activity: #{id}\n" "#{e.message}\n#{e.backtra...
Runs the block setting the start and end time of the run . The given block is passed an instance of the agent and a URI representing this Activity .
15,067
def close_connection if connected? get . connect . close . call else return false end rescue Emailvision :: Exception => e ensure invalidate_token! not connected? end
Logout from Emailvision API
15,068
def call ( command , params ) @command = command request = Net :: HTTP :: Get . new ( uri . request_uri + "?" + params ) response = http . request ( request ) Response . new ( response . body , response ) end
Make the actual call to the prowl api
15,069
def aggregation agg = DPLA :: MAP :: Aggregation . new ( id ) return nil unless agg . exists? agg . get agg end
Get the aggregation populated with data from Marmotta which corresponds to this SearchIndexDocument
15,070
def find_inheritable_template_folder ( view_context , name , partial , formats , param = nil ) find_inheritable_template_folder_cached ( view_context , name , partial , formats , param ) do find_inheritable_artifact ( param ) do | folder | view_context . template_exists? ( name , folder , partial ) end end end
Performs a lookup for the given filename and returns the most specific folder that contains the file .
15,071
def inheritance_lookup_path path = [ self ] until path . last == inheritable_root_controller path << path . last . superclass end path . collect ( & :controller_path ) end
The inheritance path of controllers that is used as default lookup path .
15,072
def find_inheritable_template_folder_cached ( view_context , name , partial , formats , param = nil ) prefix = inheritable_cache_get ( formats , name , partial , param ) return prefix if prefix prefix = yield if prefix template = view_context . find_template_without_lookup ( name , prefix , partial ) inheritable_cache_...
Performs a lookup for a template folder using the cache .
15,073
def inheritable_cache @inheritable_cache ||= Hash . new do | h1 , k1 | Hash . new do | h2 , k2 | Hash . new do | h3 , k3 | Hash . new end end end end
A simple template lookup cache for each controller .
15,074
def inheritable_cache_get ( formats , name , partial , param ) prefixes = formats . collect { | format | inheritable_cache [ format . to_sym ] [ partial ] [ name ] [ param ] } prefixes . compact! prefixes . empty? ? nil : prefixes . first end
Gets the prefix from the cache . Returns nil if it s not there yet .
15,075
def inheritable_cache_set ( formats , name , partial , param , prefix ) formats . each do | format | inheritable_cache [ format . to_sym ] = hf = inheritable_cache [ format . to_sym ] hf [ partial ] = hp = hf [ partial ] hp [ name ] = hn = hp [ name ] hn [ param ] = prefix end end
Stores the found prefix in the cache .
15,076
def find_template_with_lookup ( name , prefix = nil , partial = false ) if prefix == controller_path folder = controller . find_inheritable_template_folder ( name , partial ) prefix = folder if folder end find_template_without_lookup ( name , prefix , partial ) end
Perform a template lookup if the prefix corresponds to the current controller s path .
15,077
def add ( name , value , created_on ) meter = fetch ( name , nil ) return cache ( name , value , created_on ) unless meter if meter . created_on != created_on flush ( name ) cache ( name , value , created_on ) return end meter . value += value flush ( name ) if meter . expired? end
Adds the given value to the hash Flushes expired data to DB
15,078
def cache ( name , value , created_on ) meter = Meter . new ( name : name , value : value , created_on : created_on , created_at : Time . now ) store ( name , meter ) end
Creates a new Meter and stores is in the hash
15,079
def add_child ( name , opts = { } , & block ) delete_property ( name ) properties << ChildDeclaration . new ( name , opts . delete ( :class ) , opts , & block ) end
Add a ChildDeclaration to this mapping
15,080
def add_property ( name , value = nil , & block ) delete_property ( name ) properties << PropertyDeclaration . new ( name , value , & block ) end
Add a PropertyDeclaration to this mapping
15,081
def to_bytes ( ) packer = Packer . new ( ) full_flags = ( ( @qr << 15 ) & 0x8000 ) | ( ( @opcode << 11 ) & 0x7800 ) | ( ( @flags << 7 ) & 0x0780 ) | ( ( @rcode << 0 ) & 0x000F ) packer . pack ( 'nnnnnn' , @trn_id , full_flags , @questions . length ( ) , @answers . length ( ) , 0 , 0 , ) questions . each do | q | q . pa...
Serialize the packet to an array of bytes .
15,082
def get_results ( resource , method ) http = Net :: HTTP . new ( "api.espn.com" ) request = Net :: HTTP :: Get . new ( "/#{EspnRb::API_VERSION}#{resource}#{method}?apikey=#{@api_key}" ) HeadlineResponse . new JSON . parse ( http . request ( request ) . body ) end
The final request to ESPN api after all option parsing has been completed .
15,083
def parse ( date_str , allow_interval = false ) str = preprocess ( date_str . dup ) date = parse_interval ( str ) if allow_interval date ||= parse_m_d_y ( str ) date ||= Date . edtf ( str . gsub ( '.' , '-' ) ) date ||= partial_edtf ( str ) date ||= decade_hyphen ( str ) date ||= month_year ( str ) date ||= decade_s ( ...
Attempts to parse a string into a valid EDTF or Date format .
15,084
def range_match ( str ) str = str . gsub ( 'to' , '-' ) . gsub ( 'until' , '-' ) regexp = %r{ \s \d \- \/ \. \? \~ \s \d \d \- \d \- \. \? \~ \s \. \s \s \d \- \/ \. \? \~ \s \d \d \- \d \- \. \? \~ }x regexp . match ( str ) do | m | [ m [ 1 ] , m [ 2 ] ] end end
Matches a wide variety of date ranges separated by .. or -
15,085
def preprocess ( str ) str . gsub! ( / /i , '' ) str . gsub! ( / /i , '' ) str . strip! str . gsub! ( / \s / , ' ' ) str . gsub! ( '0s' , 'x' ) if str . match ( / / ) str . gsub! ( '-' , 'x' ) if str . match ( / \- / ) str end
Preprocess the date string to remove extra whitespace and convert ad hoc formatting to equivalent EDTF .
15,086
def circa ( str ) run = str . gsub! ( / \. /i , '' ) run ||= str . gsub! ( / /i , '' ) date = parse ( str ) if run return nil if date . nil? if date . respond_to? :uncertain! date . uncertain! elsif date . is_a? EDTF :: Interval date . from = date . from . uncertain! if date . from . respond_to? :uncertain! date . to =...
Remove circa or about or variations and return an uncertian ETDF dates .
15,087
def execute ( force = false ) return false if executed? && ! force evaluate_recipes transaction = apply rescue Exception => e false else not transaction . any_failed? ensure @executed = true end
Execute this manifest applying all resources defined . Execute returns true if successfull and false if unsucessfull . By default this will only execute a manifest that has not already been executed? . The + force + argument if true removes this check .
15,088
def execute! ( force = false ) return false if executed? && ! force evaluate_recipes transaction = apply rescue Exception => e raise e else not transaction . any_failed? ensure @executed = true end
Execute this manifest applying all resources defined . Execute returns true if successfull and raises an exception if not . By default this will only execute a manifest that has not already been executed? . The + force + argument if true removes this check .
15,089
def evaluate_recipes self . class . recipes . each do | meth , args | case arity = method ( meth ) . arity when 1 , - 1 send ( meth , args ) else send ( meth ) end end end
Evaluate the methods calls queued in self . recipes
15,090
def reference ( type , title , params = { } ) Puppet :: Resource . new ( type . name . to_s . capitalize , title . to_s ) end
Create a reference to another Puppet Resource .
15,091
def add_resource ( type , title , params = { } ) catalog . add_resource ( new_resource ( type , title , params ) ) end
Creates a new Puppet Resource and adds it to the Catalog .
15,092
def index @current_provider = params [ :provider ] report = Krikri :: ValidationReport . new report . provider_id = @current_provider @validation_reports = report . all if @current_provider @provider = Krikri :: Provider . find ( @current_provider ) @qa_reports = Array ( Krikri :: QAReport . find_by ( provider : @curre...
Renders the index view giving
15,093
def attributes_for_request ( * ) attributes = filled_attributes . dup billing = attributes . delete ( :billing ) attributes . merge! ( billing . attributes_for_request ) if billing shipping = attributes . delete ( :shipping ) attributes . merge! ( shipping . attributes_for_request ) if shipping super ( attributes ) end
Overloaded method to return all the attributes from the sale + billing + shipping objects .
15,094
def revoke! ( cakey = nil , crl = nil , next_update = 36000 ) if cakey . nil? fail EasyRSA :: Revoke :: MissingCARootKey , 'Please provide the root CA cert for the CRL' end unless cakey . is_a? OpenSSL :: PKey :: RSA if cakey . include? ( 'BEGIN RSA PRIVATE KEY' ) cakey = OpenSSL :: PKey :: RSA . new cakey else begin c...
Lets get revoking
15,095
def with_return_type ( value ) if value . nil? && allow_nil? if allow_nil? nil else raise ArgumentError , "Cannot return `nil` without allow_nil: true" end elsif @return_type == :symbol value . to_sym elsif @return_type == :string value . to_s end end
Ensure the value is returned with the correct type
15,096
def valid_fallback? ( fallback ) return true if fallback . nil? && allow_nil? return true if include? fallback false end
Check if the provided fallback is valid
15,097
def set_default ( fallback ) if valid_fallback? ( fallback ) || fallback == NO_DEFAULT @default = fallback else raise InvalidFallback , "Cannot set #{fallback.inspect} as default" , caller end end
Set the default fallback value .
15,098
def gc_statistics ( * args ) options = Rails . application . config . active_profiling . gc_statistics . merge ( args . extract_options! ) result , gc_report = gc_statistics_report ( options ) do yield end ActiveSupport :: Notifications . instrument ( 'gc_statistics.active_profiling' , { :report => gc_report , :title =...
Profiles a block capturing information on the garbage collector . The return value is an Array containing the result of the yielded block and a String with a report on the profiling results .
15,099
def process_request ( control , sym , args ) instance = factory . call ( control ) instance . send ( sym , * args ) end
Processes exactly one request but doesn t define how the request gets here .