idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
15,400 | def long_poll ( routing_keys , ack , & handler ) raise ArgumentError , "Block missing" unless block_given? params = { :wait_time => @options [ :listen_timeout ] - 5 , :timestamp => Time . now . to_f } params [ :routing_keys ] = routing_keys if routing_keys params [ :ack ] = ack if ack && ack . any? options = { :request... | Make long - polling request to receive one or more events Do not return until an event is received or the polling times out or fails |
15,401 | def process_long_poll ( result ) case result when Exceptions :: Unauthorized , Exceptions :: ConnectivityFailure , Exceptions :: RetryableError , Exceptions :: InternalServerError @connect_interval = CONNECT_INTERVAL update_listen_state ( :choose , backoff_reconnect_interval ) result = nil when Exception ErrorTracker .... | Process result from long - polling attempt Not necessary to log failure since should already have been done by underlying HTTP client |
15,402 | def init ( type , auth_client , options ) raise ArgumentError , "Auth client does not support server type #{type.inspect}" unless auth_client . respond_to? ( type . to_s + "_url" ) raise ArgumentError , ":api_version option missing" unless options [ :api_version ] @type = type @auth_client = auth_client @http_client = ... | Set configuration of this client and initialize HTTP access |
15,403 | def create_http_client close_http_client ( "reconnecting" ) url = @auth_client . send ( @type . to_s + "_url" ) Log . info ( "Connecting to #{@options[:server_name]} via #{url.inspect}" ) options = { :server_name => @options [ :server_name ] } options [ :api_version ] = @options [ :api_version ] if @options [ :api_vers... | Create HTTP client If there is an existing client close it first |
15,404 | def close_http_client ( reason ) @http_client . close ( reason ) if @http_client true rescue StandardError => e ErrorTracker . log ( self , "Failed closing connection" , e ) false end | Close HTTP client persistent connections |
15,405 | def check_health begin @http_client . check_health self . state = :connected rescue BalancedHttpClient :: NotResponding => e ErrorTracker . log ( self , "Failed #{@options[:server_name]} health check" , e . nested_exception ) self . state = :disconnected rescue StandardError => e ErrorTracker . log ( self , "Failed #{@... | Check health of RightApi directly without applying RequestBalancer Do not check whether HTTP client exists |
15,406 | def reconnect unless @reconnecting @reconnecting = true if EM . reactor_running? @stats [ "reconnects" ] . update ( "initiate" ) @reconnect_timer = EM_S :: PeriodicTimer . new ( rand ( @options [ :reconnect_interval ] ) ) do begin reconnect_once rescue Exception => e ErrorTracker . log ( self , "Failed #{@options[:serv... | If EventMachine reactor is running begin attempting to periodically reconnect with server by checking health . Randomize initial attempt to reduce server spiking . |
15,407 | def make_request ( verb , path , params = { } , type = nil , options = { } ) raise Exceptions :: Terminating if state == :closed started_at = Time . now time_to_live = ( options [ :time_to_live ] && options [ :time_to_live ] > 0 ) ? options [ :time_to_live ] : nil expires_at = started_at + [ time_to_live || @options [ ... | Make request via HTTP . Attempt to reconnect first if disconnected and EM reactor is not running . Rely on underlying HTTP client to log request and response . Retry request if response indicates to or if there are connectivity failures . |
15,408 | def handle_exception ( exception , type , request_uuid , expires_at , attempts ) result = request_uuid if exception . respond_to? ( :http_code ) case exception . http_code when 301 , 302 handle_redirect ( exception , type , request_uuid ) when 401 raise Exceptions :: Unauthorized . new ( exception . http_body , excepti... | Examine exception to determine whether to setup retry raise new exception or re - raise |
15,409 | def handle_redirect ( redirect , type , request_uuid ) Log . info ( "Received REDIRECT #{redirect} for #{type} request <#{request_uuid}>" ) if redirect . respond_to? ( :response ) && ( location = redirect . response . headers [ :location ] ) && ! location . empty? Log . info ( "Requesting auth client to handle redirect... | Treat redirect response as indication that no longer accessing the correct shard Handle it by informing auth client so that it can re - authorize Do not retry but tell client to with the expectation that re - auth will correct the situation |
15,410 | def handle_retry_with ( retry_result , type , request_uuid , expires_at , attempts ) case ( interval = retry_interval ( expires_at , attempts , 1 ) ) when nil @stats [ "request failures" ] . update ( "#{type} - retry" ) raise Exceptions :: RetryableError . new ( retry_result . http_body , retry_result ) when 0 @stats [... | Handle retry response by retrying it only once This indicates the request was received but a retryable error prevented it from being processed ; the retry responsibility may be passed on If retrying this function does not return until it is time to retry |
15,411 | def handle_not_responding ( not_responding , type , request_uuid , expires_at , attempts ) case ( interval = retry_interval ( expires_at , attempts ) ) when nil @stats [ "request failures" ] . update ( "#{type} - no result" ) self . state = :disconnected raise Exceptions :: ConnectivityFailure . new ( not_responding . ... | Handle not responding response by determining whether okay to retry If request is being retried this function does not return until it is time to retry |
15,412 | def retry_interval ( expires_at , attempts , max_retries = nil ) if @options [ :retry_enabled ] if max_retries . nil? || attempts <= max_retries interval = @options [ :retry_intervals ] [ attempts - 1 ] || @options [ :retry_intervals ] [ - 1 ] ( ( Time . now + interval ) < expires_at ) ? interval : 0 else 0 end end end | Determine time interval before next retry |
15,413 | def wait ( interval ) if @options [ :non_blocking ] fiber = Fiber . current EM . add_timer ( interval ) { fiber . resume } Fiber . yield else sleep ( interval ) end true end | Wait the specified interval in non - blocking fashion if possible |
15,414 | def handle_response ( r ) return true if @done @raw_response = r res = result_from ( r ) if res . success? if @cancel_timer @cancel_timer . cancel @cancel_timer = nil end @done = true succeed ( res . content ) else reason = res . content if res . non_delivery? Log . info ( "Request non-delivery (#{reason}) for #{@opera... | Process request response and retry if needed |
15,415 | def dump ( obj , encrypt = nil ) must_encrypt = encrypt || @encrypt serialize_format = if obj . respond_to? ( :send_version ) && can_handle_msgpack_result? ( obj . send_version ) @serializer . format else :json end encode_format = serialize_format == :json ? :pem : :der msg = @serializer . dump ( obj , serialize_format... | Initialize serializer must be called prior to using it |
15,416 | def load ( msg , id = nil ) msg = @serializer . load ( msg ) sig = Signature . from_data ( msg [ 'signature' ] ) certs = @store . get_signer ( msg [ 'id' ] ) raise MissingCertificate . new ( "Could not find a certificate for signer #{msg['id']}" ) unless certs certs = [ certs ] unless certs . respond_to? ( :any? ) rais... | Decrypt authorize signature and unserialize message Use x . 509 certificate store for decrypting and validating signature |
15,417 | def fill_out ( session ) session [ 'scope' ] = "attachments" if @digest session [ 'resource' ] = @digest else session [ 'resource' ] = to_hash session [ 'url' ] = @url session [ 'etag' ] = @etag end @token = session . to_s end | Fill out the session cookie appropriately for this attachment . |
15,418 | def parse_chunk ( chunk ) @buildup << chunk chunks = @buildup . split ( CommandSerializer :: SEPARATOR , - 1 ) if ( do_call = chunks . size > 1 ) commands = [ ] ( 0 .. chunks . size - 2 ) . each do | i | begin commands << CommandSerializer . load ( chunks [ i ] ) rescue StandardError => e Log . error ( "Failed parsing ... | Register callback block |
15,419 | def issue_cert test_dn = { 'C' => 'US' , 'ST' => 'California' , 'L' => 'Santa Barbara' , 'O' => 'Agent' , 'OU' => 'Certification Services' , 'CN' => 'Agent test' } dn = DistinguishedName . new ( test_dn ) key = RsaKeyPair . new [ Certificate . new ( key , dn , dn ) , key ] end | Create test certificate |
15,420 | def dispatch ( request ) token = request . token actor , method , idempotent = route ( request ) received_at = @request_stats . update ( method , ( token if request . is_a? ( Request ) ) ) if ( dup = duplicate? ( request , method , idempotent ) ) raise DuplicateRequest , dup end unless ( result = expired? ( request , m... | Route request to appropriate actor for servicing Reject requests whose TTL has expired or that are duplicates of work already dispatched |
15,421 | def stats ( reset = false ) stats = { "dispatched cache" => ( @dispatched_cache . stats if @dispatched_cache ) , "dispatch failures" => @dispatch_failure_stats . all , "rejects" => @reject_stats . all , "requests" => @request_stats . all } reset_stats if reset stats end | Get dispatcher statistics |
15,422 | def expired? ( request , method ) if ( expires_at = request . expires_at ) && expires_at > 0 && ( now = Time . now . to_i ) >= expires_at @reject_stats . update ( "expired (#{method})" ) Log . info ( "REJECT EXPIRED <#{request.token}> from #{request.from} TTL #{RightSupport::Stats.elapsed(now - expires_at)} ago" ) if c... | Determine if request TTL has expired |
15,423 | def duplicate? ( request , method , idempotent ) if ! idempotent && @dispatched_cache if ( serviced_by = @dispatched_cache . serviced_by ( request . token ) ) from_retry = "" else from_retry = "retry " request . tries . each { | t | break if ( serviced_by = @dispatched_cache . serviced_by ( t ) ) } end if serviced_by @... | Determine whether this request is a duplicate |
15,424 | def route ( request ) prefix , method = request . type . split ( '/' ) [ 1 .. - 1 ] method ||= :index method = method . to_sym actor = @registry . actor_for ( prefix ) if actor . nil? || ! actor . respond_to? ( method ) raise InvalidRequestType , "Unknown actor or method for dispatching request <#{request.token}> of ty... | Use request type to route request to actor and an associated method |
15,425 | def perform ( request , actor , method , idempotent ) @dispatched_cache . store ( request . token ) if @dispatched_cache && ! idempotent if actor . method ( method ) . arity . abs == 1 actor . send ( method , request . payload ) else actor . send ( method , request . payload , request ) end rescue StandardError => e Er... | Perform requested action |
15,426 | def save ( file ) File . open ( file , "w" ) do | f | f . write ( @raw_cert . to_pem ) end true end | Save certificate to file in PEM format |
15,427 | def load events = [ ] File . open ( @history , "r" ) { | f | events = f . readlines . map { | l | JSON . legacy_load ( l ) } } if File . readable? ( @history ) events end | Load events from history file |
15,428 | def map_request ( type , payload , options ) verb , path = API_MAP [ type ] raise ArgumentError , "Unsupported request type: #{type}" if path . nil? actor , action = type . split ( "/" ) [ 1 .. - 1 ] path , params , request_options = parameterize ( actor , action , payload , path ) if action == "query_tags" map_query_t... | Convert request to RightApi form and then make request via HTTP |
15,429 | def map_response ( response , path ) case path when "/audit_entries" response . sub! ( / \/ \/ \/ / , "" ) if response . is_a? ( String ) when "/tags/by_resource" , "/tags/by_tag" tags = { } if response response . each do | hash | r = { } hash [ "links" ] . each { | l | r [ l [ "href" ] ] = { "tags" => [ ] } if l [ "hr... | Convert response from request into required form where necessary |
15,430 | def map_query_tags ( verb , params , action , options ) response = { } hrefs = params [ :resource_hrefs ] || [ ] hrefs . concat ( query_by_tag ( verb , params [ :tags ] , action , options ) ) if params [ :tags ] response = query_by_resource ( verb , hrefs , action , options ) if hrefs . any? response end | Convert tag query request into one or more API requests and then convert responses Currently only retrieving instances resources |
15,431 | def query_by_tag ( verb , tags , action , options ) path = "/tags/by_tag" params = { :tags => tags , :match_all => false , :resource_type => "instances" } map_response ( make_request ( verb , path , params , action , options ) , path ) . keys end | Query API for resources with specified tags |
15,432 | def query_by_resource ( verb , hrefs , action , options ) path = "/tags/by_resource" params = { :resource_hrefs => hrefs } map_response ( make_request ( verb , path , params , action , options ) , path ) end | Query API for tags associated with a set of resources |
15,433 | def parameterize ( actor , action , payload , path ) options = { } params = { } if actor == "auditor" path = path . sub ( / / , payload [ :audit_id ] . to_s || "" ) params = parameterize_audit ( action , payload ) options = { :filter_params => AUDIT_FILTER_PARAMS } elsif actor == "router" && action =~ / / if action != ... | Convert payload to HTTP parameters |
15,434 | def parameterize_audit ( action , payload ) params = { } summary = non_blank ( payload [ :summary ] ) detail = non_blank ( payload [ :detail ] ) case action when "create_entry" params [ :audit_entry ] = { :auditee_href => @self_href } params [ :audit_entry ] [ :summary ] = truncate ( summary , MAX_AUDIT_SUMMARY_LENGTH ... | Translate audit request payload to HTTP parameters Truncate audit summary to MAX_AUDIT_SUMMARY_LENGTH the limit imposed by RightApi |
15,435 | def truncate ( value , max_length ) raise ArgumentError , "max_length must be greater than 3" if max_length <= 3 if value . is_a? ( String ) && value . bytesize > max_length max_truncated = max_length - 3 truncated = value [ 0 , max_truncated ] while truncated . bytesize > max_truncated do truncated . chop! end truncat... | Truncate string if it exceeds maximum length Do length check with bytesize rather than size since this method is only intended for use with ruby 1 . 9 and above otherwise multi - byte characters could cause this code to be too lenient |
15,436 | def cut! create_backup_copy MiniMagick :: Tool :: Mogrify . new do | mogrify | mogrify . resize ( max_size ) mogrify . strip if jpeg? mogrify . colorspace ( Kirigami . config . jpeg_colorspace ) mogrify . sampling_factor ( Kirigami . config . jpeg_sampling_factor ) mogrify . interlace ( Kirigami . config . jpeg_interla... | Create a new Image |
15,437 | def infer_schema ( samples_count : 0 , extended : false ) if db_backend == :postgresql sch = db_adapter . client . schema ( read_dataset_name ) . to_h sch = sch . reject { | k , v | k == :_id } . map { | k , v | [ k , { type : v [ :type ] . to_s } ] } . to_h self . inferred_schema = sch save return sch end data_count =... | if this change update the regex that use the character directly in this mixin Generate a schema based on this collection s records . We evaluate the schema of each record and then merge all the information together . |
15,438 | def assist_with ( submission ) @rules . select { | it | it . matches? ( submission ) } . map { | it | it . message_for ( submission . attemps_count ) } end | Provides tips for the student for the given submission based on the rules . |
15,439 | def ko_deeper_merge! ( source , options = { } ) default_opts = { :knockout_prefix => "--" , :preserve_unmergeables => false } DeepMerge :: deep_merge! ( source , self , default_opts . merge ( options ) ) end | ko_hash_merge! will merge and knockout elements prefixed with DEFAULT_FIELD_KNOCKOUT_PREFIX |
15,440 | def with_exclusive_scope ( method_scoping = { } , & block ) if method_scoping . values . any? { | e | e . is_a? ( ActiveRecord :: Relation ) } raise ArgumentError , <<-MSG MSG end with_scope ( method_scoping , :overwrite , & block ) end | Works like with_scope but discards any nested properties . |
15,441 | def set ( var , value = "" ) value = "\"#{value}\"" if QUOTED . include? var unless value =~ / / @settings << [ :set , var , value ] end | Set a variable to the given value . + Var + must be a gnuplot variable and + value + must be the value to set it to . Automatic quoting will be performed if the variable requires it . |
15,442 | def merge ( object ) object = case object when JOSE :: Map , Hash object when String JOSE . decode ( object ) when JOSE :: JWT object . to_map else raise ArgumentError , "'object' must be a Hash, String, or JOSE::JWT" end return JOSE :: JWT . from_map ( self . to_map . merge ( object ) ) end | Merges object into current map . |
15,443 | def block_encrypt ( plain_text , jwe = nil ) jwe ||= block_encryptor return JOSE :: JWE . block_encrypt ( self , plain_text , jwe ) end | Encrypts the plain_text using the jwk and algorithms specified by the jwe . |
15,444 | def box_decrypt ( encrypted , public_jwk = nil ) if public_jwk return JOSE :: JWE . block_decrypt ( [ public_jwk , self ] , encrypted ) else return JOSE :: JWE . block_decrypt ( self , encrypted ) end end | Key Agreement decryption of the encrypted binary or map using my_private_jwk . |
15,445 | def box_encrypt ( plain_text , jwk_secret = nil , jwe = nil ) epk_secret = nil jwk_public = self if jwk_secret . nil? epk_secret = jwk_secret = jwk_public . generate_key end if not jwk_secret . is_a? ( JOSE :: JWK ) jwk_secret = JOSE :: JWK . from ( jwk_secret ) end if jwe . nil? jwe = jwk_public . block_encryptor end ... | Key Agreement encryption of plain_text by generating an ephemeral private key based on other_public_jwk curve . |
15,446 | def shared_secret ( other_jwk ) other_jwk = from ( other_jwk ) if not other_jwk . is_a? ( JOSE :: JWK ) raise ArgumentError , "key types must match" if other_jwk . kty . class != kty . class raise ArgumentError , "key type does not support shared secret computations" if not kty . respond_to? ( :derive_key ) return kty ... | Computes the shared secret between two keys . |
15,447 | def sign ( plain_text , jws = nil , header = nil ) jws ||= signer return JOSE :: JWS . sign ( self , plain_text , jws , header ) end | Signs the plain_text using the jwk and the default signer algorithm jws for the key type . |
15,448 | def sign ( jwk , plain_text , header = nil ) protected_binary = JOSE . urlsafe_encode64 ( to_binary ) payload = JOSE . urlsafe_encode64 ( plain_text ) signing_input = signing_input ( plain_text , protected_binary ) signature = JOSE . urlsafe_encode64 ( alg . sign ( jwk , signing_input ) ) return signature_to_map ( payl... | Signs the plain_text using the jwk and algorithm specified by the jws . |
15,449 | def verify ( jwk , plain_text , signature , protected_binary = nil ) protected_binary ||= JOSE . urlsafe_encode64 ( to_binary ) signing_input = signing_input ( plain_text , protected_binary ) return alg . verify ( jwk , signing_input , signature ) , plain_text , self end | Verifies the signature using the jwk plain_text and protected_binary . |
15,450 | def supports jwe_enc = __jwe_enc_support_check__ ( [ 'A128GCM' , 'A192GCM' , 'A256GCM' , 'A128CBC-HS256' , 'A192CBC-HS384' , 'A256CBC-HS512' ] ) jwe_alg = __jwe_alg_support_check__ ( [ [ 'A128GCMKW' , :block ] , [ 'A192GCMKW' , :block ] , [ 'A256GCMKW' , :block ] , [ 'A128KW' , :block ] , [ 'A192KW' , :block ] , [ 'A25... | Returns the current listing of supported JOSE algorithms . |
15,451 | def block_decrypt ( key , aad , cipher_text , cipher_tag , encrypted_key , iv ) cek = key_decrypt ( key , encrypted_key ) return uncompress ( enc . block_decrypt ( [ aad , cipher_text , cipher_tag ] , cek , iv ) ) end | Decrypts the cipher_text binary using the key aad cipher_tag encrypted_key and iv . |
15,452 | def block_encrypt ( key , block , cek = nil , iv = nil ) jwe = self if cek . nil? cek , jwe = next_cek ( key ) end iv ||= jwe . next_iv aad , plain_text = block if plain_text . nil? plain_text = aad aad = nil end encrypted_key , jwe = jwe . key_encrypt ( key , cek ) protected_binary = JOSE . urlsafe_encode64 ( jwe . to... | Encrypts the block binary using the key cek and iv . |
15,453 | def key_encrypt ( key , decrypted_key ) encrypted_key , new_alg = alg . key_encrypt ( key , enc , decrypted_key ) new_jwe = JOSE :: JWE . from_map ( to_map ) new_jwe . alg = new_alg return encrypted_key , new_jwe end | Encrypts the decrypted_key using the key and the alg and enc specified by the jwe . |
15,454 | def next_cek ( key ) decrypted_key , new_alg = alg . next_cek ( key , enc ) new_jwe = JOSE :: JWE . from_map ( to_map ) new_jwe . alg = new_alg return decrypted_key , new_jwe end | Returns the next cek using the jwk and the alg and enc specified by the jwe . |
15,455 | def run ( cookbook , options = { } ) log . info ( "Running validations for `#{klass.id}.#{id}'" ) inside ( cookbook ) do instance = klass . new ( cookbook , options ) unless result = instance . instance_eval ( & block ) log . debug ( "Validation failed, result: #{result.inspect}" ) error = Error . const_get ( "#{Util.c... | Create a new validator object . |
15,456 | def tar ( root , slip ) io = StringIO . new ( '' , 'r+b' ) Gem :: Package :: TarWriter . new ( io ) do | tar | slip . each do | original_file , tarball_file | mode = File . stat ( original_file ) . mode if File . directory? ( original_file ) tar . mkdir ( tarball_file , mode ) else tar . add_file ( tarball_file , mode ... | Create a tar file from the given root and packaging slip |
15,457 | def option_parser @option_parser ||= OptionParser . new do | opts | opts . banner = 'Usage: stove [OPTIONS]' opts . separator '' opts . separator 'Plugins:' opts . on ( '--no-git' , 'Do not use the git plugin. Skips tagging if specified.' ) do options [ :no_git ] = true end opts . separator '' opts . separator 'Upload ... | The option parser for handling command line flags . |
15,458 | def options @options ||= { :endpoint => nil , :username => Config . username , :key => Config . key , :extended_metadata => true , :ssl_verify => true , :remote => 'origin' , :branch => 'master' , :sign => false , :artifactory => false , :artifactory_key => ENV [ 'ARTIFACTORY_API_KEY' ] , :log_level => :warn , :path =>... | The options to pass to the cookbook . Includes default values that are manipulated by the option parser . |
15,459 | def upload ( cookbook , extended_metadata = false ) connection . post ( 'cookbooks' , { 'tarball' => cookbook . tarball ( extended_metadata ) , 'cookbook' => JSON . fast_generate ( category : 'Other' ) , } ) end | Upload a cookbook to the community site . |
15,460 | def connection @connection ||= ChefAPI :: Connection . new do | conn | conn . endpoint = ENV [ 'STOVE_ENDPOINT' ] || Config . endpoint || DEFAULT_ENDPOINT conn . client = ENV [ 'STOVE_USERNAME' ] || Config . username conn . key = ENV [ 'STOVE_KEY' ] || Config . key conn . ssl_verify = ENV [ 'STOVE_NO_SSL_VERIFY' ] || C... | The ChefAPI connection object with lots of pretty middleware . |
15,461 | def upload ( cookbook , extended_metadata = false ) response = request ( :get , "api/v1/cookbooks/#{cookbook.name}/versions/#{cookbook.version}" ) unless response . code == '404' || ( response . code == '200' && response . body . to_s == '' ) raise Error :: CookbookAlreadyExists . new ( cookbook : cookbook ) end respon... | Upload a cookbook to an Artifactory server . |
15,462 | def connection @connection ||= begin uri = URI ( Config . artifactory . strip ) http = Net :: HTTP . new ( uri . host , uri . port ) if uri . scheme == 'https' http . use_ssl = true if ENV [ 'STOVE_NO_SSL_VERIFY' ] || ! Config . ssl_verify http . verify_mode = OpenSSL :: SSL :: VERIFY_NONE end end http . start end end | Create an HTTP connect to the Artifactory server . |
15,463 | def request ( method , path , & block ) uri_string = Config . artifactory . strip uri_string << '/' unless uri_string . end_with? ( '/' ) uri_string << path uri = URI ( uri_string ) request = Net :: HTTP . const_get ( method . to_s . capitalize ) . new ( uri ) request [ 'X-Jfrog-Art-Api' ] = Config . artifactory_key . ... | Send an HTTP request to the Artifactory server . |
15,464 | def released? Supermarket . cookbook ( name , version ) true rescue ChefAPI :: Error :: HTTPNotFound false end | Deterine if this cookbook version is released on the Supermarket |
15,465 | def run ( cookbook , options = { } ) log . info ( message ) instance = klass . new ( cookbook , options ) inside ( cookbook ) do instance . instance_eval ( & block ) end end | Create a new filter object . |
15,466 | def evaluate ( _context = Context . new ) _context = Context . new ( _context ) if _context . is_a? ( Hash ) @_proc ||= eval ( "proc { #{@src} }" , binding ( ) , @filename || '(erubis)' ) return _context . instance_eval ( & @_proc ) end | invoke context . instance_eval ( |
15,467 | def def_method ( object , method_name , filename = nil ) m = object . is_a? ( Module ) ? :module_eval : :instance_eval object . __send__ ( m , "def #{method_name}; #{@src}; end" , filename || @filename || '(erubis)' ) end | if object is an Class or Module then define instance method to it else define singleton method to it . |
15,468 | def convert ( input ) codebuf = "" @preamble . nil? ? add_preamble ( codebuf ) : ( @preamble && ( codebuf << @preamble ) ) convert_input ( codebuf , input ) @postamble . nil? ? add_postamble ( codebuf ) : ( @postamble && ( codebuf << @postamble ) ) @_proc = nil return codebuf end | convert input string into target language |
15,469 | def detect_spaces_at_bol ( text , is_bol ) lspace = nil if text . empty? lspace = "" if is_bol elsif text [ - 1 ] == ?\n lspace = "" else rindex = text . rindex ( ?\n ) if rindex s = text [ rindex + 1 .. - 1 ] if s =~ / \A \t \z / lspace = s text [ rindex + 1 .. - 1 ] = '' end else if is_bol && text =~ / \A \t \z / lsp... | detect spaces at beginning of line |
15,470 | def process ( input , context = nil , filename = nil ) code = convert ( input ) filename ||= '(erubis)' if context . is_a? ( Binding ) return eval ( code , context , filename ) else context = Context . new ( context ) if context . is_a? ( Hash ) return context . instance_eval ( code , filename ) end end | helper method to convert and evaluate input text with context object . context may be Binding Hash or Object . |
15,471 | def process_proc ( proc_obj , context = nil , filename = nil ) if context . is_a? ( Binding ) filename ||= '(erubis)' return eval ( proc_obj , context , filename ) else context = Context . new ( context ) if context . is_a? ( Hash ) return context . instance_eval ( & proc_obj ) end end | helper method evaluate Proc object with contect object . context may be Binding Hash or Object . |
15,472 | def open ppHandle = FFI :: MemoryPointer . new :pointer res = Call . libusb_open ( @pDev , ppHandle ) LIBUSB . raise_error res , "in libusb_open" if res! = 0 handle = DevHandle . new self , ppHandle . read_pointer return handle unless block_given? begin yield handle ensure handle . close end end | Open the device and obtain a device handle . |
15,473 | def max_packet_size ( endpoint ) endpoint = endpoint . bEndpointAddress if endpoint . respond_to? :bEndpointAddress res = Call . libusb_get_max_packet_size ( @pDev , endpoint ) LIBUSB . raise_error res , "in libusb_get_max_packet_size" unless res >= 0 res end | Convenience function to retrieve the wMaxPacketSize value for a particular endpoint in the active device configuration . |
15,474 | def max_iso_packet_size ( endpoint ) endpoint = endpoint . bEndpointAddress if endpoint . respond_to? :bEndpointAddress res = Call . libusb_get_max_iso_packet_size ( @pDev , endpoint ) LIBUSB . raise_error res , "in libusb_get_max_iso_packet_size" unless res >= 0 res end | Calculate the maximum packet size which a specific endpoint is capable is sending or receiving in the duration of 1 microframe . |
15,475 | def config_descriptor ( index ) ppConfig = FFI :: MemoryPointer . new :pointer res = Call . libusb_get_config_descriptor ( @pDev , index , ppConfig ) LIBUSB . raise_error res , "in libusb_get_config_descriptor" if res! = 0 pConfig = ppConfig . read_pointer config = Configuration . new ( self , pConfig ) config end | Obtain a config descriptor of the device . |
15,476 | def configurations configs = [ ] bNumConfigurations . times do | config_index | begin configs << config_descriptor ( config_index ) rescue RuntimeError end end configs end | Return configurations of the device . |
15,477 | def eventmachine_register @eventmachine_attached_fds = { } @eventmachine_timer = nil pollfds = self . pollfds if pollfds pollfds . each do | pollfd | eventmachine_add_pollfd ( pollfd ) end self . on_pollfd_added do | pollfd | eventmachine_add_pollfd ( pollfd ) end self . on_pollfd_removed do | pollfd | eventmachine_rm_... | Register libusb s file descriptors and timeouts to EventMachine . |
15,478 | def claim_interface ( interface ) interface = interface . bInterfaceNumber if interface . respond_to? :bInterfaceNumber res = Call . libusb_claim_interface ( @pHandle , interface ) LIBUSB . raise_error res , "in libusb_claim_interface" if res! = 0 return self unless block_given? begin yield self ensure release_interfac... | Claim an interface on a given device handle . |
15,479 | def set_configuration ( configuration ) configuration = configuration . bConfigurationValue if configuration . respond_to? :bConfigurationValue res = Call . libusb_set_configuration ( @pHandle , configuration || - 1 ) LIBUSB . raise_error res , "in libusb_set_configuration" if res! = 0 end | Set the active configuration for a device . |
15,480 | def set_interface_alt_setting ( setting_or_interface_number , alternate_setting = nil ) alternate_setting ||= setting_or_interface_number . bAlternateSetting if setting_or_interface_number . respond_to? :bAlternateSetting setting_or_interface_number = setting_or_interface_number . bInterfaceNumber if setting_or_interfa... | Activate an alternate setting for an interface . |
15,481 | def kernel_driver_active? ( interface ) interface = interface . bInterfaceNumber if interface . respond_to? :bInterfaceNumber res = Call . libusb_kernel_driver_active ( @pHandle , interface ) LIBUSB . raise_error res , "in libusb_kernel_driver_active" unless res >= 0 return res == 1 end | Determine if a kernel driver is active on an interface . |
15,482 | def detach_kernel_driver ( interface ) interface = interface . bInterfaceNumber if interface . respond_to? :bInterfaceNumber res = Call . libusb_detach_kernel_driver ( @pHandle , interface ) LIBUSB . raise_error res , "in libusb_detach_kernel_driver" if res! = 0 end | Detach a kernel driver from an interface . |
15,483 | def bulk_transfer ( args = { } , & block ) timeout = args . delete ( :timeout ) || 1000 endpoint = args . delete ( :endpoint ) || raise ( ArgumentError , "no endpoint given" ) endpoint = endpoint . bEndpointAddress if endpoint . respond_to? :bEndpointAddress if endpoint & ENDPOINT_IN != 0 dataIn = args . delete ( :data... | Perform a USB bulk transfer . |
15,484 | def control_transfer ( args = { } , & block ) bmRequestType = args . delete ( :bmRequestType ) || raise ( ArgumentError , "param :bmRequestType not given" ) bRequest = args . delete ( :bRequest ) || raise ( ArgumentError , "param :bRequest not given" ) wValue = args . delete ( :wValue ) || raise ( ArgumentError , "para... | Perform a USB control transfer . |
15,485 | def device_capabilities pp_ext = FFI :: MemoryPointer . new :pointer caps = [ ] ptr = pointer + offset_of ( :dev_capability ) bNumDeviceCaps . times do cap = DeviceCapability . new self , ptr . read_pointer case cap . bDevCapabilityType when LIBUSB :: BT_WIRELESS_USB_DEVICE_CAPABILITY when LIBUSB :: BT_USB_2_0_EXTENSIO... | bNumDeviceCap Device Capability Descriptors |
15,486 | def submit! ( & block ) self . callback = block if block_given? res = Call . libusb_submit_transfer ( @transfer ) LIBUSB . raise_error res , "in libusb_submit_transfer" if res! = 0 end | Submit a transfer . |
15,487 | def submit_and_wait raise ArgumentError , "#{self.class}#dev_handle not set" unless @dev_handle @completion_flag . completed = false submit! do | tr2 | @completion_flag . completed = true end until @completion_flag . completed? begin @dev_handle . device . context . handle_events nil , @completion_flag rescue ERROR_INT... | Submit the transfer and wait until the transfer completes or fails . |
15,488 | def handle_events ( timeout = nil , completion_flag = nil ) if completion_flag && ! completion_flag . is_a? ( Context :: CompletionFlag ) raise ArgumentError , "completion_flag is not a CompletionFlag" end if timeout timeval = Call :: Timeval . new timeval . in_ms = timeout res = if Call . respond_to? ( :libusb_handle_... | Handle any pending events in blocking mode . |
15,489 | def devices ( filter_hash = { } ) device_list . select do | dev | ( ! filter_hash [ :bClass ] || ( dev . bDeviceClass == CLASS_PER_INTERFACE ? dev . settings . map ( & :bInterfaceClass ) . & ( [ filter_hash [ :bClass ] ] . flatten ) . any? : [ filter_hash [ :bClass ] ] . flatten . include? ( dev . bDeviceClass ) ) ) &&... | Obtain a list of devices currently attached to the USB system optionally matching certain criteria . |
15,490 | def pollfds ppPollfds = Call . libusb_get_pollfds ( @ctx ) return nil if ppPollfds . null? offs = 0 pollfds = [ ] while ! ( pPollfd = ppPollfds . get_pointer ( offs ) ) . null? pollfd = Call :: Pollfd . new pPollfd pollfds << Pollfd . new ( pollfd [ :fd ] , pollfd [ :events ] ) offs += FFI . type_size :pointer end if C... | Retrieve a list of file descriptors that should be polled by your main loop as libusb event sources . |
15,491 | def next_timeout timeval = Call :: Timeval . new res = Call . libusb_get_next_timeout @ctx , timeval LIBUSB . raise_error res , "in libusb_get_next_timeout" if res < 0 res == 1 ? timeval . in_s : nil end | Determine the next internal timeout that libusb needs to handle . |
15,492 | def on_pollfd_added & block @on_pollfd_added = proc do | fd , events , _ | pollfd = Pollfd . new fd , events block . call pollfd end Call . libusb_set_pollfd_notifiers @ctx , @on_pollfd_added , @on_pollfd_removed , nil end | Register a notification block for file descriptor additions . |
15,493 | def on_pollfd_removed & block @on_pollfd_removed = proc do | fd , _ | pollfd = Pollfd . new fd block . call pollfd end Call . libusb_set_pollfd_notifiers @ctx , @on_pollfd_added , @on_pollfd_removed , nil end | Register a notification block for file descriptor removals . |
15,494 | def on_hotplug_event ( args = { } , & block ) events = args . delete ( :events ) || ( HOTPLUG_EVENT_DEVICE_ARRIVED | HOTPLUG_EVENT_DEVICE_LEFT ) flags = args . delete ( :flags ) || 0 vendor_id = args . delete ( :vendor_id ) || HOTPLUG_MATCH_ANY product_id = args . delete ( :product_id ) || HOTPLUG_MATCH_ANY dev_class =... | Register a hotplug event notification . |
15,495 | def send_message ( params ) extra_params_validation = { text : { required : true , class : [ String ] } , parse_mode : { required : false , class : [ String ] } , disable_web_page_preview : { required : false , class : [ TrueClass , FalseClass ] } } send_something ( :message , params , extra_params_validation ) end | Send text messages to a user or group chat . |
15,496 | def forward_message ( params ) params_validation = { chat_id : { required : true , class : [ Fixnum ] } , from_chat_id : { required : true , class : [ String ] } , message_id : { required : true , class : [ Fixnum ] } } response = api_request ( 'forwardMessage' , params , params_validation ) Telegrammer :: DataTypes ::... | Forward message to a user or group chat . |
15,497 | def send_photo ( params ) extra_params_validation = { photo : { required : true , class : [ File , String ] } , caption : { required : false , class : [ String ] } } send_something ( :photo , params , extra_params_validation ) end | Sends a photo to a user or group chat . |
15,498 | def send_audio ( params ) extra_params_validation = { audio : { required : true , class : [ File , String ] } , duration : { required : false , class : [ Integer ] } , performer : { required : false , class : [ String ] } , title : { required : false , class : [ String ] } } send_something ( :audio , params , extra_par... | Sends audio file to a user or group chat . |
15,499 | def send_voice ( params ) extra_params_validation = { voice : { required : true , class : [ File , String ] } , duration : { required : false , class : [ Integer ] } } send_something ( :audio , params , extra_params_validation ) end | Sends audio files file to a user or group chat that the users will see as a playable voice message . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.