idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
15,500
def send_document ( params ) extra_params_validation = { document : { required : true , class : [ File , String ] } } send_something ( :document , params , extra_params_validation ) end
Sends a document to a user or group chat .
15,501
def send_sticker ( params ) extra_params_validation = { sticker : { required : true , class : [ File , String ] } } send_something ( :sticker , params , extra_params_validation ) end
Send WebP images as stickers .
15,502
def send_video ( params ) extra_params_validation = { video : { required : true , class : [ File , String ] } , duration : { required : false , class : [ Integer ] } , caption : { required : false , class : [ String ] } } send_something ( :video , params , extra_params_validation ) end
Sends a video file to a user or group chat .
15,503
def send_location ( params ) extra_params_validation = { latitude : { required : true , class : [ Float ] } , longitude : { required : true , class : [ Float ] } } send_something ( :location , params , extra_params_validation ) end
Sends point on the map to a user or group chat .
15,504
def send_chat_action ( params ) params_validation = { chat_id : { required : true , class : [ Fixnum , String ] } , action : { required : true , class : [ String ] } } api_request ( 'sendChatAction' , params , params_validation ) end
Sends a status action to a user or group chat .
15,505
def get_user_profile_photos ( params ) params_validation = { user_id : { required : true , class : [ Fixnum ] } , offset : { required : false , class : [ Fixnum ] } , limit : { required : false , class : [ Fixnum ] } } response = api_request ( 'getUserProfilePhotos' , params , params_validation ) Telegrammer :: DataTyp...
Get a list of profile pictures for a user .
15,506
def get_file ( params ) params_validation = { file_id : { required : true , class : [ String ] } } response = api_request ( "getFile" , params , params_validation ) file_object = Telegrammer :: DataTypes :: File . new ( response . result ) "#{API_ENDPOINT}/file/bot#{@api_token}/#{file_object.file_path}" end
Get basic info about a file and prepare it for downloading .
15,507
def answer_inline_query ( params ) params_validation = { inline_query_id : { required : true , class : [ String ] } , results : { required : true , class : [ Array ] } , cache_time : { required : false , class : [ Fixnum ] } , is_personal : { required : false , class : [ TrueClass , FalseClass ] } , next_offset : { req...
Answer an inline query . On success True is returned . No more than 50 results per query are allowed .
15,508
def distance_matrix ( origins , destinations , mode : nil , language : nil , avoid : nil , units : nil , departure_time : nil , arrival_time : nil , transit_mode : nil , transit_routing_preference : nil ) params = { origins : GoogleMapsService :: Convert . waypoints ( origins ) , destinations : GoogleMapsService :: Con...
Gets travel distance and time for a matrix of origins and destinations .
15,509
def components ( arg ) if arg . kind_of? ( Hash ) arg = arg . sort . map { | k , v | "#{k}:#{v}" } return arg . join ( "|" ) end raise ArgumentError , "Expected a Hash for components, but got #{arg.class}" end
Converts a dict of components to the format expected by the Google Maps server .
15,510
def waypoint ( waypoint ) if waypoint . kind_of? ( String ) return waypoint end return GoogleMapsService :: Convert . latlng ( waypoint ) end
Converts a waypoints to the format expected by the Google Maps server .
15,511
def reverse_geocode ( latlng , location_type : nil , result_type : nil , language : nil ) params = { latlng : GoogleMapsService :: Convert . latlng ( latlng ) } params [ :result_type ] = GoogleMapsService :: Convert . join_list ( '|' , result_type ) if result_type params [ :location_type ] = GoogleMapsService :: Conver...
Reverse geocoding is the process of converting geographic coordinates into a human - readable address .
15,512
def timezone ( location , timestamp : Time . now , language : nil ) location = GoogleMapsService :: Convert . latlng ( location ) timestamp = GoogleMapsService :: Convert . time ( timestamp ) params = { location : location , timestamp : timestamp } params [ :language ] = language if language return get ( '/maps/api/tim...
Get time zone for a location on the earth as well as that location s time offset from UTC .
15,513
def sign_hmac ( secret , payload ) secret = secret . encode ( 'ASCII' ) payload = payload . encode ( 'ASCII' ) raw_key = Base64 . urlsafe_decode64 ( secret ) digest = OpenSSL :: Digest . new ( 'sha1' ) raw_signature = OpenSSL :: HMAC . digest ( digest , raw_key , payload ) signature = Base64 . urlsafe_encode64 ( raw_si...
Returns a base64 - encoded HMAC - SHA1 signature of a given string .
15,514
def unquote_unreserved ( uri ) parts = uri . split ( '%' ) ( 1 .. parts . length - 1 ) . each do | i | h = parts [ i ] [ 0 .. 1 ] if h =~ / \h / and c = $1 . to_i ( 16 ) . chr and UNRESERVED_SET . include? ( c ) parts [ i ] = c + $2 else parts [ i ] = '%' + parts [ i ] end end parts . join end
Un - escape any percent - escape sequences in a URI that are unreserved characters . This leaves all reserved illegal and non - ASCII bytes encoded .
15,515
def new_client client = Hurley :: Client . new client . request_options . query_class = Hurley :: Query :: Flat client . request_options . redirection_limit = 0 client . header [ :user_agent ] = user_agent client . connection = @connection if @connection @request_options . each_pair { | key , value | client . request_o...
Create a new HTTP client .
15,516
def get ( path , params , base_url : DEFAULT_BASE_URL , accepts_client_id : true , custom_response_decoder : nil ) url = base_url + generate_auth_url ( path , params , accepts_client_id ) Retriable . retriable timeout : @retry_timeout , on : RETRIABLE_ERRORS do | try | begin request_query_ticket response = client . get...
Make API call .
15,517
def generate_auth_url ( path , params , accepts_client_id ) if params . kind_of? ( Hash ) params = params . sort else params = params . dup end if accepts_client_id and @client_id and @client_secret params << [ "client" , @client_id ] path = [ path , GoogleMapsService :: Url . urlencode_params ( params ) ] . join ( "?"...
Returns the path and query string portion of the request URL first adding any necessary parameters .
15,518
def decode_response_body ( response ) check_response_status_code ( response ) body = MultiJson . load ( response . body , :symbolize_keys => true ) check_body_error ( response , body ) body end
Extract and parse body response as hash . Throw an error if there is something wrong with the response .
15,519
def check_response_status_code ( response ) case response . status_code when 200 .. 300 when 301 , 302 , 303 , 307 raise GoogleMapsService :: Error :: RedirectError . new ( response ) , sprintf ( 'Redirect to %s' , response . header [ :location ] ) when 401 raise GoogleMapsService :: Error :: ClientError . new ( respon...
Check HTTP response status code . Raise error if the status is not 2xx .
15,520
def directions ( origin , destination , mode : nil , waypoints : nil , alternatives : false , avoid : nil , language : nil , units : nil , region : nil , departure_time : nil , arrival_time : nil , optimize_waypoints : false , transit_mode : nil , transit_routing_preference : nil ) params = { origin : GoogleMapsService...
Get directions between an origin point and a destination point .
15,521
def elevation_along_path ( path , samples ) if path . kind_of? ( String ) path = "enc:%s" % path else path = GoogleMapsService :: Convert . waypoints ( path ) end params = { path : path , samples : samples } return get ( '/maps/api/elevation/json' , params ) [ :results ] end
Provides elevation data sampled along a path on the surface of the earth .
15,522
def snap_to_roads ( path , interpolate : false ) path = GoogleMapsService :: Convert . waypoints ( path ) params = { path : path } params [ :interpolate ] = 'true' if interpolate return get ( '/v1/snapToRoads' , params , base_url : ROADS_BASE_URL , accepts_client_id : false , custom_response_decoder : method ( :extract...
Snaps a path to the most likely roads travelled .
15,523
def nearest_roads ( points ) points = GoogleMapsService :: Convert . waypoints ( points ) params = { points : points } return get ( '/v1/nearestRoads' , params , base_url : ROADS_BASE_URL , accepts_client_id : false , custom_response_decoder : method ( :extract_roads_body ) ) [ :snappedPoints ] end
Returns the nearest road segments for provided points . The points passed do not need to be part of a continuous path .
15,524
def extract_roads_body ( response ) begin body = MultiJson . load ( response . body , :symbolize_keys => true ) rescue unless response . status_code == 200 check_response_status_code ( response ) end raise GoogleMapsService :: Error :: ApiError . new ( response ) , 'Received a malformed response.' end check_roads_body_...
Extracts a result from a Roads API HTTP response .
15,525
def encode ( points ) last_lat = last_lng = 0 result = "" points . each do | point | ll = GoogleMapsService :: Convert . normalize_latlng ( point ) lat = ( ll [ 0 ] * 1e5 ) . round . to_i lng = ( ll [ 1 ] * 1e5 ) . round . to_i d_lat = lat - last_lat d_lng = lng - last_lng [ d_lat , d_lng ] . each do | v | v = ( v < 0 ...
Encodes a list of points into a polyline string .
15,526
def map_query_filters ( filters ) Hash [ filters . map do | key , value | case value when Hash then if value . key? :any then format_query_filter ( '$in' , key , value [ :any ] ) elsif value . key? :all then format_query_filter ( '$all' , key , value [ :all ] ) else raise UnknownFilterQueryOperator , value . keys . joi...
Take a list of filters to be mapped so they can update the query used upon the fulltext search of the ngrams
15,527
def =~ ( other ) other = coerce ( other ) return ( other and self . name == other . name and self . version . to_s == other . version . to_s and self . platform_string == other . platform_string ) end
Lets be comparable!
15,528
def mirror ( spec , upstream_host ) raise Stickler :: Repository :: Error , "gem #{spec.full_name} already exists in remote repository" if remote_gem_file_exist? ( spec ) resource_request ( mirror_resource ( spec , upstream_host ) ) end
Tell the remote repoistory to mirror the given gem from an upstream repository
15,529
def marshalled_specs ( spec_a ) a = spec_a . collect { | s | s . to_rubygems_a } marshal ( optimize_specs ( a ) ) end
Convert to the array format used by gem servers everywhere
15,530
def parser me = self @parser ||= Trollop :: Parser . new do banner me . class . banner opt :server , "The gem or stickler server URL" , :type => :string , :default => Client . config . server opt :debug , "Output debug information for the server interaction" , :default => false end end
Create a new client
15,531
def find_value ( context ) locations . each do | location | begin value = context . instance_exec ( & location ) next if value . nil? return value rescue end end nil end
Finds attribute value in the JSON response by looking at the given locations .
15,532
def add_locations ( hash ) hash . each do | attribute_name , locations | find ( attribute_name ) . add_locations ( locations ) end end
Shorthand for adding locations to multiple attributes at once .
15,533
def record_api_methods before do stub_const ( "Flickr::Client::Data" , Class . new ( Flickr :: Client :: Data ) do def do_request ( http_method , flickr_method , params = { } ) VCR . use_cassette ( flickr_method ) { super } end end ) stub_const ( "Flickr::Client::Upload" , Class . new ( Flickr :: Client :: Upload ) do ...
Wraps a VCR cassette around API calls with the same name as the Flickr method called . For example the cassette for Flickr . sets . create will be called flickr . photosets . create . Because we repeat the same API calls in different examples we can just reuse those VCR cassettes rather than recording new ones .
15,534
def inspect attribute_values = self . class . attributes . inject ( { } ) { | hash , attribute | hash . update ( attribute . name => send ( attribute . name ) ) } . reject { | name , value | value . nil? or ( value . respond_to? ( :empty? ) and value . empty? ) } attributes = attribute_values . map { | name , value | "...
Displays all the attributes and their values .
15,535
def sanitize! if rails_file? @file = @original @content_type = @original . content_type @path = @original . tempfile elsif sinatra_file? @file = @original [ :tempfile ] @content_type = @original [ :type ] @path = @original [ :tempfile ] . path elsif io? @file = @original @content_type = @original . content_type if @ori...
Extracts the tempfile content type and path .
15,536
def link_to_modal ( * args , & block ) if block_given? options = args . first || { } html_options = args . second block_result = capture ( & block ) link_to_modal ( block_result , options , html_options ) else name = args [ 0 ] options = args [ 1 ] || { } html_options = args [ 2 ] || { } html_options [ :rel ] = "modal:...
Creates a link tag to a given url or path and ensures that the linke will be rendered as jquery modal dialog
15,537
def read_theme_data if @theme . data_path inspect_theme_data theme_data = ThemeDataReader . new ( site ) . read ( site . config [ "data_dir" ] ) @site . data = Jekyll :: Utils . deep_merge_hashes ( theme_data , @site . data ) inspect_merged_hash if site . config [ "show-data" ] && site . config [ "verbose" ] end end
Read data files within a theme gem and add them to internal data
15,538
def inspect_inner_hash ( hash ) hash . each do | key , value | if value . is_a? Array print_label key extract_hashes_and_print value elsif value . is_a? Hash print_subkey_and_value key , value else print_hash key , value end end end
Analyse deeper hashes and extract contents to output
15,539
def print_subkey_and_value ( key , value ) print_label key value . each do | subkey , val | if val . is_a? Hash print_inner_subkey subkey inspect_inner_hash val elsif val . is_a? Array print_inner_subkey subkey extract_hashes_and_print val elsif val . is_a? String print_hash subkey , val end end end
Prints label keys and values of mappings
15,540
def should_send_ping? ( now , keep_alive , last_packet_received_at ) last_pingreq_sent_at = @sender . last_pingreq_sent_at last_pingresp_received_at = @handler . last_pingresp_received_at if ! last_pingreq_sent_at || ( last_pingresp_received_at && ( last_pingreq_sent_at <= last_pingresp_received_at ) ) next_pingreq_at ...
Would return true if ping requset should be sent and nil if not
15,541
def array_wrap ( object ) if object . nil? [ ] elsif object . respond_to? ( :to_ary ) object . to_ary || [ object ] else [ object ] end end
Ported from activesupport gem
15,542
def failure_message matching_files = @fixture . files & @local . files fixture_only_files = @fixture . files - @local . files local_only_files = @local . files - @fixture . files buf = "expected fixture #{@fixture.path} to match files:\n" ( @fixture . files | @local . files ) . sort . each do | file | if matching_files...
Callback fro RSpec . Returns a human - readable failure message .
15,543
def file_content_match? @fixture . full_files . zip ( @local . full_files ) . all? do | fixture_file , local_file | if File . directory? ( fixture_file ) File . directory? ( local_file ) else ! File . directory? ( local_file ) && IO . read ( fixture_file ) == IO . read ( local_file ) end end end
Do the file contents match?
15,544
def file ( path , content = nil , & block ) raise "file path should be relative the the temporary directory." if path == File . expand_path ( path ) before do content = instance_eval ( & block ) if block dest_path = File . join ( temp_path , path ) FileUtils . mkdir_p ( File . dirname ( dest_path ) ) IO . write ( dest_...
Create a file in the temporary directory for this example .
15,545
def fixture_file ( path , dest = nil ) raise "file path should be relative the the temporary directory." if path == File . expand_path ( path ) before do | example | fixture_path = find_fixture ( example . file_path , path ) dest_path = dest ? File . join ( temp_path , dest ) : temp_path FileUtils . mkdir_p ( dest_path...
Copy fixture data from the spec folder to the temporary directory for this example .
15,546
def environment ( variables ) before do variables . each do | key , value | if value . nil? _environment . delete ( key . to_s ) else _environment [ key . to_s ] = value . to_s end end end end
Set an environment variable for this example .
15,547
def randomize ( value ) case value when Array then value [ rand ( value . size ) ] when Range then rand ( ( value . last + 1 ) - value . first ) + value . first else value end end
return a random value from an array or range
15,548
def sequential ( value ) index = index_variable_for ( value ) index = ( index ? index + 1 : 0 ) index = 0 if index == value . length set_index_variable ( value , index ) value [ index ] end
return an element from the array . The first request will return the first element the second request will return the second and so forth .
15,549
def let ( clearance_level , actions , resource , options = { } ) clearance_level = clearance_level . to_s . singularize . to_sym actions = Array ( actions ) . map ( & :to_sym ) controller = get_controller_name ( resource , options ) @rules [ controller ] ||= { } @rules [ controller ] [ clearance_level ] ||= [ ] @rules ...
Set clearance to perform actions over a resource . Clearance level and resource can be either plural or singular .
15,550
def lets? ( clearance_level , action , resource , options = { } ) clearance_level = clearance_level . to_s . singularize . to_sym action = action . to_sym controller = get_controller_name ( resource , options ) controller . constantize . new rules = @rules [ controller ] return false unless rules Array ( rules [ :all ]...
Check if a given clearance level allows to perform an action on a resource . Clearance level and resource can be either plural or singular .
15,551
def validate_access! action = self . action_name clearance_levels = Array ( current_clearance_levels ) authorized = clearance_levels . any? { | c | keeper . lets? c , action , self . class } not_authorized! unless authorized end
Validate access to the current route .
15,552
def not_authorized! ( * args ) options = args . extract_options! message = options [ :message ] || I18n . t ( 'action_access.redirection_message' , default : 'Not authorized.' ) path = options [ :path ] || unauthorized_access_redirection_path redirect_to path , alert : message end
Redirect if not authorized . May be used inside action methods for finer control .
15,553
def can? ( action , resource , options = { } ) keeper = ActionAccess :: Keeper . instance clearance_levels = Array ( clearance_levels ( ) ) clearance_levels . any? { | c | keeper . lets? c , action , resource , options } end
Check if the user is authorized to perform a given action . Resource can be either plural or singular .
15,554
def send_image ( path , refer , & callback ) if @type == 'encr_chat' logger . warn ( "Currently telegram-cli has a bug with send_typing, then prevent this for safety" ) return end fail_back ( & callback ) if not File . exist? ( path ) @client . send_photo ( targetize , path , & callback ) end
Send an image
15,555
def send_image_url ( url , opt , refer , & callback ) begin opt = { } if opt . nil? http = EM :: HttpRequest . new ( url , :connect_timeout => 2 , :inactivity_timeout => 5 ) . get opt file = Tempfile . new ( [ 'image' , 'jpg' ] ) http . stream { | chunk | file . write ( chunk ) } http . callback { file . close type = F...
Send an image with given url not implemen
15,556
def send_video ( path , refer , & callback ) fail_back ( & callback ) if not File . exist? ( path ) @client . send_video ( targetize , path , & callback ) end
Send a video
15,557
def reply ( type , content , target = nil , & callback ) target = @target if target . nil? case type when :text target . send_message ( content , self , & callback ) when :image option = nil content , option = content if content . class == Array if content . include? ( 'http' ) target . method ( :send_image_url ) . cal...
Reply a message to the chat
15,558
def update! ( & cb ) done = false EM . synchrony do multi = EM :: Synchrony :: Multi . new multi . add :profile , update_profile! multi . add :contacts , update_contacts! multi . add :chats , update_chats! multi . perform done = true end check_done = Proc . new { if done @starts_at = Time . now cb . call unless cb . ni...
Update user profile contacts and chats
15,559
def update_profile! assert! callback = Callback . new @profile = nil @connection . communicate ( 'get_self' ) do | success , data | if success callback . trigger ( :success ) contact = TelegramContact . pick_or_new ( self , data ) @contacts << contact unless self . contacts . include? ( contact ) @profile = contact els...
Update user profile
15,560
def update_contacts! assert! callback = Callback . new @contacts = [ ] @connection . communicate ( 'contact_list' ) do | success , data | if success and data . class == Array callback . trigger ( :success ) data . each { | contact | contact = TelegramContact . pick_or_new ( self , contact ) @contacts << contact unless ...
Update user contacts
15,561
def update_chats! assert! callback = Callback . new collected = 0 collect_done = Proc . new do | id , data , count | collected += 1 @chats << TelegramChat . new ( self , data ) callback . trigger ( :success ) if collected == count end collect = Proc . new do | id , count | @connection . communicate ( [ 'chat_info' , "c...
Update user chats
15,562
def send_contact ( peer , phone , first_name , last_name ) assert! @connection . communicate ( [ 'send_contact' , peer , phone , first_name , last_name ] ) end
Send contact to peer chat
15,563
def download_attachment ( type , seq , & callback ) assert! raise "Type mismatch" unless %w( photo video audio ) . include? ( type ) @connection . communicate ( [ "load_#{type.to_s}" , seq ] , & callback ) end
Download an attachment from a message
15,564
def format_message message = Message . new message . id = @id message . text = @raw_data [ 'text' ] ||= '' media = @raw_data [ 'media' ] message . type = media ? media [ 'type' ] : 'text' message . raw_from = @raw_data [ 'from' ] [ 'peer_id' ] message . from_type = @raw_data [ 'from' ] [ 'peer_type' ] message . raw_to ...
Process raw data in which event type is message given .
15,565
def communicate ( * messages , & callback ) @available = false @data = '' @callback = callback messages = messages . first if messages . size == 1 and messages . first . is_a? ( Array ) messages = messages . join ( ' ' ) << "\n" send_data ( messages ) end
Communicate telegram - rb with telegram - cli connection
15,566
def receive_data ( data ) @data << data return unless data . index ( "\n\n" ) begin result = _receive_data ( @data ) rescue raise result = nil end @callback . call ( ! result . nil? , result ) unless @callback . nil? @callback = nil @available = true end
This method will be called by EventMachine when data arrived then parse given data and execute callback method if exists
15,567
def acquire ( & callback ) acq = Proc . new { conn = self . find { | conn | conn . available? } if not conn . nil? and conn . connected? callback . call ( conn ) else logger . warn ( "Failed to acquire available connection, retry after 0.1 second" ) EM . add_timer ( 0.1 , & acq ) end } EM . add_timer ( 0 , & acq ) end
Acquire available connection
15,568
def execute cli_arguments = Telegram :: CLIArguments . new ( @config ) command = "'#{@config.daemon}' #{cli_arguments.to_s}" @stdout = IO . popen ( command , 'a+' ) initialize_stdout_reading end
Initialize Telegram Client
15,569
def poll logger . info ( "Start polling for events" ) while ( data = @stdout . gets ) begin brace = data . index ( '{' ) data = data [ brace .. - 2 ] data = Oj . load ( data , mode : :compat ) @events << data rescue end end end
Do the long - polling from stdout of the telegram - cli
15,570
def connect ( & block ) logger . info ( "Trying to start telegram-cli and then connect" ) @connect_callback = block process_data EM . defer ( method ( :execute ) , method ( :create_pool ) , method ( :execution_failed ) ) end
Start telegram - cli daemon
15,571
def flatten messages = struct . messages . map do | message | if message . compressed? s = message . decompressed_value MessageSet . read_without_size ( Protocol :: ResponseBuffer . new ( s ) ) . flatten else message end end . flatten end
Builds an array of Message objects from the MessageStruct objects . Decompressing messages if necessary .
15,572
def add ( message , partition_id ) @messages << message @topics [ message . topic ] ||= { } @topics [ message . topic ] [ partition_id ] ||= [ ] @topics [ message . topic ] [ partition_id ] << message end
Add a messages for this broker
15,573
def build_protocol_objects ( compression_config ) @topics . map do | topic , messages_by_partition | codec = compression_config . compression_codec_for_topic ( topic ) messages_for_partitions = messages_by_partition . map do | partition , messages | message_set = MessageSet . new ( messages ) if codec Protocol :: Messa...
Build protocol objects for this broker!
15,574
def messages_for_brokers messages_for_broker_ids = { } @messages . each do | message | partition_id , broker_id = @message_conductor . destination ( message . topic , message . key ) messages_for_broker_ids [ broker_id ] ||= MessagesForBroker . new ( broker_id ) messages_for_broker_ids [ broker_id ] . add ( message , p...
Groups messages by broker and preps them for transmission .
15,575
def produce ( required_acks , timeout , messages_for_topics ) ensure_connected req = ProduceRequest . new ( request_common ( :produce ) , required_acks , timeout , messages_for_topics ) send_request ( req ) if required_acks != 0 read_response ( ProduceResponse ) else true end end
Execute a produce call
15,576
def fetch ( max_wait_time , min_bytes , topic_fetches ) ensure_connected req = FetchRequest . new ( request_common ( :fetch ) , REPLICA_ID , max_wait_time , min_bytes , topic_fetches ) send_request ( req ) read_response ( FetchResponse ) end
Execute a fetch call
15,577
def topic_metadata ( topic_names ) ensure_connected req = MetadataRequest . new ( request_common ( :metadata ) , topic_names ) send_request ( req ) read_response ( MetadataResponse ) end
Fetch metadata for + topic_names +
15,578
def update ( topic_metadata_response ) update_brokers ( topic_metadata_response . brokers ) update_topics ( topic_metadata_response . topics ) @last_refreshed_at = Time . now nil end
Update what we know about the cluter based on MetadataResponse
15,579
def destination ( topic , key = nil ) topic_metadata = topic_metadatas [ topic ] if topic_metadata && topic_metadata . leader_available? partition_id = determine_partition ( topic_metadata , key ) broker_id = topic_metadata . partition_leader ( partition_id ) || NO_BROKER else partition_id = NO_PARTITION broker_id = NO...
Create a new message conductor
15,580
def fetch ( options = { } ) fetch_max_wait = options . delete ( :max_wait_ms ) || max_wait_ms fetch_max_bytes = options . delete ( :max_bytes ) || max_bytes fetch_min_bytes = options . delete ( :min_bytes ) || min_bytes if options . keys . any? raise ArgumentError , "Unknown options: #{options.keys.inspect}" end topic_...
Create a new consumer which reads the specified topic and partition from the host .
15,581
def send_messages ( messages ) raise Errors :: ProducerShutdownError if @shutdown if ! messages . respond_to? ( :each ) raise ArgumentError , "messages must respond to #each" end @producer . send_messages ( convert_to_messages_objects ( messages ) ) end
Returns a new Producer .
15,582
def size size = size_from_java size ||= size_from_win_api size ||= size_from_ioctl size ||= size_from_io_console size ||= size_from_readline size ||= size_from_tput size ||= size_from_stty size ||= size_from_env size ||= size_from_ansicon size || DEFAULT_SIZE end
Get terminal rows and columns
15,583
def size_from_win_api ( verbose : nil ) require 'fiddle' kernel32 = Fiddle :: Handle . new ( 'kernel32' ) get_std_handle = Fiddle :: Function . new ( kernel32 [ 'GetStdHandle' ] , [ - Fiddle :: TYPE_INT ] , Fiddle :: TYPE_INT ) get_console_buffer_info = Fiddle :: Function . new ( kernel32 [ 'GetConsoleScreenBufferInfo'...
Determine terminal size with a Windows native API
15,584
def size_from_java ( verbose : nil ) return unless jruby? require 'java' java_import 'jline.TerminalFactory' terminal = TerminalFactory . get size = [ terminal . get_height , terminal . get_width ] return size if nonzero_column? ( size [ 1 ] ) rescue warn 'failed to import java terminal package' if verbose end
Determine terminal size on jruby using native Java libs
15,585
def size_from_ioctl return if jruby? return unless @output . respond_to? ( :ioctl ) format = 'SSSS' buffer = ( [ 0 ] * format . size ) . pack ( format ) if ioctl? ( TIOCGWINSZ , buffer ) || ioctl? ( TIOCGWINSZ_PPC , buffer ) rows , cols , = buffer . unpack ( format ) [ 0 .. 1 ] return [ rows , cols ] if nonzero_column?...
Read terminal size from Unix ioctl
15,586
def size_from_readline if defined? ( Readline ) && Readline . respond_to? ( :get_screen_size ) size = Readline . get_screen_size size if nonzero_column? ( size [ 1 ] ) end rescue NotImplementedError end
Detect screen size using Readline
15,587
def size_from_tput return unless @output . tty? lines = run_command ( 'tput' , 'lines' ) . to_i cols = run_command ( 'tput' , 'cols' ) . to_i [ lines , cols ] if nonzero_column? ( lines ) rescue IOError , SystemCallError end
Detect terminal size from tput utility
15,588
def size_from_stty return unless @output . tty? out = run_command ( 'stty' , 'size' ) return unless out size = out . split . map ( & :to_i ) size if nonzero_column? ( size [ 1 ] ) rescue IOError , SystemCallError end
Detect terminal size from stty utility
15,589
def run_command ( * args ) require 'tempfile' out = Tempfile . new ( 'tty-screen' ) result = system ( * args , out : out . path , err : File :: NULL ) return if result . nil? out . rewind out . read ensure out . close if out end
Runs command silently capturing the output
15,590
def validate_options ( options , raise_error_if_unrecognized = true ) keys = [ ] for key , value in options unless value . nil? keys << key end end missing = requirements - keys unless missing . empty? raise ArgumentError , "Missing required arguments: #{missing.map(&:to_s).sort.join(', ')}" end if ! recognizes . empty...
Ensures that required arguments are present and that optional arguments are recognized .
15,591
def consume_at_rule ( input = @tokens ) rule = { } rule [ :tokens ] = input . collect do rule [ :name ] = input . consume [ :value ] rule [ :prelude ] = [ ] while token = input . consume node = token [ :node ] if node == :comment next elsif node == :semicolon break elsif node === :' ' rule [ :block ] = consume_simple_b...
Initializes a parser based on the given _input_ which may be a CSS string or an array of tokens .
15,592
def consume_component_value ( input = @tokens ) return nil unless token = input . consume case token [ :node ] when :' ' , :' ' , :' ' consume_simple_block ( input ) when :function if token . key? ( :name ) token else consume_function ( input ) end else token end end
Consumes a component value and returns it or nil if there are no more tokens .
15,593
def consume_declaration ( input = @tokens ) declaration = { } value = [ ] declaration [ :tokens ] = input . collect do declaration [ :name ] = input . consume [ :value ] next_token = input . peek while next_token && next_token [ :node ] == :whitespace input . consume next_token = input . peek end unless next_token && n...
Consumes a declaration and returns it or nil on parse error .
15,594
def consume_declarations ( input = @tokens , options = { } ) declarations = [ ] while token = input . consume case token [ :node ] when :comment , :semicolon , :whitespace declarations << token unless options [ :strict ] when :at_keyword input . reconsume declarations << consume_at_rule ( input ) when :ident decl_token...
Consumes a list of declarations and returns them .
15,595
def consume_function ( input = @tokens ) function = { :name => input . current [ :value ] , :value => [ ] , :tokens => [ input . current ] } function [ :tokens ] . concat ( input . collect { while token = input . consume case token [ :node ] when :' ' break when :comment next else input . reconsume function [ :value ] ...
Consumes a function and returns it .
15,596
def consume_qualified_rule ( input = @tokens ) rule = { :prelude => [ ] } rule [ :tokens ] = input . collect do while true unless token = input . consume return create_node ( :error , :value => 'invalid' ) end if token [ :node ] == :' ' rule [ :block ] = consume_simple_block ( input ) [ :value ] break elsif token [ :no...
Consumes a qualified rule and returns it or nil if a parse error occurs .
15,597
def consume_rules ( flags = { } ) rules = [ ] while token = @tokens . consume case token [ :node ] when :comment , :whitespace rules << token when :cdc , :cdo unless flags [ :top_level ] @tokens . reconsume rule = consume_qualified_rule rules << rule if rule end when :at_keyword @tokens . reconsume rule = consume_at_ru...
Consumes a list of rules and returns them .
15,598
def consume_simple_block ( input = @tokens ) start_token = input . current [ :node ] end_token = BLOCK_END_TOKENS [ start_token ] block = { :start => start_token . to_s , :end => end_token . to_s , :value => [ ] , :tokens => [ input . current ] } block [ :tokens ] . concat ( input . collect do while token = input . con...
Consumes and returns a simple block associated with the current input token .
15,599
def parse_component_value ( input = @tokens ) input = TokenScanner . new ( input ) unless input . is_a? ( TokenScanner ) while input . peek && input . peek [ :node ] == :whitespace input . consume end if input . peek . nil? return create_node ( :error , :value => 'empty' ) end value = consume_component_value ( input ) ...
Parses a single component value and returns it .