idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
23,300
def save! result = Api . post ( "#{BASE_PATH}/#{customer_id}" , body : attributes . to_json ) Customer . new ( result . parsed_response [ "rg_customer" ] ) end
Create or update a customer with given id
23,301
def parse_index_list self . seek ( self . stat . size - 200 ) tmp = self . read tmp =~ MzML :: RGX :: INDEX_OFFSET offset = $1 unless ( offset ) return compute_index_list end @index = { } @spectrum_list = [ ] @chromatogram_list = [ ] self . seek ( offset . to_i ) tmp = Nokogiri :: XML . parse ( self . read ) . root tmp . css ( "index" ) . each do | idx | index_type = idx [ :name ] . to_sym @index [ index_type ] = { } idx . css ( "offset" ) . each do | o | @index [ index_type ] [ o [ :idRef ] ] = o . text ( ) . to_i if index_type == :spectrum @spectrum_list << o [ :idRef ] else @chromatogram_list << o [ :idRef ] end end end self . rewind return @index end
Parses the IndexList
23,302
def expire ( ttl ) ttl = ( ttl . to_f * 1000 ) . floor return coerce_bool ( self . connection . pexpire ( @key , ttl ) ) end
Sets the key to expire after ttl seconds
23,303
def expire_at ( time ) time = ( time . to_f * 1000 ) . floor return coerce_bool ( self . connection . pexpireat ( @key , time ) ) end
Sets the key to expire at the given timestamp .
23,304
def restore ( serialized , ttl : 0 ) ttl = ( ttl . to_f * 1000 ) . floor return self . connection . restore ( @key , ttl , serialized ) end
Restores the struct to its serialized value as given
23,305
def parse ( args ) @global_opts = create_global_args ( args ) @cmd = args . shift || '' @search_data = '' if cmd == 'search' @search_data << args . shift unless args . empty? elsif ! CLI :: SUB_COMMANDS . include? ( cmd ) Trollop . die "unknown subcommand '#{cmd}'" end end
Parse arguments and setup attributes .
23,306
def field ( identifier ) ensure_loaded do fields . each do | f | return f if f . identifier == identifier end end nil end
The field with a specific identifier
23,307
def load_associated_collections array = association_fields if array . map { | f | f . collection_loaded? } . include? ( false ) StorageRoom . log ( "Fetching associated collections for '#{name}'" ) array . each { | f | f . collection } end end
Load all Collections that are related to the current one through AssociationFields
23,308
def created_by? ( check_user ) return false unless check_user . present? return true if check_user . cornerstone_admin? self . user && self . user == check_user end
returns true if it was created by given user or if given user is an admin
23,309
def participants ( exclude_email = nil ) ps = [ ] self . posts . each do | p | if p . author_name && p . author_email ps << [ p . author_name , p . author_email ] end end ps . delete_if { | p | p [ 1 ] == exclude_email } . uniq end
returns an array of participants for the discussion
23,310
def count ( column_name = nil , options = { } ) column_name , options = nil , column_name if column_name . is_a? ( Hash ) calculate ( :count , column_name , options ) end
Count operates using three different approaches .
23,311
def sum ( * args ) if block_given? self . to_a . sum ( * args ) { | * block_args | yield ( * block_args ) } else calculate ( :sum , * args ) end end
Calculates the sum of values on a given column . The value is returned with the same data type of the column 0 if there s no row . See + calculate + for examples with options .
23,312
def reorder ( * args ) return self if args . blank? relation = clone relation . reordering_value = true relation . order_values = args . flatten relation end
Replaces any existing order defined on the relation with the specified order .
23,313
def matches? ( person , context_binding ) matched = if BUILTIN_ROLES . include? @roles [ 0 ] has_builtin_authorization? person , context_binding else has_named_authorizations? person , context_binding end passed_conditionals = matched ? passes_conditionals? ( person , context_binding ) : false passed = matched && passed_conditionals return passed end
Creates a new PermitRule .
23,314
def best ( * names ) names . map do | name | @groups [ name ] || name end . flatten . each do | name | begin return const_get ( name ) rescue NameError , LoadError ; end end const_get ( names . first ) end
Return the first available dependency from the list of constant names .
23,315
def set_options ( opts ) opts . version , opts . banner = options . version , options . banner opts . set_program_name 'LinkShrink' options . api . map do | k , v | arg = k . to_s . downcase opts . on_head ( "-#{arg[0]}" , "--#{arg}" , argument_text_for ( k ) ) do options . api [ k ] = true end end opts . on_tail ( '-v' , '--version' , 'display the version of LinkShrink and exit' ) do puts opts . ver exit end opts . on_tail ( '-h' , '--help' , 'print this help' ) do puts opts . help exit end end
Configures the arguments for the command
23,316
def parse opts = OptionParser . new ( & method ( :set_options ) ) opts . parse! ( @args ) return process_url if url_present? opts . help end
Parses the command - line arguments and runs the executable
23,317
def log_and_raise ( exception , message , shift = 2 ) Base . log_and_raise ( config . ui . logger , exception , message , shift ) end
Logs an exception and then raises it .
23,318
def direct_log ( log_level , & blocK ) @config . ui . logger . nil? and raise BaseError , "You must supply a logger for direct logging support!" if ! block_given? log_and_raise ( BaseError , "You must supply a block to the log method!" ) elsif ( @config . ui . logger . level <= :: Logger . const_get ( log_level . to_s . upcase ) ) @config . ui . logger << ZTK :: ANSI . uncolor ( yield ) end end
Direct logging method .
23,319
def load_config_file_settings ( config_file_hash ) @login = config_file_hash . data [ :login ] @password = config_file_hash . data [ :password ] @cache_file_path = config_file_hash . data [ :cache_file_path ] @auto_check = config_file_hash . data [ :auto_check ] end
Load settings from the configuration file hash .
23,320
def load_cmd_line_settings ( options ) @login = options [ :login ] if options [ :login ] @password = options [ :password ] if options [ :password ] @cache_file_path = options [ :cache_file_path ] if options [ :cache_file_path ] @auto_check = options [ :auto_check ] if options [ :auto_check ] end
Load settings from the command line hash . Load a setting only if it was passed .
23,321
def create browser = Browser . new ( ua : params [ "user_agent" ] ) error_info = { message : params [ "message" ] , file_or_page : params [ "file_or_page" ] , line_number : params [ "line_number" ] , column_number : params [ "column_number" ] , user_agent : params [ "user_agent" ] , current_page : params [ "current_page" ] , platform : browser . platform . to_s . humanize , browser_name : browser . name , browser_version : browser . full_version , user_ip : request . remote_ip , referrer : request . env [ "HTTP_REFERER" ] , stack_trace : params [ "stack_trace" ] } :: TastesBitter :: JavascriptErrorsMailer . javascript_error ( error_info ) . deliver_later respond_to do | format | format . js { render nothing : true , status : :ok } end end
Responsible for handling errors sent from the browser parsing the data and sending the email with the information about the error .
23,322
def report_fields ( report_type ) soap_message = service . report_definition . report_fields ( credentials , report_type ) add_counters ( soap_message . counters ) els = soap_message . response . xpath ( "//getReportFieldsResponse/rval" ) els . map do | el | ReportField . from_element ( el ) end end
Query the list of field for a report type
23,323
def report_definition_delete ( repdef_or_id ) if repdef_or_id . class == ReportDefinition report_definition = repdef_or_id else report_definition = ReportDefinition . new ( self ) report_definition . instance_eval { @id = repdef_or_id } end op = ReportDefinitionOperation . remove ( report_definition ) soap_message = service . report_definition . mutate ( credentials , op . to_xml ) add_counters ( soap_message . counters ) unless @report_definitions @report_definition . delete_if { | repdef | repdef == report_definition . id } end report_definition . instance_eval { @id = - 1 } self end
Delete a report definition
23,324
def p_report_definitions ( refresh = false ) report_definitions ( refresh ) . each do | report_definition | puts report_definition . to_s end self end
Prints on stdout the list of report definition contained into account
23,325
def add_users ( users ) users . each do | user | unless @users_by_href . has_key? ( user . href ) @users_by_href [ user . href ] = RsUserPolicy :: User . new ( user ) end end end
Adds users to this collection only if the collection does not already include the specified users . The users RightScale API href is used as the unique identifier for deduplication
23,326
def receive ( ** options ) message = '' @socket . recv_string message message = message . match ( / \ \ /m ) decoded = ( options [ :decode ] || @decode ) . call message [ 'body' ] if block_given? yield decoded , message [ 'topic' ] else [ decoded , message [ 'topic' ] ] end end
Creates a new Subscriber socket .
23,327
def render ( tmpl ) t = Tilt . new ( File . join ( 'views' , tmpl ) ) t . render ( self ) end
Renders a template .
23,328
def get_json ( path ) @request_uri = "#{@base_uri}#{path}" req = get_request ( path ) @res = http_connection . start { | http | http . request ( req ) } handle_error ( @res , @request_uri ) JSON . parse ( @res . body ) end
GET the JSON API
23,329
def post_json ( path , data = { } ) @request_uri = "#{@base_uri}#{path}" body = JSON . generate ( data ) extheader = { 'Content-Type' => 'application/json' } req = post_request ( path , body , extheader ) @res = http_connection . start { | http | http . request ( req ) } handle_error ( @res , @request_uri ) JSON . parse ( @res . body ) end
POST the JSON API
23,330
def post_query ( path , data = { } ) @request_uri = "#{@base_uri}#{path}" body = URI . encode_www_form ( data ) extheader = { 'Content-Type' => 'application/x-www-form-urlencoded' } req = post_request ( path , body , extheader ) @res = http_connection . start { | http | http . request ( req ) } handle_error ( @res , @request_uri ) JSON . parse ( @res . body ) end
POST the non - JSON API
23,331
def tokens ( cmd , text ) valide_command! ( cmd ) Enumerator . new do | yielder | call ( cmd , text ) . each do | freeling_line | yielder << parse_token_line ( freeling_line ) unless freeling_line . empty? end end end
Generate tokens for a given text
23,332
def find_workspace params = { } workspaces . find do | ws | matches = true params . keys . each do | key | matches = matches && ( ws . send ( key . to_sym ) == params [ key ] ) end matches end end
Find a workspace according to the given params .
23,333
def ex ( klass , response ) klass . new ( "Expected response to have code 2xx, got #{response.code} instead" ) . tap do | ex | ex . response = response end end
Instantiates an exception and fills in a response .
23,334
def checkbox_should_be_checked ( checkbox , scope = { } ) in_scope ( scope ) do field_checked = find_field ( checkbox ) [ 'checked' ] if ! field_checked raise Kelp :: Unexpected , "Expected '#{checkbox}' to be checked, but it is unchecked." end end end
Verify that the given checkbox is checked .
23,335
def parse_email_headers ( s ) keys = { } match = ( s =~ / \A \w \w \s \_ \- \n \s \n / ) if match != 0 keys [ :data ] = s else keys [ :data ] = $' headers = $1 headers . split ( "\n" ) . each do | l | k , v = l . split ( ':' , 2 ) k , v = normalize_key_and_value ( k , v ) k = k . to_sym keys [ k ] = v end end keys end
This parses email headers . Returns an hash .
23,336
def normalize_key_and_value ( k , v ) v = v ? v . strip : true k = k . strip v = true if [ 'yes' , 'true' ] . include? ( v . to_s . downcase ) v = false if [ 'no' , 'false' ] . include? ( v . to_s . downcase ) k = k . downcase . gsub ( ' ' , '_' ) return k , v end
Keys are downcased space becomes underscore converted to symbols .
23,337
def number_of_leading_spaces ( s ) n = 0 ; i = 0 ; while i < s . size c = s [ i , 1 ] if c == ' ' i += 1 ; n += 1 ; elsif c == "\t" i += 1 ; n += TabSize ; else break end end n end
Returns the number of leading spaces considering that a tab counts as TabSize spaces .
23,338
def spaces_before_first_char ( s ) case s . md_type when :ulist i = 0 ; while s [ i , 1 ] =~ / \s / ; i += 1 end i += 1 while s [ i , 1 ] =~ / \s / ; i += 1 end return i when :olist i = 0 ; while s [ i , 1 ] =~ / \s / ; i += 1 end while s [ i , 1 ] =~ / \d / ; i += 1 end i += 1 while s [ i , 1 ] =~ / \s / ; i += 1 end return i else tell_user "BUG (my bad): '#{s}' is not a list" 0 end end
This returns the position of the first real char in a list item
23,339
def strip_hashes ( s ) s = s [ num_leading_hashes ( s ) , s . size ] i = s . size - 1 while i > 0 && ( s [ i , 1 ] =~ / \s / ) ; i -= 1 ; end s [ 0 , i + 1 ] . strip end
Strips initial and final hashes
23,340
def strip_indent ( s , n ) i = 0 while i < s . size && n > 0 c = s [ i , 1 ] if c == ' ' n -= 1 ; elsif c == "\t" n -= TabSize ; else break end i += 1 end s [ i , s . size ] end
toglie al massimo n caratteri
23,341
def dump ( options = { } ) options = options . dup limit = options . delete ( :nb ) || 100 self . find ( limit ) . map { | tl_entry | tl_entry . humanize ( options ) } end
Dump humanization of last timeline entries
23,342
def trim! if ( self . trim_max_length > 0 ) && ( self . count > self . trim_max_length ) last_tle = self . find ( 1 , :skip => self . trim_max_length - 1 ) . first if last_tle self . delete ( :before => last_tle . activity . at ) end end end
Remove old timeline entries
23,343
def content_related_to ( taxon , used_related_links ) statsd . time ( :taxonomy_sidebar_search_time ) do begin results = Services . rummager . search ( similar_to : @content_item . base_path , start : 0 , count : 3 , filter_taxons : [ taxon . content_id ] , filter_navigation_document_supertype : 'guidance' , reject_link : used_related_links . to_a , fields : %w[ title link ] , ) [ 'results' ] statsd . increment ( :taxonomy_sidebar_searches ) results . map { | result | { title : result [ 'title' ] , link : result [ 'link' ] , } } . sort_by { | result | result [ :title ] } rescue StandardError => e GovukNavigationHelpers . configuration . error_handler . notify ( e ) [ ] end end end
This method will fetch content related to content_item and tagged to taxon . This is a temporary method that uses search to achieve this . This behaviour is to be moved into the content store
23,344
def to_sp_text ( rounds , format ) attrs = [ num . to_s , name , id . to_s , ( '%.1f' % points ) . sub ( / \. / , '' ) ] ( 1 .. rounds ) . each do | r | result = find_result ( r ) attrs << ( result ? result . to_sp_text : " : " ) end format % attrs end
Format a player s record as it would appear in an SP text export file .
23,345
def to_sp_text sp = opponent ? opponent . to_s : '0' sp << ':' if rateable sp << score else sp << case score when 'W' then '+' when 'L' then '-' else '=' end end end
Format a player s result as it would appear in an SP text export file .
23,346
def get_baseline_value ( baseline_type , obj , ts = Time . now . ceil ) unless Octo :: Counter . constants . include? baseline_type raise ArgumentError , 'No such baseline defined' end args = { ts : ts , type : Octo :: Counter . const_get ( baseline_type ) , uid : obj . unique_id , enterprise_id : obj . enterprise . id } bl = get_cached ( args ) if bl bl . val else 0.01 end end
Finds baseline value of an object
23,347
def aggregate ( type , ts ) Octo :: Enterprise . each do | enterprise | aggregate_baseline enterprise . id , type , ts end end
Does an aggregation of type for a timestamp
23,348
def aggregate_baseline ( enterprise_id , type , ts = Time . now . floor ) clazz = @baseline_for . constantize _ts = ts start_calc_time = ( _ts . to_datetime - MAX_DURATION . day ) . to_time last_n_days_interval = start_calc_time . ceil . to ( _ts , 24 . hour ) last_n_days_interval . each do | hist | args = { ts : hist , type : type , enterprise_id : enterprise_id } counters = @baseline_for . constantize . send ( :where , args ) baseline = baseline_from_counters ( counters ) store_baseline enterprise_id , type , hist , baseline end end
Aggregates the baseline for a minute
23,349
def store_baseline ( enterprise_id , type , ts , baseline ) return if baseline . nil? or baseline . empty? baseline . each do | uid , val | self . new ( { enterprise_id : enterprise_id , type : type , ts : ts , uid : uid , val : val } ) . save! end end
Stores the baseline for an enterprise and type
23,350
def baseline_from_counters ( counters ) baseline = { } uid_groups = counters . group_by { | x | x . uid } uid_groups . each do | uid , counts | baseline [ uid ] = score_counts ( counts ) end baseline end
Calculates the baseline from counters
23,351
def score_counts ( counts ) if counts . count > 0 _num = counts . map { | x | x . obp } _num . percentile ( 90 ) else 0.01 end end
Calculates the baseline score from an array of scores
23,352
def locale_dating_naming_checks ( args , options ) options . reverse_merge! ( :format => :default ) options [ :ending ] ||= "as_#{options[:format]}" . to_sym unless options [ :format ] == :default options [ :ending ] ||= :as_text raise MethodOverwriteError , "multiple attributes cannot be wrapped with an explicitly named method" if args . length > 1 && options . key? ( :name ) end
Given the options for a locale_dating call set the defaults for the naming convention to use .
23,353
def escape_symbols ( txt ) esc = '' txt . to_s . each_byte { | byte | esc << if ( entity = @@symbol_entities [ byte ] ) '&' << entity << ';' else byte end } esc end
escape symbol - font strings
23,354
def nacho_select_tag ( name , choices = nil , options = { } , html_options = { } ) nacho_options = build_options ( name , choices , options , html_options ) select_element = select_tag ( name , options_for_select ( nacho_options [ :choices ] ) , nacho_options [ :options ] , nacho_options [ :html_options ] ) select_element += nacho_options [ :button ] if nacho_options [ :html_options ] [ :multiple ] select_element end
A tag helper version for a FormBuilder class . Will create the select and the needed modal that contains the given form for the target model to create .
23,355
def create_custom_activity ( options = { } ) response = connection . post do | req | req . url "custom_activities" , options end return_error_or_body ( response ) end
Notify checkd . in of a custom activity ocurring
23,356
def list ( domain = nil ) if domain @mailgun . response = Mailgun :: Base . fire ( :get , @mailgun . api_url + "/domains/#{domain}" ) else @mailgun . response = Mailgun :: Base . fire ( :get , @mailgun . api_url + "/domains" ) [ "items" ] || [ ] end end
Used internally List Domains . If domain name is passed return detailed information otherwise return a list of all domains .
23,357
def add ( response ) if @list . key? response . name raise DuplicateResponse , "A response named #{response.name} already exists" end @list [ response . name ] = response end
Add a response to the list
23,358
def restore_attrs draftable_columns . each do | key | self . send "#{key}=" , self . draft . data [ key ] if self . respond_to? ( key ) end self end
Whack the draft data onto the real object .
23,359
def restore_files draft . draft_uploads . each do | draft_upload | uploader = draft_upload . draftable_mount_column self . send ( uploader + "=" , draft_upload . file_data ) end end
Attach draft files to the real object .
23,360
def body_tag ( options = { } , & block ) options = canonicalize_options ( options ) options . delete ( :class ) if options [ :class ] . blank? options [ :data ] ||= { } options [ :data ] [ :controller ] = controller . controller_name options [ :data ] [ :action ] = controller . action_name content_tag ( :body , options ) do yield end end
Includes controller and action name as data attributes .
23,361
def errors found_errors = @record . all ( '[data-error-for]' ) error_list = ActiveModel :: Errors . new ( self ) found_errors . each do | error | attribute = error [ 'data-error-for' ] message = error . text error_list . add ( attribute , message ) end error_list end
Searches the record for any errors and returns them
23,362
def kaltura_player_embed ( entry_id , options = { } ) player_conf_parameter = "/ui_conf_id/" options [ :div_id ] ||= "kplayer" options [ :size ] ||= [ ] options [ :use_url ] ||= false width = PLAYER_WIDTH height = PLAYER_HEIGHT source_type = "entryId" unless options [ :size ] . empty? width = options [ :size ] . first height = options [ :size ] . last end if options [ :use_url ] == true source_type = "url" end unless options [ :player_conf_id ] . nil? player_conf_parameter += "#{options[:player_conf_id]}" else unless KalturaFu . config . player_conf_id . nil? player_conf_parameter += "#{KalturaFu.config.player_conf_id}" else player_conf_parameter += "#{DEFAULT_KPLAYER}" end end "<div id=\"#{options[:div_id]}\"></div> <script type=\"text/javascript\"> var params= { allowscriptaccess: \"always\", allownetworking: \"all\", allowfullscreen: \"true\", wmode: \"opaque\", bgcolor: \"#000000\" }; var flashVars = {}; flashVars.sourceType = \"#{source_type}\"; flashVars.entryId = \"#{entry_id}\"; flashVars.emptyF = \"onKdpEmpty\"; flashVars.readyF = \"onKdpReady\"; var attributes = { id: \"#{options[:div_id]}\", name: \"#{options[:div_id]}\" }; swfobject.embedSWF(\"#{KalturaFu.config.service_url}/kwidget/wid/_#{KalturaFu.config.partner_id}" + player_conf_parameter + "\",\"#{options[:div_id]}\",\"#{width}\",\"#{height}\",\"10.0.0\",\"http://ttv.mit.edu/swfs/expressinstall.swf\",flashVars,params,attributes); </script>" end
Returns the code needed to embed a KDPv3 player .
23,363
def kaltura_seek_link ( content , seek_time , options = { } ) options [ :div_id ] ||= "kplayer" options [ :onclick ] = "$(#{options[:div_id]}).get(0).sendNotification('doSeek',#{seek_time});window.scrollTo(0,0);return false;" options . delete ( :div_id ) link_to ( content , "#" , options ) end
Creates a link_to tag that seeks to a certain time on a KDPv3 player .
23,364
def op ( sym , o ) case o when Duration Duration . new ( @seconds . send ( sym , o . to_i ) ) when Numeric Duration . new ( @seconds . send ( sym , o ) ) else a , b = o . coerce ( self ) a . send ( sym , b ) end end
generic operator implementation
23,365
def follow ( link , scope = { } ) in_scope ( scope ) do begin click_link ( link ) rescue Capybara :: ElementNotFound raise Kelp :: MissingLink , "No link with title, id or text '#{link}' found" end end end
Follow a link on the page .
23,366
def press ( button , scope = { } ) in_scope ( scope ) do begin click_button ( button ) rescue Capybara :: ElementNotFound raise Kelp :: MissingButton , "No button with value, id or text '#{button}' found" end end end
Press a button on the page .
23,367
def click_link_in_row ( link , text ) begin row = find ( :xpath , xpath_row_containing ( [ link , text ] ) ) rescue Capybara :: ElementNotFound raise Kelp :: MissingRow , "No table row found containing '#{link}' and '#{text}'" end begin row . click_link ( link ) rescue Capybara :: ElementNotFound raise Kelp :: MissingLink , "No link with title, id or text '#{link}' found in the same row as '#{text}'" end end
Click a link in a table row containing the given text .
23,368
def should_be_on_page ( page_name_or_path ) if defined? path_to expect_path = path_to ( page_name_or_path ) else expect_path = page_name_or_path end actual_path = URI . parse ( current_url ) . path if actual_path != expect_path raise Kelp :: Unexpected , "Expected to be on page: '#{expect_path}'" + "\nActually on page: '#{actual_path}'" end end
Verify that the current page matches the path of page_name_or_path . The cucumber - generated path_to function will be used if it s defined to translate human - readable names into URL paths . Otherwise assume a raw absolute path string .
23,369
def should_have_query ( params ) query = URI . parse ( current_url ) . query actual_params = query ? CGI . parse ( query ) : { } expected_params = { } params . each_pair do | k , v | expected_params [ k ] = v . split ( ',' ) end if actual_params != expected_params raise Kelp :: Unexpected , "Expected query params: '#{expected_params.inspect}'" + "\nActual query params: '#{actual_params.inspect}'" end end
Verify that the current page has the given query parameters .
23,370
def compile compiled_assets = { } machined . sprockets . each do | sprocket | next unless sprocket . compile? sprocket . each_logical_path do | logical_path | url = File . join ( sprocket . config . url , logical_path ) next unless compiled_assets [ url ] . nil? && compile? ( url ) if asset = sprocket . find_asset ( logical_path ) compiled_assets [ url ] = write_asset ( sprocket , asset ) end end end compiled_assets end
Creates a new instance which will compile the assets to the given + output_path + . Loop through and compile each available asset to the appropriate output path .
23,371
def write_asset ( environment , asset ) filename = path_for ( environment , asset ) FileUtils . mkdir_p File . dirname ( filename ) asset . write_to filename asset . write_to "#{filename}.gz" if gzip? ( filename ) asset . digest end
Writes the asset to its destination also writing a gzipped version if necessary .
23,372
def path_for ( environment , asset ) path = digest? ( environment , asset ) ? asset . digest_path : asset . logical_path File . join ( machined . output_path , environment . config . url , path ) end
Gets the full output path for the given asset . If it s supposed to include a digest it will return the digest_path .
23,373
def call ( env ) @request = Rack :: Request . new ( env ) @params = @path_params . merge ( @request . params . symbolize_keys ) process_response ( instance_exec ( self , params , request , & @block ) ) end
Creates a new RouteHandler wrapping a handler block .
23,374
def join_table_name ( first_table_name , second_table_name ) if first_table_name < second_table_name join_table = "#{first_table_name}_#{second_table_name}" else join_table = "#{second_table_name}_#{first_table_name}" end model . table_name_prefix + join_table + model . table_name_suffix end
Generates a join table name from two provided table names . The names in the join table names end up in lexicographic order .
23,375
def row_counts ( number_of_columns ) per_column = ( number_of_elements / number_of_columns ) . floor counts = [ per_column ] * number_of_columns left_overs = number_of_elements % number_of_columns left_overs . times { | n | counts [ n ] = counts [ n ] + 1 } counts end
Returns an array with an element for each column containing the number of rows for that column
23,376
def require_models model_dir = File . join ( File . dirname ( __FILE__ ) , %w{ model } ) unless Dir . exist? model_dir raise "model directory '#{model_dir}' not exists" end Dir [ File . join ( model_dir , '*.rb' ) ] . each do | f | require f end end
model must be loaded after the connection is established
23,377
def solrize_objects ( opts = { } ) num_docs = 1000000 puts "WARNING: You have turned off indexing of Full Text content. Be sure to re-run indexer with @@index_full_text set to true in main.rb" if index_full_text == false if @@index_list == false solrize_from_fedora_search ( opts ) else solrize_from_csv end end
Retrieve a comprehensive list of all the unique identifiers in Fedora and solrize each object s full - text and facets into the search index
23,378
def generate_files ip = local_ip version = Farmstead :: VERSION scaffold_path = "#{File.dirname __FILE__}/scaffold" scaffold = Dir . glob ( "#{scaffold_path}/**/*.erb" , File :: FNM_DOTMATCH ) scaffold . each do | file | basename = File . basename ( file ) folderstruct = file . match ( "#{scaffold_path}/(.*)" ) [ 1 ] if basename != folderstruct foldername = File . dirname ( folderstruct ) create_recursive ( "#{@name}/#{foldername}" ) end projectpath = "#{@name}/#{folderstruct}" . chomp ( ".erb" ) template = File . read ( file ) results = ERB . new ( template ) . result ( binding ) copy_to_directory ( results , projectpath ) end end
Generate from templates in scaffold
23,379
def acts_as_referred ( options = { } ) has_one :referee , as : :referable , dependent : :destroy , class_name : 'Referee' after_create :create_referrer include ActsAsReferred :: InstanceMethods end
Hook to serve behavior to ActiveRecord - Descendants
23,380
def add_role_reader_for! ( rolekey ) return if private_method_defined? ( rolekey ) define_method ( rolekey ) { __context . send ( rolekey ) } private rolekey end
Defines a new private reader instance method for a context mate role delegating it to the context object .
23,381
def render @result_html = '' @result_html += "<div class=\"rs-container #{self.class.name}\" id=\"#{@id}\">" @result_html += render_controls . gsub ( "<option value=\"rs-#{@effect}\">" , "<option value=\"rs-#{@effect}\" selected=\"selected\">" ) @result_html += "<div class=\"rs-wrapper\">" @result_html += "<div class=\"rs-shadow\"></div>" @result_html += '<div class="rs-images">' @images_urls . each do | url | @result_html += "<img src=\"#{url}\"/>" end @result_html += '</div>' @result_html += '<div class="rs-cover">' @result_html += '<a class="rs-animation-command rs-pause" href="javascript:void(0)">Play/Pause</a>' @result_html += "<img src=\"#{@images_urls.first}\"/>" @result_html += '</div>' @result_html += '<div class="rs-transition">' @result_html += render_flips @result_html += render_multi_flips @result_html += render_cubes @result_html += render_unfolds @result_html += '</div>' @result_html += '</div>' @result_html += render_bullets @result_html += '</div>' @result_html . html_safe end
rendering images with rails slider effects
23,382
def admin_menu @admin_menu ||= [ [ 'overview' , :dashboard , { controller : 'gricer/dashboard' , action : 'overview' } ] , [ 'visitors' , :menu , [ [ 'entry_pages' , :spread , { controller : 'gricer/requests' , action : 'spread_stats' , field : 'entry_path' } ] , [ 'referers' , :spread , { controller : 'gricer/requests' , action : 'spread_stats' , field : 'referer_host' } ] , [ 'search_engines' , :spread , { controller : 'gricer/requests' , action : 'spread_stats' , field : 'search_engine' } ] , [ 'search_terms' , :spread , { controller : 'gricer/requests' , action : 'spread_stats' , field : 'search_query' } ] , [ 'countries' , :spread , { controller : 'gricer/sessions' , action : 'spread_stats' , field : 'country' } ] , [ 'domains' , :spread , { controller : 'gricer/sessions' , action : 'spread_stats' , field : 'domain' } ] , [ 'locales' , :spread , { controller : 'gricer/sessions' , action : 'spread_stats' , field : 'requested_locale_major' } ] ] ] , [ 'pages' , :menu , [ [ 'views' , :spread , { controller : 'gricer/requests' , action : 'spread_stats' , field : 'path' } ] , [ 'hosts' , :spread , { controller : 'gricer/requests' , action : 'spread_stats' , field : 'host' } ] , [ 'methods' , :spread , { controller : 'gricer/requests' , action : 'spread_stats' , field : 'method' } ] , [ 'protocols' , :spread , { controller : 'gricer/requests' , action : 'spread_stats' , field : 'protocol' } ] , ] ] , [ 'browsers' , :menu , [ [ 'browsers' , :spread , { controller : 'gricer/sessions' , action : 'spread_stats' , field : 'agent.name' } ] , [ 'operating_systems' , :spread , { controller : 'gricer/sessions' , action : 'spread_stats' , field : 'agent.os' } ] , [ 'engines' , :spread , { controller : 'gricer/sessions' , action : 'spread_stats' , field : 'agent.engine_name' } ] , [ 'javascript' , :spread , { controller : 'gricer/sessions' , action : 'spread_stats' , field : 'javascript' } ] , [ 'java' , :spread , { controller : 'gricer/sessions' , action : 'spread_stats' , field : 'java' } ] , [ 'silverlight' , :spread , { controller : 'gricer/sessions' , action : 'spread_stats' , field : 'silverlight_major_version' } ] , [ 'flash' , :spread , { controller : 'gricer/sessions' , action : 'spread_stats' , field : 'flash_major_version' } ] , [ 'screen_sizes' , :spread , { controller : 'gricer/sessions' , action : 'spread_stats' , field : 'screen_size' } ] , [ 'color_depths' , :spread , { controller : 'gricer/sessions' , action : 'spread_stats' , field : 'screen_depth' } ] ] ] ] end
Configure the structure of Gricer s admin menu
23,383
def process_field ( child ) if [ 'complexContent' , 'simpleContent' , 'sequence' , 'group' , 'choice' , 'extension' , 'restriction' ] . include? ( child . name ) child . elements . each { | grandchild | process_field ( grandchild ) } elsif child . name == 'element' element = Element . new ( child , self . schema , self ) @elements [ element . name ] = element elsif child . name == 'attribute' attribute = Attribute . new ( child , self . schema , self ) @attributes [ attribute . name ] = attribute elsif child . name == 'complexType' type = ComplexType . build ( child , self . schema ) @types [ type . name ] = type elsif child . name == 'simpleType' type = SimpleType . build ( child , self . schema ) @types [ type . name ] = type elsif child . name == 'anyAttribute' @special_fields << SpecialField . new ( "##anyAttribute" ) elsif child . name == 'anyElement' @special_fields << SpecialField . new ( "##anyElement" ) elsif child . name == 'attributeGroup' if self . kind_of? ( Schema ) type = ComplexType . build ( child , self . schema ) @types [ type . name ] = type else Type . find ( child . attributes [ 'ref' ] . value , nil , stix_version ) . attributes . each { | attrib | @attributes [ attrib . name ] = attrib } end else $logger . debug "Skipping: #{child.name}" if defined? ( $logger ) end end
Runs through the list of fields under this type and creates the appropriate objects
23,384
def helper_exist? ( helper ) Object . const_defined? ( helper ) && Object . const_get ( helper ) . instance_of? ( :: Module ) end
check if the helper exist
23,385
def logging_query_plan return yield unless logger threshold = auto_explain_threshold_in_seconds current = Thread . current if threshold && current [ :available_queries_for_explain ] . nil? begin queries = current [ :available_queries_for_explain ] = [ ] start = Time . now result = yield logger . warn ( exec_explain ( queries ) ) if Time . now - start > threshold result ensure current [ :available_queries_for_explain ] = nil end else yield end end
If auto explain is enabled this method triggers EXPLAIN logging for the queries triggered by the block if it takes more than the threshold as a whole . That is the threshold is not checked against each individual query but against the duration of the entire block . This approach is convenient for relations .
23,386
def silence_auto_explain current = Thread . current original , current [ :available_queries_for_explain ] = current [ :available_queries_for_explain ] , false yield ensure current [ :available_queries_for_explain ] = original end
Silences automatic EXPLAIN logging for the duration of the block .
23,387
def validate_spki unless @spki . is_a? ( OpenSSL :: ASN1 :: Sequence ) raise SPKIError , "SPKI data is not an ASN1 sequence (got a #{@spki.class})" end if @spki . value . length != 2 raise SPKIError , "SPKI top-level sequence must have two elements (length is #{@spki.value.length})" end alg_id , key_data = @spki . value unless alg_id . is_a? ( OpenSSL :: ASN1 :: Sequence ) raise SPKIError , "SPKI algorithm_identifier must be a sequence (got a #{alg_id.class})" end unless ( 1 .. 2 ) === alg_id . value . length raise SPKIError , "SPKI algorithm sequence must have one or two elements (got #{alg_id.value.length} elements)" end unless alg_id . value . first . is_a? ( OpenSSL :: ASN1 :: ObjectId ) raise SPKIError , "SPKI algorithm identifier does not contain an object ID (got #{alg_id.value.first.class})" end unless key_data . is_a? ( OpenSSL :: ASN1 :: BitString ) raise SPKIError , "SPKI publicKeyInfo field must be a BitString (got a #{@spki.value.last.class})" end end
Make sure that the SPKI data we were passed is legit .
23,388
def setsockopt name , value , length = nil if 1 == @option_lookup [ name ] length = 8 pointer = LibC . malloc length pointer . write_long_long value elsif 0 == @option_lookup [ name ] length = 4 pointer = LibC . malloc length pointer . write_int value elsif 2 == @option_lookup [ name ] length ||= value . size pointer = LibC . malloc length pointer . write_string value end rc = LibXS . xs_setsockopt @socket , name , pointer , length LibC . free ( pointer ) unless pointer . nil? || pointer . null? rc end
Allocates a socket of type + type + for sending and receiving data .
23,389
def more_parts? rc = getsockopt XS :: RCVMORE , @more_parts_array Util . resultcode_ok? ( rc ) ? @more_parts_array . at ( 0 ) : false end
Convenience method for checking on additional message parts .
23,390
def send_strings parts , flag = 0 return - 1 if ! parts || parts . empty? flag = NonBlocking if dontwait? ( flag ) parts [ 0 .. - 2 ] . each do | part | rc = send_string part , ( flag | XS :: SNDMORE ) return rc unless Util . resultcode_ok? ( rc ) end send_string parts [ - 1 ] , flag end
Send a sequence of strings as a multipart message out of the + parts + passed in for transmission . Every element of + parts + should be a String .
23,391
def send_and_close message , flag = 0 rc = sendmsg message , flag message . close rc end
Sends a message . This will automatically close the + message + for both successful and failed sends .
23,392
def recv_strings list , flag = 0 array = [ ] rc = recvmsgs array , flag if Util . resultcode_ok? ( rc ) array . each do | message | list << message . copy_out_string message . close end end rc end
Receive a multipart message as a list of strings .
23,393
def recv_multipart list , routing_envelope , flag = 0 parts = [ ] rc = recvmsgs parts , flag if Util . resultcode_ok? ( rc ) routing = true parts . each do | part | if routing routing_envelope << part routing = part . size > 0 else list << part end end end rc end
Should only be used for XREQ XREP DEALER and ROUTER type sockets . Takes a + list + for receiving the message body parts and a + routing_envelope + for receiving the message parts comprising the 0mq routing information .
23,394
def sockopt_buffers option_type if 1 == option_type unless @longlong_cache length = FFI :: MemoryPointer . new :size_t length . write_int 8 @longlong_cache = [ FFI :: MemoryPointer . new ( :int64 ) , length ] end @longlong_cache elsif 0 == option_type unless @int_cache length = FFI :: MemoryPointer . new :size_t length . write_int 4 @int_cache = [ FFI :: MemoryPointer . new ( :int32 ) , length ] end @int_cache elsif 2 == option_type length = FFI :: MemoryPointer . new :size_t length . write_int 255 [ FFI :: MemoryPointer . new ( 255 ) , length ] else unless @int_cache length = FFI :: MemoryPointer . new :size_t length . write_int 4 @int_cache = [ FFI :: MemoryPointer . new ( :int32 ) , length ] end @int_cache end end
Calls to xs_getsockopt require us to pass in some pointers . We can cache and save those buffers for subsequent calls . This is a big perf win for calling RCVMORE which happens quite often . Cannot save the buffer for the IDENTITY .
23,395
def getsockopt name , array rc = __getsockopt__ name , array if Util . resultcode_ok? ( rc ) && ( RCVMORE == name ) array [ 0 ] = 1 == array [ 0 ] end rc end
Get the options set on this socket .
23,396
def role = role raise ArgumentError , '#add_role takes a single role String or Symbol as the argument' if ! role || role . kind_of? ( Array ) self . roles = role end
set a single role
23,397
def add_role role raise ArgumentError , '#add_role takes a single role String or Symbol as the argument' if ! role || role . kind_of? ( Array ) add_roles role end
add a single role
23,398
def remove_role role raise ArgumentError , '#remove_role takes a single role String or Symbol as the argument' if ! role || role . kind_of? ( Array ) remove_roles role end
remove a single role
23,399
def v8_context V8 :: C :: Locker ( ) do context = V8 :: Context . new context . eval ( source ) yield context end end
V8 context with Handlerbars code compiled