idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
22,600
def sitemap_attributes ( key = :default ) key = key . blank? ? :default : key . to_sym unless self . class . sitemap_attributes [ key ] . kind_of? ( Hash ) key = :default end return self . class . sitemap_attributes [ key ] end
Returns a Hash associated with a key . The Hash represents all of the attributes for a given action name on a controller .
22,601
def hcat ( y ) unless self . dims [ 0 ] == y . dims [ 0 ] raise ArgumentError , "Matrices must have same number of rows" end DoubleMatrix . concat_horizontally ( self , y ) end
Return a new matrix which consists of the _self_ and _y_ side by side . In general the hcat method should be used sparingly as it creates a new matrix and copies everything on each use . You should always ask yourself if an array of vectors or matrices doesn t serve you better . That said you _can_ do funny things with + inject + . For example
22,602
def vcat ( y ) unless self . dims [ 1 ] == y . dims [ 1 ] raise ArgumentError , "Matrices must have same number of columns" end DoubleMatrix . concat_vertically ( self , y ) end
Return a new matrix which consists of the _self_ on top of _y_ . In general the hcat methods should be used sparingly . You should always ask yourself if an array of vectors or matrices doesn t serve you better . See also hcat .
22,603
def arguments ( value ) case value when true [ @flag ] when false , nil [ ] else value = super ( value ) if @multiple args = [ ] value . each do | arg | args += Array ( @formatter . call ( self , [ arg ] ) ) end return args else value = [ value . join ( @separator ) ] if @separator return Array ( @formatter . call ( self , value ) ) end end end
Creates a new Option object with . If a block is given it will be used for the custom formatting of the option . If a block is not given the option will use the default_format when generating the arguments .
22,604
def close return if sessions . empty? sessions . each do | session | session . close session . delete_observer self end end
Closes all sessions .
22,605
def get_json ( url ) r = Mei :: WebServiceBase . fetch ( url ) JSON . parse ( r . body ) end
mix - in to retreive and parse JSON content from the web
22,606
def creator = ( creator ) @creator = creator . is_a? ( Hash ) ? Logan :: Person . new ( creator ) : creator end
sets the creator for this todo
22,607
def assignee = ( assignee ) @assignee = assignee . is_a? ( Hash ) ? Logan :: Person . new ( assignee ) : assignee end
sets the assignee for this todo
22,608
def create_comment ( comment ) post_params = { :body => comment . post_json , :headers => Logan :: Client . headers . merge ( { 'Content-Type' => 'application/json' } ) } response = Logan :: Client . post "/projects/#{@project_id}/todos/#{@id}/comments.json" , post_params Logan :: Comment . new response end
create a create in this todo list via the Basecamp API
22,609
def today_transcript ( & callback ) connection . http ( :get , "/room/#{id}/transcript.json" ) do | data , http | callback . call ( data [ :messages ] . map { | msg | Firering :: Message . instantiate ( connection , msg ) } ) if callback end end
Returns all the messages sent today to a room .
22,610
def transcript ( year , month , day , & callback ) connection . http ( :get , "/room/#{id}/transcript/#{year}/#{month}/#{day}.json" ) do | data , http | callback . call ( data [ :messages ] . map { | msg | Firering :: Message . instantiate ( connection , msg ) } ) if callback end end
Returns all the messages sent on a specific date to a room .
22,611
def speak ( data , & callback ) connection . http ( :post , "/room/#{id}/speak.json" , "message" => data ) do | data , http | callback . call ( Firering :: Message . instantiate ( connection , data , "message" ) ) if callback end end
Sends a new message with the currently authenticated user as the sender . The XML for the new message is returned on a successful request .
22,612
def ensure_valid_emotion_name unless Emotions . emotions . include? ( emotion . try ( :to_sym ) ) errors . add :emotion , I18n . t ( :invalid , scope : [ :errors , :messages ] ) end end
Make sure we re using an allowed emotion name
22,613
def of number raise_on_type_mismatch number digits = convert_number_to_digits ( number ) [ 0 .. 9 ] sum = digits . reverse_each . with_index . reduce ( 0 ) do | check , ( digit , idx ) | check += digit * ( idx + 2 ) end check = ( 11 - sum % 11 ) % 11 check == 10 ? "X" : check end
Calculates ISBN - 10 checksum
22,614
def valid? number raise_on_type_mismatch number num , check = split_isbn_number ( number ) convert_number_to_digits ( num ) . length == 9 && self . of ( num ) == check end
ISBN - 10 validation of provided number
22,615
def convert number raise_on_type_mismatch number check = self . of ( number ) if number . is_a? ( String ) or check . is_a? ( String ) number . to_s << self . of ( number ) . to_s else convert_to_int ( number ) * 10 + self . of ( number ) end end
Transforms a number by appending the ISBN - 10 checksum digit
22,616
def api_call ( method , path , params = { } , & proc ) if cache = caching? && ( @cache [ cache_key ( path , params ) ] ) return cache else if @logging Calculated :: Logging . log_calculated_api ( method , path , params ) do api_call_without_logging ( method , path , params , & proc ) end else api_call_without_logging ( method , path , params , & proc ) end end end
if we caching and we have the same cache lets try and get the cache ; otherwise we will make the request logging if need be
22,617
def split_parts_and_interval ( expression_str ) interval = nil parts = expression_str . split ( / / ) . map do | part | part , part_interval = part . split ( '/' ) interval = part_interval unless part_interval . blank? next nil if part . blank? || part == '*' part end [ parts , interval ] end
Split a cron string and extract the LAST interval that appears
22,618
def string_to_expression_parts ( expression_str ) return { } if expression_str . nil? parts , interval = split_parts_and_interval ( expression_str ) expression_parts = :: Hash [ EXPRESSION_PART_KEYS . zip ( parts ) ] expression_parts . select! do | _key , value | ! value . nil? end expression_parts [ :interval ] = interval unless interval . nil? expression_parts end
Split string expression into parts
22,619
def parse ( scanner , rules , scope = ParserScope . empty ) pos = scanner . pos result = ( child . parse ( scanner , rules , scope ) && true ) scanner . pos = pos result end
Succeed or fail like the decorated parser but do not consume any input and return + true + on success .
22,620
def post_link_hook ( linker , bb ) basic_name = get_basic_name ( linker , bb ) symlink_lib_to ( basic_name , bb ) end
Some symbolic links ln - s foo . dylib foo . A . dylib
22,621
def transaction_list ( start = ( Time . now - 24 . hours ) , stop = Time . now , msisdn = nil , destination = nil , code = nil ) @params = { stop_date : to_yyyymmdd ( stop ) , start_date : to_yyyymmdd ( start ) } code && ! code . empty? && @params [ :code ] = code msisdn && ! msisdn . empty? && @params [ :msisdn ] = msisdn destination && ! destination . empty? && @params [ :destination_msisdn ] = destination run_action :trans_list end
This method is used to retrieve the list of transactions performed within the date range by the MSISDN if set . Note that both dates are included during the search .
22,622
def detach_volume ( volume_id ) volume = ProfitBricks :: Volume . get ( datacenterId , nil , volume_id ) volume . detach ( id ) end
Detach volume from server .
22,623
def sitemap_setup ( options = { } ) rows = [ ] DuckMap . logger . debug "sitemap_setup: action_name => #{options[:action_name]} source => #{options[:source]} model => #{options[:model]}" attributes = self . sitemap_attributes ( options [ :action_name ] ) DuckMap . logger . debug "sitemap_setup: attributes => #{attributes}" if attributes . kind_of? ( Hash ) && attributes [ :handler ] . kind_of? ( Hash ) && ! attributes [ :handler ] [ :action_name ] . blank? config = { handler : attributes [ :handler ] } . merge ( options ) rows = self . send ( attributes [ :handler ] [ :action_name ] , config ) end return rows end
Determines all of the attributes defined for a controller then calls the handler method on the controller to generate and return an Array of Hashes representing all of the url nodes to be included in the sitemap for the current route being processed .
22,624
def run show_result @parser_class . parse! ( ARGF . read ) rescue Rattler :: Runtime :: SyntaxError => e puts e end
Create a new command line interface for the given parser class
22,625
def patch ( name ) raise ConfigurationError , "patch_dir has not been set" if patch_dir . nil? raise ConfigurationError , "patch_dir is not a directory" unless Dir . exist? ( patch_dir ) Patch . from_yaml File . join ( patch_dir , "#{name}.yml" ) end
Loads a patch from the patch_dir
22,626
def run if result = analyze synthesize ( result ) else puts parser . failure exit ERRNO_PARSE_ERROR end end
Create a new command - line parser .
22,627
def get_dewpoints ( start_date , end_date , location ) response = get_planner_response ( start_date , end_date , location ) return response [ 'response' ] [ 'error' ] unless response [ 'response' ] [ 'error' ] . nil? highs = response [ 'trip' ] [ 'dewpoint_high' ] lows = response [ 'trip' ] [ 'dewpoint_low' ] { high : { imperial : { minimum : highs [ 'min' ] [ 'F' ] . to_i , maximum : highs [ 'max' ] [ 'F' ] . to_i , average : highs [ 'avg' ] [ 'F' ] . to_i } , metric : { minimum : highs [ 'min' ] [ 'C' ] . to_i , maximum : highs [ 'max' ] [ 'C' ] . to_i , average : highs [ 'avg' ] [ 'C' ] . to_i } } , low : { imperial : { minimum : lows [ 'min' ] [ 'F' ] . to_i , maximum : lows [ 'max' ] [ 'F' ] . to_i , average : lows [ 'avg' ] [ 'F' ] . to_i } , metric : { minimum : lows [ 'min' ] [ 'C' ] . to_i , maximum : lows [ 'max' ] [ 'C' ] . to_i , average : lows [ 'avg' ] [ 'C' ] . to_i } } } end
Gets the dewpoint highs and lows for the date range .
22,628
def get_planner_response ( start_date , end_date , location ) start = start_date . strftime ( '%m%d' ) final = end_date . strftime ( '%m%d' ) get ( "planner_#{start}#{final}" , location ) end
Gets the full planner API response .
22,629
def hash_key_path ( hash , * path ) result = nil path . each do | key | return nil unless hash . respond_to? :" " result = hash = hash [ key ] end return result end
A utility method that lets you access a nested hash returning nil if any intermediate hashes are unavailable .
22,630
def options VALID_OPTION_KEYS . inject ( { } ) do | option , key | option . merge! ( key => send ( key ) ) end end
Create a hash of options and their values .
22,631
def create_project ( name , description = nil ) post_params = { :body => { name : name , description : description } . to_json , :headers => Logan :: Client . headers . merge ( { 'Content-Type' => 'application/json' } ) } response = Logan :: Client . post "/project_templates/#{@id}/projects.json" , post_params Logan :: Project . new response end
create a project based on this project template via Basecamp API
22,632
def log_level ( value , options = { } ) DuckMap :: Logger . log_level = value if options . has_key? ( :full ) DuckMap . logger . full_exception = options [ :full ] end end
Sets the logging level .
22,633
def leading_non_options args = [ ] @options . each do | name , value | non_opt = get_non_option ( name ) if ( non_opt && non_opt . leading? ) args += non_opt . arguments ( value ) end end @subtasks . each_value do | task | args += task . leading_non_options end return args end
Generates the command - line arguments for all leading non - options .
22,634
def options args = [ ] @subtasks . each_value do | task | args += task . arguments end @options . each do | name , value | opt = get_option ( name ) args += opt . arguments ( value ) if opt end return args end
Generates the command - line arguments from all options .
22,635
def tailing_non_options args = [ ] @subtasks . each_value do | task | args += task . tailing_non_options end @options . each do | name , value | non_opt = get_non_option ( name ) if ( non_opt && non_opt . tailing? ) args += non_opt . arguments ( value ) end end return args end
Generates the command - line arguments from all tailing non - options .
22,636
def arguments tailing_args = tailing_non_options if tailing_args . any? { | arg | arg [ 0 , 1 ] == '-' } tailing_args . unshift ( '--' ) end return leading_non_options + options + tailing_args end
Generates the command - line arguments from the task .
22,637
def deep_apply ( parser , context ) parser = apply ( parser , context ) apply ( parser . map_children { | child | deep_apply ( child , child_context ( parser , context ) ) } , context ) end
Apply the optimzations to + parser + s children then to + parser + in + context + .
22,638
def parse ( scanner , rules , scope = ParserScope . empty ) for child in children if r = child . parse ( scanner , rules , scope ) return r end end false end
Try each parser in order until one succeeds and return that result .
22,639
def compress ( files , verbose = false ) if files . any? { | f | ! File . file? ( f ) } raise ArgumentError , "Files supplied must all be real, actual files -- not directories or symlinks." end configure_archive compress_files ( files , verbose ) free_archive end
Create a new Compress object . Takes a filename as string and args as hash .
22,640
def do_POST ( req , resp ) path = req . path [ 1 .. - 1 ] . split ( '/' ) resp [ 'Cache-Control' ] = 'no-cache, no-store' resp [ 'Pragma' ] = 'no-cache' resp [ 'Expires' ] = '-1' response_class = CfRestService . const_get 'CfRestService' raise "#{response_class} not a Class" unless response_class . is_a? ( Class ) raise HTTPStatus :: NotFound unless path [ 1 ] response_method = path [ 1 ] . to_sym raise HTTPStatus :: NotFound unless response_class . respond_to? response_method if :sync == response_method resp . body = response_class . send response_method , req , resp , @cf end if :knock == response_method resp . body = response_class . send response_method , req , resp , @cf end if path . length > 2 resp . body = response_class . send response_method , req , resp , @cf , path [ 1 .. - 1 ] else resp . body = response_class . send response_method , req , resp , @cf end raise HTTPStatus :: OK end
Initializer to construct a new CfApiServlet object .
22,641
def update! ( ** kwords ) kwords = kwords . map { | k , v | [ k . to_s . capitalize , v ] } . to_h response = @connection . send ( :put , "/snapshots/#{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
Updates this snapshot
22,642
def diff ( other_snapshot ) endpoint = "/snapshots/#{self.Name}/diff/#{other_snapshot.Name}" response = @connection . send ( :get , endpoint ) JSON . parse ( response . body ) end
Find differences between this and another snapshot
22,643
def git_root_till_home Pathname . new ( Dir . pwd ) . ascend do | dir_pathname | return dir_pathname if File . directory? ( "#{dir_pathname}/.git" ) return nil if dir_pathname . to_s == home_dir end end
ascend from the current dir till I find a . git folder or reach home_dir
22,644
def node_properties collection = connection [ node_properties_collection ] result = { } collection . find . batch_size ( 999 ) . each do | values | id = values . delete ( '_id' ) result [ id ] = values end result end
initialize access to mongodb
22,645
def all_nodes collection = connection [ nodes_collection ] collection . find . batch_size ( 999 ) . projection ( _id : 1 ) . map { | k | k [ :_id ] } end
get all node names
22,646
def query_nodes ( query ) collection = connection [ nodes_collection ] collection . find ( query ) . batch_size ( 999 ) . projection ( _id : 1 ) . map { | k | k [ :_id ] } end
get node names that fulfill given mongodb query
22,647
def query_facts ( query , facts = [ ] ) fields = Hash [ facts . collect { | fact | [ fact . to_sym , 1 ] } ] collection = connection [ nodes_collection ] result = { } collection . find ( query ) . batch_size ( 999 ) . projection ( fields ) . each do | values | id = values . delete ( '_id' ) result [ id ] = values end result end
get nodes and their facts that fulfill given mongodb query
22,648
def query_facts_exist ( query , facts = [ ] ) result = query_facts ( query , facts ) unless facts . empty? result . keep_if do | _k , v | facts . any? { | f | ! v [ f ] . nil? } end end result end
get nodes and their facts that fulfill given mongodb query and have at least one value for one the given fact names
22,649
def search_facts ( query , pattern , facts = [ ] , facts_found = [ ] , check_names = false ) collection = connection [ nodes_collection ] result = { } collection . find ( query ) . batch_size ( 999 ) . each do | values | id = values . delete ( '_id' ) found = { } values . each do | k , v | if v =~ pattern found [ k ] = v elsif check_names && k =~ pattern found [ k ] = v end end next if found . empty? facts_found . concat ( found . keys ) . uniq! facts . each do | f | found [ f ] = values [ f ] end result [ id ] = found end result end
get nodes and their facts for a pattern
22,650
def single_node_facts ( node , facts ) fields = Hash [ facts . collect { | fact | [ fact . to_sym , 1 ] } ] collection = connection [ nodes_collection ] result = collection . find ( _id : node ) . limit ( 1 ) . batch_size ( 1 ) . projection ( fields ) . to_a . first result . delete ( "_id" ) if result result end
get facts for given node name
22,651
def meta collection = connection [ meta_collection ] result = collection . find . first result . delete ( :_id ) result end
get meta informations about updates
22,652
def node_update ( node , facts ) logger . debug " updating #{node}" connection [ nodes_collection ] . find ( _id : node ) . replace_one ( facts , upsert : true , bypass_document_validation : true , check_keys : false , validating_keys : false ) rescue :: Mongo :: Error :: OperationFailure => e logger . warn " updating #{node} failed with: #{e.message}" raise e unless e . message =~ / / || e . message =~ / / logger . warn " we transform the dots into underline characters" begin facts = Hash [ facts . map { | k , v | [ k . tr ( '.' , '_' ) , v ] } ] connection [ nodes_collection ] . find ( _id : node ) . replace_one ( facts , upsert : true , bypass_document_validation : true , check_keys : false , validating_keys : false ) rescue logger . error " inserting node #{node} failed again with: #{e.message}" end end
update or insert facts for given node name
22,653
def node_properties_update ( new_node_properties ) collection = connection [ node_properties_collection ] old_names = collection . find . batch_size ( 999 ) . projection ( _id : 1 ) . map { | k | k [ :_id ] } delete = old_names - new_node_properties . keys data = new_node_properties . map do | k , v | { replace_one : { filter : { _id : k } , replacement : v , upsert : true } } end collection . bulk_write ( data ) collection . delete_many ( _id : { '$in' => delete } ) end
update node properties
22,654
def meta_fact_update ( method , ts_begin , ts_end ) connection [ meta_collection ] . find_one_and_update ( { } , { '$set' => { last_fact_update : { ts_begin : ts_begin . iso8601 , ts_end : ts_end . iso8601 , method : method } , method => { ts_begin : ts_begin . iso8601 , ts_end : ts_end . iso8601 } } } , { upsert : true } ) end
update or insert timestamps for given fact update method
22,655
def meta_node_properties_update ( ts_begin , ts_end ) connection [ meta_collection ] . find_one_and_update ( { } , { '$set' => { last_node_properties_update : { ts_begin : ts_begin . iso8601 , ts_end : ts_end . iso8601 } } } , { upsert : true } ) @node_properties_update_timestamp = ts_begin end
update or insert timestamps for node_properties_update
22,656
def find_same_occurence selected = @candidates . select { | delim , count | begin CSV . parse ( @sample , col_sep : delim ) . select { | e | ! e . empty? } . map { | e | e . count } . uniq . count == 1 rescue Exception => ex false end } . keys return selected . first if selected . count == 1 return DEFAULT_DELIMITER if selected . include? ( DEFAULT_DELIMITER ) end
high confident level
22,657
def keys_required? keys = self . segment_keys . dup keys . delete ( :format ) return keys . length > 0 ? true : false end
Indicates if the current route requirements segments keys to generate a url .
22,658
def next_page raise Ork :: NoNextPage . new 'There is no next page' unless has_next_page? self . class . new ( @model , @index , @query , @options . merge ( continuation : keys . continuation ) ) end
Get a new ResultSet fetch for the next page
22,659
def threaded_run! ( files , change ) return if files . empty? file_number = 0 total_files = files . length mutex = Mutex . new threads = [ ] 5 . times do | i | threads [ i ] = Thread . new { until files . empty? mutex . synchronize do file_number += 1 Thread . current [ "file_number" ] = file_number end file = files . pop rescue nil next unless file Rails . logger . info "[#{Thread.current["file_number"]}/#{total_files}] to #{change}..." case change when 'destroy' when 'create' when 'update' end end } end threads . each { | t | t . join } end
todo improve speed
22,660
def intersperse ( enum , opts = { } ) sep = opts [ :sep ] newlines = opts [ :newlines ] || ( opts [ :newline ] ? 1 : 0 ) enum . each_with_index do | _ , i | if i > 0 self << sep if sep newlines . times { newline } end yield _ end self end
Add a separator or newlines or both in between code generated in the given block for each element in + enum + . Newlines are always added after the separator .
22,661
def get_status @result [ 'tracks' ] . collect { | track | track . name if track . failure? } . compact . count . zero? ? 'Success' : 'Failure' end
collect track status
22,662
def formatted_value ( value , format , width ) value_str = value ? format ( format , value ) : ' ' * width length = value_str . length if length > width value_str . slice ( 0 .. width - 1 ) elsif length < width ' ' * ( width - length ) + value_str else value_str end end
format the string using given format if the result is shorter than width pad space to the left if the result is longer than width truncate the last characters
22,663
def map! ( & block ) ( 0 ... length ) . each do | i | put ( i , block . call ( get ( i ) ) ) end self end
Map each element and store the result in the matrix .
22,664
def endpoint ( path ) normalized = normalize_path_info ( path ) fullpath = File . join ( @root , normalized ) endpoint = if FileTest . file? ( fullpath ) fullpath elsif needs_redirect_to_dir? ( fullpath ) :must_redirect elsif FileTest . file? ( fullpath_html = "#{fullpath}.html" ) fullpath_html else :not_found end endpoint end
Creates a Router for the given root directory . Returns the full file system path of the file corresponding to the given URL + path + or
22,665
def custom_404_body filename = File . join ( root , "404.html" ) File . exist? ( filename ) ? File . binread ( filename ) : nil end
Returns the body of the custom 404 page or + nil + if none exists .
22,666
def filter ( conditions ) if conditions conditions . each do | key , value | if self . respond_to? ( key ) self . send ( key , value ) end end end end
A convenience method that takes a hash where each key is the symbol of a method and each value is the parameters passed to that method .
22,667
def find_array_parents ( toc , title ) parents = '' toc . each do | item | if item . is_a? ( Hash ) parents = find_hash_parents ( item , title ) break unless parents . empty? end end parents end
Given a category file that s an array this method finds the parent of an item
22,668
def find_hash_parents ( toc , title ) parents = '' toc . each_key do | key | next if toc [ key ] . nil? toc [ key ] . each do | item | if item . is_a? ( Hash ) if item . keys . include? ( title ) parents = key break else if item [ item . keys . first ] . include? ( title ) parents = key break end end elsif title == item parents = key break end end break unless parents . empty? end parents end
Given a category file that s a hash this method finds the parent of an item
22,669
def find_array_children ( toc , title ) toc . each do | item | next unless item . is_a? ( Hash ) item . each_pair do | key , values | if key == title children = values . flatten return children end end end Array . new end
Given a category file that s an array this method finds the children of an item probably a map topic
22,670
def find_hash_children ( toc , title ) toc . each_key do | key | next if toc [ key ] . nil? toc [ key ] . each do | item | next unless item . is_a? ( Hash ) if item [ title ] children = item . values . flatten return children end end end Array . new end
Given a category file that s a hash this method finds the children of an item probably a map topic
22,671
def hatt_add_service ( name , url_or_svc_cfg_hash ) svc_cfg = case url_or_svc_cfg_hash when String { 'url' => url_or_svc_cfg_hash } when Hash url_or_svc_cfg_hash else raise ArgumentError , "'#{url_or_svc_cfg_hash}' is not a url string nor hash with url key" end init_config services_config = hatt_configuration [ 'hatt_services' ] services_config [ name ] = svc_cfg @hatt_configuration . tcfg_set 'hatt_services' , services_config @hatt_http_clients ||= { } @hatt_http_clients [ name ] = Hatt :: HTTP . new hatt_configuration [ 'hatt_services' ] [ name ] define_singleton_method name . intern do @hatt_http_clients [ name ] end end
add a service to hatt
22,672
def details ( address_id ) details_url = File . join ( DOMESTIC_URL , address_id . to_s ) response = @connection . get details_url OpenStruct . new ( response . parsed [ 'address' ] ) end
Return domestic address details for a domestic address id
22,673
def australian_details ( address_id ) details_url = File . join ( AUSTRALIAN_URL , address_id . to_s ) response = @connection . get details_url RecursiveOpenStruct . new ( response . parsed [ 'address' ] , recurse_over_arrays : true ) end
Return australian address details for a specific international address id
22,674
def international_search ( query , count = 5 , country_code = nil ) return [ ] if query . length < 4 response = @connection . get INTERNATIONAL_URL , params : { q : query . to_ascii , count : count , country_code : country_code } response . parsed [ 'addresses' ] . map { | address | OpenStruct . new ( address ) } end
Search for an International Address
22,675
def international_details ( address_id ) details_url = File . join ( INTERNATIONAL_URL , address_id . to_s ) response = @connection . get details_url RecursiveOpenStruct . new ( response . parsed [ 'result' ] , recurse_over_arrays : true ) end
Return international address details for a specific international address id
22,676
def find_petition_pages ( name , limit : 10 , offset : 0 ) target = "#{self.base_url}/petitionpage/" options = { basic_auth : self . auth , query : { _limit : limit , _offset : offset , name : name } } self . class . get ( target , options ) end
Find petition pages matching a given name .
22,677
def create_petition_page ( name , title , lang , canonical_url ) target = "#{self.base_url}/petitionpage/" options = { basic_auth : self . auth , headers : { 'Content-type' => 'application/json; charset=UTF-8' } , :body => { :type => 'petitionpage' , :hidden => false , :name => name , :title => title , :language => lang , :canonical_url => canonical_url } . to_json , format : :json } self . class . post ( target , options ) end
Create a petition page in your ActionKit instance .
22,678
def create_action ( page_name , email , options = { } ) target = "#{self.base_url}/action/" body = { page : page_name , email : email } . merge self . parse_action_options ( options ) options = { basic_auth : self . auth , body : body . to_json , format : :json , headers : { 'Content-Type' => 'application/json; charset=UTF-8' } } self . class . post ( target , options ) end
Creates an action which associates a user with a page .
22,679
def create_donation_action ( options = { } ) target = "#{self.base_url}/donationpush/" options = self . validate_donation_options ( options ) page_opts = { basic_auth : self . auth , body : options . to_json , headers : { 'Content-Type' => 'application/json; charset=UTF-8' } } self . class . post ( target , page_opts ) end
Creates an action which registers a donation with a user account .
22,680
def list_users ( offset = 0 , limit = 20 ) target = "#{self.base_url}/user/" options = { basic_auth : self . auth , query : { _limit : limit , _offset : offset } } self . class . get ( target , options ) end
Lists users in your instance .
22,681
def setup_config_file ( file = nil ) if file . nil? or ! File . exists? ( file ) setup_config_dir dst_file = File . join ( default_retrospec_dir , 'config.yaml' ) src_file = File . join ( gem_dir , 'config.yaml.sample' ) safe_copy_file ( src_file , dst_file ) file = dst_file end @config_file = file end
we should be able to lookup where the user stores the config map so the user doesn t have to pass this info each time create a blank yaml config file it file does not exist
22,682
def field ( * fields , export_only : false ) @config . fields += fields . map ( & :to_sym ) @config . fields . uniq! if export_only @config . export_only_fields += fields . map ( & :to_sym ) @config . export_only_fields . uniq! end nil end
Add one or many fields to the csv format .
22,683
def has_one ( name ) @config . root or raise NotImplementedError , "nested associations are not supported" @config . has_ones [ name . to_sym ] ||= Config . new yield self . class . new config : @config . has_ones [ name . to_sym ] , root : false nil end
Define a one to one association . This is also aliased as belongs_to . Expects a name and a block to define the fields on associated record .
22,684
def has_many ( name ) @config . root or raise NotImplementedError , "nested associations are not supported" @config . has_manys [ name . to_sym ] ||= Config . new yield self . class . new config : @config . has_manys [ name . to_sym ] , root : false nil end
Define a one to many association . Expect a name and a block to define the fields on associated records .
22,685
def build_rule ( expression ) rule = build_root_recurrence_rule ( expression ) rule = build_year_rules ( rule , expression ) rule = build_weekday_rule ( rule , expression ) rule = build_day_rules ( rule , expression ) rule = build_time_rules ( rule , expression ) rule = rule . until ( expression . until ) unless expression . until . blank? rule end
Generates a rule based on a parsed expression
22,686
def jsonify ( obj ) case obj when String JSON . pretty_generate ( JSON . parse ( obj ) ) when Hash , Array JSON . pretty_generate ( obj ) else obj . to_s end rescue Exception obj . to_s end
always returns a string intended for request bodies every attempt is made to ensure string is valid json but if that is not possible then its returned as is
22,687
def objectify ( json_string ) return nil if json_string . nil? || json_string == '' case json_string when Hash , Array return json_string else JSON . parse ( json_string . to_s ) end rescue Exception json_string end
attempts to parse json strings into native ruby objects
22,688
def count_values ( * values ) values . inject ( Hash . new ( 0 ) ) { | h , v | h [ v ] += 1 ; h } end
Returns a hash where the keys are the values in the passed array and the values are the number of times that value appears in the list .
22,689
def get_uid ( username ) Etc . passwd { | u | return u . uid if u . name == username } end
Returns the UID for the username on the host .
22,690
def get_gid ( group_name ) Etc . group { | g | return g . gid if g . name == group_name } end
Returns GID for the group on the host .
22,691
def podbay_info ( ip_address , path , timeout = 5 ) JSON . parse ( get_request ( "http://#{ip_address}:#{Podbay::SERVER_INFO_PORT}/#{path}" , timeout : timeout ) . body , symbolize_names : true ) end
Makes a GET request to the Podbay servers that are listening for Podbay data requests
22,692
def update2 update_node_properties logger . info "update2 started (full update)" tsb = Time . now source_nodes = source_node_properties . keys destination_nodes = destination . all_nodes delete_missing ( destination_nodes , source_nodes ) errors = false complete = source . facts complete . each do | node , facts | begin destination . node_update ( node , facts ) rescue errors = true logger . error $! end end tse = Time . now logger . info "update2 updated #{source_nodes.size} nodes in #{tse - tsb}" destination . meta_fact_update ( "update2" , tsb , tse ) unless errors end
update by deleting missing nodes and get a complete map of nodes with facts and update or insert facts for each one
22,693
def update_node_properties logger . info "update_node_properties started" tsb = Time . now @source_node_properties = source . node_properties destination . node_properties_update ( source_node_properties ) tse = Time . now logger . info "update_node_properties got #{source_node_properties.size} nodes " "in #{tse - tsb}" destination . meta_node_properties_update ( tsb , tse ) end
update node update information
22,694
def matches ( encoding ) values . select { | v | v == encoding || v == '*' } . sort { | a , b | a == '*' ? 1 : ( b == '*' ? - 1 : 0 ) } end
Returns an array of encodings from this header that match the given + encoding + ordered by precedence .
22,695
def belongs_to_selection ( target , options = { } ) belongs_to target , options . merge ( :class_name => "Selection" ) if ActiveRecord :: Base . connection . table_exists? Selection . table_name prefix = self . name . downcase parent = Selection . where ( system_code : "#{prefix}_#{target}" ) . first if parent target_id = "#{target}_id" . to_sym parent . children . each do | s | method_name = "#{s.system_code.sub("#{prefix}_", '')}?" . to_sym class_eval do define_method method_name do send ( target_id ) == s . id end end end end end end
Helper for belongs_to and accepts all the standard rails options
22,696
def full_colspan raw_span = components . keys . collect { | key | key . at ( 0 ) } . max . to_i ( raw_span > 0 ) ? raw_span + 1 : nil end
= begin def explode!
22,697
def subscribe ( & blk ) pres = connection . presence_stanza ( 'to' => jid . bare , 'type' => 'subscribe' ) connection . send_stanza pres , & blk end
sends a subscription request to the bare entity
22,698
def accept_subscription ( & blk ) pres = connection . presence_stanza ( 'to' => jid . bare , 'type' => 'subscribed' ) connection . send_stanza pres , & blk end
send a subscription stanza to accept an incoming subscription request
22,699
def unsubscribe ( & blk ) pres = connection . presence_stanza ( 'to' => jid . bare , 'type' => 'unsubscribe' ) connection . send_stanza pres , & blk end
unsubscribes from from the bare entity