idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
23,500 | def xpath_row_containing ( texts ) texts = [ texts ] if texts . class == String conditions = texts . collect do | text | "contains(., #{xpath_sanitize(text)})" end . join ( ' and ' ) return ".//tr[#{conditions}]" end | Return an XPath for any table row containing all strings in texts within the current context . |
23,501 | def respond_to_action_responses if ! respond_to_performed? && action_responses . any? respond_to do | responder | action_responses . each { | response | instance_exec ( responder , & response ) } end end end | if the response . content_type has not been set ( if it has then responthere are responses for the current action then respond_to them |
23,502 | def load_dir ( src_dir ) merged_content = "" Pathname . glob ( "#{src_dir}/*.yml" ) . sort . each do | yaml_path | content = yaml_path . read . gsub ( / / , "" ) merged_content << content end YAML . load ( merged_content ) end | load divided yaml files |
23,503 | def translation_locale locale = @translation_locale || I18n . locale . to_s locale == I18n . default_locale . to_s ? nil : locale end | Provide the locale which is currently in use with the object or the current global locale . If the default is in use always return nil . |
23,504 | def translation if translation_enabled? if ! @translation || ( @translation . locale != translation_locale ) raise MissingParent , "Cannot create translations without a stored parent" if new_record? @translation = translations . where ( :locale => translation_locale ) . first || translations . build ( :locale => translation_locale ) end @translation else nil end end | Provide a translation object based on the parent and the translation_locale current value . |
23,505 | def attributes_with_locale = ( new_attributes , guard_protected_attributes = true ) return if new_attributes . nil? attributes = new_attributes . dup attributes . stringify_keys! attributes = sanitize_for_mass_assignment ( attributes ) if guard_protected_attributes send ( :locale= , attributes [ "locale" ] ) if attributes . has_key? ( "locale" ) and respond_to? ( :locale= ) send ( :attributes_without_locale= , attributes , guard_protected_attributes ) end | Override the default mass assignment method so that the locale variable is always given preference . |
23,506 | def validate_parents parent_relationships . each do | relationship | parent = relationship . get ( self ) unless parent . valid? unless errors [ relationship . name ] . include? ( parent . errors ) errors [ relationship . name ] = parent . errors end end end end | Run validations on the associated parent resources |
23,507 | def validate_children child_associations . each do | collection | if collection . dirty? collection . each do | child | unless child . valid? relationship_errors = ( errors [ collection . relationship . name ] ||= [ ] ) unless relationship_errors . include? ( child . errors ) relationship_errors << child . errors end end end end end end | Run validations on the associated child resources |
23,508 | def method_missing ( meth , * args , & block ) db . to_hash ( :key , :value ) . send ( meth , * args , & block ) end | Handle all other Hash methods |
23,509 | def validate_key ( key ) unless key . is_a? ( Symbol ) || key . is_a? ( String ) raise ArgumentError , 'Key must be a string or symbol' end key end | Make sure the key is valid |
23,510 | def run ( ** options ) @options = options fail RequirementsNotMet . new ( "#{self} requires the following parameters #{requirements}" ) unless requirements_met? new ( @options ) . tap do | interaction | interaction . __send__ ( :run ) end end | checks if requirements are met from the requires params creates an instance of the interaction calls run on the instance |
23,511 | def run! ( ** options ) interaction = run ( options ) raise error_class . new ( interaction . error ) unless interaction . success? interaction . result end | runs interaction raises if any error or returns the interaction result |
23,512 | def add_option ( name , parameters ) self . class . handle_warnings ( name , ** parameters . dup ) chain_options . merge ( name => parameters . merge ( method_hash ( parameters ) ) ) end | Checks the given option - parameters for incompatibilities and registers a new option . |
23,513 | def option ( name ) config = chain_options [ name ] || raise_no_option_error ( name ) Option . new ( config ) . tap { | o | o . initial_value ( values [ name ] ) if values . key? ( name ) } end | Returns an option registered under name . |
23,514 | def set_request_defaults ( endpoint , private_token , sudo = nil ) raise Error :: MissingCredentials . new ( "Please set an endpoint to API" ) unless endpoint @private_token = private_token self . class . base_uri endpoint self . class . default_params :sudo => sudo self . class . default_params . delete ( :sudo ) if sudo . nil? end | Sets a base_uri and default_params for requests . |
23,515 | def best_match ( given_word ) words = ( @word_list . is_a? Array ) ? @word_list : @word_list . keys word_bigrams = bigramate ( given_word ) word_hash = words . map do | key | [ key , bigram_compare ( word_bigrams , bigramate ( key ) ) ] end word_hash = Hash [ word_hash ] word_hash = apply_usage_weights ( word_hash ) if @word_list . is_a? Hash word_hash . max_by { | _key , value | value } . first end | Returns the closest matching word in the dictionary |
23,516 | def num_matching ( one_bigrams , two_bigrams , acc = 0 ) return acc if one_bigrams . empty? || two_bigrams . empty? one_two = one_bigrams . index ( two_bigrams [ 0 ] ) two_one = two_bigrams . index ( one_bigrams [ 0 ] ) if one_two . nil? && two_one . nil? num_matching ( one_bigrams . drop ( 1 ) , two_bigrams . drop ( 1 ) , acc ) else two_one ||= one_two one_two ||= two_one if one_two < two_one num_matching ( one_bigrams . drop ( one_two + 1 ) , two_bigrams . drop ( 1 ) , acc + 1 ) else num_matching ( one_bigrams . drop ( 1 ) , two_bigrams . drop ( two_one + 1 ) , acc + 1 ) end end end | Returns the number of matching bigrams between the two sets of bigrams |
23,517 | def bigram_compare ( word1_bigrams , word2_bigrams ) most_bigrams = [ word1_bigrams . count , word2_bigrams . count ] . max num_matching ( word1_bigrams , word2_bigrams ) . to_f / most_bigrams end | Returns a value from 0 to 1 for how likely these two words are to be a match |
23,518 | def apply_usage_weights ( word_hash ) max_usage = @word_list . values . max . to_f max_usage = 1 if max_usage == 0 weighted_array = word_hash . map do | word , bigram_score | usage_score = @word_list [ word ] . to_f / max_usage [ word , ( bigram_score * ( 1 - @alpha ) ) + ( usage_score * @alpha ) ] end Hash [ weighted_array ] end | For each word adjust it s score by usage |
23,519 | def call ( env ) conf = configuration ( env ) if login_required? ( env ) if interactive? ( env ) :: Warden :: Strategies [ conf . ui_mode ] . new ( env ) . on_ui_failure . finish else headers = { } headers [ "WWW-Authenticate" ] = conf . api_modes . collect { | mode_key | :: Warden :: Strategies [ mode_key ] . new ( env ) . challenge } . join ( "\n" ) headers [ "Content-Type" ] = "text/plain" [ 401 , headers , [ "Authentication required" ] ] end else log_authorization_failure ( env ) msg = "#{user(env).username} may not use this page." Rack :: Response . new ( "<html><head><title>Authorization denied</title></head><body>#{msg}</body></html>" , 403 , "Content-Type" => "text/html" ) . finish end end | Receives the rack environment in case of a failure and renders a response based on the interactiveness of the request and the nature of the configured modes . |
23,520 | def shuffle_by ( playlist , field ) pl = playlist . entries . wait . value artists = Hash . new rnd = Random . new playlist . clear . wait field = field . to_sym pl . each do | id | infos = self . medialib_get_info ( id ) . wait . value a = infos [ field ] . first [ 1 ] if artists . has_key? ( a ) artists [ a ] . insert ( 0 , id ) else artists [ a ] = [ id ] end end artist_names = artists . keys for _ in pl artist_idx = ( rnd . rand * artist_names . length ) . to_i artist = artist_names [ artist_idx ] songs = artists [ artist ] song_idx = rnd . rand * songs . length song = songs [ song_idx ] playlist . add_entry ( song ) . wait songs . delete ( song ) if songs . empty? artists . delete ( artist ) artist_names . delete ( artist ) end end end | Shuffles the playlist by selecting randomly among the tracks as grouped by the given field |
23,521 | def extract_medialib_info ( id , * fields ) infos = self . medialib_get_info ( id ) . wait . value res = Hash . new if ! infos . nil? fields = fields . map! { | f | f . to_sym } fields . each do | field | values = infos [ field ] if not values . nil? my_value = values . first [ 1 ] if field == :url my_value = Xmms :: decode_xmms2_url ( my_value ) end res [ field ] = my_value . to_s . force_encoding ( "utf-8" ) end end end res end | returns a hash of the passed in fields with the first - found values for the fields |
23,522 | def check_scope ( scope = nil ) return self unless scope change_scope = / \s \[ \w \] / . match ( @note ) return self unless change_scope if change_scope [ 0 ] [ 1 .. - 2 ] == scope @note = change_scope . post_match . strip return self else return nil end end | Checks the scope of the Change and the change out if the scope does not match . |
23,523 | def vms logger . debug "get all VMs in all datacenters: begin" result = dcs . inject ( [ ] ) do | r , dc | r + serviceContent . viewManager . CreateContainerView ( container : dc . vmFolder , type : [ 'VirtualMachine' ] , recursive : true ) . view end logger . debug "get all VMs in all datacenters: end" result end | get all vms in all datacenters |
23,524 | def various? joined_names = "#{name} #{appears_as}" . downcase various_variations = [ "vario" , "v???????????????rio" , "v.a" , "vaious" , "varios" "vaious" , "varoius" , "variuos" , "soundtrack" , "karaoke" , "original cast" , "diverse artist" ] various_variations . each { | various_variation | return true if joined_names . include? ( various_variation ) } return false end | does this artist represents various artists? |
23,525 | def command_callback ( id , buffer , args ) Weechat :: Command . find_by_id ( id ) . call ( Weechat :: Buffer . from_ptr ( buffer ) , args ) end | low level Callback method used for commands |
23,526 | def command_run_callback ( id , buffer , command ) Weechat :: Hooks :: CommandRunHook . find_by_id ( id ) . call ( Weechat :: Buffer . from_ptr ( buffer ) , command ) end | low level Callback used for running commands |
23,527 | def timer_callback ( id , remaining ) Weechat :: Timer . find_by_id ( id ) . call ( remaining . to_i ) end | low level Timer callback |
23,528 | def input_callback ( method , buffer , input ) Weechat :: Buffer . call_input_callback ( method , buffer , input ) end | low level buffer input callback |
23,529 | def bar_build_callback ( id , item , window ) Weechat :: Bar :: Item . call_build_callback ( id , window ) end | low level bar build callback |
23,530 | def info_callback ( id , info , arguments ) Weechat :: Info . find_by_id ( id ) . call ( arguments ) . to_s end | low level info callback |
23,531 | def print_callback ( id , buffer , date , tags , displayed , highlight , prefix , message ) buffer = Weechat :: Buffer . from_ptr ( buffer ) date = Time . at ( date . to_i ) tags = tags . split ( "," ) displayed = Weechat . integer_to_bool ( displayed ) highlight = Weechat . integer_to_bool ( highlight ) line = PrintedLine . new ( buffer , date , tags , displayed , highlight , prefix , message ) Weechat :: Hooks :: Print . find_by_id ( id ) . call ( line ) end | low level print callback |
23,532 | def signal_callback ( id , signal , data ) data = Weechat :: Utilities . apply_transformation ( signal , data , SignalCallbackTransformations ) Weechat :: Hooks :: Signal . find_by_id ( id ) . call ( signal , data ) end | low level callback for signal hooks |
23,533 | def config_callback ( id , option , value ) ret = Weechat :: Hooks :: Config . find_by_id ( id ) . call ( option , value ) end | low level config callback |
23,534 | def process_callback ( id , command , code , stdout , stderr ) code = case code when Weechat :: WEECHAT_HOOK_PROCESS_RUNNING :running when Weechat :: WEECHAT_HOOK_PROCESS_ERROR :error else code end process = Weechat :: Process . find_by_id ( id ) if process . collect? process . buffer ( stdout , stderr ) if code == :error || code != :running process . call ( code , process . stdout , process . stderr ) end else process . call ( code , stdout , stderr ) end end | low level process callback |
23,535 | def modifier_callback ( id , modifier , modifier_data , s ) classes = Weechat :: Hook . hook_classes modifier_data = Weechat :: Utilities . apply_transformation ( modifier , modifier_data , ModifierCallbackTransformations ) modifier_data = [ modifier_data ] unless modifier_data . is_a? ( Array ) args = modifier_data + [ Weechat :: Line . parse ( s ) ] callback = classes . map { | cls | cls . find_by_id ( id ) } . compact . first ret = callback . call ( * args ) return Weechat :: Utilities . apply_transformation ( modifier , ret , ModifierCallbackRTransformations ) . to_s end | low level modifier hook callback |
23,536 | def auth = ( authorization ) clensed_auth_hash = { } authorization . each { | k , v | clensed_auth_hash [ k . to_sym ] = v } authorization = clensed_auth_hash if authorization . has_key? :access_token self . class . default_options . reject! { | k | k == :basic_auth } self . class . headers . merge! ( "Authorization" => "Bearer #{authorization[:access_token]}" ) elsif authorization . has_key? ( :username ) && authorization . has_key? ( :password ) self . class . basic_auth authorization [ :username ] , authorization [ :password ] self . class . headers . reject! { | k , v | k == "Authorization" } else raise "Incomplete Authorization hash. Please check the Authentication Hash." end end | Initializes the connection to Basecamp using httparty . |
23,537 | def kill_zombie_users ( users ) @mutex . synchronize do ( @users - users - Set . new ( [ @thaum_user ] ) ) . each do | user | @users . delete ( user ) end end end | Removes all users from the UserList that don t share channels with the Thaum . |
23,538 | def lines ret = [ Attributes :: HEADER ] @attrs . sort_by { | x | x [ :name ] == 'id' ? '_' : x [ :name ] } . each do | row | line = "# * #{row[:name]} [#{row[:type]}]#{row[:desc].to_s.empty? ? "" : " - #{row[:desc]}"}" lt = wrap_text ( line , MAX_CHARS_PER_LINE - 3 ) . split ( "\n" ) line = ( [ lt [ 0 ] ] + lt [ 1 .. - 1 ] . map { | x | "# #{x}" } ) . join ( "\n" ) ret << line end ret end | Convert attributes array back to attributes lines representation to be put into file |
23,539 | def update! @model . columns . each do | column | if row = @attrs . find { | x | x [ :name ] == column . name } if row [ :type ] != type_str ( column ) puts " M #{@model}##{column.name} [#{row[:type]} -> #{type_str(column)}]" row [ :type ] = type_str ( column ) elsif row [ :desc ] == InitialDescription :: DEFAULT_DESCRIPTION new_desc = InitialDescription . for ( @model , column . name ) if row [ :desc ] != new_desc puts " M #{@model}##{column.name} description updated" row [ :desc ] = new_desc end end else puts " A #{@model}##{column.name} [#{type_str(column)}]" @attrs << { :name => column . name , :type => type_str ( column ) , :desc => InitialDescription . for ( @model , column . name ) } end end orphans = @attrs . map { | x | x [ :name ] } - @model . columns . map ( & :name ) unless orphans . empty? orphans . each do | orphan | puts " D #{@model}##{orphan}" @attrs = @attrs . select { | x | x [ :name ] != orphan } end end @attrs end | Update attribudes array to the current database state |
23,540 | def parse @lines . each do | line | if m = line . match ( R_ATTRIBUTE ) @attrs << { :name => m [ 1 ] . strip , :type => m [ 2 ] . strip , :desc => m [ 4 ] . strip } elsif m = line . match ( R_ATTRIBUTE_NEXT_LINE ) @attrs [ - 1 ] [ :desc ] += " #{m[1].strip}" end end end | Convert attributes lines into meaniningful array |
23,541 | def truncate_default ( str ) return str unless str . kind_of? String str . sub! ( / /m , '\1' ) str = "#{str[0..10]}..." if str . size > 10 str . inspect end | default value could be a multiple lines string which would ruin annotations so we truncate it and display inspect of that string |
23,542 | def type_str ( c ) ret = c . type . to_s ret << ", primary" if c . primary ret << ", default=#{truncate_default(c.default)}" if c . default ret << ", not null" unless c . null ret << ", limit=#{c.limit}" if c . limit && ( c . limit != 255 && c . type != :string ) ret end | Human readable description of given column type |
23,543 | def run ( global_opts , cmd , search_data ) settings = load_settings ( global_opts ) process_cmd ( cmd , search_data , settings . login , settings . password , ContactsCache . new ( settings . cache_file_path , settings . auto_check ) ) end | Run application . |
23,544 | def load_settings ( global_opts ) settings = Settings . new settings . load ( ConfigFile . new ( global_opts [ :config_file ] ) , global_opts ) settings end | Load settings combining arguments from cmd lien and the settings file . |
23,545 | def search ( cache , search_data ) puts '' cache . search ( search_data ) . each { | k , v | puts "#{k}\t#{v}" } end | Search the cache for the requested search_data and write the results to std output . |
23,546 | def asset_root File . expand_path ( File . join ( File . dirname ( __FILE__ ) , %w( .. .. .. ) , %w( assets aker form ) ) ) end | Where to look for HTML and CSS assets . |
23,547 | def login_html ( env , options = { } ) login_base = env [ 'SCRIPT_NAME' ] + login_path ( env ) template = File . read ( File . join ( asset_root , 'login.html.erb' ) ) ERB . new ( template ) . result ( binding ) end | Provides the HTML for the login form . |
23,548 | def passed? passed = nil @report . each { | r | if passed == nil passed = ( r [ :status ] == PS_OK ) else passed &= ( r [ :status ] == PS_OK ) end } passed end | Test whether this set of results passed or not |
23,549 | def get_auth_data auth_key = @@http_auth_headers . detect { | h | request . env . has_key? ( h ) } auth_data = request . env [ auth_key ] . to_s . split unless auth_key . blank? return auth_data && auth_data [ 0 ] == 'Basic' ? Base64 . decode64 ( auth_data [ 1 ] ) . split ( ':' ) [ 0 .. 1 ] : [ nil , nil ] end | gets BASIC auth info |
23,550 | def parse_jobfile ( jobfile ) YAML . load ( File . read ( jobfile ) ) rescue Errno :: ENOENT Mongolicious . logger . error ( "Could not find job file at #{ARGV[0]}" ) exit rescue ArgumentError => e Mongolicious . logger . error ( "Could not parse job file #{ARGV[0]} - #{e}" ) exit end | Parse YAML job configuration . |
23,551 | def schedule_jobs ( jobs ) scheduler = Rufus :: Scheduler . start_new jobs . each do | job | if job [ 'cron' ] Mongolicious . logger . info ( "Scheduled new job for #{job['db'].split('/').last} with cron: #{job['cron']}" ) scheduler . cron job [ 'cron' ] do backup ( job ) end else scheduler . every job [ 'interval' ] do Mongolicious . logger . info ( "Scheduled new job for #{job['db'].split('/').last} with interval: #{job['interval']}" ) backup ( job ) end end end scheduler . join end | Schedule the jobs to be executed in the given interval . |
23,552 | def add ( resource ) if @list . key? resource . route raise DuplicateResource , "A resource accessible via #{resource.http_verb} #{resource.url} already exists" end @list [ resource . route ] = resource end | Add a resource to the list |
23,553 | def named ( name ) resource = all . detect { | resource | resource . name == name } if resource . nil? raise UnknownResource , "Resource named #{name} doesn't exist" else resource end end | Returns a resource based on its name |
23,554 | def trusted? ( pem ) if cert = OpenSSL :: X509 :: Certificate . new ( pem ) rescue nil @store . verify ( cert ) . tap do | trusted | @store . add_cert ( cert ) if trusted rescue nil end end end | Return true if the certificate is signed by a CA certificate in the store . If the certificate can be trusted it s added to the store so it can be used to trust other certs . |
23,555 | def certs unless @@certs pattern = / \n \n /m dir = @cert_directory certs = Dir [ File . join ( dir , '*.crt' ) ] . map { | f | File . read ( f ) } certs = certs . map { | c | c . scan ( pattern ) } . flatten certs . map! { | c | OpenSSL :: X509 :: Certificate . new ( c ) } @@certs = certs . reject { | c | c . not_after < Time . now } end @@certs end | Return the trusted root CA certificates installed in the |
23,556 | def url ( name = nil ) if name if version_identifiers . include? ( name . to_s ) self [ :@versions ] [ name . to_s ] [ :@url ] else raise "Invalid Image Version identifier: '#{name}' (must be #{version_identifiers.join(', ')})" end else self [ :@url ] end end | Returns the URL of an Image or the URL of a version if a string or symbol is passed |
23,557 | def field_attribute ( attr ) return 'id' if attr == :_id return attr unless attr . is_a? Hash return attr [ :object ] if attr . has_key? :object return attr [ :array ] if attr . has_key? :array return attr [ :value ] if attr . has_key? :value return attr [ :link ] if attr . has_key? :link attr . keys [ 0 ] end | Use for sort_if_enabled which requires the attribute name |
23,558 | def lookup ( code ) TAXONOMY . select { | t | t . code . eql? ( code ) } . first end | Use this method if you have a taxonomy code and need to lookup the information about that code |
23,559 | def add ( error ) if @list . key? error . name raise DuplicateError , "An error named #{error.name} already exists" end @list [ error . name ] = error end | Add a error to the list |
23,560 | def draw drawns = [ ] @options [ :include ] . each { | n | drawns << n } unless @options [ :include ] . nil? count = @options [ :include ] ? @options [ :pick ] - @options [ :include ] . count : @options [ :pick ] count . times { drawns << pick ( drawns ) } drawns end | Returns a set of drawn numbers |
23,561 | def basket numbers = ( 1 .. @options [ :of ] ) numbers = numbers . reject { | n | @options [ :include ] . include? n } unless @options [ :include ] . nil? numbers = numbers . reject { | n | @options [ :exclude ] . include? n } unless @options [ :exclude ] . nil? numbers end | Returns the basket with numbers |
23,562 | def activities ( options = { } ) response = connection . get do | req | req . url "activities" , options end return_error_or_body ( response ) end | Get a list of all activities for the authenticating client . |
23,563 | def signature params = payload . to_h . reject { | key , value | key == :sha_sign } . reject { | key , value | value == '' || value == false } . sort . map { | key , value | "#{key}=#{value}#{passphrase}" } . join Digest :: SHA512 . hexdigest ( params ) . upcase end | Initialize the notification . |
23,564 | def process_p p @viewer . receive_p p if @viewer if p . action! = Edoors :: ACT_ERROR and p . action! = Edoors :: ACT_PASS_THROUGH p2 = @postponed [ p . link_value ] ||= p return if p2 == p @postponed . delete p . link_value p , p2 = p2 , p if p . action == Edoors :: ACT_FOLLOW p . merge! p2 end @saved = p receive_p p _garbage if not @saved . nil? end | process the given particle then forward it to user code |
23,565 | def determine_offsets ( block , source ) tokens = Ripper . lex ( source ) start_offset , start_token = determine_start_offset ( block , tokens ) expected_match = start_token == :on_kw ? :on_kw : :on_rbrace end_offset = determine_end_offset ( block , tokens , source , expected_match ) [ start_offset , end_offset ] end | Tokenizes the source of the block as determined by the method_source gem and determines the beginning and end of the block . |
23,566 | def method_missing ( m , * args , & block ) column_name = m . to_s . gsub ( / \= / , '' ) raise ExtendModelAt :: InvalidColumn , "#{column_name} not exist" if @static == true and not ( @columns . try ( :keys ) . try ( :include? , column_name . to_sym ) ) if m !~ / \= / self [ m . to_s ] else self [ column_name . to_s ] = args . first end end | Use the undefined method as a column |
23,567 | def get_adapter ( column , value ) if @columns [ column . to_sym ] [ :type ] == String return :to_s elsif @columns [ column . to_sym ] [ :type ] == Fixnum return :to_i if value . respond_to? :to_i elsif @columns [ column . to_sym ] [ :type ] == Float return :to_f if value . respond_to? :to_f elsif @columns [ column . to_sym ] [ :type ] == Time return :to_time if value . respond_to? :to_time elsif @columns [ column . to_sym ] [ :type ] == Date return :to_date if value . respond_to? :to_date end nil end | Meta functions Return the correct method used to transform the column value the correct Ruby class |
23,568 | def get_defaults_values ( options = { } ) defaults_ = { } options [ :columns ] . each do | column , config | defaults_ [ column . to_s ] = @columns [ column . to_sym ] [ :default ] || nil end defaults_ end | Get all default values |
23,569 | def point_account_entries ( options = { } ) response = connection . get do | req | req . url "point_account_entries" , options end return_error_or_body ( response ) end | Get a list of point account entries . |
23,570 | def process! ( body , url , effective_url ) before_process! body = parse! ( body ) @process_callback . call ( body , url , effective_url ) if @process_callback after_process! rescue => e error! ( e ) end | Runs the process callback . If it fails with an exception it will send the exception to the error callback . |
23,571 | def get_qr_codes_with_http_info ( ) @api_client . config . logger . debug 'Calling API: SignatureApi.get_qr_codes ...' if @api_client . config . debugging local_var_path = '/signature/qrcodes' query_params = { } header_params = { } header_params [ 'Accept' ] = @api_client . select_header_accept ( [ 'application/json' , 'application/xml' ] ) header_params [ 'Content-Type' ] = @api_client . select_header_content_type ( [ 'application/json' , 'application/xml' ] ) form_params = { } post_body = nil data , status_code , headers = @api_client . call_api ( :GET , local_var_path , header_params : header_params , query_params : query_params , form_params : form_params , body : post_body , access_token : get_access_token , return_type : 'QRCodeCollection' ) if @api_client . config . debugging @api_client . config . logger . debug "API called: SignatureApi#get_qr_codes\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end [ data , status_code , headers ] end | Retrieves list of supported QR - Code type names . |
23,572 | def post_verification_collection_with_http_info ( request ) raise ArgumentError , 'Incorrect request type' unless request . is_a? PostVerificationCollectionRequest @api_client . config . logger . debug 'Calling API: SignatureApi.post_verification_collection ...' if @api_client . config . debugging raise ArgumentError , 'Missing the required parameter name when calling SignatureApi.post_verification_collection' if @api_client . config . client_side_validation && request . name . nil? local_var_path = '/signature/{name}/collection/verification' local_var_path = local_var_path . sub ( '{' + downcase_first_letter ( 'Name' ) + '}' , request . name . to_s ) query_params = { } if local_var_path . include? ( '{' + downcase_first_letter ( 'Password' ) + '}' ) local_var_path = local_var_path . sub ( '{' + downcase_first_letter ( 'Password' ) + '}' , request . password . to_s ) else query_params [ downcase_first_letter ( 'Password' ) ] = request . password unless request . password . nil? end if local_var_path . include? ( '{' + downcase_first_letter ( 'Folder' ) + '}' ) local_var_path = local_var_path . sub ( '{' + downcase_first_letter ( 'Folder' ) + '}' , request . folder . to_s ) else query_params [ downcase_first_letter ( 'Folder' ) ] = request . folder unless request . folder . nil? end if local_var_path . include? ( '{' + downcase_first_letter ( 'Storage' ) + '}' ) local_var_path = local_var_path . sub ( '{' + downcase_first_letter ( 'Storage' ) + '}' , request . storage . to_s ) else query_params [ downcase_first_letter ( 'Storage' ) ] = request . storage unless request . storage . nil? end header_params = { } header_params [ 'Accept' ] = @api_client . select_header_accept ( [ 'application/json' , 'application/xml' ] ) header_params [ 'Content-Type' ] = @api_client . select_header_content_type ( [ 'application/json' , 'application/xml' ] ) form_params = { } post_body = @api_client . object_to_http_body ( request . verify_options_collection_data ) data , status_code , headers = @api_client . call_api ( :POST , local_var_path , header_params : header_params , query_params : query_params , form_params : form_params , body : post_body , access_token : get_access_token , return_type : 'VerifiedDocumentResponse' ) if @api_client . config . debugging @api_client . config . logger . debug "API called: SignatureApi#post_verification_collection\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end [ data , status_code , headers ] end | Verify the Document . |
23,573 | def desc = ( value ) node = at './desc' node ||= add_child Nokogiri :: XML :: Node . new ( 'desc' , document ) node . content = value end | Sets description of node . |
23,574 | def added = ( value ) set_attribute 'added' , case value when Time ; value . strftime '%Y-%m-%d' when String ; value else raise ArgumentError end end | Sets addition date . |
23,575 | def parse ( tweets ) retdict = { mentions : { } , hashtags : { } , clients : { } , smileys : { } , times_of_day : [ 0 ] * 24 , tweet_count : 0 , retweet_count : 0 , selftweet_count : 0 , } tweets . each do | tweet | parsed_tweet = self . parse_one tweet if parsed_tweet [ :retweet ] retdict [ :retweet_count ] += 1 else parsed_tweet [ :mentions ] . each do | user , data | retdict [ :mentions ] [ user ] ||= { count : 0 } retdict [ :mentions ] [ user ] [ :count ] += data [ :count ] retdict [ :mentions ] [ user ] [ :name ] ||= data [ :name ] retdict [ :mentions ] [ user ] [ :examples ] ||= [ ] retdict [ :mentions ] [ user ] [ :examples ] << data [ :example ] end parsed_tweet [ :hashtags ] . each do | hashtag , data | retdict [ :hashtags ] [ hashtag ] ||= { count : 0 } retdict [ :hashtags ] [ hashtag ] [ :count ] += data [ :count ] retdict [ :hashtags ] [ hashtag ] [ :hashtag ] ||= data [ :hashtag ] retdict [ :hashtags ] [ hashtag ] [ :examples ] ||= [ ] retdict [ :hashtags ] [ hashtag ] [ :examples ] << data [ :example ] end parsed_tweet [ :smileys ] . each do | smile , data | retdict [ :smileys ] [ smile ] ||= { count : 0 } retdict [ :smileys ] [ smile ] [ :frown ] ||= data [ :frown ] retdict [ :smileys ] [ smile ] [ :count ] += data [ :count ] retdict [ :smileys ] [ smile ] [ :smiley ] ||= data [ :smiley ] retdict [ :smileys ] [ smile ] [ :examples ] ||= [ ] retdict [ :smileys ] [ smile ] [ :examples ] << data [ :example ] end retdict [ :selftweet_count ] += 1 end client_dict = parsed_tweet [ :client ] [ :name ] retdict [ :clients ] [ client_dict ] ||= { count : 0 } retdict [ :clients ] [ client_dict ] [ :count ] += 1 retdict [ :clients ] [ client_dict ] [ :name ] = parsed_tweet [ :client ] [ :name ] retdict [ :clients ] [ client_dict ] [ :url ] = parsed_tweet [ :client ] [ :url ] retdict [ :times_of_day ] [ parsed_tweet [ :time_of_day ] ] += 1 retdict [ :tweet_count ] += 1 end retdict end | Parses an array of tweets |
23,576 | def run if response . is_a? @expected_response self . class . on_response . call ( self , response ) response . tap do parse_response! end else raise HTTPError . new ( error_message , response : response ) end end | Sends the request and returns the response with the body parsed from JSON . |
23,577 | def read ( name , field = nil ) field ||= self . field if name . is_a? ( Integer ) field . read_field ( name ) elsif bits = @field_list [ name ] field . read_field ( bits ) end end | Read a field or bit from its bit index or name |
23,578 | def write ( name , target_value ) if name . is_a? ( Symbol ) self . write ( @field_list [ name ] , target_value ) elsif name . is_a? ( Integer ) self . update self . field . write_bits ( name => @options [ :bool_caster ] . call ( target_value ) ) elsif name . respond_to? ( :[] ) and target_value . respond_to? ( :[] ) bits = { } name . each_with_index do | bit , i | bits [ bit ] = @options [ :bool_caster ] . call ( target_value [ i ] ) end self . update self . field . write_bits bits end end | Write a field or bit from its field name or index |
23,579 | def as_json ( _ = nil ) json = { 'id' => id } json [ 'allegedShooters' ] = alleged_shooters unless alleged_shooters . nil? json . merge ( 'casualties' => casualties . stringify_keys , 'date' => date . iso8601 , 'location' => location , 'references' => references . map ( & :to_s ) ) end | Returns a hash representing the shooting . |
23,580 | def prune ( nodes ) nodes . each do | node | node . parent . children . reject! { | n | n == node } if ( node != @root ) && ( node . diff_score < @score_threshold ) end end | prune away nodes that don t meet the configured score threshold |
23,581 | def headers! ( hash ) changing = headers . select { | header | hash . has_key? ( header . key ) } changing . each do | header | new_values = hash [ header . key ] header . raw = new_values [ :raw ] if new_values [ :raw ] header . key = new_values [ :key ] if new_values [ :key ] end Redhead :: HeaderSet . new ( changing ) end | Returns true if self . headers == other . headers and self . string == other . string . Modifies the headers in the set using the given _hash_ which has the form |
23,582 | def method_missing ( name , * args , & block ) return attr ( name [ 0 .. - 2 ] , args [ 0 ] ) if args . size == 1 and name [ - 1 ] == '=' end | Dynamically write value |
23,583 | def dir ( name , mode = 16877 , & block ) name_parts = name . split ( :: File :: SEPARATOR ) innermost_child_name = name_parts . pop if name_parts . empty? Directory . new ( name , mode ) . tap do | directory | add_directory ( directory ) block . call ( directory ) if block end else innermost_parent = name_parts . reduce ( self ) do | parent , child_name | parent . dir ( child_name ) end innermost_parent . dir ( innermost_child_name , & block ) end end | Add a + Directory + named + name + to this entity s list of children . The + name + may simply be the name of the directory or may be a path to the directory . |
23,584 | def file ( name , mode = 33188 , & content ) content ||= NO_CONTENT name_parts = name . split ( :: File :: SEPARATOR ) file_name = name_parts . pop if name_parts . empty? File . new ( name , mode , content ) . tap do | file | add_file ( file ) end else dir ( name_parts . join ( :: File :: SEPARATOR ) ) do | parent | parent . file ( file_name , mode , & content ) end end end | Add a + File + named + name + to this entity s list of children . The + name + may simply be the name of the file or may be a path to the file . |
23,585 | def request_xml request_params = @params . dup token = request_params . delete ( "token" ) xml = "" request_params . each do | key , value | xml << "<var name=\"#{escape(key)}\" value=\"#{escape(value)}\"/>" end "<sessions><token>#{token}</token>#{xml}</sessions>" end | Generates xml suitable for an XML POST request to Tropo |
23,586 | def to_attributes ( only : nil , except : nil ) self . class . attributes . each_with_object ( { } ) do | ( name , options ) , attrs | next if ( only && ! match_attribute? ( only , name ) ) || ( except && match_attribute? ( except , name ) ) next unless serialize_attribute? ( name , options ) attrs [ name ] = send ( name ) end end | Project the current state of the object to a hash of attributes that can be used to restore the attribute object at a later time . |
23,587 | def compact_attr_qnames ( ns_stack , attrs ) Hash [ attrs . map do | name , value | [ compact_qname ( ns_stack , name ) , value ] end ] end | compact all attribute QNames to Strings |
23,588 | def find_namespace_uri ( ns_stack , prefix , uri_check = nil ) tns = ns_stack . reverse . find { | ns | ns . has_key? ( prefix ) } uri = tns [ prefix ] if tns raise "prefix: '#{prefix}' is bound to uri: '#{uri}', but should be '#{uri_check}'" if uri_check && uri && uri! = uri_check uri end | returns the namespace uri for a prefix if declared in the stack |
23,589 | def undeclared_namespace_bindings ( ns_stack , ns_explicit ) Hash [ ns_explicit . map do | prefix , uri | [ prefix , uri ] if ! find_namespace_uri ( ns_stack , prefix , uri ) end . compact ] end | figure out which explicit namespaces need declaring |
23,590 | def exploded_namespace_declarations ( ns ) Hash [ ns . map do | prefix , uri | if prefix == "" [ "xmlns" , uri ] else [ [ prefix , "xmlns" ] , uri ] end end ] end | produce a Hash of namespace declaration attributes with exploded QNames from a Hash of namespace prefix bindings |
23,591 | def namespace_attributes ( ns ) Hash [ ns . map do | prefix , uri | if prefix == "" [ "xmlns" , uri ] else [ [ "xmlns" , prefix ] . join ( ":" ) , uri ] end end ] end | produces a Hash of compact namespace attributes from a Hash of namespace bindings |
23,592 | def merge_namespace_bindings ( ns1 , ns2 ) m = ns1 . clone ns2 . each do | k , v | raise "bindings clash: '#{k}'=>'#{m[k]}' , '#{k}'=>'#{v}'" if m . has_key? ( k ) && m [ k ] != v m [ k ] = v end m end | merges two sets of namespace bindings raising error on clash |
23,593 | def spawn_process ( command_line ) host_stdout , cmd_stdout = IO . pipe host_stderr , cmd_stderr = IO . pipe pid = Process . spawn ( command_line . command_environment , command_line . command , :out => cmd_stdout , :err => cmd_stderr ) cmd_stdout . close cmd_stderr . close return pid , host_stdout , host_stderr end | Creates a process to run a command . Handles connecting pipes to stardard streams launching the process and returning a pid for it . |
23,594 | def execute ( command_line ) result = collect_result ( command_line , * spawn_process ( command_line ) ) result . wait result end | Run the command wait for termination and collect the results . Returns an instance of CommandRunResult that contains the output and exit code of the command . |
23,595 | def run_as_replacement ( * args , & block ) command_line = normalize_command_line ( * args , & block ) report "Ceding execution to: " report command_line . string_format Process . exec ( command_line . command_environment , command_line . command ) end | Completely replace the running process with a command . Good for setting up a command and then running it without worrying about what happens after that . Uses exec under the hood . |
23,596 | def run_detached ( * args , & block ) command_line = normalize_command_line ( * args , & block ) pid , out , err = spawn_process ( command_line ) Process . detach ( pid ) return collect_result ( command_line , pid , out , err ) end | Run the command in the background . The command can survive the caller . Works for instance to kick off some long running processes that we don t care about . Note that this isn t quite full daemonization - we don t close the streams of the other process or scrub its environment or anything . |
23,597 | def can? action , target target = target . to_s if target . is_a? Symbol action = action . to_s policies . sort_by ( & :priority ) . reverse . each do | policy | opinion = policy . can? ( self , action , target ) return opinion . to_bool if %i[ allow deny ] . include? opinion end return false end | Checks if this holder can perform some action on an object by checking the Holder s policies |
23,598 | def referenced_sections recursive = true result = PartialParser . find_sections partial_content if recursive i = - 1 while ( i += 1 ) < result . size Section . new ( result [ i ] ) . referenced_sections ( false ) . each do | referenced_section | result << referenced_section unless result . include? referenced_section end end end result . sort! end | Returns the sections that this section references . If recursive = true is given searches recursively for sections referenced by the referenced sections . Otherwise simply returns the sections that are referenced by this section . |
23,599 | def render & block raise "Section #{folder_filepath} doesn't exist." unless Dir . exists? folder_filepath result = [ ] render_assets result if Rails . application . config . assets . compile render_partial result , & block result . join ( "\n" ) . html_safe end | Renders this section i . e . returns the HTML for this section . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.