idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
16,800 | def send_message ( chat_id : , text : , disable_web_page_preview : false , reply_to_message_id : nil , reply_markup : nil , parse_mode : nil ) result = call ( :sendMessage , chat_id : chat_id , text : text , disable_web_page_preview : disable_web_page_preview , reply_to_message_id : reply_to_message_id , reply_markup :... | Send text message . |
16,801 | def forward_message ( chat_id : , from_chat_id : , message_id : ) result = call ( :forwardMessage , chat_id : chat_id , from_chat_id : from_chat_id , message_id : message_id ) Message . new ( result ) end | Use this method to forward messages of any kind . |
16,802 | def send_photo ( chat_id : , photo : , caption : nil , reply_to_message_id : nil , reply_markup : nil ) result = call ( :sendPhoto , chat_id : chat_id , photo : photo , caption : caption , reply_to_message_id : reply_to_message_id , reply_markup : reply_markup ) Message . new ( result ) end | Send a picture . |
16,803 | def send_document ( chat_id : , document : , reply_to_message_id : nil , reply_markup : nil ) result = call ( :sendDocument , chat_id : chat_id , document : document , reply_to_message_id : reply_to_message_id , reply_markup : reply_markup ) Message . new ( result ) end | Send general file . |
16,804 | def send_sticker ( chat_id : , sticker : , reply_to_message_id : nil , reply_markup : nil ) result = call ( :sendSticker , chat_id : chat_id , sticker : sticker , reply_to_message_id : reply_to_message_id , reply_markup : reply_markup ) Message . new ( result ) end | Use this method to send . webp stickers . |
16,805 | def send_location ( chat_id : , latitude : , longitude : , reply_to_message_id : nil , reply_markup : nil ) result = call ( :sendLocation , chat_id : chat_id , latitude : latitude , longitude : longitude , reply_to_message_id : reply_to_message_id , reply_markup : reply_markup ) Message . new ( result ) end | Send a point on the map . |
16,806 | def get_user_profile_photos ( user_id : , offset : nil , limit : nil ) result = call ( :getUserProfilePhotos , user_id : user_id , offset : offset , limit : limit ) UserProfilePhotos . new ( result ) end | Use this method to get a list of profile pictures for a user . |
16,807 | def add_lambda ( * new_lambda ) flattened_lambdas = new_lambda . flatten flattened_lambdas . each { | lambda | parameter_guard ( lambda , LambdaWrap :: Lambda , 'LambdaWrap::Lambda' ) } lambdas . concat ( flattened_lambdas ) end | Constructor for the high level API Manager class . |
16,808 | def deploy ( environment_options ) environment_parameter_guard ( environment_options ) if no_op? puts 'Nothing to deploy.' return end deployment_start_message = 'Deploying ' deployment_start_message += "#{dynamo_tables.length} Dynamo Tables, " unless dynamo_tables . empty? deployment_start_message += "#{lambdas.length}... | Deploys all services to the specified environment . |
16,809 | def delete if dynamo_tables . empty? && lambdas . empty? && api_gateways . empty? puts 'Nothing to Deleting.' return end deployment_start_message = 'Deleting ' deployment_start_message += "#{dynamo_tables.length} Dynamo Tables, " unless dynamo_tables . empty? deployment_start_message += "#{lambdas.length} Lambdas, " un... | Deletes all services from the cloud . |
16,810 | def deploy ( environment_options , client , region = 'AWS_REGION' ) super puts "Deploying Lambda: #{@lambda_name} to Environment: #{environment_options.name}" unless File . exist? ( @path_to_zip_file ) raise ArgumentError , "Deployment Package Zip File does not exist: #{@path_to_zip_file}!" end lambda_details = retriev... | Initializes a Lambda Manager . Frontloaded configuration . |
16,811 | def delete ( client , region = 'AWS_REGION' ) super puts "Deleting all versions and aliases for Lambda: #{@lambda_name}" lambda_details = retrieve_lambda_details if lambda_details . nil? puts 'No Lambda to delete.' else options = { function_name : @lambda_name } @client . delete_function ( options ) puts "Lambda #{@lam... | Deletes the Lambda Object with associated versions code configuration and aliases . |
16,812 | def teardown ( environment_options , client , region = 'AWS_REGION' ) super api_id = get_id_for_api ( @api_name ) if api_id delete_stage ( api_id , environment_options . name ) else puts "API Gateway Object #{@api_name} not found. No environment to tear down." end true end | Tearsdown environment for API Gateway . Deletes stage . |
16,813 | def delete ( client , region = 'AWS_REGION' ) super api_id = get_id_for_api ( @api_name ) if api_id options = { rest_api_id : api_id } @client . delete_rest_api ( options ) puts "Deleted API: #{@api_name} ID:#{api_id}" else puts "API Gateway Object #{@api_name} not found. Nothing to delete." end true end | Deletes all stages and API Gateway object . |
16,814 | def deploy ( environment_options , client , region = 'AWS_REGION' ) super puts "Deploying Table: #{@table_name} to Environment: #{environment_options.name}" full_table_name = @table_name + ( @append_environment_on_deploy ? "-#{environment_options.name}" : '' ) table_details = retrieve_table_details ( full_table_name ) ... | Sets up the DynamoTable for the Dynamo DB Manager . Preloading the configuration in the constructor . |
16,815 | def wait_until_table_is_available ( full_table_name , delay = 5 , max_attempts = 5 ) puts "Waiting for Table #{full_table_name} to be available." puts "Waiting with a #{delay} second delay between attempts, for a maximum of #{max_attempts} attempts." max_time = Time . at ( delay * max_attempts ) . utc . strftime ( '%H:... | Waits for the table to be available |
16,816 | def build_global_index_updates_array ( current_global_indexes ) indexes_to_update = [ ] return indexes_to_update if current_global_indexes . empty? current_global_indexes . each do | current_index | @global_secondary_indexes . each do | target_index | next unless target_index [ :index_name ] == current_index [ :index_n... | Looks through the list current of Global Secondary Indexes and builds an array if the Provisioned Throughput in the intended Indexes are higher than the current Indexes . |
16,817 | def photos = ( values ) @photos = values . map do | photo | photo . map do | photo_size_attrs | PhotoSize . new ( photo_size_attrs ) end end end | Assign Array of Array of PhotoSize |
16,818 | def contains_point? ( point ) return false unless inside_bounding_box? ( point ) c = false i = - 1 j = size - 1 while ( i += 1 ) < size if ( self [ i ] . y <= point . y && point . y < self [ j ] . y ) || ( self [ j ] . y <= point . y && point . y < self [ i ] . y ) if point . x < ( self [ j ] . x - self [ i ] . x ) * (... | Quick and dirty hash function |
16,819 | def list_unspent ( oa_address_list = [ ] ) btc_address_list = oa_address_list . map { | oa_address | oa_address_to_address ( oa_address ) } outputs = get_unspent_outputs ( btc_address_list ) result = outputs . map { | out | out . to_hash } result end | get UTXO for colored coins . |
16,820 | def get_balance ( address = nil ) outputs = get_unspent_outputs ( address . nil? ? [ ] : [ oa_address_to_address ( address ) ] ) colored_outputs = outputs . map { | o | o . output } sorted_outputs = colored_outputs . sort_by { | o | o . script . to_string } groups = sorted_outputs . group_by { | o | o . script . to_str... | Returns the balance in both bitcoin and colored coin assets for all of the addresses available in your Bitcoin Core wallet . |
16,821 | def issue_asset ( from , amount , metadata = nil , to = nil , fees = nil , mode = 'broadcast' , output_qty = 1 ) to = from if to . nil? colored_outputs = get_unspent_outputs ( [ oa_address_to_address ( from ) ] ) issue_param = OpenAssets :: Transaction :: TransferParameters . new ( colored_outputs , to , from , amount ... | Creates a transaction for issuing an asset . |
16,822 | def send_asset ( from , asset_id , amount , to , fees = nil , mode = 'broadcast' , output_qty = 1 ) colored_outputs = get_unspent_outputs ( [ oa_address_to_address ( from ) ] ) asset_transfer_spec = OpenAssets :: Transaction :: TransferParameters . new ( colored_outputs , to , from , amount , output_qty ) tx = create_t... | Creates a transaction for sending an asset from an address to another . |
16,823 | def send_assets ( from , send_asset_params , fees = nil , mode = 'broadcast' ) transfer_specs = send_asset_params . map { | param | colored_outputs = get_unspent_outputs ( [ oa_address_to_address ( param . from || from ) ] ) [ param . asset_id , OpenAssets :: Transaction :: TransferParameters . new ( colored_outputs , ... | Creates a transaction for sending multiple asset from an address to another . |
16,824 | def send_bitcoin ( from , amount , to , fees = nil , mode = 'broadcast' , output_qty = 1 ) validate_address ( [ from , to ] ) colored_outputs = get_unspent_outputs ( [ from ] ) btc_transfer_spec = OpenAssets :: Transaction :: TransferParameters . new ( colored_outputs , to , from , amount , output_qty ) tx = create_tx_... | Creates a transaction for sending bitcoins from an address to another . |
16,825 | def send_bitcoins ( from , send_params , fees = nil , mode = 'broadcast' ) colored_outputs = get_unspent_outputs ( [ from ] ) btc_transfer_specs = send_params . map { | param | OpenAssets :: Transaction :: TransferParameters . new ( colored_outputs , param . to , from , param . amount ) } tx = create_tx_builder . trans... | Creates a transaction for sending multiple bitcoins from an address to others . |
16,826 | def burn_asset ( oa_address , asset_id , fees = nil , mode = 'broadcast' ) unspents = get_unspent_outputs ( [ oa_address_to_address ( oa_address ) ] ) tx = create_tx_builder . burn_asset ( unspents , asset_id , fees . nil? ? @config [ :default_fees ] : fees ) process_transaction ( tx , mode ) end | Creates a transaction for burn asset . |
16,827 | def get_unspent_outputs ( addresses ) validate_address ( addresses ) unspent = provider . list_unspent ( addresses , @config [ :min_confirmation ] , @config [ :max_confirmation ] ) result = unspent . map { | item | output_result = get_output ( item [ 'txid' ] , item [ 'vout' ] ) output_result . account = item [ 'accoun... | Get unspent outputs . |
16,828 | def get_outputs_from_txid ( txid , use_cache = false ) tx = get_tx ( txid , use_cache ) outputs = get_color_outputs_from_tx ( tx ) outputs . map . with_index { | out , i | out . to_hash . merge ( { 'txid' => tx . hash , 'vout' => i } ) } end | Get tx outputs . |
16,829 | def parse_issuance_p2sh_pointer ( script_sig ) script = Bitcoin :: Script . new ( script_sig ) . chunks . last redeem_script = Bitcoin :: Script . new ( script ) return nil unless redeem_script . chunks [ 1 ] == Bitcoin :: Script :: OP_DROP asset_def = to_bytes ( redeem_script . chunks [ 0 ] . to_s . bth ) [ 0 .. - 1 ]... | parse issuance p2sh which contains asset definition pointer |
16,830 | def chef_runner_options super . tap do | options | options [ :halite_gemspec ] = halite_gemspec options [ :default_attributes ] . update ( default_attributes ) options [ :normal_attributes ] . update ( normal_attributes ) options [ :override_attributes ] . update ( override_attributes ) options . update ( chefspec_opti... | Merge in extra options data . |
16,831 | def install extend Rake :: DSL unless options [ :no_gem ] desc "Convert #{gemspec.name}-#{gemspec.version} to a cookbook in the pkg directory" task 'chef:build' do build_cookbook end desc "Push #{gemspec.name}-#{gemspec.version} to Supermarket" task 'chef:release' => [ 'chef:build' ] do release_cookbook ( pkg_path ) en... | Install all Rake tasks . |
16,832 | def remove_files_in_folder ( base_path ) existing_files = Dir . glob ( File . join ( base_path , '**' , '*' ) , File :: FNM_DOTMATCH ) . map { | path | File . expand_path ( path ) } . uniq . reverse existing_files . delete ( base_path ) existing_files . each do | path | if File . file? ( path ) File . unlink ( path ) e... | Remove everything in a path but not the directory itself |
16,833 | def readWithTimeout ( socket , length , timeout ) rc = IO . select ( [ socket ] , nil , nil , timeout ) if ! rc raise "Waiting for response from UDP tracker #{@host}:#{@trackerPort} timed out after #{@timeout} seconds" elsif rc [ 0 ] . size > 0 socket . recvfrom ( length ) [ 0 ] else raise "Error receiving response fro... | Throws exception if timeout occurs |
16,834 | def find_gem_name ( base ) spec = Dir [ File . join ( base , '*.gemspec' ) ] . first File . basename ( spec , '.gemspec' ) if spec end | Search a directory for a . gemspec file to determine the gem name . Returns nil if no gemspec is found . |
16,835 | def gemspec @gemspec ||= begin raise Error . new ( "Unable to automatically determine gem name from specs in #{base}. Please set the gem name via #{self.class.name}.install_tasks(gem_name: 'name')" ) unless gem_name g = Bundler . load_gemspec ( File . join ( base , gem_name + '.gemspec' ) ) g . full_gem_path = base g e... | Gem specification for the current gem . |
16,836 | def metainfoCompletedLength num = @completePieces . countSet extra = 0 if @completePieces . set? ( @completePieces . length - 1 ) num -= 1 extra = @lastPieceLength end num * BlockSize + extra end | Return the number of bytes of the metainfo that we have downloaded so far . |
16,837 | def savePiece ( pieceIndex , data ) id = @pieceManager . writeBlock pieceIndex , 0 , data @pieceManagerRequests [ id ] = PieceManagerRequestMetadata . new ( :write , pieceIndex ) id end | Save the specified piece to disk asynchronously . |
16,838 | def readPiece ( pieceIndex ) length = BlockSize length = @lastPieceLength if pieceIndex == @numPieces - 1 id = @pieceManager . readBlock pieceIndex , 0 , length @pieceManagerRequests [ id ] = PieceManagerRequestMetadata . new ( :read , pieceIndex ) id end | Read a piece from disk . This method is asynchronous ; it returns a handle that can be later used to retreive the result . |
16,839 | def checkResults results = [ ] while true result = @pieceManager . nextResult break if ! result results . push result metaData = @pieceManagerRequests . delete ( result . requestId ) if ! metaData @logger . error "Can't find metadata for PieceManager request #{result.requestId}" next end if metaData . type == :write if... | Check the results of savePiece and readPiece . This method returns a list of the PieceManager results . |
16,840 | def findRequestablePieces piecesRequired = [ ] removeOldRequests @numPieces . times do | pieceIndex | piecesRequired . push pieceIndex if ! @completePieces . set? ( pieceIndex ) && ! @requestedPieces . set? ( pieceIndex ) end piecesRequired end | Return a list of torrent pieces that can still be requested . These are pieces that are not completed and are not requested . |
16,841 | def findRequestablePeers ( classifiedPeers ) result = [ ] classifiedPeers . establishedPeers . each do | peer | result . push peer if ! @badPeers . findByAddr ( peer . trackerPeer . ip , peer . trackerPeer . port ) end result end | Return a list of peers from whom we can request pieces . These are peers for whom we have an established connection and are not marked as bad . See markPeerBad . |
16,842 | def setPieceRequested ( pieceIndex , bool ) if bool @requestedPieces . set pieceIndex @pieceRequestTime [ pieceIndex ] = Time . new else @requestedPieces . clear pieceIndex @pieceRequestTime [ pieceIndex ] = nil end end | Set whether the piece with the passed pieceIndex is requested or not . |
16,843 | def removeOldRequests now = Time . new @requestedPieces . length . times do | i | if @requestedPieces . set? i if now - @pieceRequestTime [ i ] > @requestTimeout @requestedPieces . clear i @pieceRequestTime [ i ] = nil end end end end | Remove any pending requests after a timeout . |
16,844 | def scheduleTimer ( duration , metainfo = nil , recurring = true , immed = false ) @reactor . scheduleTimer ( duration , metainfo , recurring , immed ) if @reactor end | Schedule a timer . |
16,845 | def connect ( addr , port , metainfo , timeout = nil ) @reactor . connect ( addr , port , metainfo , timeout ) if @reactor end | Create a TCP connection to the specified host and port . Associate the passed metainfo with the IO representing the connection . |
16,846 | def read ( length ) data = '' while data . length < length begin toRead = length - data . length rateLimited = false if @ioInfo . readRateLimit avail = @ioInfo . readRateLimit . avail . to_i if avail < toRead toRead = avail rateLimited = true end @ioInfo . readRateLimit . withdraw toRead end @logger . debug "IoFacade: ... | Read length bytes . |
16,847 | def connect ( addr , port , metainfo , timeout = nil ) ioInfo = startConnection ( port , addr , metainfo ) @ioInfo [ ioInfo . io ] = ioInfo if timeout && ioInfo . state == :connecting ioInfo . connectTimeout = timeout ioInfo . connectTimer = scheduleTimer ( timeout , InternalTimerInfo . new ( :connect_timeout , ioInfo ... | Create a TCP connection to the specified host . Note that this method may raise exceptions . For example Too many open files might be raised if the process is using too many file descriptors |
16,848 | def listen ( addr , port , metainfo ) listener = Socket . new ( AF_INET , SOCK_STREAM , 0 ) sockaddr = Socket . pack_sockaddr_in ( port , "0.0.0.0" ) listener . setsockopt ( Socket :: SOL_SOCKET , Socket :: SO_REUSEADDR , true ) listener . bind ( sockaddr ) @logger . debug "listening on port #{port}" if @logger listene... | Create a TCP server that listens for connections on the specified port |
16,849 | def open ( path , mode , metainfo , useErrorhandler = true ) file = File . open ( path , mode ) info = IOInfo . new ( file , metainfo , true ) info . useErrorhandler = useErrorhandler info . readFiberIoFacade . logger = @logger if @logger info . state = :connected @ioInfo [ info . io ] = info end | Open the specified file for the specified mode . |
16,850 | def start while true begin break if eventLoopBody == :halt rescue @logger . error "Unexpected exception in reactor event loop: #{$!}" if @logger @logger . error $! . backtrace . join "\n" if @logger end end @logger . info "Reactor shutting down" if @logger @ioInfo . each do | k , v | k . close end end | Run event loop |
16,851 | def findIoByMetainfo ( metainfo ) @ioInfo . each_value do | info | if info . metainfo == metainfo io = info . readFiberIoFacade io = WriteOnlyIoFacade . new ( info ) if @currentHandlerCallback == :timer return io end end nil end | Meant to be called from the handler . Find an IO by metainfo . The == operator is used to match the metainfo . |
16,852 | def handleAccept ( ioInfo ) socket , clientAddr = ioInfo . io . accept info = IOInfo . new ( socket , ioInfo . metainfo ) info . readFiberIoFacade . logger = @logger if @logger info . state = :connected @ioInfo [ info . io ] = info if @logger port , addr = Socket . unpack_sockaddr_in ( clientAddr ) @logger . debug "Acc... | Given the ioInfo for a listening socket call accept and return the new ioInfo for the client s socket |
16,853 | def withReadFiber ( ioInfo ) if ioInfo . readFiber . nil? || ! ioInfo . readFiber . alive? ioInfo . readFiber = Fiber . new do | ioInfo | yield ioInfo . readFiberIoFacade end end ioInfo . readFiber . resume ( ioInfo ) if ioInfo . state == :error @currentHandlerCallback = :error @handler . error ( ioInfo . metainfo , io... | Call the passed block in the context of the read Fiber . Basically the passed block is run as normal but if the block performs a read from an io and that read would block the block is paused and withReadFiber returns . The next time withReadFiber is called the block will be resumed at the point of the read . |
16,854 | def manageConnections ( classifiedPeers ) n = classifiedPeers . handshakingPeers . size + classifiedPeers . establishedPeers . size if n < @targetActivePeerCount result = classifiedPeers . disconnectedPeers . shuffle . first ( @targetActivePeerCount - n ) @logger . debug "There are #{n} peers connected or in handshakin... | Determine if we need to connect to more peers . Returns a list of peers to connect to . |
16,855 | def selectOptimisticPeer ( classifiedPeers ) if ! @lastOptimisticPeerChangeTime || ( Time . new - @lastOptimisticPeerChangeTime > @optimisticPeerChangeDuration ) list = [ ] classifiedPeers . establishedPeers . each do | peer | if ( Time . new - peer . firstEstablishTime ) < @newlyConnectedDuration 3 . times { list . pu... | Choose a peer that we will optimistically unchoke . |
16,856 | def extract_blocks ( lines ) init_doc_lines = lines . each_index . select { | i | lines [ i ] . include? "=begin" } end_doc_lines = lines . each_index . select { | i | lines [ i ] . include? "=end" } blocks = init_doc_lines . each_index . map do | i | { :init => init_doc_lines [ i ] , :end => end_doc_lines [ i ] } end ... | Gets init and end lines of each comment block |
16,857 | def create_snapshot ( droplet ) fail_if_shutdown ( droplet ) logger . info "Start creating snapshot for droplet id: #{droplet.id} name: #{droplet.name}." today = DateTime . now name = "#{droplet.name}_#{today.strftime('%Y_%m_%d')}" snapshot_size = api . snapshots ( droplet ) . size logger . debug 'Wait until snapshot w... | Trying to create a snapshot . |
16,858 | def dispatch_droplets droplets . each do | droplet | id = droplet . id . to_s next if exclude . include? id next unless only . empty? || only . include? ( id ) prepare_droplet id , droplet . name end end | Dispatch received droplets each by each . |
16,859 | def prepare_droplet ( id , name ) logger . debug "Droplet id: #{id} name: #{name}\n" droplet = api . droplet id return unless droplet logger . info "Preparing droplet id: #{droplet.id} name: #{droplet.name} to take snapshot." return if too_much_snapshots? ( droplet ) processed_droplet_ids << droplet . id thread_runner ... | Preparing droplet to take a snapshot . Droplet instance must be powered off first! |
16,860 | def cleanup_snapshots ( droplet , size ) return unless size > keep warning_size ( droplet . id , droplet . name , size ) logger . debug "Cleaning up snapshots for droplet id: #{droplet.id} name: #{droplet.name}." api . cleanup_snapshots ( droplet , size - keep - 1 ) rescue => e raise SnapshotCleanupError , e . message ... | Cleanup our snapshots . |
16,861 | def search ( opts = { } ) iso_country_code = opts [ :iso_country_code ] || 'US' resource = opts . delete ( :resource ) params = { :AreaCode => opts [ :area_code ] , :InPostalCode => opts [ :postal_code ] , :InRegion => opts [ :in_region ] , :Contains => opts [ :contains ] , :NearLatLong => opts [ :near_lat_long ] , :Ne... | The Search method handles the searching of both local and toll - free numbers . |
16,862 | def addTrackerClient ( infoHash , info , trackerclient ) raise "There is already a tracker registered for torrent #{QuartzTorrent.bytesToHex(infoHash)}" if @torrentData . has_key? infoHash torrentData = TorrentData . new ( infoHash , info , trackerclient ) trackerclient . alarms = torrentData . alarms @torrentData [ in... | Add a new tracker client . This effectively adds a new torrent to download . Returns the TorrentData object for the new torrent . |
16,863 | def removeTorrent ( infoHash , deleteFiles = false ) @logger . info "#{QuartzTorrent.bytesToHex(infoHash)}: Scheduling immediate timer to remove torrent. #{deleteFiles ? "Will" : "Wont"} delete downloaded files." @reactor . scheduleTimer ( 0 , [ :removetorrent , infoHash , deleteFiles ] , false , true ) end | Remove a torrent . |
16,864 | def setDownloadRateLimit ( infoHash , bytesPerSecond ) torrentData = @torrentData [ infoHash ] if ! torrentData @logger . warn "Asked to set download rate limit for a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}" return end if bytesPerSecond if ! torrentData . downRateLimit torrentData . downRateLimit = R... | Set the download rate limit . Pass nil as the bytesPerSecond to disable the limit . |
16,865 | def setUploadRateLimit ( infoHash , bytesPerSecond ) torrentData = @torrentData [ infoHash ] if ! torrentData @logger . warn "Asked to set upload rate limit for a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}" return end if bytesPerSecond if ! torrentData . upRateLimit torrentData . upRateLimit = RateLimit... | Set the upload rate limit . Pass nil as the bytesPerSecond to disable the limit . |
16,866 | def adjustBytesDownloaded ( infoHash , adjustment ) torrentData = @torrentData [ infoHash ] if ! torrentData @logger . warn "Asked to adjust uploaded bytes for a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}" return end runInReactorThread do torrentData . bytesDownloaded += adjustment torrentData . bytesDo... | Adjust the bytesDownloaded property of the specified torrent by the passed amount . Adjustment should be an integer . It is added to the current bytesDownloaded amount . |
16,867 | def updateDelegateTorrentData ( delegate ) return if stopped? semaphore = Semaphore . new @reactor . scheduleTimer ( 0 , [ :update_torrent_data , delegate , semaphore ] , false , true ) semaphore . wait result end | Update the data stored in a TorrentDataDelegate to the latest information . |
16,868 | def serverInit ( metadata , addr , port ) @logger . warn "Peer connection from #{addr}:#{port}" begin msg = PeerHandshake . unserializeExceptPeerIdFrom currentIo rescue @logger . warn "Peer failed handshake: #{$!}" close return end torrentData = torrentDataForHandshake ( msg , "#{addr}:#{port}" ) if ! torrentData @logg... | REACTOR METHODS Reactor method called when a peer has connected to us . |
16,869 | def clientInit ( peer ) torrentData = @torrentData [ peer . infoHash ] if ! torrentData @logger . warn "No tracker client found for peer #{peer}. Closing connection." close return end trackerclient = torrentData . trackerClient @logger . info "Connected to peer #{peer}. Sending handshake." msg = PeerHandshake . new msg... | Reactor method called when we have connected to a peer . |
16,870 | def recvData ( peer ) msg = nil @logger . debug "Got data from peer #{peer}" if peer . state == :handshaking begin @logger . debug "Reading handshake from #{peer}" msg = PeerHandshake . unserializeFrom currentIo rescue @logger . warn "Peer #{peer} failed handshake: #{$!}" setPeerDisconnected ( peer ) close return end e... | Reactor method called when there is data ready to be read from a socket |
16,871 | def timerExpired ( metadata ) if metadata . is_a? ( Array ) && metadata [ 0 ] == :manage_peers managePeers ( metadata [ 1 ] ) elsif metadata . is_a? ( Array ) && metadata [ 0 ] == :request_blocks requestBlocks ( metadata [ 1 ] ) elsif metadata . is_a? ( Array ) && metadata [ 0 ] == :check_piece_manager checkPieceManage... | Reactor method called when a scheduled timer expires . |
16,872 | def requestMetadataPieces ( infoHash ) torrentData = @torrentData [ infoHash ] if ! torrentData @logger . error "Request metadata pices: torrent data for torrent #{QuartzTorrent.bytesToHex(infoHash)} not found." return end return if torrentData . paused || torrentData . queued return if ! torrentData . metainfoPieceSta... | For a torrent where we don t have the metainfo request metainfo pieces from peers . |
16,873 | def withPeersIo ( peer , what = nil ) io = findIoByMetainfo ( peer ) if io yield io else s = "" s = "when #{what}" if what @logger . warn "Couldn't find the io for peer #{peer} #{what}" end end | Find the io associated with the peer and yield it to the passed block . If no io is found an error is logged . |
16,874 | def getPeersFromTracker ( torrentData , infoHash ) addPeer = Proc . new do | trackerPeer | peer = Peer . new ( trackerPeer ) peer . infoHash = infoHash torrentData . peers . add peer true end classifiedPeers = nil replaceDisconnectedPeer = Proc . new do | trackerPeer | classifiedPeers = ClassifiedPeers . new ( torrentD... | Update our internal peer list for this torrent from the tracker client |
16,875 | def handleRemoveTorrent ( infoHash , deleteFiles ) torrentData = @torrentData . delete infoHash if ! torrentData @logger . warn "Asked to remove a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}" return end @logger . info "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Removing torrent. #{deleteFiles ? ... | Remove a torrent that we are downloading . |
16,876 | def handlePause ( infoHash , value ) torrentData = @torrentData [ infoHash ] if ! torrentData @logger . warn "Asked to pause a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}" return end return if torrentData . paused == value torrentData . paused = value if ! value queue ( torrentData , :unshift ) end setFr... | Pause or unpause a torrent that we are downloading . |
16,877 | def queue ( torrentData , mode = :queue ) return if torrentData . queued if mode == :unshift @torrentQueue . unshift torrentData else @torrentQueue . push torrentData end setFrozen torrentData , true if ! torrentData . paused end | Queue a torrent |
16,878 | def dequeue torrents = @torrentQueue . dequeue ( @torrentData . values ) torrents . each do | torrentData | if torrentData . state == :initializing initTorrent torrentData else setFrozen torrentData , false if ! torrentData . paused end end end | Dequeue any torrents that can now run based on available space |
16,879 | def setFrozen ( torrent , value ) torrentData = torrent if ! torrent . is_a? ( TorrentData ) torrentData = @torrentData [ torrent ] if ! torrentData @logger . warn "Asked to freeze a non-existent torrent #{QuartzTorrent.bytesToHex(torrent)}" return end end if value torrentData . peers . all . each do | peer | if peer .... | Freeze or unfreeze a torrent . If value is true then we disconnect from all peers for this torrent and forget the peers . If value is false we start reconnecting to peers . Parameter torrent can be an infoHash or TorrentData |
16,880 | def addTorrentByMetainfo ( metainfo ) raise "addTorrentByMetainfo should be called with a Metainfo object, not #{metainfo.class}" if ! metainfo . is_a? ( Metainfo ) trackerclient = TrackerClient . createFromMetainfo ( metainfo , false ) addTorrent ( trackerclient , metainfo . infoHash , metainfo . info ) end | Add a new torrent to manage described by a Metainfo object . This is generally the method to call if you have a . torrent file . Returns the infoHash of the newly added torrent . |
16,881 | def addTorrentWithoutMetainfo ( announceUrl , infoHash , magnet = nil ) raise "addTorrentWithoutMetainfo should be called with a Magnet object, not a #{magnet.class}" if magnet && ! magnet . is_a? ( MagnetURI ) trackerclient = TrackerClient . create ( announceUrl , infoHash , 0 , false ) addTorrent ( trackerclient , in... | Add a new torrent to manage given an announceUrl and an infoHash . The announceUrl may be a list . Returns the infoHash of the newly added torrent . |
16,882 | def addTorrentByMagnetURI ( magnet ) raise "addTorrentByMagnetURI should be called with a MagnetURI object, not a #{magnet.class}" if ! magnet . is_a? ( MagnetURI ) trackerUrl = magnet . trackers raise "addTorrentByMagnetURI can't handle magnet links that don't have a tracker URL." if ! trackerUrl addTorrentWithoutMeta... | Add a new torrent to manage given a MagnetURI object . This is generally the method to call if you have a magnet link . Returns the infoHash of the newly added torrent . |
16,883 | def adjustBytesDownloaded ( infoHash , adjustment ) return if ! adjustment raise "Bytes downloaded adjustment must be an Integer, not a #{adjustment.class}" if ! adjustment . is_a? ( Integer ) @handler . adjustBytesDownloaded ( infoHash , adjustment ) end | Adjust the bytesDownloaded property of the specified torrent by the passed amount . Adjustment should be an integer . It is added to the current bytesUploaded amount . |
16,884 | def addTorrent ( trackerclient , infoHash , info , magnet = nil ) trackerclient . port = @port torrentData = @handler . addTrackerClient ( infoHash , info , trackerclient ) torrentData . magnet = magnet trackerclient . dynamicRequestParamsBuilder = Proc . new do torrentData = @handler . torrentData [ infoHash ] dataLen... | Helper method for adding a torrent . |
16,885 | def target_dir ( f = nil ) if File . exists? ( config_file_path ) form_file_name ( target_dir_from_config , f ) else form_file_name ( File . join ( :: Rails . root . to_s , 'public/docs' ) , f ) end end | return the directory where rapidoc generates the doc |
16,886 | def examples_dir ( f = nil ) if File . exists? ( config_file_path ) form_file_name ( examples_dir_from_config_file , f ) else form_file_name ( config_dir ( '/examples' ) , f ) end end | returns the directory where rapidoc searches for examples |
16,887 | def say ( * args ) options = { :voice => 'man' , :language => 'en' , :loop => 1 } args . each do | arg | case arg when String options [ :text_to_speak ] = arg when Hash options . merge! ( arg ) else raise ArgumentError , 'say expects String or Hash argument' end end output { if options [ :pause ] loop_with_pause ( opti... | The Say verb converts text to speech that is read back to the caller . Say is useful for dynamic text that is difficult to prerecord . |
16,888 | def gather ( * args , & block ) options = args . shift || { } output { if block_given? @xml . Gather ( options ) { block . call } else @xml . Gather ( options ) end } end | The Gather verb collects digits entered by a caller into their telephone keypad . When the caller is done entering data Twilio submits that data to a provided URL as either a HTTP GET or POST request just like a web browser submits data from an HTML form . |
16,889 | def dial ( * args , & block ) number_to_dial = '' options = { } args . each do | arg | case arg when String number_to_dial = arg when Hash options . merge! ( arg ) else raise ArgumentError , 'dial expects String or Hash argument' end end output { if block_given? @xml . Dial ( options ) { block . call } else @xml . Dial... | The Dial verb connects the current caller to an another phone . If the called party picks up the two parties are connected and can communicate until one hangs up . If the called party does not pick up if a busy signal is received or the number doesn t exist the dial verb will finish . |
16,890 | def generate_info ( routes_info ) if routes_info extractor = get_controller_extractor @description = extractor . get_resource_info [ 'description' ] if extractor @actions_doc = get_actions_doc ( routes_info , extractor ) @description = [ @description ] unless @description . class == Array end end | Create description and actions_doc |
16,891 | def findBlock ( pieceIndex , offset , length ) leftOffset = @pieceSize * pieceIndex + offset rightOffset = leftOffset + length - 1 findPart ( leftOffset , rightOffset ) end | Return a list of FileRegion objects . The FileRegion offsets specify in order which regions of files the piece covers . |
16,892 | def writeBlock ( pieceIndex , offset , block ) regions = @pieceMapper . findBlock ( pieceIndex , offset , block . length ) indexInBlock = 0 regions . each do | region | io = @ioManager . get ( region . path ) if ! io raise "This process doesn't have write permission for the file #{region.path}" if File . exists? ( regi... | Write a block to an in - progress piece . The block is written to piece peiceIndex at offset offset . The block data is in block . Throws exceptions on failure . |
16,893 | def readRegions ( regions ) piece = "" regions . each do | region | io = @ioManager . get ( region . path ) if ! io if ! File . exists? ( region . path ) piece = nil break end raise "This process doesn't have read permission for the file #{region.path}" if ! File . readable? ( region . path ) begin io = @ioManager . op... | Pass an ordered list of FileRegions to load . |
16,894 | def readBlock ( pieceIndex , offset , length ) id = returnAndIncrRequestId return id if @state == :after_stop @requests . push [ id , :read_block , pieceIndex , offset , length ] @requestsSemaphore . signal id end | Read a block from the torrent asynchronously . When the operation is complete the result is stored in the results list . This method returns an id that can be used to match the response to the request . The readBlock and writeBlock methods are not threadsafe with respect to callers ; they shouldn t be called by multipl... |
16,895 | def writeBlock ( pieceIndex , offset , block ) id = returnAndIncrRequestId return id if @state == :after_stop @requests . push [ id , :write_block , pieceIndex , offset , block ] @requestsSemaphore . signal id end | Write a block to the torrent asynchronously . |
16,896 | def readPiece ( pieceIndex ) id = returnAndIncrRequestId return id if @state == :after_stop @requests . push [ id , :read_piece , pieceIndex ] @requestsSemaphore . signal id end | Read a block of the torrent asynchronously . |
16,897 | def checkPieceHash ( pieceIndex ) id = returnAndIncrRequestId return id if @state == :after_stop @requests . push [ id , :hash_piece , pieceIndex ] @requestsSemaphore . signal id end | Validate that the hash of the downloaded piece matches the hash from the metainfo . The result is successful? if the hash matches false otherwise . The data of the result is set to the piece index . |
16,898 | def license_header IO . readlines ( spec_file ) . take_while { | line | line . strip . empty? || line . strip . start_with? ( '#' ) } . join ( '' ) end | License header extacted from the gemspec . Suitable for inclusion in other Ruby source files . |
16,899 | def issues_url if spec . metadata [ 'issues_url' ] spec . metadata [ 'issues_url' ] elsif spec . homepage =~ / \/ \/ \. \. / spec . homepage . chomp ( '/' ) + '/issues' end end | URL to the issue tracker for this project . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.