idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
22,500 | def get_all_active_subscribers find_active_subscribers ( DateTime . new ( y = 1911 , m = 1 , d = 01 , h = 01 , min = 00 , s = 00 ) ) end | Gets a list of all active subscribers for a list . |
22,501 | def base_url_from_schema json_schema . links . find do | link | if link . href && link . rel == "self" return link . href end end end | Extracts the base url of the API from JSON Schema |
22,502 | def frame_read ( socket ) begin socket_content = socket . read_nonblock ( 4096 ) frame = Hash . new if match = socket_content . match ( / \S \d \s \S / ) frame [ :txnr ] , frame [ :command ] , frame [ :data_length ] , frame [ :message ] = match . captures frame [ :message ] . lstrip! else raise Relp :: FrameReadException . new ( 'Problem with reading RELP frame' ) end @logger . debug "Reading Frame #{frame.inspect}" rescue IOError @logger . error 'Problem with reading RELP frame' raise Relp :: FrameReadException . new 'Problem with reading RELP frame' rescue Errno :: ECONNRESET @logger . error 'Connection reset' raise Relp :: ConnectionClosed . new 'Connection closed' end is_valid_command ( frame [ :command ] ) return frame end | Read socket and return Relp frame information in hash |
22,503 | def is_valid_command ( command ) valid_commands = [ "open" , "close" , "rsp" , "syslog" ] if ! valid_commands . include? ( command ) @logger . error 'Invalid RELP command' raise Relp :: InvalidCommand . new ( 'Invalid command' ) end end | Check if command is one of valid commands if not raise exception |
22,504 | def client_call ( method , * args ) key = cache_key ( method , args ) cached = dalli . get ( key ) return cached if cached response = client . send ( method , * args ) dalli . set ( key , response ) response end | Call octokit using memcached response when available |
22,505 | def current_state_by_controller ( * given_controller_names , actions : [ ] ) if given_controller_names . any? { | name | name == controller_name . to_sym } if actions . present? Array ( actions ) . include? ( action_name . to_sym ) else true end end end | Returns true if one of the given controllers match the actual one . If actions are set they are taken into account . |
22,506 | def call_webservice ( method_name , arguments , schema_url , service_path ) Operations :: WebserviceCall . new ( @rforce_binding , method_name , arguments , schema_url , service_path ) . run ( ) end | Queries a salesforce webservice |
22,507 | def neo_feed ( start_date = Time . now . strftime ( '%Y-%m-%d' ) , end_date = ( Time . now + 604800 ) . strftime ( '%Y-%m-%d' ) ) request . neo . rest . v1 ( 'feed' ) . get ( :params => { :api_key => @application_id . dup , :start_date => start_date , :end_date => end_date } ) . to_h end | end_date is 1 week in seconds |
22,508 | def ruby_executable @ruby_executable ||= begin dir , name , ext = CONFIG . values_at ( * %w[ bindir RUBY_INSTALL_NAME EXEEXT ] ) :: File . join ( dir , name + ext ) . sub ( / \s /m , '"\&"' ) end end | Returns the full path to the current Ruby interpreter s executable file . This might not be the actual correct command to use for invoking the Ruby interpreter ; use ruby_command instead . |
22,509 | def command_for_ruby_tool ( name ) filename = respond_to? ( name ) ? send ( name ) : locate_ruby_tool ( name ) shebang_command ( filename ) =~ / / ? "#{ruby_command} #{filename}" : filename end | Returns the correct command string for invoking the + name + executable that belongs to the current Ruby interpreter . Returns + nil + if the command is not found . |
22,510 | def pseudo_java_class_name ( name ) result = '' name . each_char do | chr | if chr =~ JAVA_CLASS_NAME result << chr elsif chr == JAVA_PACKAGE_SEPARATOR result << JAVE_PACKAGE_SEPARATOR_HOMOGLYPH else chr = chr . unpack ( 'U' ) [ 0 ] . to_s ( 16 ) result << "&#x#{chr};" end end result end | Ruby 1 . 8 - 2 . 1 compatible Make a string suitable for parsing by Jenkins JUnit display plugin by escaping any non - valid Java class name characters as an XML entity . This prevents Jenkins from interpreting hi1 . 2 as a package - and - class name . |
22,511 | def purify ( untrusted ) if RUBY_VERSION =~ / \. / iconv = Iconv . new ( 'UTF-8//IGNORE' , 'UTF-8' ) result = iconv . iconv ( untrusted ) else result = untrusted . force_encoding ( Encoding :: BINARY ) . encode ( 'UTF-8' , :undef => :replace , :replace => '' ) end result . gsub ( INVALID_CDATA_CHARACTER ) do | ch | "&#x%s;" % [ ch . unpack ( 'H*' ) . first ] end end | Strip invalid UTF - 8 sequences from a string and entity - escape any character that can t legally appear inside XML CDATA . If test output contains weird data we could end up generating invalid JUnit XML which will choke Java . Preserve the purity of essence of our precious XML fluids! |
22,512 | def service_endpoint url endpoint = LIST . find do | ( pattern , endpoint ) | url =~ pattern end endpoint ? endpoint . last : false end | Locate the correct service endpoint for the given resource URL . |
22,513 | def delete! ( pattern ) warn "You must provide a pattern" and exit if pattern . nil? @outputter . puts "The following indices from host #{@host} are now deleted" if @verbose indices ( Regexp . new ( pattern ) ) . each do | index | @client . delete ( "/#{index}" ) @outputter . puts " * #{index.inspect}" if @verbose end end | Delete all indices matching the specified pattern |
22,514 | def close! ( pattern ) warn "You must provide a pattern" and exit if pattern . nil? @outputter . puts "The following indices from host #{@host} are now closed" if @verbose indices ( Regexp . new ( pattern ) ) . each do | index | @client . post ( "/#{index}/_close" ) @outputter . puts " * #{index.inspect}" if @verbose end end | Close all indices matching the specified pattern |
22,515 | def push_data ( items , options = { } ) if items . empty? puts "No works found in the Queue." 0 elsif options [ :access_token ] . blank? puts "An error occured: Access token missing." options [ :total ] else error_total = 0 Array ( items ) . each do | item | puts item puts "*************" error_total += push_item ( item , options ) end error_total end end | method returns number of errors |
22,516 | def init_config unless instance_variable_defined? :@hatt_configuration @hatt_configuration = TCFG :: Base . new @hatt_configuration . tcfg_set 'hatt_services' , { } @hatt_configuration . tcfg_set 'hatt_globs' , DEFAULT_HATT_GLOBS @hatt_configuration . tcfg_set_env_var_prefix 'HATT_' end if hatt_config_file_path @hatt_configuration . tcfg_config_file hatt_config_file_path else Log . warn 'No configuration file specified or found. Make a hatt.yml file and point hatt at it.' end @hatt_configuration . tcfg_set 'hatt_config_file' , hatt_config_file_path normalize_services_config @hatt_configuration nil end | ensure the configuration is resolved and ready to use |
22,517 | def auth = ( auth_hash ) new_auth_hash = { } auth_hash . each { | k , v | new_auth_hash [ k . to_sym ] = v } auth_hash = new_auth_hash if auth_hash . has_key? :access_token self . class . default_options . reject! { | k | k == :basic_auth } self . class . headers . merge! ( "Authorization" => "Bearer #{auth_hash[:access_token]}" ) elsif auth_hash . has_key? ( :username ) && auth_hash . has_key? ( :password ) self . class . basic_auth auth_hash [ :username ] , auth_hash [ :password ] self . class . headers . reject! { | k , v | k == "Authorization" } else raise "" " Incomplete authorization information passed in authorization hash. You must have either an :access_token or a username password combination (:username, :password). " "" end end | Initializes the Logan shared client with information required to communicate with Basecamp |
22,518 | def project_templates response = self . class . get '/project_templates.json' handle_response ( response , Proc . new { | h | Logan :: ProjectTemplate . new ( h ) } ) end | get project templates from Basecamp API |
22,519 | def todolists response = self . class . get '/todolists.json' handle_response ( response , Proc . new { | h | list = Logan :: TodoList . new ( h ) list . project_id = list . url . scan ( / \/ \d / ) . last . first list } ) end | get active Todo lists for all projects from Basecamp API |
22,520 | def chain ( cmd , chain , p = { } ) cmds = { new : '-N' , rename : '-E' , delete : '-X' , flush : '-F' , list_rules : '-S' , list : '-L' , zero : '-Z' , policy : '-P' } @buffer << [ 'iptables' , option ( '-t' , @table ) , cmds [ cmd ] , option ( '-n' , p [ :numeric ] ) , chain , option ( false , p [ :rulenum ] ) , option ( false , p [ :to ] ) ] . compact . join ( ' ' ) << "\n" self end | Create flush and delete chains and other iptable chain operations . |
22,521 | def append ( event_name , ** data ) id = SecureRandom . uuid event = Akasha :: Event . new ( event_name , id , { aggregate_id : aggregate_id } , ** data ) @aggregate . apply_events ( [ event ] ) @events << event end | Adds an event to the changeset . |
22,522 | def exec_api ( json_req ) begin req = sign_request ( json_req ) return HttpChannel . new ( api_uri ) . execute ( req ) rescue Curl :: Err :: CurlError => ex return JsonResponse . new ( "fail" , ex . message ) end end | Execute the given API request on the manager |
22,523 | def of number raise_on_type_mismatch number digits = convert_number_to_digits ( number ) sum = digits . reverse . map . with_index do | digit , idx | idx . even? ? ( digit * 2 ) . divmod ( 10 ) . reduce ( & :+ ) : digit end . reduce ( & :+ ) ( 10 - sum % 10 ) % 10 end | Calculates Luhn checksum |
22,524 | def valid_parent_types ( child ) str = child . respond_to? ( :entity_type ) ? child . entity_type : child self . up_taxonomy [ str ] end | access the appropriate parent entity_types for a particular child or child entity_type |
22,525 | def valid_child_types ( parent ) str = parent . respond_to? ( :entity_type ) ? parent . entity_type : child self . down_taxonomy [ str ] end | access the appropriate child entity_types for a particular parent or parent entity_type |
22,526 | def nested_handle? ( context ) ( handle? ( context . description ) || nested_handle? ( context . parent ) ) if context . respond_to? ( :description ) end | Walking the description chain looking to see if any of them are serviceable |
22,527 | def get_variant ( identifier , override = nil ) identifier = GxApi :: ExperimentIdentifier . new ( identifier ) Celluloid :: Future . new do if override . nil? self . get_variant_value ( identifier ) else Ostruct . new ( self . default_values . merge ( name : override ) ) end end end | return a variant value by name or id |
22,528 | def get_variant_value ( identifier ) data = Gxapi . with_error_handling do Timeout :: timeout ( 2.0 ) do Gxapi . cache . fetch ( self . cache_key ( identifier ) ) do @interface . get_variant ( identifier ) . to_hash end end end Ostruct . new ( data . is_a? ( Hash ) ? data : self . default_values ) end | protected method to make the actual calls to get values from the cache or from Google |
22,529 | def hijack_local_run ( context ) ( class << context ; self ; end ) . class_eval do alias_method :transactionless_local_run , :local_run def local_run ( * args ) :: ActiveRecord :: Base . transaction do transactionless_local_run ( * args ) raise :: ActiveRecord :: Rollback end end end end | Don t you just love mr . metaclass? |
22,530 | def [] ( new_size ) if new_size . is_a? Directive tags . merge! new_size . tags_for_sized_directive else tags [ :size ] = new_size end self end | Changes the size of the directive to the given size . It is possible for the given value to the a directive ; if it is it just uses the name of the directive . |
22,531 | def finalize! return if finalized? modifiers . each do | modifier | modifier . type . each_with_index do | type , i | case type when :endian , :signedness , :precision , :type , :string_type tags [ type ] = modifier . value [ i ] when :size tags [ :size ] = modifier . value [ i ] unless tags [ :size ] else raise UnknownModifierError , "Unknown modifier: #{type}" end end end @finalized = true cache_string end | Finalizes the directive . |
22,532 | def bytesize ( data = { } ) case tags [ :type ] when nil ( size ( data ) || 8 ) / 8 when :short , :int , :long BYTES_IN_STRING . fetch tags [ :type ] when :float if tags [ :precision ] == :double BYTES_IN_STRING [ :float_double ] else BYTES_IN_STRING [ :float_single ] end when :null size ( data ) || 1 when :string size ( data ) else 0 end end | The number of bytes this takes up in the resulting packed string . |
22,533 | def modify_if_needed ( str , include_endian = true ) base = if @tags [ :signedness ] == :signed str . swapcase else str end if include_endian modify_for_endianness ( base ) else base end end | Modifies the given string if it s needed according to signness and endianness . This assumes that a signed directive should be in lowercase . |
22,534 | def modify_for_endianness ( str , use_case = false ) case [ tags [ :endian ] , use_case ] when [ :little , true ] str . swapcase when [ :little , false ] str + "<" when [ :big , true ] str when [ :big , false ] str + ">" else str end end | Modifies the given string to account for endianness . If + use_case + is true it modifies the case of the given string to represent endianness ; otherwise it appends data to the string to represent endianness . |
22,535 | def restore restore_class = self . trashable_type . constantize sti_type = self . trashable_attributes [ restore_class . inheritance_column ] if sti_type begin if ! restore_class . store_full_sti_class && ! sti_type . start_with? ( "::" ) sti_type = "#{restore_class.parent.name}::#{sti_type}" end restore_class = sti_type . constantize rescue NameError => e raise e end end attrs , association_attrs = attributes_and_associations ( restore_class , self . trashable_attributes ) record = restore_class . new attrs . each_pair do | key , value | record . send ( "#{key}=" , value ) end association_attrs . each_pair do | association , attribute_values | restore_association ( record , association , attribute_values ) end return record end | Create a new trash record for the provided record . Restore a trashed record into an object . The record will not be saved . |
22,536 | def trashable_attributes return nil unless self . data uncompressed = Zlib :: Inflate . inflate ( self . data ) rescue uncompressed = self . data Marshal . load ( uncompressed ) end | Attributes of the trashed record as a hash . |
22,537 | def save __robject . content_type = model . content_type __robject . data = __persist_attributes __check_unique_indices __update_indices __robject . store @id = __robject . key self end | Persist the model attributes and update indices and unique indices . |
22,538 | def load! ( id ) self . __robject . key = id __load_robject! id , @__robject . reload ( force : true ) end | Overwrite attributes with the persisted attributes in Riak . |
22,539 | def __update_indices model . indices . values . each do | index | __robject . indexes [ index . riak_name ] = index . value_from ( attributes ) end end | Build the secondary indices of this object |
22,540 | def __check_unique_indices model . uniques . each do | uniq | if value = attributes [ uniq ] index = model . indices [ uniq ] records = model . bucket . get_index ( index . riak_name , value ) unless records . empty? || records == [ self . id ] raise Ork :: UniqueIndexViolation , "#{uniq} is not unique" end end end end | Look up into Riak for repeated values on unique attributes |
22,541 | def open! unless connected? if @data_path . exist? @connection = Rufus :: Tokyo :: Table . new ( @data_path . to_s , :mode => 'r' ) @connected = true else @connected = false raise BadWordnetDataset , "Failed to locate the tokyo words dataset at #{@data_path}. Please insure you have created it using the words gems provided 'build_wordnet' command." end end return nil end | Constructs a new tokyo ruby connector for use with the words wordnet class . |
22,542 | def set_property ( property , value ) if property == '_links' || property == '_embedded' raise ArgumentError , "Argument #{property} is a reserved property" end tap { @properties [ property ] = value } end | Sets a property in the resource . |
22,543 | def add_link ( relation , href , opts = { } ) @links . add relation , Link . new ( href , opts ) end | Adds link to relation . |
22,544 | def to_hash { } . merge ( @properties ) . tap do | h | h [ '_links' ] = { } . merge @links unless @links . empty? combined_embedded = { } combined_embedded . merge! @embedded unless @embedded . empty? combined_embedded . merge! @embedded_arrays unless @embedded_arrays . empty? h [ '_embedded' ] = combined_embedded unless combined_embedded . empty? end end | Hash representation of the resource . Will ommit links and embedded keys if they re empty |
22,545 | def get_transaction_type_from_symbol ( transaction_type ) begin target_type = transaction_type . to_s . upcase return if target_type . empty? self . class . const_get ( target_type ) rescue NameError => error raise Bitpagos :: Errors :: InvalidTransactionType . new ( error . message ) end end | Takes a symbol and returns the proper transaction type . |
22,546 | def retrieve_transactions ( query = nil , transaction_id = nil ) headers . merge! ( params : query ) if query url = "#{API_BASE}/transaction/#{transaction_id}" begin response = RestClient . get ( url , headers ) JSON . parse ( response ) rescue RestClient :: Unauthorized => error raise Bitpagos :: Errors :: Unauthorized . new ( error . message ) end end | Hits the Bitpagos transaction API returns a hash with results |
22,547 | def discover_plugin ( module_path ) plugin = plugin_classes . find { | c | c . send ( :valid_module_dir? , module_path ) } raise NoSuitablePluginFoundException unless plugin plugin end | returns the first plugin class that supports this module directory not sure what to do when we find multiple plugins would need additional criteria |
22,548 | def run ( & block ) unless @work = block raise ArgumentError , "Usage: run { while_we_have_the_lock }" end @shutdown = false @restart = false install_plugins startup on_load . call ( self ) if on_load run_loop ( & @work ) on_exit . call ( self ) if on_exit shutdown end | Takes actual block of code that is to be guarded by the lock . The + run_loop + method does the actual work . |
22,549 | def build_from ( * ip_addrs ) ip_addrs = [ * ip_addrs ] . flatten . compact begin Fleetctl . logger . info 'building from hosts: ' + ip_addrs . inspect built_from = ip_addrs . detect { | ip_addr | fetch_machines ( ip_addr ) } Fleetctl . logger . info 'built successfully from host: ' + built_from . inspect if built_from built_from rescue => e Fleetctl . logger . error 'ERROR building from hosts: ' + ip_addrs . inspect Fleetctl . logger . error e . message Fleetctl . logger . error e . backtrace . join ( "\n" ) nil end end | attempts to rebuild the cluster from any of the hosts passed as arguments returns the first ip that worked else nil |
22,550 | def fetch_machines ( host ) Fleetctl . logger . info 'Fetching machines from host: ' + host . inspect clear Fleetctl :: Command . new ( 'list-machines' , '-l' ) do | runner | runner . run ( host : host ) new_machines = parse_machines ( runner . output ) if runner . exit_code == 0 return true else return false end end end | attempts a list - machines action on the given host . returns true if successful else false |
22,551 | def discover! known_hosts = [ Fleetctl . options . fleet_host ] | fleet_hosts . to_a clear success_host = build_from ( known_hosts ) || build_from ( Fleet :: Discovery . hosts ) if success_host Fleetctl . logger . info 'Successfully recovered from host: ' + success_host . inspect else Fleetctl . logger . info 'Unable to recover!' end end | attempts to rebuild the cluster by the specified fleet host then hosts that it has built previously and finally by using the discovery url |
22,552 | def parse ( scanner , rules , scope = ParserScope . empty ) p = scanner . pos child . parse ( scanner , rules , scope ) && scanner . string [ p ... ( scanner . pos ) ] end | If the decorated parser matches return the entire matched string otherwise return a false value . |
22,553 | def method_missing ( sym , * args , & block ) name = sym . to_s unless block if ( name =~ / / && args . length == 1 ) return self [ name . chop . to_sym ] = args . first elsif args . empty? return self [ sym ] end end return super ( sym , * args , & block ) end | Provides transparent access to the options within the option list . |
22,554 | def get_total_data size = calc_total_size . to_s load_time = ( @pages . first . on_load / 1000.0 ) . to_s [ @pages . first . title , @entries . size . to_s , size , load_time ] end | Gets the common data for a page . Convenience method that can be used for bulk reading of page data . |
22,555 | def get_row_data rows = [ ] @entries . each do | entry | method = entry . request . http_method url = entry . request . url if url . end_with? ( "/" ) ressource = entry . request . url else r = url . rindex ( "/" ) ressource = url [ r .. - 1 ] end ressource = ressource [ 0 , 30 ] status = entry . response . status . to_s code = entry . response . status_text size = ( entry . response . content [ 'size' ] / 1000.0 ) . round ( 2 ) . to_s duration = ( entry . time / 1000.0 ) . to_s rows << [ method , ressource , status , code , size , duration ] end rows end | Gets the data for a row for all entries . Convenience method that can be used for bulk reading of entry data . |
22,556 | def make_request create_authorization options = { } options [ :header ] = authorization . headers . merge ( 'Authorization' => authorization . authorization_header ) options [ :query ] = query if query . any? options [ :body ] = form_body if body http_response = @httpclient . request ( method , url , options ) @response = AwsResponse . new ( self , http_response ) freeze @response end | Send the HTTP request and get a response . Returns an AwsResponse object . The instance is frozen once this method is called and cannot be used again . |
22,557 | def form_body if body . is_a? ( Hash ) body . map do | k , v | [ AwsRequest . aws_encode ( k ) , AwsRequest . aws_encode ( v ) ] . join ( "=" ) end . join ( "&" ) else body end end | Encode the form params if the body is given as a Hash . |
22,558 | def create_authorization @authorization = AwsRequestAuthorization . new . tap do | authorization | authorization . url = url authorization . method = method authorization . query = query authorization . body = form_body authorization . region = region authorization . service = service authorization . credentials = credentials authorization . headers = headers end end | Create the AwsRequestAuthorization object for the request . |
22,559 | def retrieve ( poll_time = 1 ) response = client . receive_message ( url , { "WaitTimeSeconds" => poll_time , "MaxNumberOfMessages" => 1 } ) raise QueueNotFound . new ( self , "not found at #{url}" ) if response . http_response . status == 404 response . doc . xpath ( "//Message" ) . map do | element | attributes = Hash [ * element . xpath ( "Attribute" ) . map do | attr_element | [ attr_element . xpath ( "Name" ) . text , attr_element . xpath ( "Value" ) . text ] end . flatten ] Message . new ( self , element . xpath ( "MessageId" ) . text , element . xpath ( "ReceiptHandle" ) . text , element . xpath ( "Body" ) . text , attributes ) end . first end | Retrieve a message from the queue . Returns nil if no message is waiting in the given poll time . Otherwise it returns a Message . |
22,560 | def process_permission ( permission , * args ) cached = value_from_cache ( permission , * args ) if cached . nil? evaluate_permission ( permission , * args ) else cached end end | checks if the permission has already been calculated otherwise the permission needs to be evaluated |
22,561 | def value_from_cache ( permission , * args ) o = args [ 0 ] role = get_role_of ( o ) cache . get_for_role ( permission , role ) end | checks the cache if we have calculated this permission before |
22,562 | def evaluate_permission ( permission , * args ) o = args [ 0 ] result = true role = get_role_of ( o ) if ( proc = PermissionUtilities . has_procs? ( permission ) ) result &= proc . call ( o , self ) end result &= allowed_to_perform? ( permission , role ) cache . set_for_role ( name : permission , value : result , role : role ) result end | performs a full evaluation of the permission |
22,563 | def has_role_with ( object ) if object . respond_to? ( :user_id ) if object . user_id == actor . id return IS_OWNER else return IS_UNRELATED end end IS_UNRELATED end | This method can also be overridden if one desires to have multiple types of ownership such as a collaborator - type relationship |
22,564 | def spawn_thread Thread . new do while true x = @queue . shift if x == Directive :: SUICIDE_PILL @worker_threads_count . decrement Thread . current . terminate end Thread . pass begin x . job . call ( x ) rescue StandardError => e $stderr . puts "Threadz: Error in thread, but restarting with next job: #{e.inspect}\n#{e.backtrace.join("\n")}" end end end @worker_threads_count . increment end | Spin up a new thread |
22,565 | def spawn_watch_thread @watch_thread = Thread . new do while true if @queue . num_waiting > 0 && @worker_threads_count . value > @min_size @killscore += THREADS_IDLE_SCORE * @queue . num_waiting elsif ( @queue . num_waiting == 0 && @worker_threads_count . value < @max_size ) @killscore -= THREADS_BUSY_SCORE * @queue . length else if @killscore != 0 @killscore *= 0.9 end if @killscore . abs < 1 @killscore = 0 end end if @killscore . abs >= @killthreshold @killscore > 0 ? kill_thread : spawn_thread @killscore = 0 end Threadz . dputs "killscore: #{@killscore}. waiting: #{@queue.num_waiting}. threads length: #{@worker_threads_count.value}. min/max: [#{@min_size}, #{@max_size}]" sleep 0.1 end end end | This thread watches over the pool and allocated and deallocates threads as necessary |
22,566 | def convert_to ( values , type ) buffer = [ ] if values . kind_of? ( Array ) values . each do | value | begin if type == :string buffer . push ( value . to_s ) elsif type == :symbol buffer . push ( value . to_sym ) end rescue Exception => e end end else buffer = values end return buffer end | Ensures all values in an Array are of a certain type . This is meant to be used internally by DuckMap modules and classes . |
22,567 | def from_file ( filename , encoding = 'utf-8' ) mode = "rb:#{encoding}" mode = "rb" if RUBY_VERSION < '1.9' input = File . open ( filename , mode ) { | f | f . read ( ) } compile ( parse ( input ) , filename , 1 ) return self end | Ruby 2 . 1 feature |
22,568 | def additional_params @additional_params ||= if session_scope? if oauth2_session? { application_key : application_key } else { application_key : application_key , session_key : options [ :session_key ] } end else { application_key : application_key } end end | Returns additional params which are required for all requests . Depends on request scope . |
22,569 | def api_call ( method , params = { } , force_session_call = false ) raise RequireSessionScopeError . new ( 'This API call requires session scope' ) if force_session_call and application_scope? uri = build_uri ( method , params ) Net :: HTTP . get_response ( uri ) end | Performs API call to Odnoklassniki |
22,570 | def build_uri ( method , params = { } ) uri = URI ( api_server ) uri . path = '/api/' + method . sub ( '.' , '/' ) uri . query = URI . encode_www_form ( sign ( params ) ) SchoolFriend . logger . debug "API Request: #{uri}" uri end | Builds URI object |
22,571 | def undestroy @resource = resource_proxy ( true ) . find ( params [ :id ] ) set_resource_instance @resource . deleted_at = nil @resource . save respond_with ( @resource , location : { action : :index } ) end | only works if deleting of resources occurs by setting the deleted_at field |
22,572 | def resource_proxy ( with_deleted = false ) proxy = if parent_instance . present? parent_instance . send ( resource_plural_name ) else self . class . resource_class end if with_deleted and proxy . respond_to? ( :with_deleted ) proxy = proxy . with_deleted end proxy end | determines if we want to use the parent class if available or if we just use the resource class |
22,573 | def read_maximal_term ( priority ) return nil if empty? logger . debug "read maximal term (#{priority})" first = read_minimal_term term = add_next_infix_terms ( priority , first ) logger . debug "read maximal term: #{term}" term end | Reads next maximal term . The following input doesn t make the term more complete . Respects the priority of operators by comparing it to the given value . |
22,574 | def error_messages_for ( * objects ) options = objects . extract_options! options [ :header_message ] ||= I18n . t ( :" " , :default => "Invalid Fields" ) options [ :message ] ||= I18n . t ( :" " , :default => "Correct the following errors and try again." ) messages = objects . compact . map { | o | o . errors . full_messages } . flatten unless messages . empty? content_tag ( :div , :class => "error_messages" ) do list_items = messages . map { | msg | content_tag ( :li , msg ) } content_tag ( :h2 , options [ :header_message ] ) + content_tag ( :p , options [ :message ] ) + content_tag ( :ul , list_items . join . html_safe ) end end end | Nifty generators errors helper code |
22,575 | def update_current_theme ( name , options = { } ) self . class . renders_theme ( name , options ) Rails . application . config . theme . name = current_theme_name Rails . application . config . theme . layout = current_theme_layout ShinyThemes :: Engine . theme_config . save unless options [ :dont_save ] self . class . theme end | Update the current theme for the controller and optionally save |
22,576 | def acquire_lock ( lock_name ) begin acquired = false sql = lock_query ( lock_name ) connection . query ( sql ) do | result | acquired = result . fetch_row . first == "1" end acquired rescue :: Exception false end end | Expects the connection to behave like an instance of + Mysql + If you need something else replace + acquire_lock + with your own code . Or define your own lock_function while configuring a new Revenant task . |
22,577 | def load new_config = full_config [ Rails . env ] . try ( :deep_symbolize_keys! ) || { } @defaults . reject! { | k , _ | new_config . keys . include? ( k ) } Rails . application . config . theme . merge! ( @defaults . merge ( new_config ) ) end | Create the ordered options populate with provided hash and load YAML file options . |
22,578 | def save save_config = Rails . application . config . theme . reject { | k , _ | @defaults . keys . include? ( k ) } full_config [ Rails . env ] . merge! ( save_config ) File . open ( config_pathname , 'w' ) { | f | f << full_config . to_yaml } end | Save the current state of the theme config to the theme . yml file |
22,579 | def parse ( scanner , rules , scope = ParserScope . empty ) rules . inherited_rule ( rule_name ) . parse ( scanner , rules , scope ) end | Apply the parse rule of the same name inherited from a super - grammar . |
22,580 | def exact_search_request_hash ( type , value ) values = Array ( value ) hash = { "PartnershipId" => Defaults . partnership_id , "ExactSearch" => [ ] } values . each do | value | hash [ "ExactSearch" ] << { "Type" => type . to_s . upcase , "Value" => value } end return hash end | Produce BD request hash for exact search of type eg ISBN value can be a singel value or an array of values . For array BD will OR them . |
22,581 | def raises ( err = nil ) case err when Exception @options [ :raises ] = err when String @options [ :raises ] = RuntimeError . new ( err ) else @options [ :raises ] = RuntimeError . new ( "An Error" ) end self end | Rig an expected method to raise an exception when the mock is invoked . |
22,582 | def yields ( * items ) @options [ :suppress_arguments_to_block ] = true if items . empty? @options [ :block ] = lambda do | block | if block . arity != 0 and block . arity != - 1 raise ExpectationError . new ( "The given block was expected to have no parameter count; instead, got #{block.arity} to <#{to_s}>" ) end block . call end else @options [ :block ] = lambda do | block | items . each do | item | if item . kind_of? ( Array ) if block . arity == item . size block . call * item elsif block . arity == 1 block . call item else raise ExpectationError . new ( "Can't pass #{item.inspect} to block with arity #{block.arity} to <#{to_s}>" ) end else if block . arity != 1 raise ExpectationError . new ( "Can't pass #{item.inspect} to block with arity #{block.arity} to <#{to_s}>" ) end block . call item end end end end self end | Used when an expected method accepts a block at runtime . When the expected method is invoked the block passed to that method will be invoked as well . |
22,583 | def find ( term ) raise NoWordnetConnection , "There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object." unless connected? homographs = @wordnet_connection . homographs ( term ) Homographs . new ( homographs , @wordnet_connection ) unless homographs . nil? end | Constructs a new wordnet connection object . |
22,584 | def to_rectangle ( point ) d = delta ( point ) Rectangle . new ( row , col , d . col + 1 , d . row + 1 ) end | point is used to calculate the width and height of the new rectangle |
22,585 | def up_vote ( voteable ) check_voteable ( voteable ) voting = fetch_voting ( voteable ) if voting if voting . up_vote raise Exceptions :: AlreadyVotedError . new ( true ) else voting . up_vote = true voteable . down_votes -= 1 self . down_votes -= 1 if has_attribute? ( :down_votes ) end else voting = Voting . create ( :voteable => voteable , :voter_id => self . id , :voter_type => self . class . to_s , :up_vote => true ) end voteable . up_votes += 1 self . up_votes += 1 if has_attribute? ( :up_votes ) Voting . transaction do save voteable . save voting . save end true end | Up vote a + voteable + . Raises an AlreadyVotedError if the voter already up voted the voteable . Changes a down vote to an up vote if the the voter already down voted the voteable . |
22,586 | def up_vote! ( voteable ) begin up_vote ( voteable ) success = true rescue Exceptions :: AlreadyVotedError success = false end success end | Up votes the + voteable + but doesn t raise an error if the votelable was already up voted . The vote is simply ignored then . |
22,587 | def down_vote! ( voteable ) begin down_vote ( voteable ) success = true rescue Exceptions :: AlreadyVotedError success = false end success end | Down votes the + voteable + but doesn t raise an error if the votelable was already down voted . The vote is simply ignored then . |
22,588 | def unvote ( voteable ) check_voteable ( voteable ) voting = fetch_voting ( voteable ) raise Exceptions :: NotVotedError unless voting if voting . up_vote voteable . up_votes -= 1 self . up_votes -= 1 if has_attribute? ( :up_votes ) else voteable . down_votes -= 1 self . down_votes -= 1 if has_attribute? ( :down_votes ) end Voting . transaction do save voteable . save voting . destroy end true end | Clears an already done vote on a + voteable + . Raises a NotVotedError if the voter didn t voted for the voteable . |
22,589 | def unvote! ( voteable ) begin unvote ( voteable ) success = true rescue Exceptions :: NotVotedError success = false end success end | Clears an already done vote on a + voteable + but doesn t raise an error if the voteable was not voted . It ignores the unvote then . |
22,590 | def down_voted? ( voteable ) check_voteable ( voteable ) voting = fetch_voting ( voteable ) return false if voting . nil? return true if voting . has_attribute? ( :up_vote ) && ! voting . up_vote false end | Returns true if the voter down voted the + voteable + . |
22,591 | def read_packet_buffer packets = @data [ :wave ] [ @wave_idx , 64 ] . map { | val | Packet . factory ( :wave , val ) } @wave_idx += 64 @wave_idx = 0 if @wave_idx >= @data [ :wave ] . count if @counter == 7 packets << Packet . factory ( :delta , @data [ :delta ] [ @esense_idx ] ) packets << Packet . factory ( :theta , @data [ :theta ] [ @esense_idx ] ) packets << Packet . factory ( :lo_alpha , @data [ :lo_alpha ] [ @esense_idx ] ) packets << Packet . factory ( :hi_alpha , @data [ :hi_alpha ] [ @esense_idx ] ) packets << Packet . factory ( :lo_beta , @data [ :lo_beta ] [ @esense_idx ] ) packets << Packet . factory ( :hi_beta , @data [ :hi_beta ] [ @esense_idx ] ) packets << Packet . factory ( :lo_gamma , @data [ :lo_gamma ] [ @esense_idx ] ) packets << Packet . factory ( :mid_gamma , @data [ :mid_gamma ] [ @esense_idx ] ) packets << Packet . factory ( :signal_quality , @data [ :signal_quality ] [ @esense_idx ] ) packets << Packet . factory ( :attention , @data [ :attention ] [ @esense_idx ] ) packets << Packet . factory ( :meditation , @data [ :meditation ] [ @esense_idx ] ) packets << Packet . factory ( :blink , @data [ :blink ] [ @esense_idx ] ) @esense_idx += 1 @esense_idx = 0 if @esense_idx >= @data [ :delta ] . count end @counter = ( @counter + 1 ) % 8 packets end | = begin rdoc Simulate a read of the Mindset device by returning an Array of Packet objects . This assumes it will be called 8 times a second . |
22,592 | def verify ( package_json ) inspect ( package_json ) . each do | suspicious | warn ( "`#{suspicious[:package]}` doesn't specify fixed version number" , file : package_json , line : suspicious [ :line ] ) end end | Verifies the supplied package . json file |
22,593 | def inspect ( package_json ) json = JSON . parse ( File . read ( package_json ) ) suspicious_packages = [ ] dependency_keys . each do | dependency_key | next unless json . key? ( dependency_key ) results = find_something_suspicious ( json [ dependency_key ] , package_json ) suspicious_packages . push ( * results ) end suspicious_packages end | Inspects the supplied package . json file and returns problems |
22,594 | def listen ( & block ) return if @listening @listening = true @thread = Thread . new do while @listening message = @queue . retrieve ( @poll_time ) block . call ( message ) if message . present? end end end | Listen for messages . This is asynchronous and returns immediately . |
22,595 | def token_field ( attribute_name , options = { } ) association_type = @object . send ( attribute_name ) . respond_to? ( :each ) ? :many : :one model_name = options . fetch ( :model ) { attribute_name . to_s . gsub ( / / , "" ) } . to_s association = attribute_name . to_s . gsub ( / / , "" ) . to_sym token_url = options . fetch ( :token_url ) { "/#{model_name.pluralize}/token.json" } token_url_is_function = options . fetch ( :token_url_is_function ) { false } append_to_id = options [ :append_to_id ] token_method = options . fetch ( :token_method ) { :to_token } token_limit = nil token_limit = 1 if association_type == :one id = @object . send ( :id ) html_id = "#{@object_name}_#{attribute_name.to_s}" if append_to_id == :id && id html_id << "_#{id}" elsif append_to_id && append_to_id != :id html_id << "_#{append_to_id}" end html_id = html_id . parameterize . underscore results = [ ] if association_type == :one && @object . public_send ( association ) results << @object . public_send ( association ) elsif association_type == :many && @object . public_send ( association . to_s . pluralize ) . count > 0 @object . public_send ( association . to_s . pluralize ) . each { | record | results << record } end data_pre = results . map { | result | result . public_send ( token_method ) } value = data_pre . map { | row | row [ :id ] } . join ( ',' ) on_add = options [ :on_add ] ? "#{options[:on_add]}" : "false" on_delete = options [ :on_delete ] ? "#{options[:on_delete]}" : "false" token_url = "'#{token_url}'" unless token_url_is_function js_content = " jQuery.noConflict(); jQuery(function() { jQuery('##{html_id}').tokenInput(#{token_url}, { crossDomain: false, tokenLimit: #{token_limit.nil? ? "null" : token_limit.to_i}, preventDuplicates: true, prePopulate: jQuery('##{attribute_name}').data('pre'), theme: 'facebook', hintText: '" + t ( 'helpers.token_field.hint_text' ) + "', searchingText: '" + t ( 'helpers.token_field.searching_text' ) + "', noResultsText: '" + t ( 'helpers.token_field.no_results_text' ) + "', onAdd: " + on_add + ", onDelete: " + on_delete + " }); }); " script = content_tag ( :script , js_content . html_safe , :type => Mime :: JS ) text_field ( "#{attribute_name}" , "data-pre" => data_pre . to_json , :value => value , :id => html_id ) + script end | form_for helper for token input with jquery token input plugin for has_many and belongs_to association |
22,596 | def process_node ( node , level = 1 ) entries = node . children @visitor . enter_node ( node ) entries . each do | entry | unless is_leaf? ( entry ) process_node ( entry , level + 1 ) else @visitor . visit_leaf ( entry ) end end @visitor . exit_node ( node ) end | recurse on nodes |
22,597 | def handle_whole_archive ( building_block , res , linker , flag ) if is_whole_archive ( building_block ) res . push ( flag ) if flag and ! flag . empty? end end | res the array with command line arguments that is used as result linker the linker hash sym the symbol that is used to fish out a value from the linker |
22,598 | def convert_to_rake ( ) object_multitask = prepare_tasks_for_objects ( ) res = typed_file_task get_rake_task_type ( ) , get_task_name => object_multitask do cmd = calc_command_line Dir . chdir ( @project_dir ) do mapfileStr = @mapfile ? " >#{@mapfile}" : "" rd , wr = IO . pipe cmdLinePrint = cmd printCmd ( cmdLinePrint , "Linking #{executable_name}" , false ) cmd << { :out => @mapfile ? "#{@mapfile}" : wr , :err => wr } sp = spawn ( * cmd ) cmd . pop cmd << " >#{@mapfile}" if @mapfile consoleOutput = ProcessHelper . readOutput ( sp , rd , wr ) process_result ( cmdLinePrint , consoleOutput , @tcs [ :LINKER ] [ :ERROR_PARSER ] , nil ) check_config_file ( ) post_link_hook ( @tcs [ :LINKER ] ) end end res . tags = tags res . immediate_output = true res . enhance ( @config_files ) res . enhance ( [ @project_dir + "/" + @linker_script ] ) if @linker_script add_output_dir_dependency ( get_task_name , res , true ) add_grouping_tasks ( get_task_name ) setup_rake_dependencies ( res , object_multitask ) begin libChecker = task get_task_name + "LibChecker" do if File . exists? ( get_task_name ) all_dependencies . each do | bb | if bb and StaticLibrary === bb f = bb . get_task_name if not File . exists? ( f ) or File . mtime ( f ) > File . mtime ( get_task_name ) def res . needed? true end break end end end end end rescue def res . needed? true end end libChecker . transparent_timestamp = true res . enhance ( [ libChecker ] ) return res end | create a task that will link an executable from a set of object files |
22,599 | def post_link_hook ( linker ) basic_name = get_basic_name ( linker ) soname = get_soname ( linker ) symlink_lib_to basic_name symlink_lib_to soname end | Some symbolic links ln - s libfoo . so libfoo . 1 . 2 . so ln - s libfoo . 1 . so libfoo . 1 . 2 . so |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.