idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
16,900 | def platforms raw_platforms = spec . metadata . fetch ( 'platforms' , '' ) . strip case raw_platforms when '' [ ] when 'any' , 'all' , '*' %w{ aix amazon arch centos chefspec debian dragonfly4 fedora freebsd gentoo ios_xr mac_os_x nexus omnios openbsd opensuse oracle raspbian redhat slackware smartos solaris2 suse ubun... | Platform support to be used in the Chef metadata . |
16,901 | def find_misc_path ( name ) [ name , name . upcase , name . downcase ] . each do | base | [ '.md' , '' , '.txt' , '.html' ] . each do | suffix | path = File . join ( spec . full_gem_path , base + suffix ) return path if File . exist? ( path ) && Dir . entries ( File . dirname ( path ) ) . include? ( File . basename ( p... | Search for a file like README . md or LICENSE . txt in the gem . |
16,902 | def dependency_to_spec ( dep ) spec = dep . to_spec || dep . to_specs . last raise Error . new ( "Cannot find a gem to satisfy #{dep}" ) unless spec spec rescue :: Gem :: LoadError => ex raise Error . new ( "Cannot find a gem to satisfy #{dep}: #{ex}" ) end | Find a spec given a dependency . |
16,903 | def resize ( rra_num , options ) info = self . info step = info [ "step" ] rra_step = info [ "rra[#{rra_num}].pdp_per_row" ] action = options . keys . first . to_s . upcase delta = ( options . values . first / ( step * rra_step ) ) . to_i Wrapper . resize ( rrd_file , rra_num . to_s , action , delta . to_s ) end | Writes a new file resize . rrd |
16,904 | def install cache_path . rmtree if cache_path . exist? cache_path . mkpath Halite . convert ( gem_name , cache_path ) validate_cached! ( cache_path ) end | Convert the gem . |
16,905 | def add ( peer ) raise "Peer must have it's infoHash set." if ! peer . infoHash if @peersByAddr . has_key? ( byAddrKey ( peer ) ) @log . debug "Not adding peer #{peer} since it already exists by #{@peersById.has_key?(peer.trackerPeer.id) ? "id" : "addr"}." return end if peer . trackerPeer . id @peersById . pushToList (... | Add a peer to the PeerHolder . |
16,906 | def idSet ( peer ) @peersById . each do | e | return if e . eql? ( peer ) end @peersById . pushToList ( peer . trackerPeer . id , peer ) end | Set the id for a peer . This peer which previously had no id has finished handshaking and now has an ID . |
16,907 | def delete ( peer ) @peersByAddr . delete byAddrKey ( peer ) list = @peersByInfoHash [ peer . infoHash ] if list list . collect! do | p | if ! p . eql? ( peer ) peer else nil end end list . compact! end if peer . trackerPeer . id list = @peersById [ peer . trackerPeer . id ] if list list . collect! do | p | if ! p . eq... | Delete the specified peer from the PeerHolder . |
16,908 | def to_s ( infoHash = nil ) def makeFlags ( peer ) s = "[" s << "c" if peer . amChoked s << "i" if peer . peerInterested s << "C" if peer . peerChoked s << "I" if peer . amInterested s << "]" s end if infoHash s = "Peers: \n" peers = @peersByInfoHash [ infoHash ] if peers peers . each do | peer | s << " #{peer.to_s} #... | Output a string representation of the PeerHolder for debugging purposes . |
16,909 | def btInfoHash result = nil @params [ 'xt' ] . each do | topic | if topic =~ / / hash = $1 if hash . length == 40 result = [ hash ] . pack "H*" else result = Base32 . decode hash end break end end result end | Return the first Bittorrent info hash found in the magnet URI . The returned info hash is in binary format . |
16,910 | def get_routes_doc puts "Executing 'rake routes'..." if trace? routes_doc = RoutesDoc . new routes = Dir . chdir ( :: Rails . root . to_s ) { ` ` } routes . split ( "\n" ) . each do | entry | routes_doc . add_route ( entry ) unless entry . match ( / / ) end routes_doc end | Reads rake routes output and gets the routes info |
16,911 | def get_resources routes_doc = get_routes_doc resources_names = routes_doc . get_resources_names - resources_black_list resources_names . map do | resource | puts "Generating #{resource} documentation..." if trace? ResourceDoc . new ( resource , routes_doc . get_actions_route_info ( resource ) ) end end | Create new ResourceDoc for each resource extracted from RoutesDoc |
16,912 | def evaluate_file ( instance , filepath ) absolute_path = File . expand_path ( filepath ) file_contents = IO . read ( absolute_path ) evaluate ( instance , file_contents , absolute_path , 1 ) end | Evaluate the file in the context of the cleanroom . |
16,913 | def evaluate ( instance , * args , & block ) cleanroom . new ( instance ) . instance_eval ( * args , & block ) end | Evaluate the string or block in the context of the cleanroom . |
16,914 | def cleanroom exposed = exposed_methods . keys parent = self . name || 'Anonymous' Class . new ( Object ) do class << self def class_eval raise Cleanroom :: InaccessibleError . new ( :class_eval , self ) end def instance_eval raise Cleanroom :: InaccessibleError . new ( :instance_eval , self ) end end define_method ( :... | The cleanroom instance for this class . This method is intentionally NOT cached! |
16,915 | def add_resource_route ( method , url , controller_action ) resource = controller_action . split ( '#' ) . first info = { resource : resource , action : controller_action . split ( '#' ) . last , method : method , url : url , controller : controller_action . split ( '#' ) . first } @resources_routes [ resource . to_sym... | Add new route info to resource routes array with correct format |
16,916 | def get_resource_name ( url ) new_url = url . gsub ( '(.:format)' , '' ) return $1 if new_url =~ / \/ \w \/ / return $1 if new_url =~ / \/ \w \/ \/ / return $1 if new_url =~ / \/ \w / return $1 if new_url =~ / \/ \w \/ \w / return $1 if new_url =~ / \/ \w \/ \w \/ \w / return $1 if new_url =~ / \/ \w \/ \w / return $1 ... | Extract resource name from url |
16,917 | def classForMessage ( id , payload ) if @@classForMessage . nil? @@classForMessage = [ Choke , Unchoke , Interested , Uninterested , Have , BitfieldMessage , Request , Piece , Cancel ] @@classForMessage [ 20 ] = Extended end if @@classForExtendedMessage . nil? @@classForExtendedMessage = [ ] @@classForExtendedMessage [... | Determine the class associated with the message type passed . |
16,918 | def getRequest m = Request . new m . pieceIndex = @pieceIndex m . blockOffset = @offset m . blockLength = @length m end | Return a new Bittorrent Request message that requests this block . |
16,919 | def findRequestableBlocks ( classifiedPeers , numToReturn = nil ) result = [ ] peersHavingPiece = computePeersHavingPiece ( classifiedPeers ) requestable = @completeBlocks . union ( @requestedBlocks ) . compliment! rarityOrder = nil currentPiece = 0 while true if currentPiece >= @currentPieces . length rarityOrder = co... | Return a list of BlockInfo objects representing blocjs that should be requested from peers . |
16,920 | def setBlockRequested ( blockInfo , bool ) if bool @requestedBlocks . set blockInfo . blockIndex else @requestedBlocks . clear blockInfo . blockIndex end end | Set whether the block represented by the passed BlockInfo is requested or not . |
16,921 | def setPieceCompleted ( pieceIndex , bool ) eachBlockInPiece ( pieceIndex ) do | blockIndex | if bool @completeBlocks . set blockIndex else @completeBlocks . clear blockIndex end end if bool @completePieces . set pieceIndex else @completePieces . clear pieceIndex end end | Set whether the piece is completed or not . |
16,922 | def completedLength num = @completeBlocks . countSet extra = 0 if @completeBlocks . set? ( @completeBlocks . length - 1 ) num -= 1 extra = @lastBlockLength end num * @blockSize + extra end | Number of bytes we have downloaded and verified . |
16,923 | def createBlockinfoByPieceAndBlockIndex ( pieceIndex , peersWithPiece , blockIndex ) blockSize = @blockSize blockSize = @lastBlockLength if blockIndex == @numBlocks - 1 offsetWithinPiece = ( blockIndex % @blocksPerPiece ) * @blockSize BlockInfo . new ( pieceIndex , offsetWithinPiece , blockSize , peersWithPiece , block... | Create a new BlockInfo object using the specified information . |
16,924 | def computePeersHavingPiece ( classifiedPeers ) peersHavingPiece = Array . new ( @numPieces ) classifiedPeers . requestablePeers . each do | peer | @numPieces . times do | i | if peer . bitfield . set? ( i ) if peersHavingPiece [ i ] peersHavingPiece [ i ] . push peer else peersHavingPiece [ i ] = [ peer ] end end end ... | Return an array indexed by piece index where each element is a list of peers with that piece . |
16,925 | def findValue ( value ) if ! @sorted @map . sort { | a , b | a [ 0 ] <=> b [ 0 ] } @sorted = true end @map . binsearch { | x | x [ 0 ] >= value } [ 1 ] end | Given an integer value find which region it falls in and return the object associated with that region . |
16,926 | def extract_resource_info ( lines , blocks , file_name ) blocks ? info = [ ] : blocks = [ ] blocks . each . map do | b | if lines [ b [ :init ] ] . include? "=begin resource" n_lines = b [ :end ] - b [ :init ] - 1 begin info . push YAML . load ( lines [ b [ :init ] + 1 , n_lines ] . join . gsub ( / \ / , '' ) ) rescue... | Check if exist a block with resource information rapidoc resource block |
16,927 | def extract_actions_info ( lines , blocks , file_name ) info = [ ] blocks = [ ] unless blocks blocks . each do | b | if lines [ b [ :init ] ] . include? "=begin action" n_lines = b [ :end ] - b [ :init ] - 1 begin info << YAML . load ( lines [ b [ :init ] + 1 , n_lines ] . join . gsub ( / \ / , '' ) ) rescue Exception... | Check all blocks and load those that are rapidoc actions block |
16,928 | def create ( opts ) raise "You must set either :PhoneNumber or :AreaCode" if ! opts . include? ( :AreaCode ) && ! opts . include? ( :PhoneNumber ) Twilio . post ( "/IncomingPhoneNumbers" , :body => opts ) end | Creates a phone number in Twilio . You must first find an existing number using the AvailablePhoneNumber class before creating one here . |
16,929 | def getCounts result = { } @classes . each do | c | count = 0 ObjectSpace . each_object ( c ) { count += 1 } result [ c ] = count end result end | Return a hashtable keyed by class where the value is the number of that class of object still reachable . |
16,930 | def all_keys I18n . backend . send ( :translations ) . collect do | _check_locale , translations | collect_keys ( [ ] , translations ) . sort end . flatten . uniq end | Returns an array with all keys from all locales |
16,931 | def key_exists? ( key , locale ) I18n . locale = locale I18n . translate ( key , raise : true ) return true rescue I18n :: MissingInterpolationArgument return true rescue I18n :: MissingTranslationData return false end | Returns true if key exists in the given locale |
16,932 | def serializeTo ( io ) raise "PeerId is not set" if ! @peerId raise "InfoHash is not set" if ! @infoHash result = [ ProtocolName . length ] . pack ( "C" ) result << ProtocolName result << [ 0 , 0 , 0 , 0 , 0 , 0x10 , 0 , 0 ] . pack ( "C8" ) result << @infoHash result << @peerId io . write result end | Serialize this PeerHandshake message to the passed io object . Throws exceptions on failure . |
16,933 | def start @stopped = false return if @started @started = true @worker = Thread . new do QuartzTorrent . initThread ( "trackerclient" ) @logger . info "Worker thread starting" @event = :started trackerInterval = nil while ! @stopped begin response = nil driver = currentDriver if driver begin @logger . debug "Sending req... | Start the worker thread |
16,934 | def length = ( l ) byteLen = 0 byteLen = ( l - 1 ) / 8 + 1 if l > 0 raise "Length adjustment would change size of underlying array" if byteLen != byteLength @length = l end | Adjust the length of the bitfield . This might be necessary if we had to unserialize the bitfield from a serialized array of bytes . |
16,935 | def set ( bit ) quotient = bit >> 3 remainder = bit & 0x7 mask = 0x80 >> remainder raise "Bit #{bit} out of range of bitfield with length #{length}" if quotient >= @data . length @data [ quotient ] |= mask end | Set the bit at index bit to 1 . |
16,936 | def clear ( bit ) quotient = bit >> 3 remainder = bit & 0x7 mask = ~ ( 0x80 >> remainder ) raise "Bit #{bit} out of range of bitfield with length #{length}" if quotient >= @data . length @data [ quotient ] &= mask end | Clear the bit at index bit to 0 . |
16,937 | def allSet? ( @data . length - 1 ) . times do | i | return false if @data [ i ] != 0xff end toCheck = @length % 8 toCheck = 8 if toCheck == 0 ( ( @length - toCheck ) .. ( @length - 1 ) ) . each do | i | return false if ! set? ( i ) end true end | Are all bits in the Bitfield set? |
16,938 | def union ( bitfield ) raise "That's not a bitfield" if ! bitfield . is_a? ( Bitfield ) raise "bitfield lengths must be equal" if ! bitfield . length == length result = Bitfield . new ( length ) ( @data . length ) . times do | i | result . data [ i ] = @data [ i ] | bitfield . data [ i ] end result end | Calculate the union of this bitfield and the passed bitfield and return the result as a new bitfield . |
16,939 | def intersection ( bitfield ) raise "That's not a bitfield" if ! bitfield . is_a? ( Bitfield ) raise "bitfield lengths must be equal" if ! bitfield . length == length newbitfield = Bitfield . new ( length ) newbitfield . copyFrom ( self ) newbitfield . intersection! ( bitfield ) end | Calculate the intersection of this bitfield and the passed bitfield and return the result as a new bitfield . |
16,940 | def intersection! ( bitfield ) raise "That's not a bitfield" if ! bitfield . is_a? ( Bitfield ) raise "bitfield lengths must be equal" if ! bitfield . length == length ( @data . length ) . times do | i | @data [ i ] = @data [ i ] & bitfield . data [ i ] end self end | Update this bitfield to be the intersection of this bitfield and the passed bitfield . |
16,941 | def copyFrom ( bitfield ) raise "Source bitfield is too small (#{bitfield.length} < #{length})" if bitfield . length < length ( @data . length ) . times do | i | @data [ i ] = bitfield . data [ i ] end end | Set the contents of this bitfield to be the same as the passed bitfield . An exception is thrown if the passed bitfield is smaller than this . |
16,942 | def to_s ( groupsOf = 8 ) groupsOf = 8 if groupsOf == 0 s = "" length . times do | i | s << ( set? ( i ) ? "1" : "0" ) s << " " if i % groupsOf == 0 end s end | Return a display string representing the bitfield . |
16,943 | def updateUploadRate ( msg ) @uploadRate . update msg . length if msg . is_a? Piece @uploadRateDataOnly . update msg . data . length end end | Equate peers . Update the upload rate of the peer from the passed PeerWireMessage . |
16,944 | def updateDownloadRate ( msg ) @downloadRate . update msg . length if msg . is_a? Piece @downloadRateDataOnly . update msg . data . length end end | Update the download rate of the peer from the passed PeerWireMessage . |
16,945 | def convert ( inputformat , outputformat , file_path , callback_url = nil , options = { } ) raise "File path cant be blank" if file_path . nil? @convert_request_url = start_conversion ( inputformat , outputformat ) initiate_connection ( @convert_request_url ) upload ( build_upload_params ( file_path , outputformat , ca... | request_connection = > specific to file conversion convert request for file |
16,946 | def converter_options ( inputformat = "" , outputformat = "" ) response = @conversion_connection . get "conversiontypes" , { :inputformat => inputformat , :outputformat => outputformat } parse_response ( response . body ) end | returns all possible conversions and options |
16,947 | def build_upload_params ( file_path , outputformat , callback_url = nil , options = { } ) upload_params = { :format => outputformat } upload_params . merge! ( :callback => callback ( callback_url ) ) if callback ( callback_url ) . present? upload_params . merge! ( :input => "download" , :link => file_path ) upload_para... | building params for local file |
16,948 | def gravatar_attrs ( email , * params ) url_options = Gravatarify :: Utils . merge_gravatar_options ( * params ) options = url_options [ :html ] || { } options [ :src ] = gravatar_url ( email , false , url_options ) options [ :width ] = options [ :height ] = ( url_options [ :size ] || 80 ) { :alt => '' } . merge! ( opt... | Helper method for HAML to return a neat hash to be used as attributes in an image tag . |
16,949 | def compute_changes spec_sets_diff! old_spec_set . each do | old_gem | updated_gem = new_spec_set . find { | new_gem | new_gem . name == old_gem . name } next unless updated_gem && old_gem . version != updated_gem . version fill_changes ( old_gem , updated_gem ) end end | Compute the diffs between two Gemfile . lock . |
16,950 | def fill_changes ( old_gem , updated_gem ) changes [ old_gem . name ] = { versions : { old : old_gem . version . to_s , new : updated_gem . version . to_s } , source : updated_gem . source } end | Add changes to between two versions of a gem |
16,951 | def connect_to ( host , port , timeout = nil ) timeout = timeout && Float ( timeout ) addr = Socket . getaddrinfo ( host , nil , Socket :: AF_INET ) sock = Socket . new ( Socket . const_get ( addr [ 0 ] [ 0 ] ) , Socket :: SOCK_STREAM , 0 ) sock . setsockopt Socket :: IPPROTO_TCP , Socket :: TCP_NODELAY , 1 if timeout ... | Creates a socket object which does speedy non - blocking reads and can perform reliable read timeouts . |
16,952 | def prune_cache ( mtime = 15 ) entries = remove_old_items ( mtime ) entries . each do | key , entry | FileUtils . rm_f ( entry [ :file ] ) end end | the fastest way to prune this is to use the local find command |
16,953 | def set_power ( state ) level = case state when :on 1 when :off 0 else raise ArgumentError . new ( "Must pass in either :on or :off" ) end send_message ( Protocol :: Device :: SetPower . new ( level : level ) ) self end | Attempts to set the power state to state asynchronously . This method cannot guarantee the message was received . |
16,954 | def set_site_id ( site_id ) send_message ( Protocol :: Device :: SetSite . new ( site : [ site_id ] . pack ( 'H*' ) ) ) end | Attempts to set the site id of the light . Will clear label and tags . This method cannot guarantee message receipt . |
16,955 | def set_time ( time = Time . now ) send_message ( Protocol :: Device :: SetTime . new ( time : ( time . to_f * NSEC_IN_SEC ) . round ) ) end | Attempts to set the device time on the targets |
16,956 | def query_rubygems ( tries = 0 ) JSON . parse ( open ( "https://rubygems.org/api/v1/gems/#{gem_name}.json" ) . read ) rescue OpenURI :: HTTPError => e if e . io . status . include? ( HTTP_TOO_MANY_REQUESTS ) if ( tries += 1 ) < 2 sleep 1 && retry end end end | Make the real query to rubygems It may fail in case we trigger too many requests |
16,957 | def uri_from_other_sources uri = nil source . remotes . each do | remote | break if uri uri = case remote . host when 'rubygems.org' then next when 'rails-assets.org' uri_from_railsassets else Bundler . ui . error "Source #{remote} is not supported, ' \ 'feel free to open a PR or an issue on https://gi... | Look if gem can be found in another remote |
16,958 | def compute_key ( external_identifier ) x = [ external_identifier ] . flatten x . map! { | xx | xx . to_s } x . join ( "_" ) end | Generate a string key from an array of identifiers |
16,959 | def to_graphml ( ) builder = Builder :: XmlMarkup . new ( :indent => 1 ) builder . instruct! :xml , :version => "1.0" graphml_attribs = { "xmlns" => "http://graphml.graphdrawing.org/xmlns" , "xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance" , "xmlns:y" => "http://www.yworks.com/xml/graphml" , "xmlns:yed" => "h... | Return graph as graphml text |
16,960 | def to_hsbk Protocol :: Light :: Hsbk . new ( hue : ( hue / 360.0 * UINT16_MAX ) . to_i , saturation : ( saturation * UINT16_MAX ) . to_i , brightness : ( brightness * UINT16_MAX ) . to_i , kelvin : [ KELVIN_MIN , kelvin . to_i , KELVIN_MAX ] . sort [ 1 ] ) end | Returns a struct for use by the protocol |
16,961 | def similar_to? ( other , threshold : DEFAULT_SIMILAR_THRESHOLD ) return false unless other . is_a? ( Color ) conditions = [ ] conditions << ( ( ( hue - other . hue ) . abs < ( threshold * 360 ) ) || begin hues = [ hue , other . hue ] . sort hues [ 0 ] += 360 ( hues [ 0 ] - hues [ 1 ] ) . abs < ( threshold * 360 ) end ... | 0 . 1% variance Checks if colours are equal to 0 . 1% variance |
16,962 | def fetch body = get ( Nominatim . config . reverse_url , @criteria ) . body return nil if body . empty? Nominatim :: Place . new ( body ) end | Returns search result or nil if no results received . |
16,963 | def sign ( token ) @auth_hash = { :auth_version => "1.0" , :auth_key => token . key , :auth_timestamp => Time . now . to_i . to_s } @auth_hash [ :auth_signature ] = signature ( token ) @signed = true return @auth_hash end | Sign the request with the given token and return the computed authentication parameters |
16,964 | def authenticate_by_token! ( token , timestamp_grace = 600 ) if token . secret . nil? || token . secret . empty? raise "Provided token is missing secret" end validate_version! validate_timestamp! ( timestamp_grace ) validate_signature! ( token ) true end | Authenticates the request with a token |
16,965 | def authenticate ( timestamp_grace = 600 ) raise ArgumentError , "Block required" unless block_given? key = @auth_hash [ 'auth_key' ] raise AuthenticationError , "Missing parameter: auth_key" unless key token = yield key unless token raise AuthenticationError , "Unknown auth_key" end authenticate_by_token! ( token , ti... | Authenticate a request |
16,966 | def authenticate_async ( timestamp_grace = 600 ) raise ArgumentError , "Block required" unless block_given? df = EM :: DefaultDeferrable . new key = @auth_hash [ 'auth_key' ] unless key df . fail ( AuthenticationError . new ( "Missing parameter: auth_key" ) ) return end token_df = yield key token_df . callback { | toke... | Authenticate a request asynchronously |
16,967 | def identical? ( a , b ) return true if a . nil? && b . nil? return false if a . nil? || b . nil? return false unless a . bytesize == b . bytesize a . bytes . zip ( b . bytes ) . reduce ( 0 ) { | memo , ( a , b ) | memo += a ^ b } == 0 end | Constant time string comparison |
16,968 | def method_missing ( m , * args , & block ) if args . any? args = args . first if args . length == 1 @var << { m . to_sym => args } instance_variable_set "@#{m}" , args else instance_variable_get "@#{m}" end end | Script s commands |
16,969 | def purge_unused_tags! unused_tags . each do | tag | logger . info ( "Purging tag '#{tag}'" ) entries_with ( label : tag ) . each do | entry | payload = Protocol :: Device :: SetTagLabels . new ( tags : id_to_tags_field ( entry . tag_id ) , label : '' ) context . send_message ( target : Target . new ( site_id : entry .... | This will clear out tags that currently do not resolve to any devices . If used when devices that are tagged with a tag that is not attached to an active device it will effectively untag them when they re back on . |
16,970 | def format_diff gemfile . changes . map do | gem , details | ERB . new ( template , nil , '<>' ) . result ( binding ) end end | Format the diff to get human readable information on the gems that were updated . |
16,971 | def fill_changelogs [ ] . tap do | threads | gemfile . changes . each do | gem_name , details | threads << Thread . new { retrieve_gem_changes ( gem_name , details ) } end end . each ( & :join ) end | For each gem retrieve its changelog |
16,972 | def find_source ( gem , source ) case source when Bundler :: Source :: Rubygems GemUpdater :: RubyGemsFetcher . new ( gem , source ) . source_uri when Bundler :: Source :: Git source . uri . gsub ( / / , 'http' ) . chomp ( '.git' ) end end | Find where is hosted the source of a gem |
16,973 | def template File . read ( "#{Dir.home}/.gem_updater_template.erb" ) rescue Errno :: ENOENT File . read ( File . expand_path ( '../lib/gem_updater_template.erb' , __dir__ ) ) end | Get the template for gem s diff . It can use a custom template . |
16,974 | def strategy = ( classifier ) is_interchangeable? ( classifier ) if @strategy && classifier . category_count == 0 previous_strategy = @strategy @strategy = classifier convert_categories_with_docs ( previous_strategy ) else @strategy = classifier end end | nodoc Changes classifier strategy and train new strategy if needed |
16,975 | def add_score ( score ) @total_score += score . value @scores [ score . key ] = score if @top_score_key . nil? || @scores [ @top_score_key ] . value < score . value @top_score_key = score . key end end | Method for adding new score to result |
16,976 | def add_hook ( payload_class , hook_arg = nil , & hook_block ) hook = block_given? ? hook_block : hook_arg if ! hook || ! hook . is_a? ( Proc ) raise "Must pass a proc either as an argument or a block" end @message_hooks [ payload_class ] << hook end | Adds a block to be run when a payload of class payload_class is received |
16,977 | def color ( refresh : false , fetch : true ) @color = nil if refresh send_message! ( Protocol :: Light :: Get . new , wait_for : Protocol :: Light :: State ) if fetch && ! @color @color end | Returns the color of the device . |
16,978 | def set_label ( label ) if label . bytes . length > MAX_LABEL_LENGTH raise LabelTooLong . new ( "Label length in bytes must be below or equal to #{MAX_LABEL_LENGTH}" ) end while self . label != label send_message! ( Protocol :: Device :: SetLabel . new ( label : label . encode ( 'utf-8' ) ) , wait_for : Protocol :: Dev... | Sets the label of the light |
16,979 | def set_power! ( state ) level = case state when :on 1 when :off 0 else raise ArgumentError . new ( "Must pass in either :on or :off" ) end send_message! ( Protocol :: Device :: SetPower . new ( level : level ) , wait_for : Protocol :: Device :: StatePower ) do | payload | if level == 0 payload . level == 0 else payloa... | Set the power state to state synchronously . |
16,980 | def time send_message! ( Protocol :: Device :: GetTime . new , wait_for : Protocol :: Device :: StateTime ) do | payload | Time . at ( payload . time . to_f / NSEC_IN_SEC ) end end | Returns the local time of the light |
16,981 | def latency start = Time . now . to_f send_message! ( Protocol :: Device :: GetTime . new , wait_for : Protocol :: Device :: StateTime ) Time . now . to_f - start end | Pings the device and measures response time . |
16,982 | def mesh_firmware ( fetch : true ) @mesh_firmware ||= begin send_message! ( Protocol :: Device :: GetMeshFirmware . new , wait_for : Protocol :: Device :: StateMeshFirmware ) do | payload | Firmware . new ( payload ) end if fetch end end | Returns the mesh firmware details |
16,983 | def wifi_firmware ( fetch : true ) @wifi_firmware ||= begin send_message! ( Protocol :: Device :: GetWifiFirmware . new , wait_for : Protocol :: Device :: StateWifiFirmware ) do | payload | Firmware . new ( payload ) end if fetch end end | Returns the wifi firmware details |
16,984 | def temperature send_message! ( Protocol :: Light :: GetTemperature . new , wait_for : Protocol :: Light :: StateTemperature ) do | payload | payload . temperature / 100.0 end end | Returns the temperature of the device |
16,985 | def mesh_info send_message! ( Protocol :: Device :: GetMeshInfo . new , wait_for : Protocol :: Device :: StateMeshInfo ) do | payload | { signal : payload . signal , tx : payload . tx , rx : payload . rx } end end | Returns mesh network info |
16,986 | def wifi_info send_message! ( Protocol :: Device :: GetWifiInfo . new , wait_for : Protocol :: Device :: StateWifiInfo ) do | payload | { signal : payload . signal , tx : payload . tx , rx : payload . rx } end end | Returns wifi network info |
16,987 | def version send_message! ( Protocol :: Device :: GetVersion . new , wait_for : Protocol :: Device :: StateVersion ) do | payload | { vendor : payload . vendor , product : payload . product , version : payload . version } end end | Returns version info |
16,988 | def uptime send_message! ( Protocol :: Device :: GetInfo . new , wait_for : Protocol :: Device :: StateInfo ) do | payload | payload . uptime . to_f / NSEC_IN_SEC end end | Return device uptime |
16,989 | def last_downtime send_message! ( Protocol :: Device :: GetInfo . new , wait_for : Protocol :: Device :: StateInfo ) do | payload | payload . downtime . to_f / NSEC_IN_SEC end end | Return device last downtime |
16,990 | def send_message ( payload , acknowledge : true , at_time : nil ) context . send_message ( target : Target . new ( device_id : id ) , payload : payload , acknowledge : acknowledge , at_time : at_time ) end | Compare current Light to another light |
16,991 | def send_message! ( payload , wait_for : wait_for , wait_timeout : Config . message_wait_timeout , retry_interval : Config . message_retry_interval , & block ) if Thread . current [ :sync_enabled ] raise "Cannot use synchronous methods inside a sync block" end result = nil begin block ||= Proc . new { | msg | true } pr... | Queues a message to be sent to the Light and waits for a response |
16,992 | def gav_data ( gav ) res = { } request = Typhoeus :: Request . new ( "#{host_url}/service/local/artifact/maven/resolve" , :params => gav . to_hash , :connecttimeout => 5 , :headers => { 'Accept' => 'application/json' } ) request . on_failure do | response | raise ( "Failed to get gav data for #{gav.to_s}" ) end request... | retrieves the attributes of the gav |
16,993 | def sha ( file , use_sha_file = false ) if use_sha_file and File . exists? ( "#{file}.sha1" ) begin File . open ( "#{file}.sha1" , 'r' ) { | f | f . read ( ) . strip } rescue Digest :: SHA1 . file ( File . expand_path ( file ) ) . hexdigest end else Digest :: SHA1 . file ( File . expand_path ( file ) ) . hexdigest end ... | returns the sha1 of the file |
16,994 | def sha_match? ( file , gav , use_sha_file = false ) if File . exists? ( file ) if gav . sha1 . nil? gav . sha1 = gav_data ( gav ) [ 'sha1' ] end sha ( file , use_sha_file ) == gav . sha1 else false end end | sha_match? returns bool by comparing the sha1 of the nexus gav artifact and the local file |
16,995 | def write_sha1 ( file , sha1 ) shafile = "#{file}.sha1" File . open ( shafile , 'w' ) { | f | f . write ( sha1 ) } end | writes the sha1 a file if and only if the contents of the file do not match |
16,996 | def known_https ( uri ) case uri . host when HOSTS [ :github ] URI "https://github.com#{uri.path}" when HOSTS [ :bitbucket ] URI "https://#{uri.host}#{uri.path}" when HOSTS [ :rubygems ] URI "https://#{uri.host}#{uri.path}" else uri end end | Some uris are not https but we know they should be in which case we have an https redirection which is not properly handled by open - uri |
16,997 | def changelog_names CHANGELOG_NAMES . flat_map do | name | [ name , name . upcase , name . capitalize ] end . uniq end | List possible names for a changelog since humans may have many many ways to call it . |
16,998 | def styleguide_block ( section , & block ) raise ArgumentError , "Missing block" unless block_given? @section = styleguide . section ( section ) if ! @section . raw raise "KSS styleguide section is nil, is section '#{section}' defined in your css?" end content = capture ( & block ) render 'kss/shared/styleguide_block' ... | Generates a styleguide block . A little bit evil with |
16,999 | def array name , values array_attrs = { 'soapenc:arrayType' => "xsd:string[#{values.length}]" , 'xsi:type' => 'wsdl:ArrayOfString' } builder . tag! name , array_attrs do | tag | values . each { | value | tag . item value } end self end | Appends an argument of type array |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.