idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
23,800
def multi_line_contents ( raw_cert ) cert_contents = raw_cert . split ( / / ) [ 2 ] cert_contents . lines . map do | line | line . lstrip . squeeze ( ' ' ) . split ( ' ' ) end end
Attempts to reformat multi - line certificate bodies
23,801
def append_query ( base_uri , added_params = { } ) base_params = base_uri . query ? CGI . parse ( base_uri . query ) : { } get_params = base_params . merge ( added_params . stringify_keys ) base_uri . dup . tap do | uri | assignments = get_params . map do | k , v | case v when Array ; v . map { | val | "#{::CGI.escape(k.to_s)}=#{::CGI.escape(val.to_s)}" } . join ( '&' ) else "#{::CGI.escape(k.to_s)}=#{::CGI.escape(v.to_s)}" end end uri . query = assignments . join ( '&' ) end end
Appends GET parameters to a URI instance . Duplicate parameters will be replaced with the new value .
23,802
def connection @connection ||= Net :: HTTP . new ( TENDER_API_HOST , Net :: HTTP . https_default_port ) . tap do | http | http . use_ssl = true http . start end end
Returns a persistent connection to the server reusing a connection of it was previously established .
23,803
def paged_each ( uri , list_key , options = { } , & block ) query_params = { } query_params [ :since ] = options [ :since ] . to_date . to_s ( :db ) if options [ :since ] query_params [ :page ] = [ options [ :start_page ] . to_i , 1 ] . max rescue 1 results = [ ] initial_result = get ( append_query ( uri , query_params ) ) max_page = ( initial_result [ 'total' ] . to_f / initial_result [ 'per_page' ] . to_f ) . ceil end_page = options [ :end_page ] . nil? ? max_page : [ options [ :end_page ] . to_i , max_page ] . min Love . logger . debug "Paged requests to #{uri}: #{max_page} total pages, importing #{query_params[:page]} upto #{end_page}." if Love . logger if initial_result [ list_key ] . kind_of? ( Array ) block_given? ? initial_result [ list_key ] . each { | record | yield ( record ) } : results << initial_result [ list_key ] sleep ( sleep_between_requests ) if sleep_between_requests end start_page = query_params [ :page ] . to_i + 1 start_page . upto ( end_page ) do | page | query_params [ :page ] = page result = get ( append_query ( uri , query_params ) ) if result [ list_key ] . kind_of? ( Array ) block_given? ? result [ list_key ] . each { | record | yield ( record ) } : results << result [ list_key ] sleep ( sleep_between_requests ) if sleep_between_requests end end results . flatten . map { | r | OpenStruct . new ( r ) } unless block_given? end
Iterates over a collection issuing multiple requests to get all the paged results .
23,804
def serialize stuff if stuff . is_a? Array or stuff . is_a? ActiveRecord :: Relation json = render_to_string json : QuickDryArraySerializer . new ( stuff , root : get_model . model_name . route_key ) hash = JSON . parse ( json ) temp = [ ] if hash [ get_model . model_name . route_key ] . first . has_key? get_model . model_name . route_key hash [ get_model . model_name . route_key ] . each { | x | temp << x [ get_model . model_name . route_key ] } hash [ get_model . model_name . route_key ] = temp return hash . to_json end return json elsif stuff . is_a? get_model end end
nasty hack until I can get an answer on the official way to remove the instance root keys in a list
23,805
def get_paged_search_results ( params , user : nil , model : nil ) params [ :per_page ] = 10 if params [ :per_page ] . blank? params [ :page ] = 1 if params [ :page ] . blank? user = User . new if user . blank? or ! user . class . to_s == User . to_s if model . blank? model = request . params [ :table_name ] . classify . constantize unless request . params [ :table_name ] . blank? return nil if model . blank? end result_set = model . none customer_filter = "" user . customers . each do | cust | if model . column_names . include? "cust_id" customer_filter << "(cust_id = '#{cust.cust_id(true)}') OR " unless cust . cust_id . blank? elsif model . attribute_alias? "cust_id" customer_filter << "(#{model.attribute_alias "cust_id"} = '#{cust.cust_id(true)}') OR " unless cust . cust_id . blank? elsif model . column_names . include? "order_number" customer_filter << "(order_number like '#{cust.prefix}%') OR " unless cust . prefix . blank? elsif model . attribute_alias? "order_number" customer_filter << "(#{model.attribute_alias "order_number"} like '#{cust.prefix}%') OR " unless cust . prefix . blank? end end customer_filter << " (1=0)" if params [ :columns ] . blank? result_set = model . where ( customer_filter ) else where_clause = "" params [ :columns ] . each do | name , value | where_clause << "(#{model.table_name}.#{name} like '%#{value}%') AND " unless value . blank? end where_clause << " (1=1)" result_set = model . where ( customer_filter ) . where ( where_clause ) end instances = model . paginate ( page : params [ :page ] , per_page : params [ :per_page ] ) . merge ( result_set ) . order ( updated_at : :desc ) return { instances : instances , params : params } end
Assumes the existance of a User model
23,806
def converse ( prompt , responses = { } ) i , commands = 0 , responses . map { | _key , value | value . inspect } . join ( ',' ) statement = responses . inject '' do | inner_statement , ( key , value ) | inner_statement << ( ( i += 1 ) == 1 ? %(if response is "#{value}" then\n) : %(else if response is "#{value}" then\n) ) << %(do shell script "echo '#{key}'"\n) end applescript ( %( tell application "SpeechRecognitionServer" set response to listen for {#{commands}} with prompt "#{prompt}" #{statement} end if end tell ) , ) . strip . to_sym end
Converse with speech recognition .
23,807
def authorized_for? ( obj ) logger . debug ( "Checking to see if authorized to access object" ) if @auth_user . nil? return false elsif @auth_user . role >= Roles :: ADMIN return true elsif obj . is_a? User return obj == @auth_user else return obj . try ( :user ) == @auth_user end end
Determines if the user is authorized for the object . The user must be either the creator of the object or must be an admin or above .
23,808
def get_token_payload ( token ) decoded = JWT . decode token , nil , false payload = decoded [ 0 ] if payload . nil? logger . error ( "Token payload is nil: #{token}" ) raise UNAUTHORIZED_ERROR , "Invalid token" end return payload rescue JWT :: DecodeError => e logger . error ( "Token decode error: #{e.message}" ) raise UNAUTHORIZED_ERROR , "Invalid token" end
Attempts to retrieve the payload encoded in the token . It checks if the token is valid according to JWT definition and not expired .
23,809
def verify_token ( token ) logger . debug ( "Verifying token: #{token}" ) payload = get_token_payload ( token ) user_uuid = payload [ "user_uuid" ] session_uuid = payload [ "session_uuid" ] if user_uuid . nil? || session_uuid . nil? logger . error ( "User or session is not specified" ) raise UNAUTHORIZED_ERROR , "Invalid token" end logger . debug ( "Token well defined: #{token}" ) auth_user = User . find_by_uuid ( user_uuid ) if auth_user . nil? logger . error ( "Specified user doesn't exist #{user_uuid}" ) raise UNAUTHORIZED_ERROR , "Invalid token" end auth_session = Session . find_by_uuid ( session_uuid ) if auth_session . nil? || auth_session . user != auth_user logger . error ( "Specified session doesn't exist #{session_uuid}" ) raise UNAUTHORIZED_ERROR , "Invalid token" end JWT . decode token , auth_session . secret , true logger . debug ( "Token well formatted and verified. Set cache." ) return auth_session rescue JWT :: DecodeError => e logger . error ( e . message ) raise UNAUTHORIZED_ERROR , "Invalid token" end
Truly verifies the token and its payload . It ensures the user and session specified in the token payload are indeed valid . The required role is also checked .
23,810
def get_token ( required_role : Roles :: PUBLIC ) token = params [ :token ] @auth_session = Cache . get ( kind : :session , token : token ) if @auth_session . nil? @auth_session = verify_token ( token ) @auth_session . role Cache . set ( { kind : :session , token : token } , @auth_session ) end if @auth_session . role < required_role logger . error ( "Not enough permission (role: #{@auth_session.role})" ) raise UNAUTHORIZED_ERROR , "Invalid token" end @auth_user = @auth_session . user @token = @auth_session . token return true end
Attempt to get a token for the session . Token must be specified in query string or part of the JSON object .
23,811
def get_api_key ( required_role : Roles :: PUBLIC ) api_key = params [ :api_key ] if api_key . nil? raise UNAUTHORIZED_ERROR , "Invalid api key" end auth_user = User . find_by_api_key ( api_key ) if auth_user . nil? || auth_user . role < required_role raise UNAUTHORIZED_ERROR , "Invalid api key" end @auth_user = auth_user @auth_session = nil @token = nil return true end
Get API key from the request .
23,812
def get_auth ( required_role : Roles :: USER ) if params [ :token ] get_token ( required_role : required_role ) else get_api_key ( required_role : required_role ) end end
Get auth data from the request . The token takes the precedence .
23,813
def details ( * args ) options = args . last . is_a? ( Hash ) ? args . pop : { } if args . length == 2 options . merge! ( :reaction => args [ 0 ] ) options . merge! ( :forum => args [ 1 ] ) response = get ( 'reactions/details' , options ) else puts "#{Kernel.caller.first}: Reactions.details expects 2 arguments: reaction and forum" end end
Returns reaction details
23,814
def append_info_to_payload ( payload ) super payload [ :session_id ] = request . session_options [ :id ] payload [ :uuid ] = request . uuid payload [ :host ] = request . host end
Custom attributes for lograge logging
23,815
def start RequireSpy . spy_require ( transport ) error = try_require ( require_string ) return transport . done_and_wait_for_ack unless error transport . exit_with_error ( error ) exit ( 1 ) end
Prints the process pid so it can be grabbed by the supervisor process inits tranport fifos and requires requested libraries . Installs the require - spying code and starts requiring
23,816
def find ( uri ) _try_variations_of ( uri ) do | path | content = get path return [ content ] unless content . nil? end unless uri . nil? [ ] end
Find isn t fuzzy for Special Content . It looks for full uri or the uri s basename optionally tacking on
23,817
def to_s ( include_params = true ) s = [ ] s << "JsonRequest:#{self.object_id}" s << " operation: #{self.operation}" s << " params: " + MultiJson . dump ( self . params ) if include_params s . join ( "\n" ) end
Create a new JsonRequest
23,818
def valid_params? ( name , size ) return raise TypeError . new ( "A 'name' should be a string" ) if name . class != String return raise TypeError . new ( "A 'size' should be an integer" ) if size . class != Integer true end
Validates the params by type . Could add in additional validations in this method depending on requirements . Raises exception with invalid types with early return or returns true if params are valid
23,819
def add_entry ( email , account , action , changes ) @audit_log [ email ] = [ ] unless audit_log [ email ] @audit_log [ email ] << { :account => account , :action => action , :changes => changes } end
Initializes a new AuditLog
23,820
def send! request = HTTParty . post ( self . target , :body => { :payload => generate_payload . to_json } ) unless request . code . eql? 200 false end true end
Send the message!
23,821
def common_fields_attributes = ( nested_attributes ) nested_attributes . values . each do | attributes | common_field = common_fields . find { | field | field . id . to_s == attributes [ :id ] && attributes [ :id ] . present? } || common_fields . build assign_to_or_mark_for_destruction ( common_field , attributes , true , { } ) end end
Ensure all nested attributes for common fields get saved as common fields and not as template fields
23,822
def start_time @start_time ||= @events . select { | event | event . is_a? ( RequestWillBeSent ) } . select { | event | event . request [ 'url' ] == @url } . map { | event | event . timestamp } . first end
The seconds since epoch that the request for this document started
23,823
def encoded_bytes ( resource_type ) @events . select { | e | e . is_a? ( ResponseReceived ) && e . resource_type == resource_type } . map { | e | e . request_id } . map { | request_id | data_received_for_request ( request_id ) } . flatten . inject ( 0 ) { | bytes_sum , n | bytes_sum + n . encoded_data_length } end
The number of bytes downloaded for a particular resource type . If the resource was gzipped during transfer then the gzipped size is reported .
23,824
def bytes ( resource_type ) @events . select { | e | e . is_a? ( ResponseReceived ) && e . resource_type == resource_type } . map { | e | e . request_id } . map { | request_id | data_received_for_request ( request_id ) } . flatten . inject ( 0 ) { | bytes_sum , n | bytes_sum + n . data_length } end
The number of bytes downloaded for a particular resource type . If the resource was gzipped during transfer then the uncompressed size is reported .
23,825
def request_count_by_resource ( resource_type ) @events . select { | n | n . is_a? ( ResponseReceived ) && n . resource_type == resource_type } . size end
the number of network requests of a particular resource type that were required to load this document
23,826
def to_hash hash = { } instance_variables . each do | v | hash [ v . to_s [ 1 .. - 1 ] . to_sym ] = instance_variable_get ( v ) end hash [ :results ] . each do | c | hash [ :results ] [ hash [ :results ] . index ( c ) ] = c . to_hash end hash end
Searches for sources in Google Books .
23,827
def on_close ( data , * args ) options = args . extract_options! options [ :code ] ||= ( data && data . code ) || '1000' disconnect fail SlackBotManager :: ConnectionRateLimited if %w( 1008 429 ) . include? ( options [ :code ] . to_s ) end
Handle when connection gets closed
23,828
def ox_attr ( name , o = { } , & block ) new_attr = Attr . new ( name , o . reverse_merge ( :tag_proc => @tag_proc ) , & block ) @ox_attrs << new_attr ox_accessor new_attr . accessor end
Declares a reference to a certain xml attribute .
23,829
def ox_elem ( name , o = { } , & block ) new_elem = Elem . new ( name , o . reverse_merge ( :tag_proc => @tag_proc ) , & block ) @ox_elems << new_elem ox_accessor new_elem . accessor end
Declares a reference to a certain xml element or a typed collection of elements .
23,830
def ox_tag ( tag = nil , & block ) raise 'you can only set tag or a block, not both.' if tag && block @base_tag ||= self . to_s . split ( '::' ) . last @ox_tag ||= case tag when String tag when Proc , Symbol , nil @tag_proc = ( block || tag || :to_s ) . to_proc @tag_proc . call ( @base_tag ) rescue tag . to_s else raise 'you passed something weird' end end
Sets the name of the XML element that represents this class . Use this to override the default camelcase class name .
23,831
def from_xml ( data ) xml = XML :: Node . from ( data ) raise 'invalid XML' unless xml . name == ox_tag returning new do | ox | ( ox_attrs + ox_elems ) . each { | e | ox . send ( e . setter , e . from_xml ( xml ) ) } ox . send ( :after_parse ) if ox . respond_to? ( :after_parse ) end end
Returns a new instance from XML
23,832
def to_xml ( data ) ox = XML :: Node . new ( ox_tag ) wrappers = { } ox_elems . each do | elem | if elem . in wrappers [ elem . in ] ||= XML :: Node . new elem . in elem . to_xml ( data ) . each { | e | wrappers [ elem . in ] << e } else elem . to_xml ( data ) . each { | e | ox << e } end end wrappers . each { | k , v | ox << v } ox_attrs . each do | a | val = data . send ( a . accessor ) . to_s ox [ a . tag ] = val if val . present? end ox end
Returns XML generated from an instance based on Attr & Elem definitions .
23,833
def pick tst = rand sum = 0 @map . each do | value , prob | sum += prob return value , prob if tst < sum end return nil end
randomly pick a key - value with respect to its probability in given distribution
23,834
def variance expected = self . expectation @map . reduce ( 0 ) { | sum , ( value , p ) | tmp = ( value . to_f - expectation ) sum + tmp * tmp * p } end
computes variance given that keys in distribution are numeric
23,835
def transform ( * keys ) raise ArgumentError , "requires a block" unless block_given? keys . each do | key | items . each do | item | item [ key ] = yield ( item [ key ] ) || item [ key ] end end end
Transform must be used inside an emit block . It can be used to alter named keys within the item set
23,836
def method_missing ( symbol , * args , & block ) ivar = "@#{symbol}" if args . empty? return instance_variable_get ( ivar ) || super else instance_variable_set ( ivar , args . pop ) end return self end
Used to store or retreive variables that are used to query services .
23,837
def sort ( key ) @items = @items . sort_by { | i | i [ key ] } rescue NoMethodError => e Smoke . log . info "You're trying to sort by \"#{key}\" but it does not exist in your item set" end
Re - sort items by a particular key Sort must be used inside an emit block .
23,838
def keep ( key , matcher ) @items . reject! { | i | ( i [ key ] =~ matcher ) ? false : true } end
Keep items that match the regex
23,839
def discard ( key , matcher ) @items . reject! { | i | ( i [ key ] =~ matcher ) ? true : false } end
Discard items that do not match the regex
23,840
def prepare! ( env ) @env = env @request = Rack :: Request . new ( env ) @response = Rack :: Response . new @headers = @response . header @params = @request . GET . merge ( @request . POST ) @params . default_proc = proc do | hash , key | hash [ key . to_s ] if Symbol === key end end
Creates a new Context object .
23,841
def generate_attachment payload = { } payload [ :fallback ] = self . fallback unless self . fallback . nil? payload [ :color ] = self . color unless self . color . nil? payload [ :pretext ] = self . pretext unless self . pretext . nil? payload [ :author_name ] = self . author_name unless self . author_name . nil? payload [ :author_link ] = self . author_link unless self . author_link . nil? payload [ :author_icon ] = self . author_icon unless self . author_icon . nil? payload [ :title ] = self . title unless self . title . nil? payload [ :title_link ] = self . title_link unless self . title_link . nil? payload [ :text ] = self . message unless self . message . nil? unless self . fields . nil? payload [ :fields ] = self . fields if self . fields . length > 0 end payload [ :image_url ] = self . image_url unless self . image_url . nil? payload end
Generate the payload for slack attachments
23,842
def frame return @frame if @frame chars = [ ] chars << Char . new ( 0x23 , @x_offset - 1 , @y_offset - 1 ) chars << Char . new ( 0x23 , @x_offset + @width , @y_offset - 1 ) chars << Char . new ( 0x23 , @x_offset - 1 , @y_offset + @height ) chars << Char . new ( 0x23 , @x_offset + @width , @y_offset + @height ) @width . times { | x | chars << Char . new ( 0x2d , x + @x_offset , @y_offset - 1 ) } @width . times { | x | chars << Char . new ( 0x2d , x + @x_offset , @y_offset + @height ) } @height . times { | y | chars << Char . new ( 0x7c , @x_offset - 1 , y + @y_offset ) } @height . times { | y | chars << Char . new ( 0x7c , @x_offset + @width , y + @y_offset ) } @frame = "" @frame << chars . join end
Use a fancy border around console
23,843
def update ( offset , value ) return unless ( memory_offset .. memory_offset_end ) . include? ( offset ) @to_s = nil diff = offset - @memory_offset h = diff / @width w = diff % @width @chars [ diff ] = Char . new ( value , w + @x_offset , h + @y_offset ) print @chars [ diff ] changed notify_observers ( self ) print @chars [ diff ] end
Callback from observed memory
23,844
def add_storage_adapter ( adapter ) raise ArgumentError , "#{adapter} is not a Bumbleworks storage adapter" unless [ :driver , :use? , :new_storage , :allow_history_storage? , :storage_class , :display_name ] . all? { | m | adapter . respond_to? ( m ) } @storage_adapters << adapter @storage_adapters end
Add a storage adapter to the set of possible adapters . Takes an object that responds to driver use? storage_class and display_name .
23,845
def storage_adapter @storage_adapter ||= begin all_adapters = storage_adapters raise UndefinedSetting , "No storage adapters configured" if all_adapters . empty? adapter = all_adapters . detect do | potential_adapter | potential_adapter . use? ( storage ) end raise UndefinedSetting , "Storage is missing or not supported. Supported: #{all_adapters.map(&:display_name).join(', ')}" unless adapter adapter end end
If storage_adapter is not explicitly set find first registered adapter that can use Bumbleworks . storage .
23,846
def look_up_configured_path ( path_type , options = { } ) return @cached_paths [ path_type ] if @cached_paths . has_key? ( path_type ) if user_defined_path = user_configured_path ( path_type ) if path_resolves? ( user_defined_path , :file => options [ :file ] ) return user_defined_path else raise Bumbleworks :: InvalidSetting , "#{Bumbleworks::Support.humanize(path_type)} not found (looked for #{user_defined_path || defaults.join(', ')})" end end first_existing_default_path ( options [ :defaults ] , :file => options [ :file ] ) end
If the user explicitly declared a path raises an exception if the path was not found . Missing default paths do not raise an exception since no paths are required .
23,847
def keyword_args ( * args ) argshash = args [ - 1 ] . is_a? ( Hash ) ? args . pop : { } argshash = args . hashify ( :optional ) . merge ( argshash ) others_OK = argshash . delete ( :OTHERS ) ret = { } required = [ ] check = { } argshash . each do | key , val | attrs = case val when Hash val [ :default ] ||= [ ] if val [ :enumerable ] val when :required { :required => true } when :optional { } when :enumerable { :enumerable => true , :default => [ ] } when Array { :valid => val } when Class , Module { :valid => val } else { :default => val } end required << key if attrs [ :required ] check [ key ] = case valid = attrs [ :valid ] when Enumerable [ :one_of , valid ] when Class , Module [ :is_a , valid ] else [ :ok ] end check [ key ] [ 2 ] = [ :allow_nil , :enumerable ] . select { | mod | attrs [ mod ] } ret [ key ] = attrs [ :default ] if attrs . include? ( :default ) end unless others_OK or ( others = self . keys - argshash . keys ) . empty? raise ArgumentError , "Invalid keyword arg#{others.length>1 && "s" or ""} #{others.collect{|a| a.inspect}.join(', ')}" , caller end self . each do | key , val | code , valid , mods = check [ key ] mods ||= [ ] val = [ val ] unless mods . include? ( :enumerable ) and val . is_a? ( Enumerable ) ok = val . all? { | v | if mods . include? ( :allow_nil ) and v . nil? true else case code when nil then true when :ok then true when :one_of then valid . include? ( v ) when :is_a then v . is_a? ( valid ) end end } val = val . first unless mods . include? ( :enumerable ) raise ArgumentError , "Invalid value for keyword arg #{key.inspect} => #{val.inspect}" , caller unless ok ret [ key ] = val required . delete ( key ) end unless required . empty? raise ArgumentError , "Missing required keyword arg#{required.length>1 && "s" or ""} #{required.collect{|a| a.inspect}.join(', ')}" , caller end ( class << ret ; self ; end ) . class_eval do argshash . keys . each do | key | define_method ( key ) do self [ key ] end end end ret end
given an argument hash and a description of acceptable keyword args and their default values checks validity of the arguments and raises any errors otherwise returns a new hash containing all arg values with defaults filled in as needed .
23,848
def near_pages @near_pages ||= begin if current_page <= near + 1 upper_page = shown_page_count >= last_page ? last_page : shown_page_count 1 .. upper_page elsif current_page >= last_page - near - 1 bottom_page = last_page - shown_page_count + 1 ( bottom_page > 1 ? bottom_page : 1 ) .. last_page else bottom_page = current_page - near upper_page = current_page + near ( bottom_page > 1 ? bottom_page : 1 ) .. ( upper_page < last_page ? upper_page : last_page ) end end end
pages that numbers are displayed
23,849
def prep_file ( url , dir ) parts = url . split ( '/' ) File . join ( dir , parts [ - 1 ] ) end
Pure function to create correct filename
23,850
def get schedule do inc_io @@log . info ( "Requesting: #{@url}" ) http = EM :: HttpRequest . new ( @url ) . get :redirects => 5 http . callback do | h | succeed http . response dec_io end http . headers do | headers | unless OK_ERROR_CODES . include? ( headers . status ) fail ( "Error (#{headers.status}) with url:#{@url}" ) dec_io end end http . errback do fail ( "Error downloading #{@url}" ) dec_io end end self end
Non blocking get url
23,851
def valid ( condition = true ) all . select { | d | condition == valid? ( d ) } . map { | d | model . class . new ( d ) } end
All valid documents
23,852
def multi_request ( method , paths , body = nil , param = nil , header = nil ) @multi = true if @responses . nil? @responses = [ ] end if paths . is_a? String or paths . is_a? URI paths = [ paths ] end paths = paths . map { | p | p . to_s } log . debug "Queueing multi-#{method} requests, concurrency: #{concurrency}, path(s): #{ paths.size == 1 ? paths[0]: paths.size }" paths . each do | path | multi_request = request ( path , method . downcase . to_sym , body , param , header ) multi_request . on_complete do | response | log . debug "Multi-#{method} [#{paths.size}]: " + log_message ( response ) @responses << response end hydra . queue ( multi_request ) end hydra end
Prepare and queue a multi request
23,853
def get_block ( id , metadata = nil , size = 42 ) url = "http://blocks.fishbans.com/#{id}" url += "-#{metadata}" unless metadata . nil? url += "/#{size}" if size != 42 response = get ( url , false ) ChunkyPNG :: Image . from_blob ( response . body ) end
Gets a block image by its ID and Metadata . Unfortunately it uses the old block IDs rather than the new ones so you have to memorize those pesky integers .
23,854
def get_monster ( id , three = false , size = 42 ) id = id . to_s url = 'http://blocks.fishbans.com' url += "/#{id}" if id =~ / / url += "/m#{id}" if id !~ / / url += '-3d' if three url += "/#{size}" if size != 42 response = get ( url , false ) ChunkyPNG :: Image . from_blob ( response . body ) end
Gets the monster image by its ID .
23,855
def write ( inputDir , outputFile ) entries = Dir . entries ( inputDir ) ; entries . delete ( "." ) ; entries . delete ( ".." ) io = Zip :: File . open ( outputFile , Zip :: File :: CREATE ) ; writeEntries ( entries , "" , io , inputDir ) io . close ( ) ; end
Initialize with the directory to zip and the location of the output archive . Zip the input directory .
23,856
def file_blob_id ( path ) file_path = Rails . root . join ( 'test/fixtures' . freeze ) . join ( path ) blob_contents = File . binread file_path Base64 . urlsafe_encode64 ( Digest :: SHA256 . digest ( blob_contents ) ) . inspect end
Computes the ID assigned to a blob .
23,857
def file_blob_data ( path , options = { } ) indent = ' ' * ( ( options [ :indent ] || 2 ) + 2 ) file_path = Rails . root . join ( 'test/fixtures' . freeze ) . join ( path ) blob_contents = File . binread file_path base64_data = Base64 . encode64 blob_contents base64_data . gsub! "\n" , "\n#{indent}" base64_data . strip! "!!binary |\n#{indent}#{base64_data}" end
The contents of a blob in a YAML - friendly format .
23,858
def file_blob_size ( path ) file_path = Rails . root . join ( 'test/fixtures' . freeze ) . join ( path ) File . stat ( file_path ) . size end
The number of bytes in a file .
23,859
def set_with_filename ( path ) return if path . blank? self . filename = :: File . basename ( path ) self . content_type = :: MIME :: Types . type_for ( path ) . first . content_type self . data = :: Base64 . encode64 ( :: File . read ( path ) ) end
Sets the filename content_type and data attributes from a local filename so that a File can be uploaded through the API
23,860
def download_to_directory ( path ) Dir . mkdir ( path ) unless :: File . directory? ( path ) download_file ( self [ :@url ] , :: File . join ( path , local_filename ) ) true end
Download the file to the local disk
23,861
def to_sp_text ( rounds , columns , formats ) values = columns . inject ( [ ] ) do | vals , col | val = send ( col ) . to_s val . sub! ( / \. / , '' ) if col == :points vals << val end ( 1 .. rounds ) . each do | r | result = find_result ( r ) values << ( result ? result . to_sp_text : " : " ) end formats % values end
Format a player s record as it would appear in an SP export file .
23,862
def variance ( sample = false ) a = numerify avg = a . average sum = a . inject ( 0 ) { | sum , value | sum + ( value - avg ) ** 2 } ( 1 / ( a . length . to_f - ( sample ? 1 : 0 ) ) * sum ) end
variance of an array of numbers
23,863
def run ( args = ARGV ) opts . parse! ( args ) if ! analyze_gemfile? && args . empty? puts opts . parser exit 1 end print_requires ( options , args ) end
Sets default options to be overwritten by option parser down the road
23,864
def start keywords = self . params [ "keywords" ] @thread = Thread . new do @client . filter_by_keywords ( keywords ) do | status | if retweet? ( status ) before_retweet . trigger ( status ) @retweet . retweet ( status [ "id" ] ) after_retweet . trigger ( status ) end end end @thread . join end
initializes the tracker start the tracker
23,865
def load_filters filters_config = self . params [ "filters_config" ] if ! filters_config . nil? && File . exists? ( filters_config ) begin YAML :: load_file ( filters_config ) rescue on_error . trigger ( $! , $@ ) end end end
load the YAML file that is specified in the params
23,866
def retweet? ( status ) filters = load_filters retweet = true if ! filters . nil? filters . each_pair do | path , value | array = [ ] array << value array . flatten . each do | filter_value | path_value = StreamBot :: ArrayPath . get_path ( status , path ) if path_value . eql? ( filter_value ) || path_value . include? ( filter_value ) on_match . trigger ( status , path , filter_value ) retweet = false end end end end retweet end
decide if the status is retweetable
23,867
def tag ( params ) tag = params [ 'tag' ] attr = params [ 'attr' ] cdata = params [ 'cdata' ] unless attr . kind_of? ( HTML :: AutoAttr ) attr = HTML :: AutoAttr . new ( attr , @sorted ) end unless cdata and cdata . to_s . length return ( @indent * @level ) + '<' + tag + attr . to_s + ' />' + @newline end rendered = '' no_indent = 0 if cdata . kind_of? ( Array ) if cdata [ 0 ] . kind_of? ( Hash ) @level += 1 rendered = @newline cdata . each do | hash | rendered += tag ( hash ) end @level -= 1 else str = '' cdata . each do | scalar | str += tag ( 'tag' => tag , 'attr' => attr , 'cdata' => scalar ) end return str end elsif cdata . kind_of? ( Hash ) @level += 1 rendered = @newline + tag ( cdata ) @level -= 1 else rendered = @encode ? @encoder . encode ( cdata , @encodes ) : cdata no_indent = 1 end return ( @indent * @level ) + '<' + tag + attr . to_s + '>' + rendered . to_s + ( no_indent == 1 ? '' : ( @indent * @level ) ) + '</' + tag + '>' + @newline end
Defaults to empty string which produces no encoding .
23,868
def darken_color ( hex_color , amount = 0.4 ) hex_color = hex_color . gsub ( '#' , '' ) rgb = hex_color . scan ( / / ) . map { | color | color . hex } rgb [ 0 ] = ( rgb [ 0 ] . to_i * amount ) . round rgb [ 1 ] = ( rgb [ 1 ] . to_i * amount ) . round rgb [ 2 ] = ( rgb [ 2 ] . to_i * amount ) . round "#%02x%02x%02x" % rgb end
Amount should be a decimal between 0 and 1 . Lower means darker
23,869
def lighten_color ( hex_color , amount = 0.6 ) hex_color = hex_color . gsub ( '#' , '' ) rgb = hex_color . scan ( / / ) . map { | color | color . hex } rgb [ 0 ] = [ ( rgb [ 0 ] . to_i + 255 * amount ) . round , 255 ] . min rgb [ 1 ] = [ ( rgb [ 1 ] . to_i + 255 * amount ) . round , 255 ] . min rgb [ 2 ] = [ ( rgb [ 2 ] . to_i + 255 * amount ) . round , 255 ] . min "#%02x%02x%02x" % rgb end
Amount should be a decimal between 0 and 1 . Higher means lighter
23,870
def reverse_assign_attributes ( attributes_hash ) attributes_to_assign = attributes_hash . keys . reject { | _attribute_name | attribute_present? ( _attribute_name ) } assign_attributes ( attributes_hash . slice ( attributes_to_assign ) ) end
like reverse merge only assigns attributes which have not yet been assigned
23,871
def pages result_map = map_query_to_results query_result [ "query" ] [ "pages" ] . each do | key , value | page_title = value [ "title" ] original_query = find_result_map_match_for_title ( result_map , page_title ) @page_hash [ original_query ] = MediaWiki :: Page . new ( value ) end @page_hash end
Returns a hash filled with Pages
23,872
def map_query_to_results result_map = initialize_map normalized = get_query_map ( "normalized" ) if normalized result_map = get_normalizations_for ( result_map , normalized ) end redirects = get_query_map ( "redirects" ) if redirects result_map = get_redirects_for ( result_map , redirects ) end result_map end
Maps original query to results
23,873
def add_point ( lat : , lon : , elevation : , time : ) time = Time . parse ( time ) if ! time . is_a? ( Time ) current = [ lat , lon , elevation ] if @start_time . nil? || time < @start_time @start_time = time @start_location = current end if @end_time . nil? || time > @end_time @end_time = time @end_location = current end @points [ time . to_i ] = current true end
add a point to the track
23,874
def in_time_range? ( time ) time = Time . parse ( time ) if ! time . is_a? ( Time ) time_range . cover? ( time ) end
is the supplied time covered by this track?
23,875
def at ( time ) if time . is_a? ( String ) time = Time . parse ( time ) end if time . is_a? ( Integer ) time = Time . at ( time ) end raise ArgumentError , "time must be a Time,String, or Fixnum" if ! time . is_a? ( Time ) return nil if ! in_time_range? ( time ) @interp ||= Interpolate :: Points . new ( @points ) data = @interp . at ( time . to_i ) self . class . array_to_hash ( data ) end
return the interpolated location for the given time or nil if time is outside the track s start .. end
23,876
def sh_in_dir ( dir , shell_commands ) shell_commands = [ shell_commands ] if shell_commands . is_a? ( String ) shell_commands . each { | shell_command | sh %(cd #{dir} && #{shell_command.strip}) } end
Executes a string or an array of strings in a shell in the given directory
23,877
def create_deferred_indices ( drop_existing = false ) @deferred_indices . each { | definition | name = definition . index_name if ( drop_existing && self . indices . include? ( name ) ) drop_index ( name ) end unless ( self . indices . include? ( name ) ) index = create_index ( definition ) if ( index . target_klass . respond_to? ( :odba_extent ) ) index . fill ( index . target_klass . odba_extent ) end end } end
Creates or recreates automatically defined indices
23,878
def create_index ( index_definition , origin_module = Object ) transaction { klass = if ( index_definition . fulltext ) FulltextIndex elsif ( index_definition . resolve_search_term . is_a? ( Hash ) ) ConditionIndex else Index end index = klass . new ( index_definition , origin_module ) indices . store ( index_definition . index_name , index ) indices . odba_store_unsaved index } end
Creates a new index according to IndexDefinition
23,879
def delete ( odba_object ) odba_id = odba_object . odba_id name = odba_object . odba_name odba_object . odba_notify_observers ( :delete , odba_id , odba_object . object_id ) rows = ODBA . storage . retrieve_connected_objects ( odba_id ) rows . each { | row | id = row . first begin if ( connected_object = fetch ( id , nil ) ) connected_object . odba_cut_connection ( odba_object ) connected_object . odba_isolated_store end rescue OdbaError warn "OdbaError ### deleting #{odba_object.class}:#{odba_id}" warn " ### while looking for connected object #{id}" end } delete_cache_entry ( odba_id ) delete_cache_entry ( name ) ODBA . storage . delete_persistable ( odba_id ) delete_index_element ( odba_object ) odba_object end
Permanently deletes _object_ from the database and deconnects all connected Persistables
23,880
def drop_index ( index_name ) transaction { ODBA . storage . drop_index ( index_name ) self . delete ( self . indices [ index_name ] ) } end
Permanently deletes the index named _index_name_
23,881
def next_id if @file_lock dbname = ODBA . storage . instance_variable_get ( '@dbi' ) . dbi_args . first . split ( / / ) . last id = new_id ( dbname , ODBA . storage ) else id = ODBA . storage . next_id end @peers . each do | peer | peer . reserve_next_id id rescue DRb :: DRbError end id rescue OdbaDuplicateIdError retry end
Returns the next valid odba_id
23,882
def retrieve_from_index ( index_name , search_term , meta = nil ) index = indices . fetch ( index_name ) ids = index . fetch_ids ( search_term , meta ) if meta . respond_to? ( :error_limit ) && ( limit = meta . error_limit ) && ( size = ids . size ) > limit . to_i error = OdbaResultLimitError . new error . limit = limit error . size = size error . index = index_name error . search_term = search_term error . meta = meta raise error end bulk_fetch ( ids , nil ) end
Find objects in an index
23,883
def store ( object ) odba_id = object . odba_id name = object . odba_name object . odba_notify_observers ( :store , odba_id , object . object_id ) if ( ids = Thread . current [ :txids ] ) ids . unshift ( [ odba_id , name ] ) end target_ids = object . odba_target_ids changes = store_collection_elements ( object ) prefetchable = object . odba_prefetch? dump = object . odba_isolated_dump ODBA . storage . store ( odba_id , dump , name , prefetchable , object . class ) store_object_connections ( odba_id , target_ids ) update_references ( target_ids , object ) object = store_cache_entry ( odba_id , object , name ) update_indices ( object ) @peers . each do | peer | peer . invalidate! odba_id rescue DRb :: DRbError end object end
Store a Persistable _object_ in the database
23,884
def translation_missing_icon ( translation ) missing_translations = translation . missing_translations color_id = ( missing_translations . size . to_f / translation . translations . size . to_f * 5 ) . ceil - 1 if missing_translations . size == 0 content_tag 'span' , '' , :class => 'glyphicon glyphicon-ok greentext' , :title => 'This key has been translated in all languages' , :rel => 'tooltip' else content_tag 'span' , "(#{missing_translations.size})" , :class => "color-range-#{color_id} bold" , :title => missing_translations . keys . join ( ',' ) , :rel => 'tooltip' end end
Show the number of translation missing with colorization
23,885
def add_namespace ( html , namespace ) html . gsub! ( / \- / ) do | m | classes = m . to_s . split ( '"' ) [ 1 ] . split ( ' ' ) classes . map! { | c | c = namespace + c } 'class="' + classes . join ( ' ' ) + '"' end html end
Read html to string remove namespace if any set the new namespace and update the test file . adds namespace to BP classes in a html file
23,886
def enumeration_values enumeration = @xml . xpath ( './xs:restriction/xs:enumeration' , { 'xs' => 'http://www.w3.org/2001/XMLSchema' } ) if enumeration . length > 0 return enumeration . map { | elem | [ elem . attributes [ 'value' ] . value , elem . xpath ( './xs:annotation/xs:documentation' , { 'xs' => 'http://www.w3.org/2001/XMLSchema' } ) . text ] } else raise "Not an enumeration" end end
Returns the list of values for this enumeration
23,887
def blog__create_default_category category_parent = LatoBlog :: CategoryParent . find_by ( meta_default : true ) return if category_parent category_parent = LatoBlog :: CategoryParent . new ( meta_default : true ) throw 'Impossible to create default category parent' unless category_parent . save languages = blog__get_languages_identifier languages . each do | language | category = LatoBlog :: Category . new ( title : 'Default' , meta_permalink : "default_#{language}" , meta_language : language , lato_core_superuser_creator_id : 1 , lato_blog_category_parent_id : category_parent . id ) throw 'Impossible to create default category' unless category . save end end
This function create the default category if it not exists .
23,888
def blog__clean_category_parents category_parents = LatoBlog :: CategoryParent . all category_parents . map { | cp | cp . destroy if cp . categories . empty? } end
This function cleans all old category parents without any child .
23,889
def blog__get_categories ( order : nil , language : nil , search : nil , page : nil , per_page : nil ) categories = LatoBlog :: Category . all order = order && order == 'ASC' ? 'ASC' : 'DESC' categories = _categories_filter_by_order ( categories , order ) categories = _categories_filter_by_language ( categories , language ) categories = _categories_filter_search ( categories , search ) categories = categories . uniq ( & :id ) total = categories . length page = page &. to_i || 1 per_page = per_page &. to_i || 20 categories = core__paginate_array ( categories , per_page , page ) { categories : categories && ! categories . empty? ? categories . map ( & :serialize ) : [ ] , page : page , per_page : per_page , order : order , total : total } end
This function returns an object with the list of categories with some filters .
23,890
def fetch_config Rails . logger . debug "Loading #{@file}::#{@env}" if Object . const_defined? ( 'Rails' ) && Rails . logger . present? YAML :: load_file ( @file ) [ @env . to_s ] end
Fetch the config from the file
23,891
def default_options if Object . const_defined? ( 'Rails' ) { :file => Rails . root . join ( 'config' , 'config.yml' ) , :reload => Rails . env . development? , :env => Rails . env } else { :file => File . expand_path ( "config.yml" ) , :reload => false , :env => "development" } end end
Default configuration options for Rails and non Rails applications
23,892
def next if ( value = @scoped_config [ @path_elements . last ] ) . nil? raise ConfigKeyException . new ( @path_elements ) elsif value . is_a? ( Hash ) @scoped_config = value self else value end end
Iterate to the next element in the path
23,893
def proxy_methods ( * methods ) @_methods ||= { } methods . each do | method | if method . is_a? Symbol proxy_method method elsif method . is_a? Hash method . each { | method_name , proc | proxy_method method_name , proc } end end end
Establish attributes to proxy along with an alternative proc of how the attribute should be loaded
23,894
def fetch ( args , options = { } ) @primary_fetch . is_a? ( Proc ) ? @primary_fetch [ args ] : ( raise NotFound ) rescue NotFound return nil if options [ :skip_fallback ] run_fallback ( args ) end
Method to find a record using a hash as the criteria
23,895
def unload ( force = false ) if name == "ruby" and ! force Weechat . puts "Won't unload the ruby plugin unless you force it." false else Weechat . exec ( "/plugin unload #{name}" ) true end end
Unloads the plugin .
23,896
def scripts scripts = [ ] Infolist . parse ( "#{name}_script" ) . each do | script | scripts << Script . new ( script [ :pointer ] , self ) end scripts end
Returns an array of all scripts loaded by this plugin .
23,897
def ping ( host = @host , options = { } ) super ( host ) lhost = Socket . gethostname cs = "winmgmts:{impersonationLevel=impersonate}!//#{lhost}/root/cimv2" wmi = WIN32OLE . connect ( cs ) query = "select * from win32_pingstatus where address = '#{host}'" unless options . empty? options . each { | key , value | if value . is_a? ( String ) query << " and #{key} = '#{value}'" else query << " and #{key} = #{value}" end } end status = Struct :: PingStatus . new wmi . execquery ( query ) . each { | obj | status . address = obj . Address status . buffer_size = obj . BufferSize status . no_fragmentation = obj . NoFragmentation status . primary_address_resolution_status = obj . PrimaryAddressResolutionStatus status . protocol_address = obj . ProtocolAddress status . protocol_address_resolved = obj . ProtocolAddressResolved status . record_route = obj . RecordRoute status . reply_inconsistency = obj . ReplyInconsistency status . reply_size = obj . ReplySize status . resolve_address_names = obj . ResolveAddressNames status . response_time = obj . ResponseTime status . response_time_to_live = obj . ResponseTimeToLive status . route_record = obj . RouteRecord status . route_record_resolved = obj . RouteRecordResolved status . source_route = obj . SourceRoute status . source_route_type = obj . SourceRouteType status . status_code = obj . StatusCode status . timeout = obj . Timeout status . timestamp_record = obj . TimeStampRecord status . timestamp_record_address = obj . TimeStampRecordAddress status . timestamp_record_address_resolved = obj . TimeStampRecordAddressResolved status . timestamp_route = obj . TimeStampRoute status . time_to_live = obj . TimeToLive status . type_of_service = obj . TypeOfService } status . freeze end
Unlike the ping method for other Ping subclasses this version returns a PingStatus struct which contains various bits of information about the results of the ping itself such as response time .
23,898
def query ( sql , * args , & block ) fetched = nil execute do | dbh | result = dbh . execute ( sql , * args ) if block_given? then result . each ( & block ) else fetched = result . fetch ( :all ) end result . finish end fetched end
Runs the given query .
23,899
def transact ( sql = nil , * args ) if sql then sql , * args = replace_nil_binds ( sql , args ) transact { | dbh | dbh . execute ( sql , * args ) } elsif block_given? then execute { | dbh | dbh . transaction { yield dbh } } else raise ArgumentError . new ( "SQL executor is missing the required execution block" ) end end
Runs the given SQL or block in a transaction . If SQL is provided then that SQL is executed . Otherwise the block is called .