repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
poise/halite
lib/halite/gem.rb
Halite.Gem.platforms
def platforms raw_platforms = spec.metadata.fetch('platforms', '').strip case raw_platforms when '' [] when 'any', 'all', '*' # Based on `ls lib/fauxhai/platforms | xargs echo`. %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 ubuntu windows}.map {|p| [p] } when /,/ # Comma split mode. String looks like "name, name constraint, name constraint" raw_platforms.split(/\s*,\s*/).map {|p| p.split(/\s+/, 2) } else # Whitepace split mode, assume no constraints. raw_platforms.split(/\s+/).map {|p| [p] } end end
ruby
def platforms raw_platforms = spec.metadata.fetch('platforms', '').strip case raw_platforms when '' [] when 'any', 'all', '*' # Based on `ls lib/fauxhai/platforms | xargs echo`. %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 ubuntu windows}.map {|p| [p] } when /,/ # Comma split mode. String looks like "name, name constraint, name constraint" raw_platforms.split(/\s*,\s*/).map {|p| p.split(/\s+/, 2) } else # Whitepace split mode, assume no constraints. raw_platforms.split(/\s+/).map {|p| [p] } end end
[ "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", "ubuntu", "windows", "}", ".", "map", "{", "|", "p", "|", "[", "p", "]", "}", "when", "/", "/", "raw_platforms", ".", "split", "(", "/", "\\s", "\\s", "/", ")", ".", "map", "{", "|", "p", "|", "p", ".", "split", "(", "/", "\\s", "/", ",", "2", ")", "}", "else", "raw_platforms", ".", "split", "(", "/", "\\s", "/", ")", ".", "map", "{", "|", "p", "|", "[", "p", "]", "}", "end", "end" ]
Platform support to be used in the Chef metadata. @return [Array<Array<String>>]
[ "Platform", "support", "to", "be", "used", "in", "the", "Chef", "metadata", "." ]
9ae174e6b7c5d4674f3301394e14567fa89a8b3e
https://github.com/poise/halite/blob/9ae174e6b7c5d4674f3301394e14567fa89a8b3e/lib/halite/gem.rb#L122-L139
train
poise/halite
lib/halite/gem.rb
Halite.Gem.find_misc_path
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(path)) end end # Didn't find anything nil end
ruby
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(path)) end end # Didn't find anything nil end
[ "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", "(", "path", ")", ")", "end", "end", "nil", "end" ]
Search for a file like README.md or LICENSE.txt in the gem. @param name [String] Basename to search for. @return [String, Array<String>] @example gem.misc_file('Readme') => /path/to/readme.txt
[ "Search", "for", "a", "file", "like", "README", ".", "md", "or", "LICENSE", ".", "txt", "in", "the", "gem", "." ]
9ae174e6b7c5d4674f3301394e14567fa89a8b3e
https://github.com/poise/halite/blob/9ae174e6b7c5d4674f3301394e14567fa89a8b3e/lib/halite/gem.rb#L227-L236
train
poise/halite
lib/halite/gem.rb
Halite.Gem.dependency_to_spec
def dependency_to_spec(dep) # #to_spec doesn't allow prereleases unless the requirement is # for a prerelease. Just use the last valid spec if possible. 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
ruby
def dependency_to_spec(dep) # #to_spec doesn't allow prereleases unless the requirement is # for a prerelease. Just use the last valid spec if possible. 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
[ "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. @since 1.0.1 @param dep [Gem::Dependency] Dependency to solve. @return [Gem::Specificiation]
[ "Find", "a", "spec", "given", "a", "dependency", "." ]
9ae174e6b7c5d4674f3301394e14567fa89a8b3e
https://github.com/poise/halite/blob/9ae174e6b7c5d4674f3301394e14567fa89a8b3e/lib/halite/gem.rb#L261-L269
train
morellon/rrd-ffi
lib/rrd/base.rb
RRD.Base.resize
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 # Force an integer Wrapper.resize(rrd_file, rra_num.to_s, action, delta.to_s) end
ruby
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 # Force an integer Wrapper.resize(rrd_file, rra_num.to_s, action, delta.to_s) end
[ "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' You will need to know the RRA number, starting from 0: rrd.resize(0, :grow => 10.days)
[ "Writes", "a", "new", "file", "resize", ".", "rrd" ]
84713ac3ffcb931ec25b1f63a1a19f444d1a805f
https://github.com/morellon/rrd-ffi/blob/84713ac3ffcb931ec25b1f63a1a19f444d1a805f/lib/rrd/base.rb#L70-L77
train
poise/halite
lib/berkshelf/locations/gem.rb
Berkshelf.GemLocation.install
def install cache_path.rmtree if cache_path.exist? cache_path.mkpath Halite.convert(gem_name, cache_path) validate_cached!(cache_path) end
ruby
def install cache_path.rmtree if cache_path.exist? cache_path.mkpath Halite.convert(gem_name, cache_path) validate_cached!(cache_path) end
[ "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. @see BaseLocation#install
[ "Convert", "the", "gem", "." ]
9ae174e6b7c5d4674f3301394e14567fa89a8b3e
https://github.com/poise/halite/blob/9ae174e6b7c5d4674f3301394e14567fa89a8b3e/lib/berkshelf/locations/gem.rb#L44-L49
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/peerholder.rb
QuartzTorrent.PeerHolder.add
def add(peer) raise "Peer must have it's infoHash set." if ! peer.infoHash # Do not add if peer is already present by address 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(peer.trackerPeer.id, peer) # If id is null, this is probably a peer received from the tracker that has no ID. end @peersByAddr[byAddrKey(peer)] = peer @peersByInfoHash.pushToList(peer.infoHash, peer) end
ruby
def add(peer) raise "Peer must have it's infoHash set." if ! peer.infoHash # Do not add if peer is already present by address 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(peer.trackerPeer.id, peer) # If id is null, this is probably a peer received from the tracker that has no ID. end @peersByAddr[byAddrKey(peer)] = peer @peersByInfoHash.pushToList(peer.infoHash, peer) end
[ "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", "(", "peer", ".", "trackerPeer", ".", "id", ",", "peer", ")", "end", "@peersByAddr", "[", "byAddrKey", "(", "peer", ")", "]", "=", "peer", "@peersByInfoHash", ".", "pushToList", "(", "peer", ".", "infoHash", ",", "peer", ")", "end" ]
Add a peer to the PeerHolder.
[ "Add", "a", "peer", "to", "the", "PeerHolder", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerholder.rb#L32-L50
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/peerholder.rb
QuartzTorrent.PeerHolder.idSet
def idSet(peer) @peersById.each do |e| return if e.eql?(peer) end @peersById.pushToList(peer.trackerPeer.id, peer) end
ruby
def idSet(peer) @peersById.each do |e| return if e.eql?(peer) end @peersById.pushToList(peer.trackerPeer.id, peer) end
[ "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.
[ "Set", "the", "id", "for", "a", "peer", ".", "This", "peer", "which", "previously", "had", "no", "id", "has", "finished", "handshaking", "and", "now", "has", "an", "ID", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerholder.rb#L53-L58
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/peerholder.rb
QuartzTorrent.PeerHolder.delete
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.eql?(peer) peer else nil end end list.compact! end end end
ruby
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.eql?(peer) peer else nil end end list.compact! end end end
[ "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", ".", "eql?", "(", "peer", ")", "peer", "else", "nil", "end", "end", "list", ".", "compact!", "end", "end", "end" ]
Delete the specified peer from the PeerHolder.
[ "Delete", "the", "specified", "peer", "from", "the", "PeerHolder", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerholder.rb#L61-L89
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/peerholder.rb
QuartzTorrent.PeerHolder.to_s
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} #{makeFlags(peer)}\n" end end else "PeerHolder" end s end
ruby
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} #{makeFlags(peer)}\n" end end else "PeerHolder" end s end
[ "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} #{makeFlags(peer)}\\n\"", "end", "end", "else", "\"PeerHolder\"", "end", "s", "end" ]
Output a string representation of the PeerHolder, for debugging purposes.
[ "Output", "a", "string", "representation", "of", "the", "PeerHolder", "for", "debugging", "purposes", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerholder.rb#L102-L125
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/magnet.rb
QuartzTorrent.MagnetURI.btInfoHash
def btInfoHash result = nil @params['xt'].each do |topic| if topic =~ /urn:btih:(.*)/ hash = $1 if hash.length == 40 # Hex-encoded info hash. Convert to binary. result = [hash].pack "H*" else # Base32 encoded result = Base32.decode hash end break end end result end
ruby
def btInfoHash result = nil @params['xt'].each do |topic| if topic =~ /urn:btih:(.*)/ hash = $1 if hash.length == 40 # Hex-encoded info hash. Convert to binary. result = [hash].pack "H*" else # Base32 encoded result = Base32.decode hash end break end end result end
[ "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.
[ "Return", "the", "first", "Bittorrent", "info", "hash", "found", "in", "the", "magnet", "URI", ".", "The", "returned", "info", "hash", "is", "in", "binary", "format", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/magnet.rb#L35-L51
train
rjurado01/rapidoc
lib/rapidoc/resources_extractor.rb
Rapidoc.ResourcesExtractor.get_routes_doc
def get_routes_doc puts "Executing 'rake routes'..." if trace? routes_doc = RoutesDoc.new routes = Dir.chdir( ::Rails.root.to_s ) { `rake routes` } routes.split("\n").each do |entry| routes_doc.add_route( entry ) unless entry.match(/URI/) end routes_doc end
ruby
def get_routes_doc puts "Executing 'rake routes'..." if trace? routes_doc = RoutesDoc.new routes = Dir.chdir( ::Rails.root.to_s ) { `rake routes` } routes.split("\n").each do |entry| routes_doc.add_route( entry ) unless entry.match(/URI/) end routes_doc end
[ "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 @return [RoutesDoc] class with routes info
[ "Reads", "rake", "routes", "output", "and", "gets", "the", "routes", "info" ]
03b7a8f29a37dd03f4ed5036697b48551d3b4ae6
https://github.com/rjurado01/rapidoc/blob/03b7a8f29a37dd03f4ed5036697b48551d3b4ae6/lib/rapidoc/resources_extractor.rb#L18-L29
train
rjurado01/rapidoc
lib/rapidoc/resources_extractor.rb
Rapidoc.ResourcesExtractor.get_resources
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
ruby
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
[ "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 @return [Array] ResourceDoc array
[ "Create", "new", "ResourceDoc", "for", "each", "resource", "extracted", "from", "RoutesDoc" ]
03b7a8f29a37dd03f4ed5036697b48551d3b4ae6
https://github.com/rjurado01/rapidoc/blob/03b7a8f29a37dd03f4ed5036697b48551d3b4ae6/lib/rapidoc/resources_extractor.rb#L35-L43
train
sethvargo/cleanroom
lib/cleanroom.rb
Cleanroom.ClassMethods.evaluate_file
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
ruby
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
[ "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. @param [Class] instance the instance of the class to evaluate against @param [String] filepath the path of the file to evaluate
[ "Evaluate", "the", "file", "in", "the", "context", "of", "the", "cleanroom", "." ]
339f602745cb379abd7cc5980743d2a05d2bc164
https://github.com/sethvargo/cleanroom/blob/339f602745cb379abd7cc5980743d2a05d2bc164/lib/cleanroom.rb#L53-L57
train
sethvargo/cleanroom
lib/cleanroom.rb
Cleanroom.ClassMethods.evaluate
def evaluate(instance, *args, &block) cleanroom.new(instance).instance_eval(*args, &block) end
ruby
def evaluate(instance, *args, &block) cleanroom.new(instance).instance_eval(*args, &block) end
[ "def", "evaluate", "(", "instance", ",", "*", "args", ",", "&", "block", ")", "cleanroom", ".", "new", "(", "instance", ")", ".", "instance_eval", "(", "*", "args", ",", "&", "block", ")", "end" ]
Evaluate the string or block in the context of the cleanroom. @param [Class] instance the instance of the class to evaluate against @param [Array<String>] args the args to +instance_eval+ @param [Proc] block the block to +instance_eval+
[ "Evaluate", "the", "string", "or", "block", "in", "the", "context", "of", "the", "cleanroom", "." ]
339f602745cb379abd7cc5980743d2a05d2bc164
https://github.com/sethvargo/cleanroom/blob/339f602745cb379abd7cc5980743d2a05d2bc164/lib/cleanroom.rb#L69-L71
train
sethvargo/cleanroom
lib/cleanroom.rb
Cleanroom.ClassMethods.cleanroom
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(:initialize) do |instance| define_singleton_method(:__instance__) do unless caller[0].include?(__FILE__) raise Cleanroom::InaccessibleError.new(:__instance__, self) end instance end end exposed.each do |exposed_method| define_method(exposed_method) do |*args, &block| __instance__.public_send(exposed_method, *args, &block) end end define_method(:class_eval) do raise Cleanroom::InaccessibleError.new(:class_eval, self) end define_method(:inspect) do "#<#{parent} (Cleanroom)>" end alias_method :to_s, :inspect end end
ruby
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(:initialize) do |instance| define_singleton_method(:__instance__) do unless caller[0].include?(__FILE__) raise Cleanroom::InaccessibleError.new(:__instance__, self) end instance end end exposed.each do |exposed_method| define_method(exposed_method) do |*args, &block| __instance__.public_send(exposed_method, *args, &block) end end define_method(:class_eval) do raise Cleanroom::InaccessibleError.new(:class_eval, self) end define_method(:inspect) do "#<#{parent} (Cleanroom)>" end alias_method :to_s, :inspect end end
[ "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", "(", ":initialize", ")", "do", "|", "instance", "|", "define_singleton_method", "(", ":__instance__", ")", "do", "unless", "caller", "[", "0", "]", ".", "include?", "(", "__FILE__", ")", "raise", "Cleanroom", "::", "InaccessibleError", ".", "new", "(", ":__instance__", ",", "self", ")", "end", "instance", "end", "end", "exposed", ".", "each", "do", "|", "exposed_method", "|", "define_method", "(", "exposed_method", ")", "do", "|", "*", "args", ",", "&", "block", "|", "__instance__", ".", "public_send", "(", "exposed_method", ",", "*", "args", ",", "&", "block", ")", "end", "end", "define_method", "(", ":class_eval", ")", "do", "raise", "Cleanroom", "::", "InaccessibleError", ".", "new", "(", ":class_eval", ",", "self", ")", "end", "define_method", "(", ":inspect", ")", "do", "\"#<#{parent} (Cleanroom)>\"", "end", "alias_method", ":to_s", ",", ":inspect", "end", "end" ]
The cleanroom instance for this class. This method is intentionally NOT cached! @return [Class]
[ "The", "cleanroom", "instance", "for", "this", "class", ".", "This", "method", "is", "intentionally", "NOT", "cached!" ]
339f602745cb379abd7cc5980743d2a05d2bc164
https://github.com/sethvargo/cleanroom/blob/339f602745cb379abd7cc5980743d2a05d2bc164/lib/cleanroom.rb#L103-L143
train
rjurado01/rapidoc
lib/rapidoc/routes_doc.rb
Rapidoc.RoutesDoc.add_resource_route
def add_resource_route( method, url, controller_action ) #resource = get_resource_name( url ) 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] ||= [] @resources_routes[resource.to_sym].push( info ) end
ruby
def add_resource_route( method, url, controller_action ) #resource = get_resource_name( url ) 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] ||= [] @resources_routes[resource.to_sym].push( info ) end
[ "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", "]", "||=", "[", "]", "@resources_routes", "[", "resource", ".", "to_sym", "]", ".", "push", "(", "info", ")", "end" ]
Add new route info to resource routes array with correct format
[ "Add", "new", "route", "info", "to", "resource", "routes", "array", "with", "correct", "format" ]
03b7a8f29a37dd03f4ed5036697b48551d3b4ae6
https://github.com/rjurado01/rapidoc/blob/03b7a8f29a37dd03f4ed5036697b48551d3b4ae6/lib/rapidoc/routes_doc.rb#L74-L87
train
rjurado01/rapidoc
lib/rapidoc/routes_doc.rb
Rapidoc.RoutesDoc.get_resource_name
def get_resource_name( url ) new_url = url.gsub( '(.:format)', '' ) return $1 if new_url =~ /\/(\w+)\/:id$/ # /users/:id (users) return $1 if new_url =~ /\/(\w+)\/:id\/edit$/ # /users/:id/edit (users) return $1 if new_url =~ /^\/(\w+)$/ # /users (users) return $1 if new_url =~ /\/:\w*id\/(\w+)$/ # /users/:id/images (images) return $1 if new_url =~ /\/:\w*id\/(\w+)\/\w+$/ # /users/:id/config/edit (users) return $1 if new_url =~ /^\/(\w+)\/\w+$/ # /users/edit (users) return $1 if new_url =~ /\/(\w+)\/\w+\/\w+$/ # /users/password/edit (users) return url end
ruby
def get_resource_name( url ) new_url = url.gsub( '(.:format)', '' ) return $1 if new_url =~ /\/(\w+)\/:id$/ # /users/:id (users) return $1 if new_url =~ /\/(\w+)\/:id\/edit$/ # /users/:id/edit (users) return $1 if new_url =~ /^\/(\w+)$/ # /users (users) return $1 if new_url =~ /\/:\w*id\/(\w+)$/ # /users/:id/images (images) return $1 if new_url =~ /\/:\w*id\/(\w+)\/\w+$/ # /users/:id/config/edit (users) return $1 if new_url =~ /^\/(\w+)\/\w+$/ # /users/edit (users) return $1 if new_url =~ /\/(\w+)\/\w+\/\w+$/ # /users/password/edit (users) return url end
[ "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", "if", "new_url", "=~", "/", "\\/", "\\w", "\\/", "\\w", "\\/", "\\w", "/", "return", "url", "end" ]
Extract resource name from url
[ "Extract", "resource", "name", "from", "url" ]
03b7a8f29a37dd03f4ed5036697b48551d3b4ae6
https://github.com/rjurado01/rapidoc/blob/03b7a8f29a37dd03f4ed5036697b48551d3b4ae6/lib/rapidoc/routes_doc.rb#L92-L103
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/peermsgserialization.rb
QuartzTorrent.PeerWireMessageSerializer.classForMessage
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[Extension::MetadataExtensionId] = ExtendedMetaInfo end result = @@classForMessage[id] if result == Extended && payload # Extended messages have further subtypes. extendedMsgId = payload.unpack("C")[0] if extendedMsgId == 0 result = ExtendedHandshake else # In this case the extended message number is the one we told our peers to use, not the one the peer told us. result = @@classForExtendedMessage[extendedMsgId] raise "Unsupported extended peer message id '#{extendedMsgId}'" if ! result end end result end
ruby
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[Extension::MetadataExtensionId] = ExtendedMetaInfo end result = @@classForMessage[id] if result == Extended && payload # Extended messages have further subtypes. extendedMsgId = payload.unpack("C")[0] if extendedMsgId == 0 result = ExtendedHandshake else # In this case the extended message number is the one we told our peers to use, not the one the peer told us. result = @@classForExtendedMessage[extendedMsgId] raise "Unsupported extended peer message id '#{extendedMsgId}'" if ! result end end result end
[ "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", "[", "Extension", "::", "MetadataExtensionId", "]", "=", "ExtendedMetaInfo", "end", "result", "=", "@@classForMessage", "[", "id", "]", "if", "result", "==", "Extended", "&&", "payload", "extendedMsgId", "=", "payload", ".", "unpack", "(", "\"C\"", ")", "[", "0", "]", "if", "extendedMsgId", "==", "0", "result", "=", "ExtendedHandshake", "else", "result", "=", "@@classForExtendedMessage", "[", "extendedMsgId", "]", "raise", "\"Unsupported extended peer message id '#{extendedMsgId}'\"", "if", "!", "result", "end", "end", "result", "end" ]
Determine the class associated with the message type passed.
[ "Determine", "the", "class", "associated", "with", "the", "message", "type", "passed", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peermsgserialization.rb#L53-L80
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/blockstate.rb
QuartzTorrent.BlockInfo.getRequest
def getRequest m = Request.new m.pieceIndex = @pieceIndex m.blockOffset = @offset m.blockLength = @length m end
ruby
def getRequest m = Request.new m.pieceIndex = @pieceIndex m.blockOffset = @offset m.blockLength = @length m end
[ "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.
[ "Return", "a", "new", "Bittorrent", "Request", "message", "that", "requests", "this", "block", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/blockstate.rb#L30-L36
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/blockstate.rb
QuartzTorrent.BlockState.findRequestableBlocks
def findRequestableBlocks(classifiedPeers, numToReturn = nil) # Have a list of the current pieces we are working on. Each time this method is # called, check the blocks in the pieces in list order to find the blocks to return # for requesting. If a piece is completed, remove it from this list. If we need more blocks # than there are available in the list, add more pieces to the end of the list (in rarest-first # order). result = [] # Update requestable peers to only be those that we can still request pieces from. peersHavingPiece = computePeersHavingPiece(classifiedPeers) requestable = @completeBlocks.union(@requestedBlocks).compliment! rarityOrder = nil currentPiece = 0 while true if currentPiece >= @currentPieces.length # Add more pieces in rarest-first order. If there are no more pieces, break. rarityOrder = computeRarity(classifiedPeers) if ! rarityOrder added = false rarityOrder.each do |pair| pieceIndex = pair[1] peersWithPiece = peersHavingPiece[pieceIndex] if peersWithPiece && peersWithPiece.size > 0 && [email protected](pieceIndex) && ! pieceCompleted?(pieceIndex) @logger.debug "Adding piece #{pieceIndex} to the current downloading list" @currentPieces.push pieceIndex added = true break end end if ! added @logger.debug "There are no more pieces to add to the current downloading list" break end end currentPieceIndex = @currentPieces[currentPiece] if pieceCompleted?(currentPieceIndex) @logger.debug "Piece #{currentPieceIndex} complete so removing it from the current downloading list" @currentPieces.delete_at(currentPiece) next end peersWithPiece = peersHavingPiece[currentPieceIndex] if !peersWithPiece || peersWithPiece.size == 0 @logger.debug "No peers have piece #{currentPieceIndex}" currentPiece += 1 next end eachBlockInPiece(currentPieceIndex) do |blockIndex| if requestable.set?(blockIndex) result.push createBlockinfoByPieceAndBlockIndex(currentPieceIndex, peersWithPiece, blockIndex) break if numToReturn && result.size >= numToReturn end end break if numToReturn && result.size >= numToReturn currentPiece += 1 end result end
ruby
def findRequestableBlocks(classifiedPeers, numToReturn = nil) # Have a list of the current pieces we are working on. Each time this method is # called, check the blocks in the pieces in list order to find the blocks to return # for requesting. If a piece is completed, remove it from this list. If we need more blocks # than there are available in the list, add more pieces to the end of the list (in rarest-first # order). result = [] # Update requestable peers to only be those that we can still request pieces from. peersHavingPiece = computePeersHavingPiece(classifiedPeers) requestable = @completeBlocks.union(@requestedBlocks).compliment! rarityOrder = nil currentPiece = 0 while true if currentPiece >= @currentPieces.length # Add more pieces in rarest-first order. If there are no more pieces, break. rarityOrder = computeRarity(classifiedPeers) if ! rarityOrder added = false rarityOrder.each do |pair| pieceIndex = pair[1] peersWithPiece = peersHavingPiece[pieceIndex] if peersWithPiece && peersWithPiece.size > 0 && [email protected](pieceIndex) && ! pieceCompleted?(pieceIndex) @logger.debug "Adding piece #{pieceIndex} to the current downloading list" @currentPieces.push pieceIndex added = true break end end if ! added @logger.debug "There are no more pieces to add to the current downloading list" break end end currentPieceIndex = @currentPieces[currentPiece] if pieceCompleted?(currentPieceIndex) @logger.debug "Piece #{currentPieceIndex} complete so removing it from the current downloading list" @currentPieces.delete_at(currentPiece) next end peersWithPiece = peersHavingPiece[currentPieceIndex] if !peersWithPiece || peersWithPiece.size == 0 @logger.debug "No peers have piece #{currentPieceIndex}" currentPiece += 1 next end eachBlockInPiece(currentPieceIndex) do |blockIndex| if requestable.set?(blockIndex) result.push createBlockinfoByPieceAndBlockIndex(currentPieceIndex, peersWithPiece, blockIndex) break if numToReturn && result.size >= numToReturn end end break if numToReturn && result.size >= numToReturn currentPiece += 1 end result end
[ "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", "=", "computeRarity", "(", "classifiedPeers", ")", "if", "!", "rarityOrder", "added", "=", "false", "rarityOrder", ".", "each", "do", "|", "pair", "|", "pieceIndex", "=", "pair", "[", "1", "]", "peersWithPiece", "=", "peersHavingPiece", "[", "pieceIndex", "]", "if", "peersWithPiece", "&&", "peersWithPiece", ".", "size", ">", "0", "&&", "!", "@currentPieces", ".", "index", "(", "pieceIndex", ")", "&&", "!", "pieceCompleted?", "(", "pieceIndex", ")", "@logger", ".", "debug", "\"Adding piece #{pieceIndex} to the current downloading list\"", "@currentPieces", ".", "push", "pieceIndex", "added", "=", "true", "break", "end", "end", "if", "!", "added", "@logger", ".", "debug", "\"There are no more pieces to add to the current downloading list\"", "break", "end", "end", "currentPieceIndex", "=", "@currentPieces", "[", "currentPiece", "]", "if", "pieceCompleted?", "(", "currentPieceIndex", ")", "@logger", ".", "debug", "\"Piece #{currentPieceIndex} complete so removing it from the current downloading list\"", "@currentPieces", ".", "delete_at", "(", "currentPiece", ")", "next", "end", "peersWithPiece", "=", "peersHavingPiece", "[", "currentPieceIndex", "]", "if", "!", "peersWithPiece", "||", "peersWithPiece", ".", "size", "==", "0", "@logger", ".", "debug", "\"No peers have piece #{currentPieceIndex}\"", "currentPiece", "+=", "1", "next", "end", "eachBlockInPiece", "(", "currentPieceIndex", ")", "do", "|", "blockIndex", "|", "if", "requestable", ".", "set?", "(", "blockIndex", ")", "result", ".", "push", "createBlockinfoByPieceAndBlockIndex", "(", "currentPieceIndex", ",", "peersWithPiece", ",", "blockIndex", ")", "break", "if", "numToReturn", "&&", "result", ".", "size", ">=", "numToReturn", "end", "end", "break", "if", "numToReturn", "&&", "result", ".", "size", ">=", "numToReturn", "currentPiece", "+=", "1", "end", "result", "end" ]
Return a list of BlockInfo objects representing blocjs that should be requested from peers.
[ "Return", "a", "list", "of", "BlockInfo", "objects", "representing", "blocjs", "that", "should", "be", "requested", "from", "peers", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/blockstate.rb#L101-L163
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/blockstate.rb
QuartzTorrent.BlockState.setBlockRequested
def setBlockRequested(blockInfo, bool) if bool @requestedBlocks.set blockInfo.blockIndex else @requestedBlocks.clear blockInfo.blockIndex end end
ruby
def setBlockRequested(blockInfo, bool) if bool @requestedBlocks.set blockInfo.blockIndex else @requestedBlocks.clear blockInfo.blockIndex end end
[ "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.
[ "Set", "whether", "the", "block", "represented", "by", "the", "passed", "BlockInfo", "is", "requested", "or", "not", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/blockstate.rb#L166-L172
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/blockstate.rb
QuartzTorrent.BlockState.setPieceCompleted
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
ruby
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
[ "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.
[ "Set", "whether", "the", "piece", "is", "completed", "or", "not", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/blockstate.rb#L198-L211
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/blockstate.rb
QuartzTorrent.BlockState.completedLength
def completedLength num = @completeBlocks.countSet # Last block may be smaller extra = 0 if @completeBlocks.set?(@completeBlocks.length-1) num -= 1 extra = @lastBlockLength end num*@blockSize + extra end
ruby
def completedLength num = @completeBlocks.countSet # Last block may be smaller extra = 0 if @completeBlocks.set?(@completeBlocks.length-1) num -= 1 extra = @lastBlockLength end num*@blockSize + extra end
[ "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.
[ "Number", "of", "bytes", "we", "have", "downloaded", "and", "verified", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/blockstate.rb#L233-L242
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/blockstate.rb
QuartzTorrent.BlockState.createBlockinfoByPieceAndBlockIndex
def createBlockinfoByPieceAndBlockIndex(pieceIndex, peersWithPiece, blockIndex) # If this is the very last block, then it might be smaller than the rest. blockSize = @blockSize blockSize = @lastBlockLength if blockIndex == @numBlocks-1 offsetWithinPiece = (blockIndex % @blocksPerPiece)*@blockSize BlockInfo.new(pieceIndex, offsetWithinPiece, blockSize, peersWithPiece, blockIndex) end
ruby
def createBlockinfoByPieceAndBlockIndex(pieceIndex, peersWithPiece, blockIndex) # If this is the very last block, then it might be smaller than the rest. blockSize = @blockSize blockSize = @lastBlockLength if blockIndex == @numBlocks-1 offsetWithinPiece = (blockIndex % @blocksPerPiece)*@blockSize BlockInfo.new(pieceIndex, offsetWithinPiece, blockSize, peersWithPiece, blockIndex) end
[ "def", "createBlockinfoByPieceAndBlockIndex", "(", "pieceIndex", ",", "peersWithPiece", ",", "blockIndex", ")", "blockSize", "=", "@blockSize", "blockSize", "=", "@lastBlockLength", "if", "blockIndex", "==", "@numBlocks", "-", "1", "offsetWithinPiece", "=", "(", "blockIndex", "%", "@blocksPerPiece", ")", "*", "@blockSize", "BlockInfo", ".", "new", "(", "pieceIndex", ",", "offsetWithinPiece", ",", "blockSize", ",", "peersWithPiece", ",", "blockIndex", ")", "end" ]
Create a new BlockInfo object using the specified information.
[ "Create", "a", "new", "BlockInfo", "object", "using", "the", "specified", "information", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/blockstate.rb#L261-L267
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/blockstate.rb
QuartzTorrent.BlockState.computePeersHavingPiece
def computePeersHavingPiece(classifiedPeers) # Make a list of each peer having the specified piece peersHavingPiece = Array.new(@numPieces) # This first list represents rarity by number if peers having that piece. 1 = rarest. 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 end peersHavingPiece end
ruby
def computePeersHavingPiece(classifiedPeers) # Make a list of each peer having the specified piece peersHavingPiece = Array.new(@numPieces) # This first list represents rarity by number if peers having that piece. 1 = rarest. 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 end peersHavingPiece end
[ "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", "end", "peersHavingPiece", "end" ]
Return an array indexed by piece index where each element is a list of peers with that piece.
[ "Return", "an", "array", "indexed", "by", "piece", "index", "where", "each", "element", "is", "a", "list", "of", "peers", "with", "that", "piece", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/blockstate.rb#L296-L312
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/regionmap.rb
QuartzTorrent.RegionMap.findValue
def findValue(value) if ! @sorted @map.sort{ |a,b| a[0] <=> b[0] } @sorted = true end @map.binsearch{|x| x[0] >= value}[1] end
ruby
def findValue(value) if ! @sorted @map.sort{ |a,b| a[0] <=> b[0] } @sorted = true end @map.binsearch{|x| x[0] >= value}[1] end
[ "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.
[ "Given", "an", "integer", "value", "find", "which", "region", "it", "falls", "in", "and", "return", "the", "object", "associated", "with", "that", "region", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/regionmap.rb#L58-L65
train
rjurado01/rapidoc
lib/rapidoc/yaml_parser.rb
Rapidoc.YamlParser.extract_resource_info
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 Psych::SyntaxError => e puts "Error parsing block in #{file_name} file [#{b[:init]} - #{b[:end]}]" rescue => e puts e end end end info.first ? info.first : {} end
ruby
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 Psych::SyntaxError => e puts "Error parsing block in #{file_name} file [#{b[:init]} - #{b[:end]}]" rescue => e puts e end end end info.first ? info.first : {} end
[ "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", "Psych", "::", "SyntaxError", "=>", "e", "puts", "\"Error parsing block in #{file_name} file [#{b[:init]} - #{b[:end]}]\"", "rescue", "=>", "e", "puts", "e", "end", "end", "end", "info", ".", "first", "?", "info", ".", "first", ":", "{", "}", "end" ]
Check if exist a block with resource information 'rapidoc resource block' @param lines [Array] lines that contain comments @param blocks [Hash] lines of blocks, example: { init: 1, end: 4 } @return [Hash] resource info
[ "Check", "if", "exist", "a", "block", "with", "resource", "information", "rapidoc", "resource", "block" ]
03b7a8f29a37dd03f4ed5036697b48551d3b4ae6
https://github.com/rjurado01/rapidoc/blob/03b7a8f29a37dd03f4ed5036697b48551d3b4ae6/lib/rapidoc/yaml_parser.rb#L15-L31
train
rjurado01/rapidoc
lib/rapidoc/yaml_parser.rb
Rapidoc.YamlParser.extract_actions_info
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 => e puts "Error parsing block in #{file_name} file [#{b[:init]} - #{b[:end]}]" end end end return info end
ruby
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 => e puts "Error parsing block in #{file_name} file [#{b[:init]} - #{b[:end]}]" end end end return info end
[ "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", "=>", "e", "puts", "\"Error parsing block in #{file_name} file [#{b[:init]} - #{b[:end]}]\"", "end", "end", "end", "return", "info", "end" ]
Check all blocks and load those that are 'rapidoc actions block' @param lines [Array] lines that contain comments @param blocks [Hash] lines of blocks, example: { init: 1, end: 4 } @return [Array] all actions info
[ "Check", "all", "blocks", "and", "load", "those", "that", "are", "rapidoc", "actions", "block" ]
03b7a8f29a37dd03f4ed5036697b48551d3b4ae6
https://github.com/rjurado01/rapidoc/blob/03b7a8f29a37dd03f4ed5036697b48551d3b4ae6/lib/rapidoc/yaml_parser.rb#L40-L57
train
philm/twilio
lib/twilio/incoming_phone_number.rb
Twilio.IncomingPhoneNumber.create
def create(opts) raise "You must set either :PhoneNumber or :AreaCode" if !opts.include?(:AreaCode) && !opts.include?(:PhoneNumber) Twilio.post("/IncomingPhoneNumbers", :body => opts) end
ruby
def create(opts) raise "You must set either :PhoneNumber or :AreaCode" if !opts.include?(:AreaCode) && !opts.include?(:PhoneNumber) Twilio.post("/IncomingPhoneNumbers", :body => opts) end
[ "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. Required: you must either set PhoneNumber or AreaCode as a required option For additional options, see http://www.twilio.com/docs/api/rest/incoming-phone-numbers
[ "Creates", "a", "phone", "number", "in", "Twilio", ".", "You", "must", "first", "find", "an", "existing", "number", "using", "the", "AvailablePhoneNumber", "class", "before", "creating", "one", "here", "." ]
81c05795924bbfa780ea44efd52d7ca5670bcb55
https://github.com/philm/twilio/blob/81c05795924bbfa780ea44efd52d7ca5670bcb55/lib/twilio/incoming_phone_number.rb#L21-L24
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/memprofiler.rb
QuartzTorrent.MemProfiler.getCounts
def getCounts result = {} @classes.each do |c| count = 0 ObjectSpace.each_object(c){ count += 1 } result[c] = count end result end
ruby
def getCounts result = {} @classes.each do |c| count = 0 ObjectSpace.each_object(c){ count += 1 } result[c] = count end result end
[ "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.
[ "Return", "a", "hashtable", "keyed", "by", "class", "where", "the", "value", "is", "the", "number", "of", "that", "class", "of", "object", "still", "reachable", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/memprofiler.rb#L16-L24
train
renuo/i18n-docs
lib/i18n_docs/missing_keys_finder.rb
I18nDocs.MissingKeysFinder.all_keys
def all_keys I18n.backend.send(:translations).collect do |_check_locale, translations| collect_keys([], translations).sort end.flatten.uniq end
ruby
def all_keys I18n.backend.send(:translations).collect do |_check_locale, translations| collect_keys([], translations).sort end.flatten.uniq end
[ "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
[ "Returns", "an", "array", "with", "all", "keys", "from", "all", "locales" ]
b674abfccdafd832d657fee3308cf659b1435f11
https://github.com/renuo/i18n-docs/blob/b674abfccdafd832d657fee3308cf659b1435f11/lib/i18n_docs/missing_keys_finder.rb#L10-L14
train
renuo/i18n-docs
lib/i18n_docs/missing_keys_finder.rb
I18nDocs.MissingKeysFinder.key_exists?
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
ruby
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
[ "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
[ "Returns", "true", "if", "key", "exists", "in", "the", "given", "locale" ]
b674abfccdafd832d657fee3308cf659b1435f11
https://github.com/renuo/i18n-docs/blob/b674abfccdafd832d657fee3308cf659b1435f11/lib/i18n_docs/missing_keys_finder.rb#L85-L93
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/peermsg.rb
QuartzTorrent.PeerHandshake.serializeTo
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") # Reserved. 0x10 means we support extensions (BEP 10). result << @infoHash result << @peerId io.write result end
ruby
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") # Reserved. 0x10 means we support extensions (BEP 10). result << @infoHash result << @peerId io.write result end
[ "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.
[ "Serialize", "this", "PeerHandshake", "message", "to", "the", "passed", "io", "object", ".", "Throws", "exceptions", "on", "failure", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peermsg.rb#L36-L46
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/trackerclient.rb
QuartzTorrent.TrackerClient.start
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 request to tracker #{currentAnnounceUrl}" response = driver.request(@event) @event = nil trackerInterval = response.interval rescue addError $! @logger.info "Request failed due to exception: #{$!}" @logger.debug $!.backtrace.join("\n") changeToNextTracker next @alarms.raise Alarm.new(:tracker, "Tracker request failed: #{$!}") if @alarms end end if response && response.successful? @alarms.clear :tracker if @alarms # Replace the list of peers peersHash = {} @logger.info "Response contained #{response.peers.length} peers" if response.peers.length == 0 @alarms.raise Alarm.new(:tracker, "Response from tracker contained no peers") if @alarms end response.peers.each do |p| peersHash[p] = 1 end @peersMutex.synchronize do @peers = peersHash end if @peersChangedListeners.size > 0 @peersChangedListeners.each{ |l| l.call } end else @logger.info "Response was unsuccessful from tracker: #{response.error}" addError response.error if response @alarms.raise Alarm.new(:tracker, "Unsuccessful response from tracker: #{response.error}") if @alarms && response changeToNextTracker next end # If we have no interval from the tracker yet, and the last request didn't error out leaving us with no peers, # then set the interval to 20 seconds. interval = trackerInterval interval = 20 if ! interval interval = 2 if response && !response.successful? && @peers.length == 0 @logger.debug "Sleeping for #{interval} seconds" @sleeper.sleep interval rescue @logger.warn "Unhandled exception in worker thread: #{$!}" @logger.warn $!.backtrace.join("\n") @sleeper.sleep 1 end end @logger.info "Worker thread shutting down" @logger.info "Sending final update to tracker" begin driver = currentDriver driver.request(:stopped) if driver rescue addError $! @logger.debug "Request failed due to exception: #{$!}" @logger.debug $!.backtrace.join("\n") end @started = false end end
ruby
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 request to tracker #{currentAnnounceUrl}" response = driver.request(@event) @event = nil trackerInterval = response.interval rescue addError $! @logger.info "Request failed due to exception: #{$!}" @logger.debug $!.backtrace.join("\n") changeToNextTracker next @alarms.raise Alarm.new(:tracker, "Tracker request failed: #{$!}") if @alarms end end if response && response.successful? @alarms.clear :tracker if @alarms # Replace the list of peers peersHash = {} @logger.info "Response contained #{response.peers.length} peers" if response.peers.length == 0 @alarms.raise Alarm.new(:tracker, "Response from tracker contained no peers") if @alarms end response.peers.each do |p| peersHash[p] = 1 end @peersMutex.synchronize do @peers = peersHash end if @peersChangedListeners.size > 0 @peersChangedListeners.each{ |l| l.call } end else @logger.info "Response was unsuccessful from tracker: #{response.error}" addError response.error if response @alarms.raise Alarm.new(:tracker, "Unsuccessful response from tracker: #{response.error}") if @alarms && response changeToNextTracker next end # If we have no interval from the tracker yet, and the last request didn't error out leaving us with no peers, # then set the interval to 20 seconds. interval = trackerInterval interval = 20 if ! interval interval = 2 if response && !response.successful? && @peers.length == 0 @logger.debug "Sleeping for #{interval} seconds" @sleeper.sleep interval rescue @logger.warn "Unhandled exception in worker thread: #{$!}" @logger.warn $!.backtrace.join("\n") @sleeper.sleep 1 end end @logger.info "Worker thread shutting down" @logger.info "Sending final update to tracker" begin driver = currentDriver driver.request(:stopped) if driver rescue addError $! @logger.debug "Request failed due to exception: #{$!}" @logger.debug $!.backtrace.join("\n") end @started = false end end
[ "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 request to tracker #{currentAnnounceUrl}\"", "response", "=", "driver", ".", "request", "(", "@event", ")", "@event", "=", "nil", "trackerInterval", "=", "response", ".", "interval", "rescue", "addError", "$!", "@logger", ".", "info", "\"Request failed due to exception: #{$!}\"", "@logger", ".", "debug", "$!", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", "changeToNextTracker", "next", "@alarms", ".", "raise", "Alarm", ".", "new", "(", ":tracker", ",", "\"Tracker request failed: #{$!}\"", ")", "if", "@alarms", "end", "end", "if", "response", "&&", "response", ".", "successful?", "@alarms", ".", "clear", ":tracker", "if", "@alarms", "peersHash", "=", "{", "}", "@logger", ".", "info", "\"Response contained #{response.peers.length} peers\"", "if", "response", ".", "peers", ".", "length", "==", "0", "@alarms", ".", "raise", "Alarm", ".", "new", "(", ":tracker", ",", "\"Response from tracker contained no peers\"", ")", "if", "@alarms", "end", "response", ".", "peers", ".", "each", "do", "|", "p", "|", "peersHash", "[", "p", "]", "=", "1", "end", "@peersMutex", ".", "synchronize", "do", "@peers", "=", "peersHash", "end", "if", "@peersChangedListeners", ".", "size", ">", "0", "@peersChangedListeners", ".", "each", "{", "|", "l", "|", "l", ".", "call", "}", "end", "else", "@logger", ".", "info", "\"Response was unsuccessful from tracker: #{response.error}\"", "addError", "response", ".", "error", "if", "response", "@alarms", ".", "raise", "Alarm", ".", "new", "(", ":tracker", ",", "\"Unsuccessful response from tracker: #{response.error}\"", ")", "if", "@alarms", "&&", "response", "changeToNextTracker", "next", "end", "interval", "=", "trackerInterval", "interval", "=", "20", "if", "!", "interval", "interval", "=", "2", "if", "response", "&&", "!", "response", ".", "successful?", "&&", "@peers", ".", "length", "==", "0", "@logger", ".", "debug", "\"Sleeping for #{interval} seconds\"", "@sleeper", ".", "sleep", "interval", "rescue", "@logger", ".", "warn", "\"Unhandled exception in worker thread: #{$!}\"", "@logger", ".", "warn", "$!", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", "@sleeper", ".", "sleep", "1", "end", "end", "@logger", ".", "info", "\"Worker thread shutting down\"", "@logger", ".", "info", "\"Sending final update to tracker\"", "begin", "driver", "=", "currentDriver", "driver", ".", "request", "(", ":stopped", ")", "if", "driver", "rescue", "addError", "$!", "@logger", ".", "debug", "\"Request failed due to exception: #{$!}\"", "@logger", ".", "debug", "$!", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", "end", "@started", "=", "false", "end", "end" ]
Start the worker thread
[ "Start", "the", "worker", "thread" ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/trackerclient.rb#L262-L348
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/bitfield.rb
QuartzTorrent.Bitfield.length=
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
ruby
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
[ "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.
[ "Adjust", "the", "length", "of", "the", "bitfield", ".", "This", "might", "be", "necessary", "if", "we", "had", "to", "unserialize", "the", "bitfield", "from", "a", "serialized", "array", "of", "bytes", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/bitfield.rb#L57-L64
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/bitfield.rb
QuartzTorrent.Bitfield.set
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
ruby
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
[ "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.
[ "Set", "the", "bit", "at", "index", "bit", "to", "1", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/bitfield.rb#L73-L80
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/bitfield.rb
QuartzTorrent.Bitfield.clear
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
ruby
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
[ "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.
[ "Clear", "the", "bit", "at", "index", "bit", "to", "0", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/bitfield.rb#L83-L90
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/bitfield.rb
QuartzTorrent.Bitfield.allSet?
def allSet? # Check all but last byte quickly (@data.length-1).times do |i| return false if @data[i] != 0xff end # Check last byte slowly toCheck = @length % 8 toCheck = 8 if toCheck == 0 ((@length-toCheck)..(@length-1)).each do |i| return false if ! set?(i) end true end
ruby
def allSet? # Check all but last byte quickly (@data.length-1).times do |i| return false if @data[i] != 0xff end # Check last byte slowly toCheck = @length % 8 toCheck = 8 if toCheck == 0 ((@length-toCheck)..(@length-1)).each do |i| return false if ! set?(i) end true end
[ "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?
[ "Are", "all", "bits", "in", "the", "Bitfield", "set?" ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/bitfield.rb#L99-L111
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/bitfield.rb
QuartzTorrent.Bitfield.union
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
ruby
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
[ "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.
[ "Calculate", "the", "union", "of", "this", "bitfield", "and", "the", "passed", "bitfield", "and", "return", "the", "result", "as", "a", "new", "bitfield", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/bitfield.rb#L140-L149
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/bitfield.rb
QuartzTorrent.Bitfield.intersection
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
ruby
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
[ "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.
[ "Calculate", "the", "intersection", "of", "this", "bitfield", "and", "the", "passed", "bitfield", "and", "return", "the", "result", "as", "a", "new", "bitfield", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/bitfield.rb#L153-L160
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/bitfield.rb
QuartzTorrent.Bitfield.intersection!
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
ruby
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
[ "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.
[ "Update", "this", "bitfield", "to", "be", "the", "intersection", "of", "this", "bitfield", "and", "the", "passed", "bitfield", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/bitfield.rb#L163-L171
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/bitfield.rb
QuartzTorrent.Bitfield.copyFrom
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
ruby
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
[ "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.
[ "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", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/bitfield.rb#L175-L180
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/bitfield.rb
QuartzTorrent.Bitfield.to_s
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
ruby
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
[ "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.
[ "Return", "a", "display", "string", "representing", "the", "bitfield", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/bitfield.rb#L207-L215
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/peer.rb
QuartzTorrent.Peer.updateUploadRate
def updateUploadRate(msg) @uploadRate.update msg.length if msg.is_a? Piece @uploadRateDataOnly.update msg.data.length end end
ruby
def updateUploadRate(msg) @uploadRate.update msg.length if msg.is_a? Piece @uploadRateDataOnly.update msg.data.length end end
[ "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.
[ "Equate", "peers", ".", "Update", "the", "upload", "rate", "of", "the", "peer", "from", "the", "passed", "PeerWireMessage", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peer.rb#L107-L112
train
jeffwilliams/quartz-torrent
lib/quartz_torrent/peer.rb
QuartzTorrent.Peer.updateDownloadRate
def updateDownloadRate(msg) @downloadRate.update msg.length if msg.is_a? Piece @downloadRateDataOnly.update msg.data.length end end
ruby
def updateDownloadRate(msg) @downloadRate.update msg.length if msg.is_a? Piece @downloadRateDataOnly.update msg.data.length end end
[ "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.
[ "Update", "the", "download", "rate", "of", "the", "peer", "from", "the", "passed", "PeerWireMessage", "." ]
7aeb40125d886dd60d7481deb5129282fc3e3c06
https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peer.rb#L115-L120
train
pandurang90/cloudconvert
lib/cloudconvert/conversion.rb
Cloudconvert.Conversion.convert
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 with new response host initiate_connection(@convert_request_url) upload(build_upload_params(file_path, outputformat, callback_url, options)) end
ruby
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 with new response host initiate_connection(@convert_request_url) upload(build_upload_params(file_path, outputformat, callback_url, options)) end
[ "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", ",", "callback_url", ",", "options", ")", ")", "end" ]
request_connection => specific to file conversion convert request for file
[ "request_connection", "=", ">", "specific", "to", "file", "conversion", "convert", "request", "for", "file" ]
864c9a3d16750f9de2d600d1b9df80e079284f2d
https://github.com/pandurang90/cloudconvert/blob/864c9a3d16750f9de2d600d1b9df80e079284f2d/lib/cloudconvert/conversion.rb#L13-L19
train
pandurang90/cloudconvert
lib/cloudconvert/conversion.rb
Cloudconvert.Conversion.converter_options
def converter_options(inputformat ="", outputformat = "") response = @conversion_connection.get "conversiontypes", {:inputformat => inputformat,:outputformat => outputformat } parse_response(response.body) end
ruby
def converter_options(inputformat ="", outputformat = "") response = @conversion_connection.get "conversiontypes", {:inputformat => inputformat,:outputformat => outputformat } parse_response(response.body) end
[ "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
[ "returns", "all", "possible", "conversions", "and", "options" ]
864c9a3d16750f9de2d600d1b9df80e079284f2d
https://github.com/pandurang90/cloudconvert/blob/864c9a3d16750f9de2d600d1b9df80e079284f2d/lib/cloudconvert/conversion.rb#L60-L63
train
pandurang90/cloudconvert
lib/cloudconvert/conversion.rb
Cloudconvert.Conversion.build_upload_params
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_params.merge!(options) end
ruby
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_params.merge!(options) end
[ "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_params", ".", "merge!", "(", "options", ")", "end" ]
building params for local file
[ "building", "params", "for", "local", "file" ]
864c9a3d16750f9de2d600d1b9df80e079284f2d
https://github.com/pandurang90/cloudconvert/blob/864c9a3d16750f9de2d600d1b9df80e079284f2d/lib/cloudconvert/conversion.rb#L93-L98
train
lwe/gravatarify
lib/gravatarify/helper.rb
Gravatarify.Helper.gravatar_attrs
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) # customize size { :alt => '' }.merge!(options) # to ensure validity merge with :alt => ''! end
ruby
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) # customize size { :alt => '' }.merge!(options) # to ensure validity merge with :alt => ''! end
[ "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!", "(", "options", ")", "end" ]
Helper method for HAML to return a neat hash to be used as attributes in an image tag. Now it's as simple as doing something like: %img{ gravatar_attrs(@user.mail, :size => 20) }/ This is also the base method for +gravatar_tag+. @param [String, #email, #mail, #gravatar_url] email a string or an object used to generate to gravatar url for. @param [Symbol, Hash] *params other gravatar or html options for building the resulting hash. @return [Hash] all html attributes required to build an +img+ tag.
[ "Helper", "method", "for", "HAML", "to", "return", "a", "neat", "hash", "to", "be", "used", "as", "attributes", "in", "an", "image", "tag", "." ]
195120d6e6b4f4c1d7f5e2f97d9d90120eb8db75
https://github.com/lwe/gravatarify/blob/195120d6e6b4f4c1d7f5e2f97d9d90120eb8db75/lib/gravatarify/helper.rb#L29-L35
train
MaximeD/gem_updater
lib/gem_updater/gem_file.rb
GemUpdater.GemFile.compute_changes
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
ruby
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
[ "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`. @return [Hash] gems for which there are differences.
[ "Compute", "the", "diffs", "between", "two", "Gemfile", ".", "lock", "." ]
910d30b544ad12fd31b7de831355c65ab423db8a
https://github.com/MaximeD/gem_updater/blob/910d30b544ad12fd31b7de831355c65ab423db8a/lib/gem_updater/gem_file.rb#L24-L33
train
MaximeD/gem_updater
lib/gem_updater/gem_file.rb
GemUpdater.GemFile.fill_changes
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
ruby
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
[ "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 @param old_gem [Bundler::LazySpecification] @param new_gem [Bundler::LazySpecification]
[ "Add", "changes", "to", "between", "two", "versions", "of", "a", "gem" ]
910d30b544ad12fd31b7de831355c65ab423db8a
https://github.com/MaximeD/gem_updater/blob/910d30b544ad12fd31b7de831355c65ab423db8a/lib/gem_updater/gem_file.rb#L63-L70
train
mojombo/bertrpc
lib/bertrpc/action.rb
BERTRPC.Action.connect_to
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 secs = Integer(timeout) usecs = Integer((timeout - secs) * 1_000_000) optval = [secs, usecs].pack("l_2") sock.setsockopt Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, optval sock.setsockopt Socket::SOL_SOCKET, Socket::SO_SNDTIMEO, optval begin sock.connect_nonblock(Socket.pack_sockaddr_in(port, addr[0][3])) rescue Errno::EINPROGRESS result = IO.select(nil, [sock], nil, timeout) if result.nil? raise ConnectionError.new(@svc.host, @svc.port) end begin sock.connect_nonblock(Socket.pack_sockaddr_in(port, addr[0][3])) rescue Errno::EISCONN end end else sock.connect(Socket.pack_sockaddr_in(port, addr[0][3])) end sock end
ruby
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 secs = Integer(timeout) usecs = Integer((timeout - secs) * 1_000_000) optval = [secs, usecs].pack("l_2") sock.setsockopt Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, optval sock.setsockopt Socket::SOL_SOCKET, Socket::SO_SNDTIMEO, optval begin sock.connect_nonblock(Socket.pack_sockaddr_in(port, addr[0][3])) rescue Errno::EINPROGRESS result = IO.select(nil, [sock], nil, timeout) if result.nil? raise ConnectionError.new(@svc.host, @svc.port) end begin sock.connect_nonblock(Socket.pack_sockaddr_in(port, addr[0][3])) rescue Errno::EISCONN end end else sock.connect(Socket.pack_sockaddr_in(port, addr[0][3])) end sock end
[ "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", "secs", "=", "Integer", "(", "timeout", ")", "usecs", "=", "Integer", "(", "(", "timeout", "-", "secs", ")", "*", "1_000_000", ")", "optval", "=", "[", "secs", ",", "usecs", "]", ".", "pack", "(", "\"l_2\"", ")", "sock", ".", "setsockopt", "Socket", "::", "SOL_SOCKET", ",", "Socket", "::", "SO_RCVTIMEO", ",", "optval", "sock", ".", "setsockopt", "Socket", "::", "SOL_SOCKET", ",", "Socket", "::", "SO_SNDTIMEO", ",", "optval", "begin", "sock", ".", "connect_nonblock", "(", "Socket", ".", "pack_sockaddr_in", "(", "port", ",", "addr", "[", "0", "]", "[", "3", "]", ")", ")", "rescue", "Errno", "::", "EINPROGRESS", "result", "=", "IO", ".", "select", "(", "nil", ",", "[", "sock", "]", ",", "nil", ",", "timeout", ")", "if", "result", ".", "nil?", "raise", "ConnectionError", ".", "new", "(", "@svc", ".", "host", ",", "@svc", ".", "port", ")", "end", "begin", "sock", ".", "connect_nonblock", "(", "Socket", ".", "pack_sockaddr_in", "(", "port", ",", "addr", "[", "0", "]", "[", "3", "]", ")", ")", "rescue", "Errno", "::", "EISCONN", "end", "end", "else", "sock", ".", "connect", "(", "Socket", ".", "pack_sockaddr_in", "(", "port", ",", "addr", "[", "0", "]", "[", "3", "]", ")", ")", "end", "sock", "end" ]
Creates a socket object which does speedy, non-blocking reads and can perform reliable read timeouts. Raises Timeout::Error on timeout. +host+ String address of the target TCP server +port+ Integer port of the target TCP server +timeout+ Optional Integer (in seconds) of the read timeout
[ "Creates", "a", "socket", "object", "which", "does", "speedy", "non", "-", "blocking", "reads", "and", "can", "perform", "reliable", "read", "timeouts", "." ]
c78721ecf6f4744f5d33a1733a8eab90dc01cb86
https://github.com/mojombo/bertrpc/blob/c78721ecf6f4744f5d33a1733a8eab90dc01cb86/lib/bertrpc/action.rb#L74-L104
train
logicminds/nexus-client
lib/nexus_client/cache.rb
Nexus.Cache.prune_cache
def prune_cache(mtime=15) # get old, unused entries and discard from DB and filesystem entries = remove_old_items(mtime) entries.each do |key, entry| FileUtils.rm_f(entry[:file]) end end
ruby
def prune_cache(mtime=15) # get old, unused entries and discard from DB and filesystem entries = remove_old_items(mtime) entries.each do |key, entry| FileUtils.rm_f(entry[:file]) end end
[ "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
[ "the", "fastest", "way", "to", "prune", "this", "is", "to", "use", "the", "local", "find", "command" ]
26b07e1478dd129f80bf145bf3db0f8219b12bda
https://github.com/logicminds/nexus-client/blob/26b07e1478dd129f80bf145bf3db0f8219b12bda/lib/nexus_client/cache.rb#L96-L102
train
LIFX/lifx-gem
lib/lifx/light_target.rb
LIFX.LightTarget.set_power
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
ruby
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
[ "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. @param state [:on, :off] @return [Light, LightCollection] self for chaining
[ "Attempts", "to", "set", "the", "power", "state", "to", "state", "asynchronously", ".", "This", "method", "cannot", "guarantee", "the", "message", "was", "received", "." ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light_target.rb#L139-L150
train
LIFX/lifx-gem
lib/lifx/light_target.rb
LIFX.LightTarget.set_site_id
def set_site_id(site_id) send_message(Protocol::Device::SetSite.new(site: [site_id].pack('H*'))) end
ruby
def set_site_id(site_id) send_message(Protocol::Device::SetSite.new(site: [site_id].pack('H*'))) end
[ "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. @note Don't use this unless you know what you're doing. @api private @param site_id [String] Site ID @return [void]
[ "Attempts", "to", "set", "the", "site", "id", "of", "the", "light", ".", "Will", "clear", "label", "and", "tags", ".", "This", "method", "cannot", "guarantee", "message", "receipt", "." ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light_target.rb#L180-L182
train
LIFX/lifx-gem
lib/lifx/light_target.rb
LIFX.LightTarget.set_time
def set_time(time = Time.now) send_message(Protocol::Device::SetTime.new(time: (time.to_f * NSEC_IN_SEC).round)) end
ruby
def set_time(time = Time.now) send_message(Protocol::Device::SetTime.new(time: (time.to_f * NSEC_IN_SEC).round)) end
[ "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 @api private @param time [Time] The time to set @return [void]
[ "Attempts", "to", "set", "the", "device", "time", "on", "the", "targets" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light_target.rb#L189-L191
train
MaximeD/gem_updater
lib/gem_updater/ruby_gems_fetcher.rb
GemUpdater.RubyGemsFetcher.query_rubygems
def query_rubygems(tries = 0) JSON.parse(open("https://rubygems.org/api/v1/gems/#{gem_name}.json").read) rescue OpenURI::HTTPError => e # We may trigger too many requests, in which case give rubygems a break if e.io.status.include?(HTTP_TOO_MANY_REQUESTS) if (tries += 1) < 2 sleep 1 && retry end end end
ruby
def query_rubygems(tries = 0) JSON.parse(open("https://rubygems.org/api/v1/gems/#{gem_name}.json").read) rescue OpenURI::HTTPError => e # We may trigger too many requests, in which case give rubygems a break if e.io.status.include?(HTTP_TOO_MANY_REQUESTS) if (tries += 1) < 2 sleep 1 && retry end end end
[ "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 @param tries [Integer|nil] (optional) how many times we tried
[ "Make", "the", "real", "query", "to", "rubygems", "It", "may", "fail", "in", "case", "we", "trigger", "too", "many", "requests" ]
910d30b544ad12fd31b7de831355c65ab423db8a
https://github.com/MaximeD/gem_updater/blob/910d30b544ad12fd31b7de831355c65ab423db8a/lib/gem_updater/ruby_gems_fetcher.rb#L49-L58
train
MaximeD/gem_updater
lib/gem_updater/ruby_gems_fetcher.rb
GemUpdater.RubyGemsFetcher.uri_from_other_sources
def uri_from_other_sources uri = nil source.remotes.each do |remote| break if uri uri = case remote.host when 'rubygems.org' then next # already checked 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://github.com/MaximeD/gem_updater" end end uri end
ruby
def uri_from_other_sources uri = nil source.remotes.each do |remote| break if uri uri = case remote.host when 'rubygems.org' then next # already checked 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://github.com/MaximeD/gem_updater" end end uri end
[ "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://github.com/MaximeD/gem_updater\"", "end", "end", "uri", "end" ]
Look if gem can be found in another remote @return [String|nil] uri of source code rubocop:disable Metrics/MethodLength
[ "Look", "if", "gem", "can", "be", "found", "in", "another", "remote" ]
910d30b544ad12fd31b7de831355c65ab423db8a
https://github.com/MaximeD/gem_updater/blob/910d30b544ad12fd31b7de831355c65ab423db8a/lib/gem_updater/ruby_gems_fetcher.rb#L64-L80
train
MrPowers/directed_graph
lib/directed_graph/graphml.rb
DirectedGraph.Graph.compute_key
def compute_key(external_identifier) x = [external_identifier].flatten x.map! {|xx| xx.to_s} x.join("_") end
ruby
def compute_key(external_identifier) x = [external_identifier].flatten x.map! {|xx| xx.to_s} x.join("_") end
[ "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
[ "Generate", "a", "string", "key", "from", "an", "array", "of", "identifiers" ]
eb0f607e555a068cca2a7927d2b81aadae9c743a
https://github.com/MrPowers/directed_graph/blob/eb0f607e555a068cca2a7927d2b81aadae9c743a/lib/directed_graph/graphml.rb#L7-L11
train
MrPowers/directed_graph
lib/directed_graph/graphml.rb
DirectedGraph.Graph.to_graphml
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" => "http://www.yworks.com/xml/yed/3", "xsi:schemaLocation" => "http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd", :directed => "1", :label => "test" } builder.graphml(graphml_attribs) do # Define key id's at top of graphml file builder.key({:for=>"node", :id=>"d3", "yfiles.type"=>"nodegraphics"}) # Build Graph # builder.graph({:id=>"G"}) do vertices.each do |vertex| builder.node(:id => compute_key([vertex.name, vertex.object_id])) do builder.data({:key=>"d3"}) do builder.tag!("y:ShapeNode") do graphics = vertex.data.fetch(:graphics, {}) graphics.fetch(:fill, []).each {|f| builder.tag! "y:Fill", {:color=>f, :transparent=>"false"}} graphics.fetch(:shape,[]).each {|s| builder.tag! "y:Shape", {:type=>s}} graphics.fetch(:geometry,[]).each {|s| builder.tag! "y:Geometry", s} graphics.fetch(:label,[]).each {|l| builder.tag! "y:NodeLabel", l} end end end end edges.each do |edge| source = edge.origin_vertex target = edge.destination_vertex options = edge.data[:options] label = "" builder.edge( :source => s = compute_key([source.name, source.object_id]), :target => t = compute_key([target.name, target.object_id]), :id => compute_key([source.name, target.name, edge.object_id]), :label => "#{label}" ) do #edge[:attributes].each_pair { |k, v| # id_str = compute_key([k,:edge_attr]) # builder.data(v.to_s, {:key=>@guid[id_str]}) #} end end end end builder.target! end
ruby
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" => "http://www.yworks.com/xml/yed/3", "xsi:schemaLocation" => "http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd", :directed => "1", :label => "test" } builder.graphml(graphml_attribs) do # Define key id's at top of graphml file builder.key({:for=>"node", :id=>"d3", "yfiles.type"=>"nodegraphics"}) # Build Graph # builder.graph({:id=>"G"}) do vertices.each do |vertex| builder.node(:id => compute_key([vertex.name, vertex.object_id])) do builder.data({:key=>"d3"}) do builder.tag!("y:ShapeNode") do graphics = vertex.data.fetch(:graphics, {}) graphics.fetch(:fill, []).each {|f| builder.tag! "y:Fill", {:color=>f, :transparent=>"false"}} graphics.fetch(:shape,[]).each {|s| builder.tag! "y:Shape", {:type=>s}} graphics.fetch(:geometry,[]).each {|s| builder.tag! "y:Geometry", s} graphics.fetch(:label,[]).each {|l| builder.tag! "y:NodeLabel", l} end end end end edges.each do |edge| source = edge.origin_vertex target = edge.destination_vertex options = edge.data[:options] label = "" builder.edge( :source => s = compute_key([source.name, source.object_id]), :target => t = compute_key([target.name, target.object_id]), :id => compute_key([source.name, target.name, edge.object_id]), :label => "#{label}" ) do #edge[:attributes].each_pair { |k, v| # id_str = compute_key([k,:edge_attr]) # builder.data(v.to_s, {:key=>@guid[id_str]}) #} end end end end builder.target! end
[ "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\"", "=>", "\"http://www.yworks.com/xml/yed/3\"", ",", "\"xsi:schemaLocation\"", "=>", "\"http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd\"", ",", ":directed", "=>", "\"1\"", ",", ":label", "=>", "\"test\"", "}", "builder", ".", "graphml", "(", "graphml_attribs", ")", "do", "builder", ".", "key", "(", "{", ":for", "=>", "\"node\"", ",", ":id", "=>", "\"d3\"", ",", "\"yfiles.type\"", "=>", "\"nodegraphics\"", "}", ")", "builder", ".", "graph", "(", "{", ":id", "=>", "\"G\"", "}", ")", "do", "vertices", ".", "each", "do", "|", "vertex", "|", "builder", ".", "node", "(", ":id", "=>", "compute_key", "(", "[", "vertex", ".", "name", ",", "vertex", ".", "object_id", "]", ")", ")", "do", "builder", ".", "data", "(", "{", ":key", "=>", "\"d3\"", "}", ")", "do", "builder", ".", "tag!", "(", "\"y:ShapeNode\"", ")", "do", "graphics", "=", "vertex", ".", "data", ".", "fetch", "(", ":graphics", ",", "{", "}", ")", "graphics", ".", "fetch", "(", ":fill", ",", "[", "]", ")", ".", "each", "{", "|", "f", "|", "builder", ".", "tag!", "\"y:Fill\"", ",", "{", ":color", "=>", "f", ",", ":transparent", "=>", "\"false\"", "}", "}", "graphics", ".", "fetch", "(", ":shape", ",", "[", "]", ")", ".", "each", "{", "|", "s", "|", "builder", ".", "tag!", "\"y:Shape\"", ",", "{", ":type", "=>", "s", "}", "}", "graphics", ".", "fetch", "(", ":geometry", ",", "[", "]", ")", ".", "each", "{", "|", "s", "|", "builder", ".", "tag!", "\"y:Geometry\"", ",", "s", "}", "graphics", ".", "fetch", "(", ":label", ",", "[", "]", ")", ".", "each", "{", "|", "l", "|", "builder", ".", "tag!", "\"y:NodeLabel\"", ",", "l", "}", "end", "end", "end", "end", "edges", ".", "each", "do", "|", "edge", "|", "source", "=", "edge", ".", "origin_vertex", "target", "=", "edge", ".", "destination_vertex", "options", "=", "edge", ".", "data", "[", ":options", "]", "label", "=", "\"\"", "builder", ".", "edge", "(", ":source", "=>", "s", "=", "compute_key", "(", "[", "source", ".", "name", ",", "source", ".", "object_id", "]", ")", ",", ":target", "=>", "t", "=", "compute_key", "(", "[", "target", ".", "name", ",", "target", ".", "object_id", "]", ")", ",", ":id", "=>", "compute_key", "(", "[", "source", ".", "name", ",", "target", ".", "name", ",", "edge", ".", "object_id", "]", ")", ",", ":label", "=>", "\"#{label}\"", ")", "do", "end", "end", "end", "end", "builder", ".", "target!", "end" ]
Return graph as graphml text
[ "Return", "graph", "as", "graphml", "text" ]
eb0f607e555a068cca2a7927d2b81aadae9c743a
https://github.com/MrPowers/directed_graph/blob/eb0f607e555a068cca2a7927d2b81aadae9c743a/lib/directed_graph/graphml.rb#L14-L76
train
LIFX/lifx-gem
lib/lifx/color.rb
LIFX.Color.to_hsbk
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
ruby
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
[ "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 @api private @return [Protocol::Light::Hsbk]
[ "Returns", "a", "struct", "for", "use", "by", "the", "protocol" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/color.rb#L162-L169
train
LIFX/lifx-gem
lib/lifx/color.rb
LIFX.Color.similar_to?
def similar_to?(other, threshold: DEFAULT_SIMILAR_THRESHOLD) return false unless other.is_a?(Color) conditions = [] conditions << (((hue - other.hue).abs < (threshold * 360)) || begin # FIXME: Surely there's a better way. hues = [hue, other.hue].sort hues[0] += 360 (hues[0] - hues[1]).abs < (threshold * 360) end) conditions << ((saturation - other.saturation).abs < threshold) conditions << ((brightness - other.brightness).abs < threshold) conditions.all? end
ruby
def similar_to?(other, threshold: DEFAULT_SIMILAR_THRESHOLD) return false unless other.is_a?(Color) conditions = [] conditions << (((hue - other.hue).abs < (threshold * 360)) || begin # FIXME: Surely there's a better way. hues = [hue, other.hue].sort hues[0] += 360 (hues[0] - hues[1]).abs < (threshold * 360) end) conditions << ((saturation - other.saturation).abs < threshold) conditions << ((brightness - other.brightness).abs < threshold) conditions.all? end
[ "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", ")", "conditions", "<<", "(", "(", "saturation", "-", "other", ".", "saturation", ")", ".", "abs", "<", "threshold", ")", "conditions", "<<", "(", "(", "brightness", "-", "other", ".", "brightness", ")", ".", "abs", "<", "threshold", ")", "conditions", ".", "all?", "end" ]
0.1% variance Checks if colours are equal to 0.1% variance @param other [Color] Color to compare to @param threshold: [Float] 0..1. Threshold to consider it similar @return [Boolean]
[ "0", ".", "1%", "variance", "Checks", "if", "colours", "are", "equal", "to", "0", ".", "1%", "variance" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/color.rb#L182-L195
train
jakubsvehla/nominatim
lib/nominatim/reverse.rb
Nominatim.Reverse.fetch
def fetch body = get(Nominatim.config.reverse_url, @criteria).body return nil if body.empty? Nominatim::Place.new(body) end
ruby
def fetch body = get(Nominatim.config.reverse_url, @criteria).body return nil if body.empty? Nominatim::Place.new(body) end
[ "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.
[ "Returns", "search", "result", "or", "nil", "if", "no", "results", "received", "." ]
1457ae8a1ea036efe5bd85eb81a77356d9ceaf06
https://github.com/jakubsvehla/nominatim/blob/1457ae8a1ea036efe5bd85eb81a77356d9ceaf06/lib/nominatim/reverse.rb#L10-L14
train
mloughran/signature
lib/signature.rb
Signature.Request.sign
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
ruby
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
[ "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
[ "Sign", "the", "request", "with", "the", "given", "token", "and", "return", "the", "computed", "authentication", "parameters" ]
9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20
https://github.com/mloughran/signature/blob/9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20/lib/signature.rb#L47-L58
train
mloughran/signature
lib/signature.rb
Signature.Request.authenticate_by_token!
def authenticate_by_token!(token, timestamp_grace = 600) # Validate that your code has provided a valid token. This does not # raise an AuthenticationError since passing tokens with empty secret is # a code error which should be fixed, not reported to the API's consumer 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
ruby
def authenticate_by_token!(token, timestamp_grace = 600) # Validate that your code has provided a valid token. This does not # raise an AuthenticationError since passing tokens with empty secret is # a code error which should be fixed, not reported to the API's consumer 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
[ "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 Raises an AuthenticationError if the request is invalid. AuthenticationError exception messages are designed to be exposed to API consumers, and should help them correct errors generating signatures Timestamp: Unless timestamp_grace is set to nil (which allows this check to be skipped), AuthenticationError will be raised if the timestamp is missing or further than timestamp_grace period away from the real time (defaults to 10 minutes) Signature: Raises AuthenticationError if the signature does not match the computed HMAC. The error contains a hint for how to sign.
[ "Authenticates", "the", "request", "with", "a", "token" ]
9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20
https://github.com/mloughran/signature/blob/9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20/lib/signature.rb#L74-L86
train
mloughran/signature
lib/signature.rb
Signature.Request.authenticate
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, timestamp_grace) return token end
ruby
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, timestamp_grace) return token end
[ "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", ",", "timestamp_grace", ")", "return", "token", "end" ]
Authenticate a request Takes a block which will be called with the auth_key from the request, and which should return a Signature::Token (or nil if no token can be found for the key) Raises errors in the same way as authenticate_by_token!
[ "Authenticate", "a", "request" ]
9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20
https://github.com/mloughran/signature/blob/9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20/lib/signature.rb#L105-L115
train
mloughran/signature
lib/signature.rb
Signature.Request.authenticate_async
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 { |token| begin authenticate_by_token!(token, timestamp_grace) df.succeed(token) rescue AuthenticationError => e df.fail(e) end } token_df.errback { df.fail(AuthenticationError.new("Unknown auth_key")) } ensure return df end
ruby
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 { |token| begin authenticate_by_token!(token, timestamp_grace) df.succeed(token) rescue AuthenticationError => e df.fail(e) end } token_df.errback { df.fail(AuthenticationError.new("Unknown auth_key")) } ensure return df end
[ "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", "{", "|", "token", "|", "begin", "authenticate_by_token!", "(", "token", ",", "timestamp_grace", ")", "df", ".", "succeed", "(", "token", ")", "rescue", "AuthenticationError", "=>", "e", "df", ".", "fail", "(", "e", ")", "end", "}", "token_df", ".", "errback", "{", "df", ".", "fail", "(", "AuthenticationError", ".", "new", "(", "\"Unknown auth_key\"", ")", ")", "}", "ensure", "return", "df", "end" ]
Authenticate a request asynchronously This method is useful it you're running a server inside eventmachine and need to lookup the token asynchronously. The block is passed an auth key and a deferrable which should succeed with the token, or fail if the token cannot be found This method returns a deferrable which succeeds with the valid token, or fails with an AuthenticationError which can be used to pass the error back to the user
[ "Authenticate", "a", "request", "asynchronously" ]
9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20
https://github.com/mloughran/signature/blob/9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20/lib/signature.rb#L129-L154
train
mloughran/signature
lib/signature.rb
Signature.Request.identical?
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
ruby
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
[ "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
[ "Constant", "time", "string", "comparison" ]
9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20
https://github.com/mloughran/signature/blob/9dd93b4ef0465cdd8f7ca3bde824bc11fbcb2e20/lib/signature.rb#L225-L230
train
RoxasShadow/sottolio
opal/sottolio/script.rb
Sottolio.Script.method_missing
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
ruby
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
[ "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
[ "Script", "s", "commands" ]
6687db3cd5df3278d03436b848534ae0f90a4bbd
https://github.com/RoxasShadow/sottolio/blob/6687db3cd5df3278d03436b848534ae0f90a4bbd/opal/sottolio/script.rb#L43-L51
train
LIFX/lifx-gem
lib/lifx/tag_manager.rb
LIFX.TagManager.purge_unused_tags!
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.site_id), payload: payload, acknowledge: true) end end Timeout.timeout(5) do while !unused_tags.empty? sleep 0.1 end end end
ruby
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.site_id), payload: payload, acknowledge: true) end end Timeout.timeout(5) do while !unused_tags.empty? sleep 0.1 end end end
[ "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", ".", "site_id", ")", ",", "payload", ":", "payload", ",", "acknowledge", ":", "true", ")", "end", "end", "Timeout", ".", "timeout", "(", "5", ")", "do", "while", "!", "unused_tags", ".", "empty?", "sleep", "0.1", "end", "end", "end" ]
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.
[ "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", "." ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/tag_manager.rb#L72-L87
train
MaximeD/gem_updater
lib/gem_updater.rb
GemUpdater.Updater.format_diff
def format_diff gemfile.changes.map do |gem, details| ERB.new(template, nil, '<>').result(binding) end end
ruby
def format_diff gemfile.changes.map do |gem, details| ERB.new(template, nil, '<>').result(binding) end end
[ "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.
[ "Format", "the", "diff", "to", "get", "human", "readable", "information", "on", "the", "gems", "that", "were", "updated", "." ]
910d30b544ad12fd31b7de831355c65ab423db8a
https://github.com/MaximeD/gem_updater/blob/910d30b544ad12fd31b7de831355c65ab423db8a/lib/gem_updater.rb#L41-L45
train
MaximeD/gem_updater
lib/gem_updater.rb
GemUpdater.Updater.fill_changelogs
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
ruby
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
[ "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
[ "For", "each", "gem", "retrieve", "its", "changelog" ]
910d30b544ad12fd31b7de831355c65ab423db8a
https://github.com/MaximeD/gem_updater/blob/910d30b544ad12fd31b7de831355c65ab423db8a/lib/gem_updater.rb#L50-L56
train
MaximeD/gem_updater
lib/gem_updater.rb
GemUpdater.Updater.find_source
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(/^git/, 'http').chomp('.git') end end
ruby
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(/^git/, 'http').chomp('.git') end end
[ "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 @param gem [String] the name of the gem @param source [Bundler::Source] gem's source @return [String] url where gem is hosted
[ "Find", "where", "is", "hosted", "the", "source", "of", "a", "gem" ]
910d30b544ad12fd31b7de831355c65ab423db8a
https://github.com/MaximeD/gem_updater/blob/910d30b544ad12fd31b7de831355c65ab423db8a/lib/gem_updater.rb#L63-L70
train
MaximeD/gem_updater
lib/gem_updater.rb
GemUpdater.Updater.template
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
ruby
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
[ "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. @return [ERB] the template
[ "Get", "the", "template", "for", "gem", "s", "diff", ".", "It", "can", "use", "a", "custom", "template", "." ]
910d30b544ad12fd31b7de831355c65ab423db8a
https://github.com/MaximeD/gem_updater/blob/910d30b544ad12fd31b7de831355c65ab423db8a/lib/gem_updater.rb#L87-L91
train
mustafaturan/omnicat
lib/omnicat/classifier.rb
OmniCat.Classifier.strategy=
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
ruby
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
[ "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
[ "nodoc", "Changes", "classifier", "strategy", "and", "train", "new", "strategy", "if", "needed" ]
03511027e8e1b7b8b797251834590f85eae9d879
https://github.com/mustafaturan/omnicat/blob/03511027e8e1b7b8b797251834590f85eae9d879/lib/omnicat/classifier.rb#L31-L40
train
mustafaturan/omnicat
lib/omnicat/result.rb
OmniCat.Result.add_score
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
ruby
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
[ "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 ==== Parameters * +score+ - OmniCat::Score
[ "Method", "for", "adding", "new", "score", "to", "result" ]
03511027e8e1b7b8b797251834590f85eae9d879
https://github.com/mustafaturan/omnicat/blob/03511027e8e1b7b8b797251834590f85eae9d879/lib/omnicat/result.rb#L19-L25
train
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.add_hook
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
ruby
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
[ "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 @param payload_class [Class] Payload type to execute block on @param &hook [Proc] Hook to run @api private @return [void]
[ "Adds", "a", "block", "to", "be", "run", "when", "a", "payload", "of", "class", "payload_class", "is", "received" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L56-L62
train
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.color
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
ruby
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
[ "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. @param refresh: [Boolean] If true, will request for current color @param fetch: [Boolean] If false, it will not request current color if it's not cached @return [Color] Color
[ "Returns", "the", "color", "of", "the", "device", "." ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L77-L81
train
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.set_label
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::Device::StateLabel) end self end
ruby
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::Device::StateLabel) end self end
[ "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", "::", "Device", "::", "StateLabel", ")", "end", "self", "end" ]
Sets the label of the light @param label [String] Desired label @raise [LabelTooLong] if label is greater than {MAX_LABEL_LENGTH} @return [Light] self
[ "Sets", "the", "label", "of", "the", "light" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L100-L108
train
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.set_power!
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 payload.level > 0 end end self end
ruby
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 payload.level > 0 end end self end
[ "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", "payload", ".", "level", ">", "0", "end", "end", "self", "end" ]
Set the power state to `state` synchronously. @param state [:on, :off] @return [Light, LightCollection] self for chaining
[ "Set", "the", "power", "state", "to", "state", "synchronously", "." ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L113-L130
train
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.time
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
ruby
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
[ "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 @return [Time]
[ "Returns", "the", "local", "time", "of", "the", "light" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L174-L178
train
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.latency
def latency start = Time.now.to_f send_message!(Protocol::Device::GetTime.new, wait_for: Protocol::Device::StateTime) Time.now.to_f - start end
ruby
def latency start = Time.now.to_f send_message!(Protocol::Device::GetTime.new, wait_for: Protocol::Device::StateTime) Time.now.to_f - start end
[ "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. @return [Float] Latency from sending a message to receiving a response.
[ "Pings", "the", "device", "and", "measures", "response", "time", "." ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L190-L194
train
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.mesh_firmware
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
ruby
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
[ "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 @api private @return [Hash] firmware details
[ "Returns", "the", "mesh", "firmware", "details" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L199-L206
train
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.wifi_firmware
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
ruby
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
[ "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 @api private @return [Hash] firmware details
[ "Returns", "the", "wifi", "firmware", "details" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L211-L218
train
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.temperature
def temperature send_message!(Protocol::Light::GetTemperature.new, wait_for: Protocol::Light::StateTemperature) do |payload| payload.temperature / 100.0 end end
ruby
def temperature send_message!(Protocol::Light::GetTemperature.new, wait_for: Protocol::Light::StateTemperature) do |payload| payload.temperature / 100.0 end end
[ "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 @return [Float] Temperature in Celcius
[ "Returns", "the", "temperature", "of", "the", "device" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L222-L227
train
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.mesh_info
def mesh_info send_message!(Protocol::Device::GetMeshInfo.new, wait_for: Protocol::Device::StateMeshInfo) do |payload| { signal: payload.signal, # This is in Milliwatts tx: payload.tx, rx: payload.rx } end end
ruby
def mesh_info send_message!(Protocol::Device::GetMeshInfo.new, wait_for: Protocol::Device::StateMeshInfo) do |payload| { signal: payload.signal, # This is in Milliwatts tx: payload.tx, rx: payload.rx } end end
[ "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 @api private @return [Hash] Mesh network info
[ "Returns", "mesh", "network", "info" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L232-L241
train
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.wifi_info
def wifi_info send_message!(Protocol::Device::GetWifiInfo.new, wait_for: Protocol::Device::StateWifiInfo) do |payload| { signal: payload.signal, # This is in Milliwatts tx: payload.tx, rx: payload.rx } end end
ruby
def wifi_info send_message!(Protocol::Device::GetWifiInfo.new, wait_for: Protocol::Device::StateWifiInfo) do |payload| { signal: payload.signal, # This is in Milliwatts tx: payload.tx, rx: payload.rx } end end
[ "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 @api private @return [Hash] wifi network info
[ "Returns", "wifi", "network", "info" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L246-L255
train
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.version
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
ruby
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
[ "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 @api private @return [Hash] version info
[ "Returns", "version", "info" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L260-L269
train
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.uptime
def uptime send_message!(Protocol::Device::GetInfo.new, wait_for: Protocol::Device::StateInfo) do |payload| payload.uptime.to_f / NSEC_IN_SEC end end
ruby
def uptime send_message!(Protocol::Device::GetInfo.new, wait_for: Protocol::Device::StateInfo) do |payload| payload.uptime.to_f / NSEC_IN_SEC end end
[ "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 @api private @return [Float] Device uptime in seconds
[ "Return", "device", "uptime" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L274-L279
train
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.last_downtime
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
ruby
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
[ "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 @api private @return [Float] Device's last downtime in secodns
[ "Return", "device", "last", "downtime" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L284-L289
train
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.send_message
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
ruby
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
[ "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 @param other [Light] @return [-1, 0, 1] Comparison value Queues a message to be sent the Light @param payload [Protocol::Payload] the payload to send @param acknowledge: [Boolean] whether the device should respond @param at_time: [Integer] Unix epoch in milliseconds to run the payload. Only applicable to certain payload types. @return [Light] returns self for chaining
[ "Compare", "current", "Light", "to", "another", "light" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L361-L363
train
LIFX/lifx-gem
lib/lifx/light.rb
LIFX.Light.send_message!
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 } proc = -> (payload) { result = block.call(payload) } add_hook(wait_for, proc) try_until -> { result }, timeout: wait_timeout, timeout_exception: TimeoutError, action_interval: retry_interval, signal: @message_signal do send_message(payload) end result rescue TimeoutError backtrace = caller_locations(2).map { |c| c.to_s } caller_method = caller_locations(2, 1).first.label ex = MessageTimeout.new("#{caller_method}: Timeout exceeded waiting for response from #{self}") ex.device = self ex.set_backtrace(backtrace) raise ex ensure remove_hook(wait_for, proc) end end
ruby
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 } proc = -> (payload) { result = block.call(payload) } add_hook(wait_for, proc) try_until -> { result }, timeout: wait_timeout, timeout_exception: TimeoutError, action_interval: retry_interval, signal: @message_signal do send_message(payload) end result rescue TimeoutError backtrace = caller_locations(2).map { |c| c.to_s } caller_method = caller_locations(2, 1).first.label ex = MessageTimeout.new("#{caller_method}: Timeout exceeded waiting for response from #{self}") ex.device = self ex.set_backtrace(backtrace) raise ex ensure remove_hook(wait_for, proc) end end
[ "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", "}", "proc", "=", "->", "(", "payload", ")", "{", "result", "=", "block", ".", "call", "(", "payload", ")", "}", "add_hook", "(", "wait_for", ",", "proc", ")", "try_until", "->", "{", "result", "}", ",", "timeout", ":", "wait_timeout", ",", "timeout_exception", ":", "TimeoutError", ",", "action_interval", ":", "retry_interval", ",", "signal", ":", "@message_signal", "do", "send_message", "(", "payload", ")", "end", "result", "rescue", "TimeoutError", "backtrace", "=", "caller_locations", "(", "2", ")", ".", "map", "{", "|", "c", "|", "c", ".", "to_s", "}", "caller_method", "=", "caller_locations", "(", "2", ",", "1", ")", ".", "first", ".", "label", "ex", "=", "MessageTimeout", ".", "new", "(", "\"#{caller_method}: Timeout exceeded waiting for response from #{self}\"", ")", "ex", ".", "device", "=", "self", "ex", ".", "set_backtrace", "(", "backtrace", ")", "raise", "ex", "ensure", "remove_hook", "(", "wait_for", ",", "proc", ")", "end", "end" ]
Queues a message to be sent to the Light and waits for a response @param payload [Protocol::Payload] the payload to send @param wait_for: [Class] the payload class to wait for @param wait_timeout: [Numeric] wait timeout @param block: [Proc] the block that is executed when the expected `wait_for` payload comes back. If the return value is false or nil, it will try to send the message again. @return [Object] the truthy result of `block` is returned. @raise [MessageTimeout] if the device doesn't respond in time
[ "Queues", "a", "message", "to", "be", "sent", "to", "the", "Light", "and", "waits", "for", "a", "response" ]
a33fe79a56e73781fd13e32226dae09b1c1e141f
https://github.com/LIFX/lifx-gem/blob/a33fe79a56e73781fd13e32226dae09b1c1e141f/lib/lifx/light.rb#L377-L403
train
logicminds/nexus-client
lib/nexus_client.rb
Nexus.Client.gav_data
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.on_complete do |response| res = JSON.parse(response.response_body) end request.run res['data'] end
ruby
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.on_complete do |response| res = JSON.parse(response.response_body) end request.run res['data'] end
[ "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", ".", "on_complete", "do", "|", "response", "|", "res", "=", "JSON", ".", "parse", "(", "response", ".", "response_body", ")", "end", "request", ".", "run", "res", "[", "'data'", "]", "end" ]
retrieves the attributes of the gav
[ "retrieves", "the", "attributes", "of", "the", "gav" ]
26b07e1478dd129f80bf145bf3db0f8219b12bda
https://github.com/logicminds/nexus-client/blob/26b07e1478dd129f80bf145bf3db0f8219b12bda/lib/nexus_client.rb#L80-L96
train
logicminds/nexus-client
lib/nexus_client.rb
Nexus.Client.sha
def sha(file, use_sha_file=false) if use_sha_file and File.exists?("#{file}.sha1") # reading the file is faster than doing a hash, so we keep the hash in the file # then we read back and compare. There is no reason to perform sha1 everytime 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 end
ruby
def sha(file, use_sha_file=false) if use_sha_file and File.exists?("#{file}.sha1") # reading the file is faster than doing a hash, so we keep the hash in the file # then we read back and compare. There is no reason to perform sha1 everytime 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 end
[ "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", "end" ]
returns the sha1 of the file
[ "returns", "the", "sha1", "of", "the", "file" ]
26b07e1478dd129f80bf145bf3db0f8219b12bda
https://github.com/logicminds/nexus-client/blob/26b07e1478dd129f80bf145bf3db0f8219b12bda/lib/nexus_client.rb#L99-L111
train
logicminds/nexus-client
lib/nexus_client.rb
Nexus.Client.sha_match?
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
ruby
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
[ "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
[ "sha_match?", "returns", "bool", "by", "comparing", "the", "sha1", "of", "the", "nexus", "gav", "artifact", "and", "the", "local", "file" ]
26b07e1478dd129f80bf145bf3db0f8219b12bda
https://github.com/logicminds/nexus-client/blob/26b07e1478dd129f80bf145bf3db0f8219b12bda/lib/nexus_client.rb#L114-L123
train
logicminds/nexus-client
lib/nexus_client.rb
Nexus.Client.write_sha1
def write_sha1(file,sha1) shafile = "#{file}.sha1" File.open(shafile, 'w') { |f| f.write(sha1) } end
ruby
def write_sha1(file,sha1) shafile = "#{file}.sha1" File.open(shafile, 'w') { |f| f.write(sha1) } end
[ "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
[ "writes", "the", "sha1", "a", "file", "if", "and", "only", "if", "the", "contents", "of", "the", "file", "do", "not", "match" ]
26b07e1478dd129f80bf145bf3db0f8219b12bda
https://github.com/logicminds/nexus-client/blob/26b07e1478dd129f80bf145bf3db0f8219b12bda/lib/nexus_client.rb#L128-L131
train
MaximeD/gem_updater
lib/gem_updater/source_page_parser.rb
GemUpdater.SourcePageParser.known_https
def known_https(uri) case uri.host when HOSTS[:github] # remove possible subdomain like 'wiki.github.com' 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
ruby
def known_https(uri) case uri.host when HOSTS[:github] # remove possible subdomain like 'wiki.github.com' 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
[ "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 @param uri [URI::HTTP] @return [URI::HTTPS|URI::HTTP]
[ "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" ]
910d30b544ad12fd31b7de831355c65ab423db8a
https://github.com/MaximeD/gem_updater/blob/910d30b544ad12fd31b7de831355c65ab423db8a/lib/gem_updater/source_page_parser.rb#L66-L78
train
MaximeD/gem_updater
lib/gem_updater/source_page_parser.rb
GemUpdater.SourcePageParser.changelog_names
def changelog_names CHANGELOG_NAMES.flat_map do |name| [name, name.upcase, name.capitalize] end.uniq end
ruby
def changelog_names CHANGELOG_NAMES.flat_map do |name| [name, name.upcase, name.capitalize] end.uniq end
[ "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. @return [Array] list of possible names
[ "List", "possible", "names", "for", "a", "changelog", "since", "humans", "may", "have", "many", "many", "ways", "to", "call", "it", "." ]
910d30b544ad12fd31b7de831355c65ab423db8a
https://github.com/MaximeD/gem_updater/blob/910d30b544ad12fd31b7de831355c65ab423db8a/lib/gem_updater/source_page_parser.rb#L94-L98
train
dewski/kss-rails
app/helpers/kss/application_helper.rb
Kss.ApplicationHelper.styleguide_block
def styleguide_block(section, &block) raise ArgumentError, "Missing block" unless block_given? @section = styleguide.section(section) if [email protected] raise "KSS styleguide section is nil, is section '#{section}' defined in your css?" end content = capture(&block) render 'kss/shared/styleguide_block', :section => @section, :example_html => content end
ruby
def styleguide_block(section, &block) raise ArgumentError, "Missing block" unless block_given? @section = styleguide.section(section) if [email protected] raise "KSS styleguide section is nil, is section '#{section}' defined in your css?" end content = capture(&block) render 'kss/shared/styleguide_block', :section => @section, :example_html => content end
[ "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'", ",", ":section", "=>", "@section", ",", ":example_html", "=>", "content", "end" ]
Generates a styleguide block. A little bit evil with @_out_buf, but if you're using something like Rails, you can write a much cleaner helper very easily.
[ "Generates", "a", "styleguide", "block", ".", "A", "little", "bit", "evil", "with" ]
3bec7e1a0e14b771bc2eeed10474f74ba34a03ed
https://github.com/dewski/kss-rails/blob/3bec7e1a0e14b771bc2eeed10474f74ba34a03ed/app/helpers/kss/application_helper.rb#L6-L17
train
mikamai/akamai_api
lib/akamai_api/eccu/soap_body.rb
AkamaiApi::ECCU.SoapBody.array
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
ruby
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
[ "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 @param [String] name argument name @param [Array] values @return [SoapBody]
[ "Appends", "an", "argument", "of", "type", "array" ]
a6bc1369e118bb298c71019c9788e5c9bd1753c8
https://github.com/mikamai/akamai_api/blob/a6bc1369e118bb298c71019c9788e5c9bd1753c8/lib/akamai_api/eccu/soap_body.rb#L82-L91
train