id
int32 0
24.9k
| 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
|
---|---|---|---|---|---|---|---|---|---|---|---|
2,200 | jeffwilliams/quartz-torrent | lib/quartz_torrent/reactor.rb | QuartzTorrent.Reactor.withReadFiber | def withReadFiber(ioInfo)
if ioInfo.readFiber.nil? || ! ioInfo.readFiber.alive?
ioInfo.readFiber = Fiber.new do |ioInfo|
yield ioInfo.readFiberIoFacade
end
end
# Allow handler to read some data.
# This call will return either if:
# 1. the handler needs more data but it isn't available yet,
# 2. if it's read all the data it wanted to read for the current message it's building
# 3. if a read error occurred.
#
# In case 2 the latter case the fiber will be dead. In cases 1 and 2, we should select on the socket
# until data is ready. For case 3, the state of the ioInfo is set to error and the io should be
# removed.
ioInfo.readFiber.resume(ioInfo)
if ioInfo.state == :error
@currentHandlerCallback = :error
@handler.error(ioInfo.metainfo, ioInfo.lastReadError)
disposeIo(ioInfo)
end
end | ruby | def withReadFiber(ioInfo)
if ioInfo.readFiber.nil? || ! ioInfo.readFiber.alive?
ioInfo.readFiber = Fiber.new do |ioInfo|
yield ioInfo.readFiberIoFacade
end
end
# Allow handler to read some data.
# This call will return either if:
# 1. the handler needs more data but it isn't available yet,
# 2. if it's read all the data it wanted to read for the current message it's building
# 3. if a read error occurred.
#
# In case 2 the latter case the fiber will be dead. In cases 1 and 2, we should select on the socket
# until data is ready. For case 3, the state of the ioInfo is set to error and the io should be
# removed.
ioInfo.readFiber.resume(ioInfo)
if ioInfo.state == :error
@currentHandlerCallback = :error
@handler.error(ioInfo.metainfo, ioInfo.lastReadError)
disposeIo(ioInfo)
end
end | [
"def",
"withReadFiber",
"(",
"ioInfo",
")",
"if",
"ioInfo",
".",
"readFiber",
".",
"nil?",
"||",
"!",
"ioInfo",
".",
"readFiber",
".",
"alive?",
"ioInfo",
".",
"readFiber",
"=",
"Fiber",
".",
"new",
"do",
"|",
"ioInfo",
"|",
"yield",
"ioInfo",
".",
"readFiberIoFacade",
"end",
"end",
"# Allow handler to read some data.",
"# This call will return either if:",
"# 1. the handler needs more data but it isn't available yet,",
"# 2. if it's read all the data it wanted to read for the current message it's building",
"# 3. if a read error occurred.",
"#",
"# In case 2 the latter case the fiber will be dead. In cases 1 and 2, we should select on the socket",
"# until data is ready. For case 3, the state of the ioInfo is set to error and the io should be ",
"# removed. ",
"ioInfo",
".",
"readFiber",
".",
"resume",
"(",
"ioInfo",
")",
"if",
"ioInfo",
".",
"state",
"==",
":error",
"@currentHandlerCallback",
"=",
":error",
"@handler",
".",
"error",
"(",
"ioInfo",
".",
"metainfo",
",",
"ioInfo",
".",
"lastReadError",
")",
"disposeIo",
"(",
"ioInfo",
")",
"end",
"end"
] | Call the passed block in the context of the read Fiber. Basically the
passed block is run as normal, but if the block performs a read from an io and that
read would block, the block is paused, and withReadFiber returns. The next time withReadFiber
is called the block will be resumed at the point of the read. | [
"Call",
"the",
"passed",
"block",
"in",
"the",
"context",
"of",
"the",
"read",
"Fiber",
".",
"Basically",
"the",
"passed",
"block",
"is",
"run",
"as",
"normal",
"but",
"if",
"the",
"block",
"performs",
"a",
"read",
"from",
"an",
"io",
"and",
"that",
"read",
"would",
"block",
"the",
"block",
"is",
"paused",
"and",
"withReadFiber",
"returns",
".",
"The",
"next",
"time",
"withReadFiber",
"is",
"called",
"the",
"block",
"will",
"be",
"resumed",
"at",
"the",
"point",
"of",
"the",
"read",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/reactor.rb#L856-L879 |
2,201 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peermanager.rb | QuartzTorrent.PeerManager.manageConnections | def manageConnections(classifiedPeers)
n = classifiedPeers.handshakingPeers.size + classifiedPeers.establishedPeers.size
if n < @targetActivePeerCount
result = classifiedPeers.disconnectedPeers.shuffle.first(@targetActivePeerCount - n)
@logger.debug "There are #{n} peers connected or in handshaking. Will establish #{result.size} more connections to peers."
result
else
[]
end
end | ruby | def manageConnections(classifiedPeers)
n = classifiedPeers.handshakingPeers.size + classifiedPeers.establishedPeers.size
if n < @targetActivePeerCount
result = classifiedPeers.disconnectedPeers.shuffle.first(@targetActivePeerCount - n)
@logger.debug "There are #{n} peers connected or in handshaking. Will establish #{result.size} more connections to peers."
result
else
[]
end
end | [
"def",
"manageConnections",
"(",
"classifiedPeers",
")",
"n",
"=",
"classifiedPeers",
".",
"handshakingPeers",
".",
"size",
"+",
"classifiedPeers",
".",
"establishedPeers",
".",
"size",
"if",
"n",
"<",
"@targetActivePeerCount",
"result",
"=",
"classifiedPeers",
".",
"disconnectedPeers",
".",
"shuffle",
".",
"first",
"(",
"@targetActivePeerCount",
"-",
"n",
")",
"@logger",
".",
"debug",
"\"There are #{n} peers connected or in handshaking. Will establish #{result.size} more connections to peers.\"",
"result",
"else",
"[",
"]",
"end",
"end"
] | Determine if we need to connect to more peers.
Returns a list of peers to connect to. | [
"Determine",
"if",
"we",
"need",
"to",
"connect",
"to",
"more",
"peers",
".",
"Returns",
"a",
"list",
"of",
"peers",
"to",
"connect",
"to",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peermanager.rb#L46-L56 |
2,202 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peermanager.rb | QuartzTorrent.PeerManager.selectOptimisticPeer | def selectOptimisticPeer(classifiedPeers)
# "at any one time there is a single peer which is unchoked regardless of its upload rate (if interested, it counts as one of the four allowed downloaders). Which peer is optimistically
# unchoked rotates every 30 seconds. Newly connected peers are three times as likely to start as the current optimistic unchoke as anywhere else in the rotation. This gives them a decent chance
# of getting a complete piece to upload."
if !@lastOptimisticPeerChangeTime || (Time.new - @lastOptimisticPeerChangeTime > @optimisticPeerChangeDuration)
list = []
classifiedPeers.establishedPeers.each do |peer|
if (Time.new - peer.firstEstablishTime) < @newlyConnectedDuration
3.times{ list.push peer }
else
list.push peer
end
end
@optimisticUnchokePeer = list[rand(list.size)]
if @optimisticUnchokePeer
@logger.info "Optimistically unchoked peer set to #{@optimisticUnchokePeer.trackerPeer}"
@lastOptimisticPeerChangeTime = Time.new
end
end
end | ruby | def selectOptimisticPeer(classifiedPeers)
# "at any one time there is a single peer which is unchoked regardless of its upload rate (if interested, it counts as one of the four allowed downloaders). Which peer is optimistically
# unchoked rotates every 30 seconds. Newly connected peers are three times as likely to start as the current optimistic unchoke as anywhere else in the rotation. This gives them a decent chance
# of getting a complete piece to upload."
if !@lastOptimisticPeerChangeTime || (Time.new - @lastOptimisticPeerChangeTime > @optimisticPeerChangeDuration)
list = []
classifiedPeers.establishedPeers.each do |peer|
if (Time.new - peer.firstEstablishTime) < @newlyConnectedDuration
3.times{ list.push peer }
else
list.push peer
end
end
@optimisticUnchokePeer = list[rand(list.size)]
if @optimisticUnchokePeer
@logger.info "Optimistically unchoked peer set to #{@optimisticUnchokePeer.trackerPeer}"
@lastOptimisticPeerChangeTime = Time.new
end
end
end | [
"def",
"selectOptimisticPeer",
"(",
"classifiedPeers",
")",
"# \"at any one time there is a single peer which is unchoked regardless of its upload rate (if interested, it counts as one of the four allowed downloaders). Which peer is optimistically ",
"# unchoked rotates every 30 seconds. Newly connected peers are three times as likely to start as the current optimistic unchoke as anywhere else in the rotation. This gives them a decent chance ",
"# of getting a complete piece to upload.\"",
"if",
"!",
"@lastOptimisticPeerChangeTime",
"||",
"(",
"Time",
".",
"new",
"-",
"@lastOptimisticPeerChangeTime",
">",
"@optimisticPeerChangeDuration",
")",
"list",
"=",
"[",
"]",
"classifiedPeers",
".",
"establishedPeers",
".",
"each",
"do",
"|",
"peer",
"|",
"if",
"(",
"Time",
".",
"new",
"-",
"peer",
".",
"firstEstablishTime",
")",
"<",
"@newlyConnectedDuration",
"3",
".",
"times",
"{",
"list",
".",
"push",
"peer",
"}",
"else",
"list",
".",
"push",
"peer",
"end",
"end",
"@optimisticUnchokePeer",
"=",
"list",
"[",
"rand",
"(",
"list",
".",
"size",
")",
"]",
"if",
"@optimisticUnchokePeer",
"@logger",
".",
"info",
"\"Optimistically unchoked peer set to #{@optimisticUnchokePeer.trackerPeer}\"",
"@lastOptimisticPeerChangeTime",
"=",
"Time",
".",
"new",
"end",
"end",
"end"
] | Choose a peer that we will optimistically unchoke. | [
"Choose",
"a",
"peer",
"that",
"we",
"will",
"optimistically",
"unchoke",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peermanager.rb#L148-L168 |
2,203 | rjurado01/rapidoc | lib/rapidoc/controller_extractor.rb | Rapidoc.ControllerExtractor.extract_blocks | def extract_blocks( lines )
init_doc_lines = lines.each_index.select{ |i| lines[i].include? "=begin" }
end_doc_lines = lines.each_index.select{ |i| lines[i].include? "=end" }
blocks = init_doc_lines.each_index.map do |i|
{ :init => init_doc_lines[i], :end => end_doc_lines[i] }
end
end | ruby | def extract_blocks( lines )
init_doc_lines = lines.each_index.select{ |i| lines[i].include? "=begin" }
end_doc_lines = lines.each_index.select{ |i| lines[i].include? "=end" }
blocks = init_doc_lines.each_index.map do |i|
{ :init => init_doc_lines[i], :end => end_doc_lines[i] }
end
end | [
"def",
"extract_blocks",
"(",
"lines",
")",
"init_doc_lines",
"=",
"lines",
".",
"each_index",
".",
"select",
"{",
"|",
"i",
"|",
"lines",
"[",
"i",
"]",
".",
"include?",
"\"=begin\"",
"}",
"end_doc_lines",
"=",
"lines",
".",
"each_index",
".",
"select",
"{",
"|",
"i",
"|",
"lines",
"[",
"i",
"]",
".",
"include?",
"\"=end\"",
"}",
"blocks",
"=",
"init_doc_lines",
".",
"each_index",
".",
"map",
"do",
"|",
"i",
"|",
"{",
":init",
"=>",
"init_doc_lines",
"[",
"i",
"]",
",",
":end",
"=>",
"end_doc_lines",
"[",
"i",
"]",
"}",
"end",
"end"
] | Gets init and end lines of each comment block | [
"Gets",
"init",
"and",
"end",
"lines",
"of",
"each",
"comment",
"block"
] | 03b7a8f29a37dd03f4ed5036697b48551d3b4ae6 | https://github.com/rjurado01/rapidoc/blob/03b7a8f29a37dd03f4ed5036697b48551d3b4ae6/lib/rapidoc/controller_extractor.rb#L45-L52 |
2,204 | merqlove/do_snapshot | lib/do_snapshot/command.rb | DoSnapshot.Command.create_snapshot | def create_snapshot(droplet) # rubocop:disable MethodLength,Metrics/AbcSize
fail_if_shutdown(droplet)
logger.info "Start creating snapshot for droplet id: #{droplet.id} name: #{droplet.name}."
today = DateTime.now
name = "#{droplet.name}_#{today.strftime('%Y_%m_%d')}"
# noinspection RubyResolve
snapshot_size = api.snapshots(droplet).size
logger.debug 'Wait until snapshot will be created.'
api.create_snapshot droplet.id, name
snapshot_size += 1
logger.info "Snapshot name: #{name} created successfully."
logger.info "Droplet id: #{droplet.id} name: #{droplet.name} snapshots: #{snapshot_size}."
# Cleanup snapshots.
cleanup_snapshots droplet, snapshot_size if clean
rescue => e
case e.class.to_s
when 'DoSnapshot::SnapshotCleanupError'
raise e.class, e.message, e.backtrace
when 'DoSnapshot::DropletPowerError'
return
else
raise SnapshotCreateError.new(droplet.id), e.message, e.backtrace
end
end | ruby | def create_snapshot(droplet) # rubocop:disable MethodLength,Metrics/AbcSize
fail_if_shutdown(droplet)
logger.info "Start creating snapshot for droplet id: #{droplet.id} name: #{droplet.name}."
today = DateTime.now
name = "#{droplet.name}_#{today.strftime('%Y_%m_%d')}"
# noinspection RubyResolve
snapshot_size = api.snapshots(droplet).size
logger.debug 'Wait until snapshot will be created.'
api.create_snapshot droplet.id, name
snapshot_size += 1
logger.info "Snapshot name: #{name} created successfully."
logger.info "Droplet id: #{droplet.id} name: #{droplet.name} snapshots: #{snapshot_size}."
# Cleanup snapshots.
cleanup_snapshots droplet, snapshot_size if clean
rescue => e
case e.class.to_s
when 'DoSnapshot::SnapshotCleanupError'
raise e.class, e.message, e.backtrace
when 'DoSnapshot::DropletPowerError'
return
else
raise SnapshotCreateError.new(droplet.id), e.message, e.backtrace
end
end | [
"def",
"create_snapshot",
"(",
"droplet",
")",
"# rubocop:disable MethodLength,Metrics/AbcSize",
"fail_if_shutdown",
"(",
"droplet",
")",
"logger",
".",
"info",
"\"Start creating snapshot for droplet id: #{droplet.id} name: #{droplet.name}.\"",
"today",
"=",
"DateTime",
".",
"now",
"name",
"=",
"\"#{droplet.name}_#{today.strftime('%Y_%m_%d')}\"",
"# noinspection RubyResolve",
"snapshot_size",
"=",
"api",
".",
"snapshots",
"(",
"droplet",
")",
".",
"size",
"logger",
".",
"debug",
"'Wait until snapshot will be created.'",
"api",
".",
"create_snapshot",
"droplet",
".",
"id",
",",
"name",
"snapshot_size",
"+=",
"1",
"logger",
".",
"info",
"\"Snapshot name: #{name} created successfully.\"",
"logger",
".",
"info",
"\"Droplet id: #{droplet.id} name: #{droplet.name} snapshots: #{snapshot_size}.\"",
"# Cleanup snapshots.",
"cleanup_snapshots",
"droplet",
",",
"snapshot_size",
"if",
"clean",
"rescue",
"=>",
"e",
"case",
"e",
".",
"class",
".",
"to_s",
"when",
"'DoSnapshot::SnapshotCleanupError'",
"raise",
"e",
".",
"class",
",",
"e",
".",
"message",
",",
"e",
".",
"backtrace",
"when",
"'DoSnapshot::DropletPowerError'",
"return",
"else",
"raise",
"SnapshotCreateError",
".",
"new",
"(",
"droplet",
".",
"id",
")",
",",
"e",
".",
"message",
",",
"e",
".",
"backtrace",
"end",
"end"
] | Trying to create a snapshot. | [
"Trying",
"to",
"create",
"a",
"snapshot",
"."
] | a72212ca489973a64987f0e9eb4abaae57de1abe | https://github.com/merqlove/do_snapshot/blob/a72212ca489973a64987f0e9eb4abaae57de1abe/lib/do_snapshot/command.rb#L61-L91 |
2,205 | merqlove/do_snapshot | lib/do_snapshot/command.rb | DoSnapshot.Command.dispatch_droplets | def dispatch_droplets
droplets.each do |droplet|
id = droplet.id.to_s
next if exclude.include? id
next unless only.empty? || only.include?(id)
prepare_droplet id, droplet.name
end
end | ruby | def dispatch_droplets
droplets.each do |droplet|
id = droplet.id.to_s
next if exclude.include? id
next unless only.empty? || only.include?(id)
prepare_droplet id, droplet.name
end
end | [
"def",
"dispatch_droplets",
"droplets",
".",
"each",
"do",
"|",
"droplet",
"|",
"id",
"=",
"droplet",
".",
"id",
".",
"to_s",
"next",
"if",
"exclude",
".",
"include?",
"id",
"next",
"unless",
"only",
".",
"empty?",
"||",
"only",
".",
"include?",
"(",
"id",
")",
"prepare_droplet",
"id",
",",
"droplet",
".",
"name",
"end",
"end"
] | Dispatch received droplets, each by each. | [
"Dispatch",
"received",
"droplets",
"each",
"by",
"each",
"."
] | a72212ca489973a64987f0e9eb4abaae57de1abe | https://github.com/merqlove/do_snapshot/blob/a72212ca489973a64987f0e9eb4abaae57de1abe/lib/do_snapshot/command.rb#L149-L157 |
2,206 | merqlove/do_snapshot | lib/do_snapshot/command.rb | DoSnapshot.Command.prepare_droplet | def prepare_droplet(id, name)
logger.debug "Droplet id: #{id} name: #{name}\n"
droplet = api.droplet id
return unless droplet
logger.info "Preparing droplet id: #{droplet.id} name: #{droplet.name} to take snapshot."
return if too_much_snapshots?(droplet)
processed_droplet_ids << droplet.id
thread_runner(droplet)
end | ruby | def prepare_droplet(id, name)
logger.debug "Droplet id: #{id} name: #{name}\n"
droplet = api.droplet id
return unless droplet
logger.info "Preparing droplet id: #{droplet.id} name: #{droplet.name} to take snapshot."
return if too_much_snapshots?(droplet)
processed_droplet_ids << droplet.id
thread_runner(droplet)
end | [
"def",
"prepare_droplet",
"(",
"id",
",",
"name",
")",
"logger",
".",
"debug",
"\"Droplet id: #{id} name: #{name}\\n\"",
"droplet",
"=",
"api",
".",
"droplet",
"id",
"return",
"unless",
"droplet",
"logger",
".",
"info",
"\"Preparing droplet id: #{droplet.id} name: #{droplet.name} to take snapshot.\"",
"return",
"if",
"too_much_snapshots?",
"(",
"droplet",
")",
"processed_droplet_ids",
"<<",
"droplet",
".",
"id",
"thread_runner",
"(",
"droplet",
")",
"end"
] | Preparing droplet to take a snapshot.
Droplet instance must be powered off first! | [
"Preparing",
"droplet",
"to",
"take",
"a",
"snapshot",
".",
"Droplet",
"instance",
"must",
"be",
"powered",
"off",
"first!"
] | a72212ca489973a64987f0e9eb4abaae57de1abe | https://github.com/merqlove/do_snapshot/blob/a72212ca489973a64987f0e9eb4abaae57de1abe/lib/do_snapshot/command.rb#L176-L185 |
2,207 | merqlove/do_snapshot | lib/do_snapshot/command.rb | DoSnapshot.Command.cleanup_snapshots | def cleanup_snapshots(droplet, size) # rubocop:disable Metrics/AbcSize
return unless size > keep
warning_size(droplet.id, droplet.name, size)
logger.debug "Cleaning up snapshots for droplet id: #{droplet.id} name: #{droplet.name}."
api.cleanup_snapshots(droplet, size - keep - 1)
rescue => e
raise SnapshotCleanupError, e.message, e.backtrace
end | ruby | def cleanup_snapshots(droplet, size) # rubocop:disable Metrics/AbcSize
return unless size > keep
warning_size(droplet.id, droplet.name, size)
logger.debug "Cleaning up snapshots for droplet id: #{droplet.id} name: #{droplet.name}."
api.cleanup_snapshots(droplet, size - keep - 1)
rescue => e
raise SnapshotCleanupError, e.message, e.backtrace
end | [
"def",
"cleanup_snapshots",
"(",
"droplet",
",",
"size",
")",
"# rubocop:disable Metrics/AbcSize",
"return",
"unless",
"size",
">",
"keep",
"warning_size",
"(",
"droplet",
".",
"id",
",",
"droplet",
".",
"name",
",",
"size",
")",
"logger",
".",
"debug",
"\"Cleaning up snapshots for droplet id: #{droplet.id} name: #{droplet.name}.\"",
"api",
".",
"cleanup_snapshots",
"(",
"droplet",
",",
"size",
"-",
"keep",
"-",
"1",
")",
"rescue",
"=>",
"e",
"raise",
"SnapshotCleanupError",
",",
"e",
".",
"message",
",",
"e",
".",
"backtrace",
"end"
] | Cleanup our snapshots. | [
"Cleanup",
"our",
"snapshots",
"."
] | a72212ca489973a64987f0e9eb4abaae57de1abe | https://github.com/merqlove/do_snapshot/blob/a72212ca489973a64987f0e9eb4abaae57de1abe/lib/do_snapshot/command.rb#L200-L210 |
2,208 | philm/twilio | lib/twilio/available_phone_numbers.rb | Twilio.AvailablePhoneNumbers.search | def search(opts={})
iso_country_code = opts[:iso_country_code] || 'US'
resource = opts.delete(:resource)
params = {
:AreaCode => opts[:area_code],
:InPostalCode => opts[:postal_code],
:InRegion => opts[:in_region],
:Contains => opts[:contains],
:NearLatLong => opts[:near_lat_long],
:NearNumber => opts[:near_number],
:InLata => opts[:in_lata],
:InRateCenter => opts[:in_rate_center],
:Distance => opts[:distance],
:Page => opts[:page],
:PageSize => opts[:page_size]
}.reject {|k,v| v == nil} unless opts.empty?
Twilio.get("/AvailablePhoneNumbers/#{iso_country_code}/#{resource}", :query => params)
end | ruby | def search(opts={})
iso_country_code = opts[:iso_country_code] || 'US'
resource = opts.delete(:resource)
params = {
:AreaCode => opts[:area_code],
:InPostalCode => opts[:postal_code],
:InRegion => opts[:in_region],
:Contains => opts[:contains],
:NearLatLong => opts[:near_lat_long],
:NearNumber => opts[:near_number],
:InLata => opts[:in_lata],
:InRateCenter => opts[:in_rate_center],
:Distance => opts[:distance],
:Page => opts[:page],
:PageSize => opts[:page_size]
}.reject {|k,v| v == nil} unless opts.empty?
Twilio.get("/AvailablePhoneNumbers/#{iso_country_code}/#{resource}", :query => params)
end | [
"def",
"search",
"(",
"opts",
"=",
"{",
"}",
")",
"iso_country_code",
"=",
"opts",
"[",
":iso_country_code",
"]",
"||",
"'US'",
"resource",
"=",
"opts",
".",
"delete",
"(",
":resource",
")",
"params",
"=",
"{",
":AreaCode",
"=>",
"opts",
"[",
":area_code",
"]",
",",
":InPostalCode",
"=>",
"opts",
"[",
":postal_code",
"]",
",",
":InRegion",
"=>",
"opts",
"[",
":in_region",
"]",
",",
":Contains",
"=>",
"opts",
"[",
":contains",
"]",
",",
":NearLatLong",
"=>",
"opts",
"[",
":near_lat_long",
"]",
",",
":NearNumber",
"=>",
"opts",
"[",
":near_number",
"]",
",",
":InLata",
"=>",
"opts",
"[",
":in_lata",
"]",
",",
":InRateCenter",
"=>",
"opts",
"[",
":in_rate_center",
"]",
",",
":Distance",
"=>",
"opts",
"[",
":distance",
"]",
",",
":Page",
"=>",
"opts",
"[",
":page",
"]",
",",
":PageSize",
"=>",
"opts",
"[",
":page_size",
"]",
"}",
".",
"reject",
"{",
"|",
"k",
",",
"v",
"|",
"v",
"==",
"nil",
"}",
"unless",
"opts",
".",
"empty?",
"Twilio",
".",
"get",
"(",
"\"/AvailablePhoneNumbers/#{iso_country_code}/#{resource}\"",
",",
":query",
"=>",
"params",
")",
"end"
] | The Search method handles the searching of both local and toll-free
numbers. | [
"The",
"Search",
"method",
"handles",
"the",
"searching",
"of",
"both",
"local",
"and",
"toll",
"-",
"free",
"numbers",
"."
] | 81c05795924bbfa780ea44efd52d7ca5670bcb55 | https://github.com/philm/twilio/blob/81c05795924bbfa780ea44efd52d7ca5670bcb55/lib/twilio/available_phone_numbers.rb#L12-L31 |
2,209 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClientHandler.addTrackerClient | def addTrackerClient(infoHash, info, trackerclient)
raise "There is already a tracker registered for torrent #{QuartzTorrent.bytesToHex(infoHash)}" if @torrentData.has_key? infoHash
torrentData = TorrentData.new(infoHash, info, trackerclient)
trackerclient.alarms = torrentData.alarms
@torrentData[infoHash] = torrentData
torrentData.info = info
torrentData.state = :initializing
queue(torrentData)
dequeue
torrentData
end | ruby | def addTrackerClient(infoHash, info, trackerclient)
raise "There is already a tracker registered for torrent #{QuartzTorrent.bytesToHex(infoHash)}" if @torrentData.has_key? infoHash
torrentData = TorrentData.new(infoHash, info, trackerclient)
trackerclient.alarms = torrentData.alarms
@torrentData[infoHash] = torrentData
torrentData.info = info
torrentData.state = :initializing
queue(torrentData)
dequeue
torrentData
end | [
"def",
"addTrackerClient",
"(",
"infoHash",
",",
"info",
",",
"trackerclient",
")",
"raise",
"\"There is already a tracker registered for torrent #{QuartzTorrent.bytesToHex(infoHash)}\"",
"if",
"@torrentData",
".",
"has_key?",
"infoHash",
"torrentData",
"=",
"TorrentData",
".",
"new",
"(",
"infoHash",
",",
"info",
",",
"trackerclient",
")",
"trackerclient",
".",
"alarms",
"=",
"torrentData",
".",
"alarms",
"@torrentData",
"[",
"infoHash",
"]",
"=",
"torrentData",
"torrentData",
".",
"info",
"=",
"info",
"torrentData",
".",
"state",
"=",
":initializing",
"queue",
"(",
"torrentData",
")",
"dequeue",
"torrentData",
"end"
] | Add a new tracker client. This effectively adds a new torrent to download. Returns the TorrentData object for the
new torrent. | [
"Add",
"a",
"new",
"tracker",
"client",
".",
"This",
"effectively",
"adds",
"a",
"new",
"torrent",
"to",
"download",
".",
"Returns",
"the",
"TorrentData",
"object",
"for",
"the",
"new",
"torrent",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L286-L298 |
2,210 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClientHandler.removeTorrent | def removeTorrent(infoHash, deleteFiles = false)
# Can't do this right now, since it could be in use by an event handler. Use an immediate, non-recurring timer instead.
@logger.info "#{QuartzTorrent.bytesToHex(infoHash)}: Scheduling immediate timer to remove torrent. #{deleteFiles ? "Will" : "Wont"} delete downloaded files."
@reactor.scheduleTimer(0, [:removetorrent, infoHash, deleteFiles], false, true)
end | ruby | def removeTorrent(infoHash, deleteFiles = false)
# Can't do this right now, since it could be in use by an event handler. Use an immediate, non-recurring timer instead.
@logger.info "#{QuartzTorrent.bytesToHex(infoHash)}: Scheduling immediate timer to remove torrent. #{deleteFiles ? "Will" : "Wont"} delete downloaded files."
@reactor.scheduleTimer(0, [:removetorrent, infoHash, deleteFiles], false, true)
end | [
"def",
"removeTorrent",
"(",
"infoHash",
",",
"deleteFiles",
"=",
"false",
")",
"# Can't do this right now, since it could be in use by an event handler. Use an immediate, non-recurring timer instead.",
"@logger",
".",
"info",
"\"#{QuartzTorrent.bytesToHex(infoHash)}: Scheduling immediate timer to remove torrent. #{deleteFiles ? \"Will\" : \"Wont\"} delete downloaded files.\"",
"@reactor",
".",
"scheduleTimer",
"(",
"0",
",",
"[",
":removetorrent",
",",
"infoHash",
",",
"deleteFiles",
"]",
",",
"false",
",",
"true",
")",
"end"
] | Remove a torrent. | [
"Remove",
"a",
"torrent",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L301-L305 |
2,211 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClientHandler.setDownloadRateLimit | def setDownloadRateLimit(infoHash, bytesPerSecond)
torrentData = @torrentData[infoHash]
if ! torrentData
@logger.warn "Asked to set download rate limit for a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}"
return
end
if bytesPerSecond
if ! torrentData.downRateLimit
torrentData.downRateLimit = RateLimit.new(bytesPerSecond, 2*bytesPerSecond, 0)
else
torrentData.downRateLimit.unitsPerSecond = bytesPerSecond
end
else
torrentData.downRateLimit = nil
end
torrentData.peers.all.each do |peer|
withPeersIo(peer, "setting download rate limit") do |io|
io.readRateLimit = torrentData.downRateLimit
end
end
end | ruby | def setDownloadRateLimit(infoHash, bytesPerSecond)
torrentData = @torrentData[infoHash]
if ! torrentData
@logger.warn "Asked to set download rate limit for a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}"
return
end
if bytesPerSecond
if ! torrentData.downRateLimit
torrentData.downRateLimit = RateLimit.new(bytesPerSecond, 2*bytesPerSecond, 0)
else
torrentData.downRateLimit.unitsPerSecond = bytesPerSecond
end
else
torrentData.downRateLimit = nil
end
torrentData.peers.all.each do |peer|
withPeersIo(peer, "setting download rate limit") do |io|
io.readRateLimit = torrentData.downRateLimit
end
end
end | [
"def",
"setDownloadRateLimit",
"(",
"infoHash",
",",
"bytesPerSecond",
")",
"torrentData",
"=",
"@torrentData",
"[",
"infoHash",
"]",
"if",
"!",
"torrentData",
"@logger",
".",
"warn",
"\"Asked to set download rate limit for a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}\"",
"return",
"end",
"if",
"bytesPerSecond",
"if",
"!",
"torrentData",
".",
"downRateLimit",
"torrentData",
".",
"downRateLimit",
"=",
"RateLimit",
".",
"new",
"(",
"bytesPerSecond",
",",
"2",
"*",
"bytesPerSecond",
",",
"0",
")",
"else",
"torrentData",
".",
"downRateLimit",
".",
"unitsPerSecond",
"=",
"bytesPerSecond",
"end",
"else",
"torrentData",
".",
"downRateLimit",
"=",
"nil",
"end",
"torrentData",
".",
"peers",
".",
"all",
".",
"each",
"do",
"|",
"peer",
"|",
"withPeersIo",
"(",
"peer",
",",
"\"setting download rate limit\"",
")",
"do",
"|",
"io",
"|",
"io",
".",
"readRateLimit",
"=",
"torrentData",
".",
"downRateLimit",
"end",
"end",
"end"
] | Set the download rate limit. Pass nil as the bytesPerSecond to disable the limit. | [
"Set",
"the",
"download",
"rate",
"limit",
".",
"Pass",
"nil",
"as",
"the",
"bytesPerSecond",
"to",
"disable",
"the",
"limit",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L315-L338 |
2,212 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClientHandler.setUploadRateLimit | def setUploadRateLimit(infoHash, bytesPerSecond)
torrentData = @torrentData[infoHash]
if ! torrentData
@logger.warn "Asked to set upload rate limit for a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}"
return
end
if bytesPerSecond
if ! torrentData.upRateLimit
torrentData.upRateLimit = RateLimit.new(bytesPerSecond, 2*bytesPerSecond, 0)
else
torrentData.upRateLimit.unitsPerSecond = bytesPerSecond
end
else
torrentData.upRateLimit = nil
end
torrentData.peers.all.each do |peer|
withPeersIo(peer, "setting upload rate limit") do |io|
io.writeRateLimit = torrentData.upRateLimit
end
end
end | ruby | def setUploadRateLimit(infoHash, bytesPerSecond)
torrentData = @torrentData[infoHash]
if ! torrentData
@logger.warn "Asked to set upload rate limit for a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}"
return
end
if bytesPerSecond
if ! torrentData.upRateLimit
torrentData.upRateLimit = RateLimit.new(bytesPerSecond, 2*bytesPerSecond, 0)
else
torrentData.upRateLimit.unitsPerSecond = bytesPerSecond
end
else
torrentData.upRateLimit = nil
end
torrentData.peers.all.each do |peer|
withPeersIo(peer, "setting upload rate limit") do |io|
io.writeRateLimit = torrentData.upRateLimit
end
end
end | [
"def",
"setUploadRateLimit",
"(",
"infoHash",
",",
"bytesPerSecond",
")",
"torrentData",
"=",
"@torrentData",
"[",
"infoHash",
"]",
"if",
"!",
"torrentData",
"@logger",
".",
"warn",
"\"Asked to set upload rate limit for a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}\"",
"return",
"end",
"if",
"bytesPerSecond",
"if",
"!",
"torrentData",
".",
"upRateLimit",
"torrentData",
".",
"upRateLimit",
"=",
"RateLimit",
".",
"new",
"(",
"bytesPerSecond",
",",
"2",
"*",
"bytesPerSecond",
",",
"0",
")",
"else",
"torrentData",
".",
"upRateLimit",
".",
"unitsPerSecond",
"=",
"bytesPerSecond",
"end",
"else",
"torrentData",
".",
"upRateLimit",
"=",
"nil",
"end",
"torrentData",
".",
"peers",
".",
"all",
".",
"each",
"do",
"|",
"peer",
"|",
"withPeersIo",
"(",
"peer",
",",
"\"setting upload rate limit\"",
")",
"do",
"|",
"io",
"|",
"io",
".",
"writeRateLimit",
"=",
"torrentData",
".",
"upRateLimit",
"end",
"end",
"end"
] | Set the upload rate limit. Pass nil as the bytesPerSecond to disable the limit. | [
"Set",
"the",
"upload",
"rate",
"limit",
".",
"Pass",
"nil",
"as",
"the",
"bytesPerSecond",
"to",
"disable",
"the",
"limit",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L341-L363 |
2,213 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClientHandler.adjustBytesDownloaded | def adjustBytesDownloaded(infoHash, adjustment)
torrentData = @torrentData[infoHash]
if ! torrentData
@logger.warn "Asked to adjust uploaded bytes for a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}"
return
end
runInReactorThread do
torrentData.bytesDownloaded += adjustment
torrentData.bytesDownloadedDataOnly += adjustment
end
end | ruby | def adjustBytesDownloaded(infoHash, adjustment)
torrentData = @torrentData[infoHash]
if ! torrentData
@logger.warn "Asked to adjust uploaded bytes for a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}"
return
end
runInReactorThread do
torrentData.bytesDownloaded += adjustment
torrentData.bytesDownloadedDataOnly += adjustment
end
end | [
"def",
"adjustBytesDownloaded",
"(",
"infoHash",
",",
"adjustment",
")",
"torrentData",
"=",
"@torrentData",
"[",
"infoHash",
"]",
"if",
"!",
"torrentData",
"@logger",
".",
"warn",
"\"Asked to adjust uploaded bytes for a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}\"",
"return",
"end",
"runInReactorThread",
"do",
"torrentData",
".",
"bytesDownloaded",
"+=",
"adjustment",
"torrentData",
".",
"bytesDownloadedDataOnly",
"+=",
"adjustment",
"end",
"end"
] | Adjust the bytesDownloaded property of the specified torrent by the passed amount.
Adjustment should be an integer. It is added to the current bytesDownloaded amount. | [
"Adjust",
"the",
"bytesDownloaded",
"property",
"of",
"the",
"specified",
"torrent",
"by",
"the",
"passed",
"amount",
".",
"Adjustment",
"should",
"be",
"an",
"integer",
".",
"It",
"is",
"added",
"to",
"the",
"current",
"bytesDownloaded",
"amount",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L405-L416 |
2,214 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClientHandler.updateDelegateTorrentData | def updateDelegateTorrentData(delegate)
return if stopped?
# Use an immediate, non-recurring timer.
semaphore = Semaphore.new
@reactor.scheduleTimer(0, [:update_torrent_data, delegate, semaphore], false, true)
semaphore.wait
result
end | ruby | def updateDelegateTorrentData(delegate)
return if stopped?
# Use an immediate, non-recurring timer.
semaphore = Semaphore.new
@reactor.scheduleTimer(0, [:update_torrent_data, delegate, semaphore], false, true)
semaphore.wait
result
end | [
"def",
"updateDelegateTorrentData",
"(",
"delegate",
")",
"return",
"if",
"stopped?",
"# Use an immediate, non-recurring timer.",
"semaphore",
"=",
"Semaphore",
".",
"new",
"@reactor",
".",
"scheduleTimer",
"(",
"0",
",",
"[",
":update_torrent_data",
",",
"delegate",
",",
"semaphore",
"]",
",",
"false",
",",
"true",
")",
"semaphore",
".",
"wait",
"result",
"end"
] | Update the data stored in a TorrentDataDelegate to the latest information. | [
"Update",
"the",
"data",
"stored",
"in",
"a",
"TorrentDataDelegate",
"to",
"the",
"latest",
"information",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L438-L445 |
2,215 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClientHandler.serverInit | def serverInit(metadata, addr, port)
# A peer connected to us
# Read handshake message
@logger.warn "Peer connection from #{addr}:#{port}"
begin
msg = PeerHandshake.unserializeExceptPeerIdFrom currentIo
rescue
@logger.warn "Peer failed handshake: #{$!}"
close
return
end
torrentData = torrentDataForHandshake(msg, "#{addr}:#{port}")
# Are we tracking this torrent?
if !torrentData
@logger.warn "Peer sent handshake for unknown torrent"
close
return
end
trackerclient = torrentData.trackerClient
# If we already have too many connections, don't allow this connection.
classifiedPeers = ClassifiedPeers.new torrentData.peers.all
if classifiedPeers.establishedPeers.length > @targetActivePeerCount
@logger.warn "Closing connection to peer from #{addr}:#{port} because we already have #{classifiedPeers.establishedPeers.length} active peers which is > the target count of #{@targetActivePeerCount} "
close
return
end
# Send handshake
outgoing = PeerHandshake.new
outgoing.peerId = trackerclient.peerId
outgoing.infoHash = torrentData.infoHash
outgoing.serializeTo currentIo
# Send extended handshake if the peer supports extensions
if (msg.reserved.unpack("C8")[5] & 0x10) != 0
@logger.warn "Peer supports extensions. Sending extended handshake"
extended = Extension.createExtendedHandshake torrentData.info
extended.serializeTo currentIo
end
# Read incoming handshake's peerid
msg.peerId = currentIo.read(PeerHandshake::PeerIdLen)
if msg.peerId == trackerclient.peerId
@logger.info "We got a connection from ourself. Closing connection."
close
return
end
peer = nil
peers = torrentData.peers.findById(msg.peerId)
if peers
peers.each do |existingPeer|
if existingPeer.state != :disconnected
@logger.warn "Peer with id #{msg.peerId} created a new connection when we already have a connection in state #{existingPeer.state}. Closing new connection."
close
return
else
if existingPeer.trackerPeer.ip == addr && existingPeer.trackerPeer.port == port
peer = existingPeer
end
end
end
end
if ! peer
peer = Peer.new(TrackerPeer.new(addr, port))
updatePeerWithHandshakeInfo(torrentData, msg, peer)
torrentData.peers.add peer
if ! peers
@logger.warn "Unknown peer with id #{msg.peerId} connected."
else
@logger.warn "Known peer with id #{msg.peerId} connected from new location."
end
else
@logger.warn "Known peer with id #{msg.peerId} connected from known location."
end
@logger.info "Peer #{peer} connected to us. "
peer.state = :established
peer.amChoked = true
peer.peerChoked = true
peer.amInterested = false
peer.peerInterested = false
if torrentData.info
peer.bitfield = Bitfield.new(torrentData.info.pieces.length)
else
peer.bitfield = EmptyBitfield.new
@logger.info "We have no metainfo yet, so setting peer #{peer} to have an EmptyBitfield"
end
# Send bitfield
sendBitfield(currentIo, torrentData.blockState.completePieceBitfield) if torrentData.blockState
setMetaInfo(peer)
setReadRateLimit(torrentData.downRateLimit) if torrentData.downRateLimit
setWriteRateLimit(torrentData.upRateLimit) if torrentData.upRateLimit
end | ruby | def serverInit(metadata, addr, port)
# A peer connected to us
# Read handshake message
@logger.warn "Peer connection from #{addr}:#{port}"
begin
msg = PeerHandshake.unserializeExceptPeerIdFrom currentIo
rescue
@logger.warn "Peer failed handshake: #{$!}"
close
return
end
torrentData = torrentDataForHandshake(msg, "#{addr}:#{port}")
# Are we tracking this torrent?
if !torrentData
@logger.warn "Peer sent handshake for unknown torrent"
close
return
end
trackerclient = torrentData.trackerClient
# If we already have too many connections, don't allow this connection.
classifiedPeers = ClassifiedPeers.new torrentData.peers.all
if classifiedPeers.establishedPeers.length > @targetActivePeerCount
@logger.warn "Closing connection to peer from #{addr}:#{port} because we already have #{classifiedPeers.establishedPeers.length} active peers which is > the target count of #{@targetActivePeerCount} "
close
return
end
# Send handshake
outgoing = PeerHandshake.new
outgoing.peerId = trackerclient.peerId
outgoing.infoHash = torrentData.infoHash
outgoing.serializeTo currentIo
# Send extended handshake if the peer supports extensions
if (msg.reserved.unpack("C8")[5] & 0x10) != 0
@logger.warn "Peer supports extensions. Sending extended handshake"
extended = Extension.createExtendedHandshake torrentData.info
extended.serializeTo currentIo
end
# Read incoming handshake's peerid
msg.peerId = currentIo.read(PeerHandshake::PeerIdLen)
if msg.peerId == trackerclient.peerId
@logger.info "We got a connection from ourself. Closing connection."
close
return
end
peer = nil
peers = torrentData.peers.findById(msg.peerId)
if peers
peers.each do |existingPeer|
if existingPeer.state != :disconnected
@logger.warn "Peer with id #{msg.peerId} created a new connection when we already have a connection in state #{existingPeer.state}. Closing new connection."
close
return
else
if existingPeer.trackerPeer.ip == addr && existingPeer.trackerPeer.port == port
peer = existingPeer
end
end
end
end
if ! peer
peer = Peer.new(TrackerPeer.new(addr, port))
updatePeerWithHandshakeInfo(torrentData, msg, peer)
torrentData.peers.add peer
if ! peers
@logger.warn "Unknown peer with id #{msg.peerId} connected."
else
@logger.warn "Known peer with id #{msg.peerId} connected from new location."
end
else
@logger.warn "Known peer with id #{msg.peerId} connected from known location."
end
@logger.info "Peer #{peer} connected to us. "
peer.state = :established
peer.amChoked = true
peer.peerChoked = true
peer.amInterested = false
peer.peerInterested = false
if torrentData.info
peer.bitfield = Bitfield.new(torrentData.info.pieces.length)
else
peer.bitfield = EmptyBitfield.new
@logger.info "We have no metainfo yet, so setting peer #{peer} to have an EmptyBitfield"
end
# Send bitfield
sendBitfield(currentIo, torrentData.blockState.completePieceBitfield) if torrentData.blockState
setMetaInfo(peer)
setReadRateLimit(torrentData.downRateLimit) if torrentData.downRateLimit
setWriteRateLimit(torrentData.upRateLimit) if torrentData.upRateLimit
end | [
"def",
"serverInit",
"(",
"metadata",
",",
"addr",
",",
"port",
")",
"# A peer connected to us",
"# Read handshake message",
"@logger",
".",
"warn",
"\"Peer connection from #{addr}:#{port}\"",
"begin",
"msg",
"=",
"PeerHandshake",
".",
"unserializeExceptPeerIdFrom",
"currentIo",
"rescue",
"@logger",
".",
"warn",
"\"Peer failed handshake: #{$!}\"",
"close",
"return",
"end",
"torrentData",
"=",
"torrentDataForHandshake",
"(",
"msg",
",",
"\"#{addr}:#{port}\"",
")",
"# Are we tracking this torrent?",
"if",
"!",
"torrentData",
"@logger",
".",
"warn",
"\"Peer sent handshake for unknown torrent\"",
"close",
"return",
"end",
"trackerclient",
"=",
"torrentData",
".",
"trackerClient",
"# If we already have too many connections, don't allow this connection.",
"classifiedPeers",
"=",
"ClassifiedPeers",
".",
"new",
"torrentData",
".",
"peers",
".",
"all",
"if",
"classifiedPeers",
".",
"establishedPeers",
".",
"length",
">",
"@targetActivePeerCount",
"@logger",
".",
"warn",
"\"Closing connection to peer from #{addr}:#{port} because we already have #{classifiedPeers.establishedPeers.length} active peers which is > the target count of #{@targetActivePeerCount} \"",
"close",
"return",
"end",
"# Send handshake",
"outgoing",
"=",
"PeerHandshake",
".",
"new",
"outgoing",
".",
"peerId",
"=",
"trackerclient",
".",
"peerId",
"outgoing",
".",
"infoHash",
"=",
"torrentData",
".",
"infoHash",
"outgoing",
".",
"serializeTo",
"currentIo",
"# Send extended handshake if the peer supports extensions",
"if",
"(",
"msg",
".",
"reserved",
".",
"unpack",
"(",
"\"C8\"",
")",
"[",
"5",
"]",
"&",
"0x10",
")",
"!=",
"0",
"@logger",
".",
"warn",
"\"Peer supports extensions. Sending extended handshake\"",
"extended",
"=",
"Extension",
".",
"createExtendedHandshake",
"torrentData",
".",
"info",
"extended",
".",
"serializeTo",
"currentIo",
"end",
"# Read incoming handshake's peerid",
"msg",
".",
"peerId",
"=",
"currentIo",
".",
"read",
"(",
"PeerHandshake",
"::",
"PeerIdLen",
")",
"if",
"msg",
".",
"peerId",
"==",
"trackerclient",
".",
"peerId",
"@logger",
".",
"info",
"\"We got a connection from ourself. Closing connection.\"",
"close",
"return",
"end",
"peer",
"=",
"nil",
"peers",
"=",
"torrentData",
".",
"peers",
".",
"findById",
"(",
"msg",
".",
"peerId",
")",
"if",
"peers",
"peers",
".",
"each",
"do",
"|",
"existingPeer",
"|",
"if",
"existingPeer",
".",
"state",
"!=",
":disconnected",
"@logger",
".",
"warn",
"\"Peer with id #{msg.peerId} created a new connection when we already have a connection in state #{existingPeer.state}. Closing new connection.\"",
"close",
"return",
"else",
"if",
"existingPeer",
".",
"trackerPeer",
".",
"ip",
"==",
"addr",
"&&",
"existingPeer",
".",
"trackerPeer",
".",
"port",
"==",
"port",
"peer",
"=",
"existingPeer",
"end",
"end",
"end",
"end",
"if",
"!",
"peer",
"peer",
"=",
"Peer",
".",
"new",
"(",
"TrackerPeer",
".",
"new",
"(",
"addr",
",",
"port",
")",
")",
"updatePeerWithHandshakeInfo",
"(",
"torrentData",
",",
"msg",
",",
"peer",
")",
"torrentData",
".",
"peers",
".",
"add",
"peer",
"if",
"!",
"peers",
"@logger",
".",
"warn",
"\"Unknown peer with id #{msg.peerId} connected.\"",
"else",
"@logger",
".",
"warn",
"\"Known peer with id #{msg.peerId} connected from new location.\"",
"end",
"else",
"@logger",
".",
"warn",
"\"Known peer with id #{msg.peerId} connected from known location.\"",
"end",
"@logger",
".",
"info",
"\"Peer #{peer} connected to us. \"",
"peer",
".",
"state",
"=",
":established",
"peer",
".",
"amChoked",
"=",
"true",
"peer",
".",
"peerChoked",
"=",
"true",
"peer",
".",
"amInterested",
"=",
"false",
"peer",
".",
"peerInterested",
"=",
"false",
"if",
"torrentData",
".",
"info",
"peer",
".",
"bitfield",
"=",
"Bitfield",
".",
"new",
"(",
"torrentData",
".",
"info",
".",
"pieces",
".",
"length",
")",
"else",
"peer",
".",
"bitfield",
"=",
"EmptyBitfield",
".",
"new",
"@logger",
".",
"info",
"\"We have no metainfo yet, so setting peer #{peer} to have an EmptyBitfield\"",
"end",
"# Send bitfield",
"sendBitfield",
"(",
"currentIo",
",",
"torrentData",
".",
"blockState",
".",
"completePieceBitfield",
")",
"if",
"torrentData",
".",
"blockState",
"setMetaInfo",
"(",
"peer",
")",
"setReadRateLimit",
"(",
"torrentData",
".",
"downRateLimit",
")",
"if",
"torrentData",
".",
"downRateLimit",
"setWriteRateLimit",
"(",
"torrentData",
".",
"upRateLimit",
")",
"if",
"torrentData",
".",
"upRateLimit",
"end"
] | REACTOR METHODS
Reactor method called when a peer has connected to us. | [
"REACTOR",
"METHODS",
"Reactor",
"method",
"called",
"when",
"a",
"peer",
"has",
"connected",
"to",
"us",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L451-L551 |
2,216 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClientHandler.clientInit | def clientInit(peer)
# We connected to a peer
# Send handshake
torrentData = @torrentData[peer.infoHash]
if ! torrentData
@logger.warn "No tracker client found for peer #{peer}. Closing connection."
close
return
end
trackerclient = torrentData.trackerClient
@logger.info "Connected to peer #{peer}. Sending handshake."
msg = PeerHandshake.new
msg.peerId = trackerclient.peerId
msg.infoHash = peer.infoHash
msg.serializeTo currentIo
peer.state = :handshaking
@reactor.scheduleTimer(@handshakeTimeout, [:handshake_timeout, peer], false)
@logger.debug "Done sending handshake."
# Send bitfield
sendBitfield(currentIo, torrentData.blockState.completePieceBitfield) if torrentData.blockState
setReadRateLimit(torrentData.downRateLimit) if torrentData.downRateLimit
setWriteRateLimit(torrentData.upRateLimit) if torrentData.upRateLimit
end | ruby | def clientInit(peer)
# We connected to a peer
# Send handshake
torrentData = @torrentData[peer.infoHash]
if ! torrentData
@logger.warn "No tracker client found for peer #{peer}. Closing connection."
close
return
end
trackerclient = torrentData.trackerClient
@logger.info "Connected to peer #{peer}. Sending handshake."
msg = PeerHandshake.new
msg.peerId = trackerclient.peerId
msg.infoHash = peer.infoHash
msg.serializeTo currentIo
peer.state = :handshaking
@reactor.scheduleTimer(@handshakeTimeout, [:handshake_timeout, peer], false)
@logger.debug "Done sending handshake."
# Send bitfield
sendBitfield(currentIo, torrentData.blockState.completePieceBitfield) if torrentData.blockState
setReadRateLimit(torrentData.downRateLimit) if torrentData.downRateLimit
setWriteRateLimit(torrentData.upRateLimit) if torrentData.upRateLimit
end | [
"def",
"clientInit",
"(",
"peer",
")",
"# We connected to a peer",
"# Send handshake",
"torrentData",
"=",
"@torrentData",
"[",
"peer",
".",
"infoHash",
"]",
"if",
"!",
"torrentData",
"@logger",
".",
"warn",
"\"No tracker client found for peer #{peer}. Closing connection.\"",
"close",
"return",
"end",
"trackerclient",
"=",
"torrentData",
".",
"trackerClient",
"@logger",
".",
"info",
"\"Connected to peer #{peer}. Sending handshake.\"",
"msg",
"=",
"PeerHandshake",
".",
"new",
"msg",
".",
"peerId",
"=",
"trackerclient",
".",
"peerId",
"msg",
".",
"infoHash",
"=",
"peer",
".",
"infoHash",
"msg",
".",
"serializeTo",
"currentIo",
"peer",
".",
"state",
"=",
":handshaking",
"@reactor",
".",
"scheduleTimer",
"(",
"@handshakeTimeout",
",",
"[",
":handshake_timeout",
",",
"peer",
"]",
",",
"false",
")",
"@logger",
".",
"debug",
"\"Done sending handshake.\"",
"# Send bitfield",
"sendBitfield",
"(",
"currentIo",
",",
"torrentData",
".",
"blockState",
".",
"completePieceBitfield",
")",
"if",
"torrentData",
".",
"blockState",
"setReadRateLimit",
"(",
"torrentData",
".",
"downRateLimit",
")",
"if",
"torrentData",
".",
"downRateLimit",
"setWriteRateLimit",
"(",
"torrentData",
".",
"upRateLimit",
")",
"if",
"torrentData",
".",
"upRateLimit",
"end"
] | Reactor method called when we have connected to a peer. | [
"Reactor",
"method",
"called",
"when",
"we",
"have",
"connected",
"to",
"a",
"peer",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L554-L579 |
2,217 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClientHandler.recvData | def recvData(peer)
msg = nil
@logger.debug "Got data from peer #{peer}"
if peer.state == :handshaking
# Read handshake message
begin
@logger.debug "Reading handshake from #{peer}"
msg = PeerHandshake.unserializeFrom currentIo
rescue
@logger.warn "Peer #{peer} failed handshake: #{$!}"
setPeerDisconnected(peer)
close
return
end
else
begin
@logger.debug "Reading wire-message from #{peer}"
msg = peer.peerMsgSerializer.unserializeFrom currentIo
#msg = PeerWireMessage.unserializeFrom currentIo
rescue EOFError
@logger.info "Peer #{peer} disconnected."
setPeerDisconnected(peer)
close
return
rescue
@logger.warn "Unserializing message from peer #{peer} failed: #{$!}"
@logger.warn $!.backtrace.join "\n"
setPeerDisconnected(peer)
close
return
end
peer.updateUploadRate msg
torrentData = @torrentData[peer.infoHash]
torrentData.bytesDownloaded += msg.length if torrentData
@logger.debug "Peer #{peer} upload rate: #{peer.uploadRate.value} data only: #{peer.uploadRateDataOnly.value}"
end
if msg.is_a? PeerHandshake
# This is a remote peer that we connected to returning our handshake.
processHandshake(msg, peer)
peer.state = :established
peer.amChoked = true
peer.peerChoked = true
peer.amInterested = false
peer.peerInterested = false
elsif msg.is_a? BitfieldMessage
@logger.debug "Received bitfield message from peer."
handleBitfield(msg, peer)
elsif msg.is_a? Unchoke
@logger.debug "Received unchoke message from peer."
peer.amChoked = false
elsif msg.is_a? Choke
@logger.debug "Received choke message from peer."
peer.amChoked = true
elsif msg.is_a? Interested
@logger.debug "Received interested message from peer."
peer.peerInterested = true
elsif msg.is_a? Uninterested
@logger.debug "Received uninterested message from peer."
peer.peerInterested = false
elsif msg.is_a? Piece
@logger.debug "Received piece message from peer for torrent #{QuartzTorrent.bytesToHex(peer.infoHash)}: piece #{msg.pieceIndex} offset #{msg.blockOffset} length #{msg.data.length}."
handlePieceReceive(msg, peer)
elsif msg.is_a? Request
@logger.debug "Received request message from peer for torrent #{QuartzTorrent.bytesToHex(peer.infoHash)}: piece #{msg.pieceIndex} offset #{msg.blockOffset} length #{msg.blockLength}."
handleRequest(msg, peer)
elsif msg.is_a? Have
@logger.debug "Received have message from peer for torrent #{QuartzTorrent.bytesToHex(peer.infoHash)}: piece #{msg.pieceIndex}"
handleHave(msg, peer)
elsif msg.is_a? KeepAlive
@logger.debug "Received keep alive message from peer."
elsif msg.is_a? ExtendedHandshake
@logger.debug "Received extended handshake message from peer."
handleExtendedHandshake(msg, peer)
elsif msg.is_a? ExtendedMetaInfo
@logger.debug "Received extended metainfo message from peer."
handleExtendedMetainfo(msg, peer)
else
@logger.warn "Received a #{msg.class} message but handler is not implemented"
end
end | ruby | def recvData(peer)
msg = nil
@logger.debug "Got data from peer #{peer}"
if peer.state == :handshaking
# Read handshake message
begin
@logger.debug "Reading handshake from #{peer}"
msg = PeerHandshake.unserializeFrom currentIo
rescue
@logger.warn "Peer #{peer} failed handshake: #{$!}"
setPeerDisconnected(peer)
close
return
end
else
begin
@logger.debug "Reading wire-message from #{peer}"
msg = peer.peerMsgSerializer.unserializeFrom currentIo
#msg = PeerWireMessage.unserializeFrom currentIo
rescue EOFError
@logger.info "Peer #{peer} disconnected."
setPeerDisconnected(peer)
close
return
rescue
@logger.warn "Unserializing message from peer #{peer} failed: #{$!}"
@logger.warn $!.backtrace.join "\n"
setPeerDisconnected(peer)
close
return
end
peer.updateUploadRate msg
torrentData = @torrentData[peer.infoHash]
torrentData.bytesDownloaded += msg.length if torrentData
@logger.debug "Peer #{peer} upload rate: #{peer.uploadRate.value} data only: #{peer.uploadRateDataOnly.value}"
end
if msg.is_a? PeerHandshake
# This is a remote peer that we connected to returning our handshake.
processHandshake(msg, peer)
peer.state = :established
peer.amChoked = true
peer.peerChoked = true
peer.amInterested = false
peer.peerInterested = false
elsif msg.is_a? BitfieldMessage
@logger.debug "Received bitfield message from peer."
handleBitfield(msg, peer)
elsif msg.is_a? Unchoke
@logger.debug "Received unchoke message from peer."
peer.amChoked = false
elsif msg.is_a? Choke
@logger.debug "Received choke message from peer."
peer.amChoked = true
elsif msg.is_a? Interested
@logger.debug "Received interested message from peer."
peer.peerInterested = true
elsif msg.is_a? Uninterested
@logger.debug "Received uninterested message from peer."
peer.peerInterested = false
elsif msg.is_a? Piece
@logger.debug "Received piece message from peer for torrent #{QuartzTorrent.bytesToHex(peer.infoHash)}: piece #{msg.pieceIndex} offset #{msg.blockOffset} length #{msg.data.length}."
handlePieceReceive(msg, peer)
elsif msg.is_a? Request
@logger.debug "Received request message from peer for torrent #{QuartzTorrent.bytesToHex(peer.infoHash)}: piece #{msg.pieceIndex} offset #{msg.blockOffset} length #{msg.blockLength}."
handleRequest(msg, peer)
elsif msg.is_a? Have
@logger.debug "Received have message from peer for torrent #{QuartzTorrent.bytesToHex(peer.infoHash)}: piece #{msg.pieceIndex}"
handleHave(msg, peer)
elsif msg.is_a? KeepAlive
@logger.debug "Received keep alive message from peer."
elsif msg.is_a? ExtendedHandshake
@logger.debug "Received extended handshake message from peer."
handleExtendedHandshake(msg, peer)
elsif msg.is_a? ExtendedMetaInfo
@logger.debug "Received extended metainfo message from peer."
handleExtendedMetainfo(msg, peer)
else
@logger.warn "Received a #{msg.class} message but handler is not implemented"
end
end | [
"def",
"recvData",
"(",
"peer",
")",
"msg",
"=",
"nil",
"@logger",
".",
"debug",
"\"Got data from peer #{peer}\"",
"if",
"peer",
".",
"state",
"==",
":handshaking",
"# Read handshake message",
"begin",
"@logger",
".",
"debug",
"\"Reading handshake from #{peer}\"",
"msg",
"=",
"PeerHandshake",
".",
"unserializeFrom",
"currentIo",
"rescue",
"@logger",
".",
"warn",
"\"Peer #{peer} failed handshake: #{$!}\"",
"setPeerDisconnected",
"(",
"peer",
")",
"close",
"return",
"end",
"else",
"begin",
"@logger",
".",
"debug",
"\"Reading wire-message from #{peer}\"",
"msg",
"=",
"peer",
".",
"peerMsgSerializer",
".",
"unserializeFrom",
"currentIo",
"#msg = PeerWireMessage.unserializeFrom currentIo",
"rescue",
"EOFError",
"@logger",
".",
"info",
"\"Peer #{peer} disconnected.\"",
"setPeerDisconnected",
"(",
"peer",
")",
"close",
"return",
"rescue",
"@logger",
".",
"warn",
"\"Unserializing message from peer #{peer} failed: #{$!}\"",
"@logger",
".",
"warn",
"$!",
".",
"backtrace",
".",
"join",
"\"\\n\"",
"setPeerDisconnected",
"(",
"peer",
")",
"close",
"return",
"end",
"peer",
".",
"updateUploadRate",
"msg",
"torrentData",
"=",
"@torrentData",
"[",
"peer",
".",
"infoHash",
"]",
"torrentData",
".",
"bytesDownloaded",
"+=",
"msg",
".",
"length",
"if",
"torrentData",
"@logger",
".",
"debug",
"\"Peer #{peer} upload rate: #{peer.uploadRate.value} data only: #{peer.uploadRateDataOnly.value}\"",
"end",
"if",
"msg",
".",
"is_a?",
"PeerHandshake",
"# This is a remote peer that we connected to returning our handshake.",
"processHandshake",
"(",
"msg",
",",
"peer",
")",
"peer",
".",
"state",
"=",
":established",
"peer",
".",
"amChoked",
"=",
"true",
"peer",
".",
"peerChoked",
"=",
"true",
"peer",
".",
"amInterested",
"=",
"false",
"peer",
".",
"peerInterested",
"=",
"false",
"elsif",
"msg",
".",
"is_a?",
"BitfieldMessage",
"@logger",
".",
"debug",
"\"Received bitfield message from peer.\"",
"handleBitfield",
"(",
"msg",
",",
"peer",
")",
"elsif",
"msg",
".",
"is_a?",
"Unchoke",
"@logger",
".",
"debug",
"\"Received unchoke message from peer.\"",
"peer",
".",
"amChoked",
"=",
"false",
"elsif",
"msg",
".",
"is_a?",
"Choke",
"@logger",
".",
"debug",
"\"Received choke message from peer.\"",
"peer",
".",
"amChoked",
"=",
"true",
"elsif",
"msg",
".",
"is_a?",
"Interested",
"@logger",
".",
"debug",
"\"Received interested message from peer.\"",
"peer",
".",
"peerInterested",
"=",
"true",
"elsif",
"msg",
".",
"is_a?",
"Uninterested",
"@logger",
".",
"debug",
"\"Received uninterested message from peer.\"",
"peer",
".",
"peerInterested",
"=",
"false",
"elsif",
"msg",
".",
"is_a?",
"Piece",
"@logger",
".",
"debug",
"\"Received piece message from peer for torrent #{QuartzTorrent.bytesToHex(peer.infoHash)}: piece #{msg.pieceIndex} offset #{msg.blockOffset} length #{msg.data.length}.\"",
"handlePieceReceive",
"(",
"msg",
",",
"peer",
")",
"elsif",
"msg",
".",
"is_a?",
"Request",
"@logger",
".",
"debug",
"\"Received request message from peer for torrent #{QuartzTorrent.bytesToHex(peer.infoHash)}: piece #{msg.pieceIndex} offset #{msg.blockOffset} length #{msg.blockLength}.\"",
"handleRequest",
"(",
"msg",
",",
"peer",
")",
"elsif",
"msg",
".",
"is_a?",
"Have",
"@logger",
".",
"debug",
"\"Received have message from peer for torrent #{QuartzTorrent.bytesToHex(peer.infoHash)}: piece #{msg.pieceIndex}\"",
"handleHave",
"(",
"msg",
",",
"peer",
")",
"elsif",
"msg",
".",
"is_a?",
"KeepAlive",
"@logger",
".",
"debug",
"\"Received keep alive message from peer.\"",
"elsif",
"msg",
".",
"is_a?",
"ExtendedHandshake",
"@logger",
".",
"debug",
"\"Received extended handshake message from peer.\"",
"handleExtendedHandshake",
"(",
"msg",
",",
"peer",
")",
"elsif",
"msg",
".",
"is_a?",
"ExtendedMetaInfo",
"@logger",
".",
"debug",
"\"Received extended metainfo message from peer.\"",
"handleExtendedMetainfo",
"(",
"msg",
",",
"peer",
")",
"else",
"@logger",
".",
"warn",
"\"Received a #{msg.class} message but handler is not implemented\"",
"end",
"end"
] | Reactor method called when there is data ready to be read from a socket | [
"Reactor",
"method",
"called",
"when",
"there",
"is",
"data",
"ready",
"to",
"be",
"read",
"from",
"a",
"socket"
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L582-L666 |
2,218 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClientHandler.timerExpired | def timerExpired(metadata)
if metadata.is_a?(Array) && metadata[0] == :manage_peers
managePeers(metadata[1])
elsif metadata.is_a?(Array) && metadata[0] == :request_blocks
requestBlocks(metadata[1])
elsif metadata.is_a?(Array) && metadata[0] == :check_piece_manager
checkPieceManagerResults(metadata[1])
elsif metadata.is_a?(Array) && metadata[0] == :handshake_timeout
handleHandshakeTimeout(metadata[1])
elsif metadata.is_a?(Array) && metadata[0] == :removetorrent
handleRemoveTorrent(metadata[1], metadata[2])
elsif metadata.is_a?(Array) && metadata[0] == :pausetorrent
handlePause(metadata[1], metadata[2])
elsif metadata.is_a?(Array) && metadata[0] == :get_torrent_data
@torrentData.each do |k,v|
begin
if metadata[3].nil? || k == metadata[3]
v = TorrentDataDelegate.new(v, self)
metadata[1][k] = v
end
rescue
@logger.error "Error building torrent data response for user: #{$!}"
@logger.error "#{$!.backtrace.join("\n")}"
end
end
metadata[2].signal
elsif metadata.is_a?(Array) && metadata[0] == :update_torrent_data
delegate = metadata[1]
if ! @torrentData.has_key?(infoHash)
delegate.state = :deleted
else
delegate.internalRefresh
end
metadata[2].signal
elsif metadata.is_a?(Array) && metadata[0] == :request_metadata_pieces
requestMetadataPieces(metadata[1])
elsif metadata.is_a?(Array) && metadata[0] == :check_metadata_piece_manager
checkMetadataPieceManagerResults(metadata[1])
elsif metadata.is_a?(Array) && metadata[0] == :runproc
metadata[1].call
else
@logger.info "Unknown timer #{metadata} expired."
end
end | ruby | def timerExpired(metadata)
if metadata.is_a?(Array) && metadata[0] == :manage_peers
managePeers(metadata[1])
elsif metadata.is_a?(Array) && metadata[0] == :request_blocks
requestBlocks(metadata[1])
elsif metadata.is_a?(Array) && metadata[0] == :check_piece_manager
checkPieceManagerResults(metadata[1])
elsif metadata.is_a?(Array) && metadata[0] == :handshake_timeout
handleHandshakeTimeout(metadata[1])
elsif metadata.is_a?(Array) && metadata[0] == :removetorrent
handleRemoveTorrent(metadata[1], metadata[2])
elsif metadata.is_a?(Array) && metadata[0] == :pausetorrent
handlePause(metadata[1], metadata[2])
elsif metadata.is_a?(Array) && metadata[0] == :get_torrent_data
@torrentData.each do |k,v|
begin
if metadata[3].nil? || k == metadata[3]
v = TorrentDataDelegate.new(v, self)
metadata[1][k] = v
end
rescue
@logger.error "Error building torrent data response for user: #{$!}"
@logger.error "#{$!.backtrace.join("\n")}"
end
end
metadata[2].signal
elsif metadata.is_a?(Array) && metadata[0] == :update_torrent_data
delegate = metadata[1]
if ! @torrentData.has_key?(infoHash)
delegate.state = :deleted
else
delegate.internalRefresh
end
metadata[2].signal
elsif metadata.is_a?(Array) && metadata[0] == :request_metadata_pieces
requestMetadataPieces(metadata[1])
elsif metadata.is_a?(Array) && metadata[0] == :check_metadata_piece_manager
checkMetadataPieceManagerResults(metadata[1])
elsif metadata.is_a?(Array) && metadata[0] == :runproc
metadata[1].call
else
@logger.info "Unknown timer #{metadata} expired."
end
end | [
"def",
"timerExpired",
"(",
"metadata",
")",
"if",
"metadata",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"metadata",
"[",
"0",
"]",
"==",
":manage_peers",
"managePeers",
"(",
"metadata",
"[",
"1",
"]",
")",
"elsif",
"metadata",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"metadata",
"[",
"0",
"]",
"==",
":request_blocks",
"requestBlocks",
"(",
"metadata",
"[",
"1",
"]",
")",
"elsif",
"metadata",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"metadata",
"[",
"0",
"]",
"==",
":check_piece_manager",
"checkPieceManagerResults",
"(",
"metadata",
"[",
"1",
"]",
")",
"elsif",
"metadata",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"metadata",
"[",
"0",
"]",
"==",
":handshake_timeout",
"handleHandshakeTimeout",
"(",
"metadata",
"[",
"1",
"]",
")",
"elsif",
"metadata",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"metadata",
"[",
"0",
"]",
"==",
":removetorrent",
"handleRemoveTorrent",
"(",
"metadata",
"[",
"1",
"]",
",",
"metadata",
"[",
"2",
"]",
")",
"elsif",
"metadata",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"metadata",
"[",
"0",
"]",
"==",
":pausetorrent",
"handlePause",
"(",
"metadata",
"[",
"1",
"]",
",",
"metadata",
"[",
"2",
"]",
")",
"elsif",
"metadata",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"metadata",
"[",
"0",
"]",
"==",
":get_torrent_data",
"@torrentData",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"begin",
"if",
"metadata",
"[",
"3",
"]",
".",
"nil?",
"||",
"k",
"==",
"metadata",
"[",
"3",
"]",
"v",
"=",
"TorrentDataDelegate",
".",
"new",
"(",
"v",
",",
"self",
")",
"metadata",
"[",
"1",
"]",
"[",
"k",
"]",
"=",
"v",
"end",
"rescue",
"@logger",
".",
"error",
"\"Error building torrent data response for user: #{$!}\"",
"@logger",
".",
"error",
"\"#{$!.backtrace.join(\"\\n\")}\"",
"end",
"end",
"metadata",
"[",
"2",
"]",
".",
"signal",
"elsif",
"metadata",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"metadata",
"[",
"0",
"]",
"==",
":update_torrent_data",
"delegate",
"=",
"metadata",
"[",
"1",
"]",
"if",
"!",
"@torrentData",
".",
"has_key?",
"(",
"infoHash",
")",
"delegate",
".",
"state",
"=",
":deleted",
"else",
"delegate",
".",
"internalRefresh",
"end",
"metadata",
"[",
"2",
"]",
".",
"signal",
"elsif",
"metadata",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"metadata",
"[",
"0",
"]",
"==",
":request_metadata_pieces",
"requestMetadataPieces",
"(",
"metadata",
"[",
"1",
"]",
")",
"elsif",
"metadata",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"metadata",
"[",
"0",
"]",
"==",
":check_metadata_piece_manager",
"checkMetadataPieceManagerResults",
"(",
"metadata",
"[",
"1",
"]",
")",
"elsif",
"metadata",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"metadata",
"[",
"0",
"]",
"==",
":runproc",
"metadata",
"[",
"1",
"]",
".",
"call",
"else",
"@logger",
".",
"info",
"\"Unknown timer #{metadata} expired.\"",
"end",
"end"
] | Reactor method called when a scheduled timer expires. | [
"Reactor",
"method",
"called",
"when",
"a",
"scheduled",
"timer",
"expires",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L669-L712 |
2,219 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClientHandler.requestMetadataPieces | def requestMetadataPieces(infoHash)
torrentData = @torrentData[infoHash]
if ! torrentData
@logger.error "Request metadata pices: torrent data for torrent #{QuartzTorrent.bytesToHex(infoHash)} not found."
return
end
return if torrentData.paused || torrentData.queued
# We may not have completed the extended handshake with the peer which specifies the torrent size.
# In this case torrentData.metainfoPieceState is not yet set.
return if ! torrentData.metainfoPieceState
@logger.info "#{QuartzTorrent.bytesToHex(infoHash)}: Obtained all pieces of metainfo." if torrentData.metainfoPieceState.complete?
pieces = torrentData.metainfoPieceState.findRequestablePieces
classifiedPeers = ClassifiedPeers.new torrentData.peers.all
peers = torrentData.metainfoPieceState.findRequestablePeers(classifiedPeers)
if peers.size > 0
# For now, just request all pieces from the first peer.
pieces.each do |pieceIndex|
msg = ExtendedMetaInfo.new
msg.msgType = :request
msg.piece = pieceIndex
withPeersIo(peers.first, "requesting metadata piece") do |io|
sendMessageToPeer msg, io, peers.first
torrentData.metainfoPieceState.setPieceRequested(pieceIndex, true)
@logger.debug "#{QuartzTorrent.bytesToHex(infoHash)}: Requesting metainfo piece from #{peers.first}: piece #{pieceIndex}"
end
end
else
@logger.error "#{QuartzTorrent.bytesToHex(infoHash)}: No peers found that have metadata."
end
end | ruby | def requestMetadataPieces(infoHash)
torrentData = @torrentData[infoHash]
if ! torrentData
@logger.error "Request metadata pices: torrent data for torrent #{QuartzTorrent.bytesToHex(infoHash)} not found."
return
end
return if torrentData.paused || torrentData.queued
# We may not have completed the extended handshake with the peer which specifies the torrent size.
# In this case torrentData.metainfoPieceState is not yet set.
return if ! torrentData.metainfoPieceState
@logger.info "#{QuartzTorrent.bytesToHex(infoHash)}: Obtained all pieces of metainfo." if torrentData.metainfoPieceState.complete?
pieces = torrentData.metainfoPieceState.findRequestablePieces
classifiedPeers = ClassifiedPeers.new torrentData.peers.all
peers = torrentData.metainfoPieceState.findRequestablePeers(classifiedPeers)
if peers.size > 0
# For now, just request all pieces from the first peer.
pieces.each do |pieceIndex|
msg = ExtendedMetaInfo.new
msg.msgType = :request
msg.piece = pieceIndex
withPeersIo(peers.first, "requesting metadata piece") do |io|
sendMessageToPeer msg, io, peers.first
torrentData.metainfoPieceState.setPieceRequested(pieceIndex, true)
@logger.debug "#{QuartzTorrent.bytesToHex(infoHash)}: Requesting metainfo piece from #{peers.first}: piece #{pieceIndex}"
end
end
else
@logger.error "#{QuartzTorrent.bytesToHex(infoHash)}: No peers found that have metadata."
end
end | [
"def",
"requestMetadataPieces",
"(",
"infoHash",
")",
"torrentData",
"=",
"@torrentData",
"[",
"infoHash",
"]",
"if",
"!",
"torrentData",
"@logger",
".",
"error",
"\"Request metadata pices: torrent data for torrent #{QuartzTorrent.bytesToHex(infoHash)} not found.\"",
"return",
"end",
"return",
"if",
"torrentData",
".",
"paused",
"||",
"torrentData",
".",
"queued",
"# We may not have completed the extended handshake with the peer which specifies the torrent size.",
"# In this case torrentData.metainfoPieceState is not yet set.",
"return",
"if",
"!",
"torrentData",
".",
"metainfoPieceState",
"@logger",
".",
"info",
"\"#{QuartzTorrent.bytesToHex(infoHash)}: Obtained all pieces of metainfo.\"",
"if",
"torrentData",
".",
"metainfoPieceState",
".",
"complete?",
"pieces",
"=",
"torrentData",
".",
"metainfoPieceState",
".",
"findRequestablePieces",
"classifiedPeers",
"=",
"ClassifiedPeers",
".",
"new",
"torrentData",
".",
"peers",
".",
"all",
"peers",
"=",
"torrentData",
".",
"metainfoPieceState",
".",
"findRequestablePeers",
"(",
"classifiedPeers",
")",
"if",
"peers",
".",
"size",
">",
"0",
"# For now, just request all pieces from the first peer.",
"pieces",
".",
"each",
"do",
"|",
"pieceIndex",
"|",
"msg",
"=",
"ExtendedMetaInfo",
".",
"new",
"msg",
".",
"msgType",
"=",
":request",
"msg",
".",
"piece",
"=",
"pieceIndex",
"withPeersIo",
"(",
"peers",
".",
"first",
",",
"\"requesting metadata piece\"",
")",
"do",
"|",
"io",
"|",
"sendMessageToPeer",
"msg",
",",
"io",
",",
"peers",
".",
"first",
"torrentData",
".",
"metainfoPieceState",
".",
"setPieceRequested",
"(",
"pieceIndex",
",",
"true",
")",
"@logger",
".",
"debug",
"\"#{QuartzTorrent.bytesToHex(infoHash)}: Requesting metainfo piece from #{peers.first}: piece #{pieceIndex}\"",
"end",
"end",
"else",
"@logger",
".",
"error",
"\"#{QuartzTorrent.bytesToHex(infoHash)}: No peers found that have metadata.\"",
"end",
"end"
] | For a torrent where we don't have the metainfo, request metainfo pieces from peers. | [
"For",
"a",
"torrent",
"where",
"we",
"don",
"t",
"have",
"the",
"metainfo",
"request",
"metainfo",
"pieces",
"from",
"peers",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L1003-L1038 |
2,220 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClientHandler.withPeersIo | def withPeersIo(peer, what = nil)
io = findIoByMetainfo(peer)
if io
yield io
else
s = ""
s = "when #{what}" if what
@logger.warn "Couldn't find the io for peer #{peer} #{what}"
end
end | ruby | def withPeersIo(peer, what = nil)
io = findIoByMetainfo(peer)
if io
yield io
else
s = ""
s = "when #{what}" if what
@logger.warn "Couldn't find the io for peer #{peer} #{what}"
end
end | [
"def",
"withPeersIo",
"(",
"peer",
",",
"what",
"=",
"nil",
")",
"io",
"=",
"findIoByMetainfo",
"(",
"peer",
")",
"if",
"io",
"yield",
"io",
"else",
"s",
"=",
"\"\"",
"s",
"=",
"\"when #{what}\"",
"if",
"what",
"@logger",
".",
"warn",
"\"Couldn't find the io for peer #{peer} #{what}\"",
"end",
"end"
] | Find the io associated with the peer and yield it to the passed block.
If no io is found an error is logged. | [
"Find",
"the",
"io",
"associated",
"with",
"the",
"peer",
"and",
"yield",
"it",
"to",
"the",
"passed",
"block",
".",
"If",
"no",
"io",
"is",
"found",
"an",
"error",
"is",
"logged",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L1451-L1460 |
2,221 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClientHandler.getPeersFromTracker | def getPeersFromTracker(torrentData, infoHash)
addPeer = Proc.new do |trackerPeer|
peer = Peer.new(trackerPeer)
peer.infoHash = infoHash
torrentData.peers.add peer
true
end
classifiedPeers = nil
replaceDisconnectedPeer = Proc.new do |trackerPeer|
classifiedPeers = ClassifiedPeers.new(torrentData.peers.all) if ! classifiedPeers
if classifiedPeers.disconnectedPeers.size > 0
torrentData.peers.delete classifiedPeers.disconnectedPeers.pop
addPeer.call trackerPeer
true
else
false
end
end
trackerclient = torrentData.trackerClient
addProc = addPeer
flipped = false
trackerclient.peers.each do |p|
if ! flipped && torrentData.peers.size >= @maxPeerCount
addProc = replaceDisconnectedPeer
flipped = true
end
# Don't treat ourself as a peer.
next if p.id && p.id == trackerclient.peerId
if ! torrentData.peers.findByAddr(p.ip, p.port)
@logger.debug "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Adding tracker peer #{p} to peers list"
break if ! addProc.call(p)
end
end
end | ruby | def getPeersFromTracker(torrentData, infoHash)
addPeer = Proc.new do |trackerPeer|
peer = Peer.new(trackerPeer)
peer.infoHash = infoHash
torrentData.peers.add peer
true
end
classifiedPeers = nil
replaceDisconnectedPeer = Proc.new do |trackerPeer|
classifiedPeers = ClassifiedPeers.new(torrentData.peers.all) if ! classifiedPeers
if classifiedPeers.disconnectedPeers.size > 0
torrentData.peers.delete classifiedPeers.disconnectedPeers.pop
addPeer.call trackerPeer
true
else
false
end
end
trackerclient = torrentData.trackerClient
addProc = addPeer
flipped = false
trackerclient.peers.each do |p|
if ! flipped && torrentData.peers.size >= @maxPeerCount
addProc = replaceDisconnectedPeer
flipped = true
end
# Don't treat ourself as a peer.
next if p.id && p.id == trackerclient.peerId
if ! torrentData.peers.findByAddr(p.ip, p.port)
@logger.debug "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Adding tracker peer #{p} to peers list"
break if ! addProc.call(p)
end
end
end | [
"def",
"getPeersFromTracker",
"(",
"torrentData",
",",
"infoHash",
")",
"addPeer",
"=",
"Proc",
".",
"new",
"do",
"|",
"trackerPeer",
"|",
"peer",
"=",
"Peer",
".",
"new",
"(",
"trackerPeer",
")",
"peer",
".",
"infoHash",
"=",
"infoHash",
"torrentData",
".",
"peers",
".",
"add",
"peer",
"true",
"end",
"classifiedPeers",
"=",
"nil",
"replaceDisconnectedPeer",
"=",
"Proc",
".",
"new",
"do",
"|",
"trackerPeer",
"|",
"classifiedPeers",
"=",
"ClassifiedPeers",
".",
"new",
"(",
"torrentData",
".",
"peers",
".",
"all",
")",
"if",
"!",
"classifiedPeers",
"if",
"classifiedPeers",
".",
"disconnectedPeers",
".",
"size",
">",
"0",
"torrentData",
".",
"peers",
".",
"delete",
"classifiedPeers",
".",
"disconnectedPeers",
".",
"pop",
"addPeer",
".",
"call",
"trackerPeer",
"true",
"else",
"false",
"end",
"end",
"trackerclient",
"=",
"torrentData",
".",
"trackerClient",
"addProc",
"=",
"addPeer",
"flipped",
"=",
"false",
"trackerclient",
".",
"peers",
".",
"each",
"do",
"|",
"p",
"|",
"if",
"!",
"flipped",
"&&",
"torrentData",
".",
"peers",
".",
"size",
">=",
"@maxPeerCount",
"addProc",
"=",
"replaceDisconnectedPeer",
"flipped",
"=",
"true",
"end",
"# Don't treat ourself as a peer.",
"next",
"if",
"p",
".",
"id",
"&&",
"p",
".",
"id",
"==",
"trackerclient",
".",
"peerId",
"if",
"!",
"torrentData",
".",
"peers",
".",
"findByAddr",
"(",
"p",
".",
"ip",
",",
"p",
".",
"port",
")",
"@logger",
".",
"debug",
"\"#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Adding tracker peer #{p} to peers list\"",
"break",
"if",
"!",
"addProc",
".",
"call",
"(",
"p",
")",
"end",
"end",
"end"
] | Update our internal peer list for this torrent from the tracker client | [
"Update",
"our",
"internal",
"peer",
"list",
"for",
"this",
"torrent",
"from",
"the",
"tracker",
"client"
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L1517-L1556 |
2,222 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClientHandler.handleRemoveTorrent | def handleRemoveTorrent(infoHash, deleteFiles)
torrentData = @torrentData.delete infoHash
if ! torrentData
@logger.warn "Asked to remove a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}"
return
end
@logger.info "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Removing torrent. #{deleteFiles ? "Will" : "Wont"} delete downloaded files."
@logger.info "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Removing torrent: no torrentData.metainfoRequestTimer" if ! torrentData.metainfoRequestTimer
@logger.info "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Removing torrent: no torrentData.managePeersTimer" if ! torrentData.managePeersTimer
@logger.info "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Removing torrent: no torrentData.checkMetadataPieceManagerTimer" if ! torrentData.checkMetadataPieceManagerTimer
@logger.info "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Removing torrent: no torrentData.checkPieceManagerTimer" if ! torrentData.checkPieceManagerTimer
@logger.info "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Removing torrent: no torrentData.requestBlocksTimer" if ! torrentData.requestBlocksTimer
# Stop all timers
cancelTimer torrentData.metainfoRequestTimer if torrentData.metainfoRequestTimer
cancelTimer torrentData.managePeersTimer if torrentData.managePeersTimer
cancelTimer torrentData.checkMetadataPieceManagerTimer if torrentData.checkMetadataPieceManagerTimer
cancelTimer torrentData.checkPieceManagerTimer if torrentData.checkPieceManagerTimer
cancelTimer torrentData.requestBlocksTimer if torrentData.requestBlocksTimer
torrentData.trackerClient.removePeersChangedListener(torrentData.peerChangeListener)
# Remove all the peers for this torrent.
torrentData.peers.all.each do |peer|
if peer.state != :disconnected
# Close socket
withPeersIo(peer, "when removing torrent") do |io|
setPeerDisconnected(peer)
close(io)
@logger.debug "Closing connection to peer #{peer}"
end
end
torrentData.peers.delete peer
end
# Stop tracker client
torrentData.trackerClient.stop if torrentData.trackerClient
# Stop PieceManagers
torrentData.pieceManager.stop if torrentData.pieceManager
torrentData.metainfoPieceState.stop if torrentData.metainfoPieceState
# Remove metainfo file if it exists
begin
torrentData.metainfoPieceState.remove if torrentData.metainfoPieceState
rescue
@logger.warn "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Deleting metainfo file for torrent #{QuartzTorrent.bytesToHex(infoHash)} failed: #{$!}"
end
if deleteFiles
if torrentData.info
begin
path = @baseDirectory + File::SEPARATOR + torrentData.info.name
if File.exists? path
FileUtils.rm_r path
@logger.info "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Deleted #{path}"
else
@logger.warn "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Deleting '#{path}' for torrent #{QuartzTorrent.bytesToHex(infoHash)} failed: #{$!}"
end
rescue
@logger.warn "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: When removing torrent, deleting '#{path}' failed because it doesn't exist"
end
end
end
dequeue
end | ruby | def handleRemoveTorrent(infoHash, deleteFiles)
torrentData = @torrentData.delete infoHash
if ! torrentData
@logger.warn "Asked to remove a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}"
return
end
@logger.info "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Removing torrent. #{deleteFiles ? "Will" : "Wont"} delete downloaded files."
@logger.info "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Removing torrent: no torrentData.metainfoRequestTimer" if ! torrentData.metainfoRequestTimer
@logger.info "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Removing torrent: no torrentData.managePeersTimer" if ! torrentData.managePeersTimer
@logger.info "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Removing torrent: no torrentData.checkMetadataPieceManagerTimer" if ! torrentData.checkMetadataPieceManagerTimer
@logger.info "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Removing torrent: no torrentData.checkPieceManagerTimer" if ! torrentData.checkPieceManagerTimer
@logger.info "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Removing torrent: no torrentData.requestBlocksTimer" if ! torrentData.requestBlocksTimer
# Stop all timers
cancelTimer torrentData.metainfoRequestTimer if torrentData.metainfoRequestTimer
cancelTimer torrentData.managePeersTimer if torrentData.managePeersTimer
cancelTimer torrentData.checkMetadataPieceManagerTimer if torrentData.checkMetadataPieceManagerTimer
cancelTimer torrentData.checkPieceManagerTimer if torrentData.checkPieceManagerTimer
cancelTimer torrentData.requestBlocksTimer if torrentData.requestBlocksTimer
torrentData.trackerClient.removePeersChangedListener(torrentData.peerChangeListener)
# Remove all the peers for this torrent.
torrentData.peers.all.each do |peer|
if peer.state != :disconnected
# Close socket
withPeersIo(peer, "when removing torrent") do |io|
setPeerDisconnected(peer)
close(io)
@logger.debug "Closing connection to peer #{peer}"
end
end
torrentData.peers.delete peer
end
# Stop tracker client
torrentData.trackerClient.stop if torrentData.trackerClient
# Stop PieceManagers
torrentData.pieceManager.stop if torrentData.pieceManager
torrentData.metainfoPieceState.stop if torrentData.metainfoPieceState
# Remove metainfo file if it exists
begin
torrentData.metainfoPieceState.remove if torrentData.metainfoPieceState
rescue
@logger.warn "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Deleting metainfo file for torrent #{QuartzTorrent.bytesToHex(infoHash)} failed: #{$!}"
end
if deleteFiles
if torrentData.info
begin
path = @baseDirectory + File::SEPARATOR + torrentData.info.name
if File.exists? path
FileUtils.rm_r path
@logger.info "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Deleted #{path}"
else
@logger.warn "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Deleting '#{path}' for torrent #{QuartzTorrent.bytesToHex(infoHash)} failed: #{$!}"
end
rescue
@logger.warn "#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: When removing torrent, deleting '#{path}' failed because it doesn't exist"
end
end
end
dequeue
end | [
"def",
"handleRemoveTorrent",
"(",
"infoHash",
",",
"deleteFiles",
")",
"torrentData",
"=",
"@torrentData",
".",
"delete",
"infoHash",
"if",
"!",
"torrentData",
"@logger",
".",
"warn",
"\"Asked to remove a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}\"",
"return",
"end",
"@logger",
".",
"info",
"\"#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Removing torrent. #{deleteFiles ? \"Will\" : \"Wont\"} delete downloaded files.\"",
"@logger",
".",
"info",
"\"#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Removing torrent: no torrentData.metainfoRequestTimer\"",
"if",
"!",
"torrentData",
".",
"metainfoRequestTimer",
"@logger",
".",
"info",
"\"#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Removing torrent: no torrentData.managePeersTimer\"",
"if",
"!",
"torrentData",
".",
"managePeersTimer",
"@logger",
".",
"info",
"\"#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Removing torrent: no torrentData.checkMetadataPieceManagerTimer\"",
"if",
"!",
"torrentData",
".",
"checkMetadataPieceManagerTimer",
"@logger",
".",
"info",
"\"#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Removing torrent: no torrentData.checkPieceManagerTimer\"",
"if",
"!",
"torrentData",
".",
"checkPieceManagerTimer",
"@logger",
".",
"info",
"\"#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Removing torrent: no torrentData.requestBlocksTimer\"",
"if",
"!",
"torrentData",
".",
"requestBlocksTimer",
"# Stop all timers",
"cancelTimer",
"torrentData",
".",
"metainfoRequestTimer",
"if",
"torrentData",
".",
"metainfoRequestTimer",
"cancelTimer",
"torrentData",
".",
"managePeersTimer",
"if",
"torrentData",
".",
"managePeersTimer",
"cancelTimer",
"torrentData",
".",
"checkMetadataPieceManagerTimer",
"if",
"torrentData",
".",
"checkMetadataPieceManagerTimer",
"cancelTimer",
"torrentData",
".",
"checkPieceManagerTimer",
"if",
"torrentData",
".",
"checkPieceManagerTimer",
"cancelTimer",
"torrentData",
".",
"requestBlocksTimer",
"if",
"torrentData",
".",
"requestBlocksTimer",
"torrentData",
".",
"trackerClient",
".",
"removePeersChangedListener",
"(",
"torrentData",
".",
"peerChangeListener",
")",
"# Remove all the peers for this torrent.",
"torrentData",
".",
"peers",
".",
"all",
".",
"each",
"do",
"|",
"peer",
"|",
"if",
"peer",
".",
"state",
"!=",
":disconnected",
"# Close socket ",
"withPeersIo",
"(",
"peer",
",",
"\"when removing torrent\"",
")",
"do",
"|",
"io",
"|",
"setPeerDisconnected",
"(",
"peer",
")",
"close",
"(",
"io",
")",
"@logger",
".",
"debug",
"\"Closing connection to peer #{peer}\"",
"end",
"end",
"torrentData",
".",
"peers",
".",
"delete",
"peer",
"end",
"# Stop tracker client",
"torrentData",
".",
"trackerClient",
".",
"stop",
"if",
"torrentData",
".",
"trackerClient",
"# Stop PieceManagers",
"torrentData",
".",
"pieceManager",
".",
"stop",
"if",
"torrentData",
".",
"pieceManager",
"torrentData",
".",
"metainfoPieceState",
".",
"stop",
"if",
"torrentData",
".",
"metainfoPieceState",
"# Remove metainfo file if it exists",
"begin",
"torrentData",
".",
"metainfoPieceState",
".",
"remove",
"if",
"torrentData",
".",
"metainfoPieceState",
"rescue",
"@logger",
".",
"warn",
"\"#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Deleting metainfo file for torrent #{QuartzTorrent.bytesToHex(infoHash)} failed: #{$!}\"",
"end",
"if",
"deleteFiles",
"if",
"torrentData",
".",
"info",
"begin",
"path",
"=",
"@baseDirectory",
"+",
"File",
"::",
"SEPARATOR",
"+",
"torrentData",
".",
"info",
".",
"name",
"if",
"File",
".",
"exists?",
"path",
"FileUtils",
".",
"rm_r",
"path",
"@logger",
".",
"info",
"\"#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Deleted #{path}\"",
"else",
"@logger",
".",
"warn",
"\"#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: Deleting '#{path}' for torrent #{QuartzTorrent.bytesToHex(infoHash)} failed: #{$!}\"",
"end",
"rescue",
"@logger",
".",
"warn",
"\"#{QuartzTorrent.bytesToHex(torrentData.infoHash)}: When removing torrent, deleting '#{path}' failed because it doesn't exist\"",
"end",
"end",
"end",
"dequeue",
"end"
] | Remove a torrent that we are downloading. | [
"Remove",
"a",
"torrent",
"that",
"we",
"are",
"downloading",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L1559-L1627 |
2,223 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClientHandler.handlePause | def handlePause(infoHash, value)
torrentData = @torrentData[infoHash]
if ! torrentData
@logger.warn "Asked to pause a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}"
return
end
return if torrentData.paused == value
torrentData.paused = value
if !value
# On unpause, queue the torrent since there might not be room for it to run.
# Make sure it goes to the head of the queue.
queue(torrentData, :unshift)
end
setFrozen infoHash, value if ! torrentData.queued
dequeue
end | ruby | def handlePause(infoHash, value)
torrentData = @torrentData[infoHash]
if ! torrentData
@logger.warn "Asked to pause a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}"
return
end
return if torrentData.paused == value
torrentData.paused = value
if !value
# On unpause, queue the torrent since there might not be room for it to run.
# Make sure it goes to the head of the queue.
queue(torrentData, :unshift)
end
setFrozen infoHash, value if ! torrentData.queued
dequeue
end | [
"def",
"handlePause",
"(",
"infoHash",
",",
"value",
")",
"torrentData",
"=",
"@torrentData",
"[",
"infoHash",
"]",
"if",
"!",
"torrentData",
"@logger",
".",
"warn",
"\"Asked to pause a non-existent torrent #{QuartzTorrent.bytesToHex(infoHash)}\"",
"return",
"end",
"return",
"if",
"torrentData",
".",
"paused",
"==",
"value",
"torrentData",
".",
"paused",
"=",
"value",
"if",
"!",
"value",
"# On unpause, queue the torrent since there might not be room for it to run.",
"# Make sure it goes to the head of the queue.",
"queue",
"(",
"torrentData",
",",
":unshift",
")",
"end",
"setFrozen",
"infoHash",
",",
"value",
"if",
"!",
"torrentData",
".",
"queued",
"dequeue",
"end"
] | Pause or unpause a torrent that we are downloading. | [
"Pause",
"or",
"unpause",
"a",
"torrent",
"that",
"we",
"are",
"downloading",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L1630-L1650 |
2,224 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClientHandler.queue | def queue(torrentData, mode = :queue)
return if torrentData.queued
# Queue the torrent
if mode == :unshift
@torrentQueue.unshift torrentData
else
@torrentQueue.push torrentData
end
setFrozen torrentData, true if ! torrentData.paused
end | ruby | def queue(torrentData, mode = :queue)
return if torrentData.queued
# Queue the torrent
if mode == :unshift
@torrentQueue.unshift torrentData
else
@torrentQueue.push torrentData
end
setFrozen torrentData, true if ! torrentData.paused
end | [
"def",
"queue",
"(",
"torrentData",
",",
"mode",
"=",
":queue",
")",
"return",
"if",
"torrentData",
".",
"queued",
"# Queue the torrent",
"if",
"mode",
"==",
":unshift",
"@torrentQueue",
".",
"unshift",
"torrentData",
"else",
"@torrentQueue",
".",
"push",
"torrentData",
"end",
"setFrozen",
"torrentData",
",",
"true",
"if",
"!",
"torrentData",
".",
"paused",
"end"
] | Queue a torrent | [
"Queue",
"a",
"torrent"
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L1653-L1664 |
2,225 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClientHandler.dequeue | def dequeue
torrents = @torrentQueue.dequeue(@torrentData.values)
torrents.each do |torrentData|
if torrentData.state == :initializing
initTorrent torrentData
else
setFrozen torrentData, false if ! torrentData.paused
end
end
end | ruby | def dequeue
torrents = @torrentQueue.dequeue(@torrentData.values)
torrents.each do |torrentData|
if torrentData.state == :initializing
initTorrent torrentData
else
setFrozen torrentData, false if ! torrentData.paused
end
end
end | [
"def",
"dequeue",
"torrents",
"=",
"@torrentQueue",
".",
"dequeue",
"(",
"@torrentData",
".",
"values",
")",
"torrents",
".",
"each",
"do",
"|",
"torrentData",
"|",
"if",
"torrentData",
".",
"state",
"==",
":initializing",
"initTorrent",
"torrentData",
"else",
"setFrozen",
"torrentData",
",",
"false",
"if",
"!",
"torrentData",
".",
"paused",
"end",
"end",
"end"
] | Dequeue any torrents that can now run based on available space | [
"Dequeue",
"any",
"torrents",
"that",
"can",
"now",
"run",
"based",
"on",
"available",
"space"
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L1667-L1676 |
2,226 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClientHandler.setFrozen | def setFrozen(torrent, value)
torrentData = torrent
if ! torrent.is_a?(TorrentData)
torrentData = @torrentData[torrent]
if ! torrentData
@logger.warn "Asked to freeze a non-existent torrent #{QuartzTorrent.bytesToHex(torrent)}"
return
end
end
if value
# Disconnect from all peers so we won't reply to any messages.
torrentData.peers.all.each do |peer|
if peer.state != :disconnected
# Close socket
withPeersIo(peer, "when removing torrent") do |io|
setPeerDisconnected(peer)
close(io)
end
end
torrentData.peers.delete peer
end
else
# Get our list of peers and start connecting right away
# Non-recurring and immediate timer
torrentData.managePeersTimer =
@reactor.scheduleTimer(@managePeersPeriod, [:manage_peers, torrentData.infoHash], false, true)
end
end | ruby | def setFrozen(torrent, value)
torrentData = torrent
if ! torrent.is_a?(TorrentData)
torrentData = @torrentData[torrent]
if ! torrentData
@logger.warn "Asked to freeze a non-existent torrent #{QuartzTorrent.bytesToHex(torrent)}"
return
end
end
if value
# Disconnect from all peers so we won't reply to any messages.
torrentData.peers.all.each do |peer|
if peer.state != :disconnected
# Close socket
withPeersIo(peer, "when removing torrent") do |io|
setPeerDisconnected(peer)
close(io)
end
end
torrentData.peers.delete peer
end
else
# Get our list of peers and start connecting right away
# Non-recurring and immediate timer
torrentData.managePeersTimer =
@reactor.scheduleTimer(@managePeersPeriod, [:manage_peers, torrentData.infoHash], false, true)
end
end | [
"def",
"setFrozen",
"(",
"torrent",
",",
"value",
")",
"torrentData",
"=",
"torrent",
"if",
"!",
"torrent",
".",
"is_a?",
"(",
"TorrentData",
")",
"torrentData",
"=",
"@torrentData",
"[",
"torrent",
"]",
"if",
"!",
"torrentData",
"@logger",
".",
"warn",
"\"Asked to freeze a non-existent torrent #{QuartzTorrent.bytesToHex(torrent)}\"",
"return",
"end",
"end",
"if",
"value",
"# Disconnect from all peers so we won't reply to any messages.",
"torrentData",
".",
"peers",
".",
"all",
".",
"each",
"do",
"|",
"peer",
"|",
"if",
"peer",
".",
"state",
"!=",
":disconnected",
"# Close socket ",
"withPeersIo",
"(",
"peer",
",",
"\"when removing torrent\"",
")",
"do",
"|",
"io",
"|",
"setPeerDisconnected",
"(",
"peer",
")",
"close",
"(",
"io",
")",
"end",
"end",
"torrentData",
".",
"peers",
".",
"delete",
"peer",
"end",
"else",
"# Get our list of peers and start connecting right away",
"# Non-recurring and immediate timer",
"torrentData",
".",
"managePeersTimer",
"=",
"@reactor",
".",
"scheduleTimer",
"(",
"@managePeersPeriod",
",",
"[",
":manage_peers",
",",
"torrentData",
".",
"infoHash",
"]",
",",
"false",
",",
"true",
")",
"end",
"end"
] | Freeze or unfreeze a torrent. If value is true, then we disconnect from all peers for this torrent and forget
the peers. If value is false, we start reconnecting to peers.
Parameter torrent can be an infoHash or TorrentData | [
"Freeze",
"or",
"unfreeze",
"a",
"torrent",
".",
"If",
"value",
"is",
"true",
"then",
"we",
"disconnect",
"from",
"all",
"peers",
"for",
"this",
"torrent",
"and",
"forget",
"the",
"peers",
".",
"If",
"value",
"is",
"false",
"we",
"start",
"reconnecting",
"to",
"peers",
".",
"Parameter",
"torrent",
"can",
"be",
"an",
"infoHash",
"or",
"TorrentData"
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L1681-L1709 |
2,227 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClient.addTorrentByMetainfo | def addTorrentByMetainfo(metainfo)
raise "addTorrentByMetainfo should be called with a Metainfo object, not #{metainfo.class}" if ! metainfo.is_a?(Metainfo)
trackerclient = TrackerClient.createFromMetainfo(metainfo, false)
addTorrent(trackerclient, metainfo.infoHash, metainfo.info)
end | ruby | def addTorrentByMetainfo(metainfo)
raise "addTorrentByMetainfo should be called with a Metainfo object, not #{metainfo.class}" if ! metainfo.is_a?(Metainfo)
trackerclient = TrackerClient.createFromMetainfo(metainfo, false)
addTorrent(trackerclient, metainfo.infoHash, metainfo.info)
end | [
"def",
"addTorrentByMetainfo",
"(",
"metainfo",
")",
"raise",
"\"addTorrentByMetainfo should be called with a Metainfo object, not #{metainfo.class}\"",
"if",
"!",
"metainfo",
".",
"is_a?",
"(",
"Metainfo",
")",
"trackerclient",
"=",
"TrackerClient",
".",
"createFromMetainfo",
"(",
"metainfo",
",",
"false",
")",
"addTorrent",
"(",
"trackerclient",
",",
"metainfo",
".",
"infoHash",
",",
"metainfo",
".",
"info",
")",
"end"
] | Add a new torrent to manage described by a Metainfo object. This is generally the
method to call if you have a .torrent file.
Returns the infoHash of the newly added torrent. | [
"Add",
"a",
"new",
"torrent",
"to",
"manage",
"described",
"by",
"a",
"Metainfo",
"object",
".",
"This",
"is",
"generally",
"the",
"method",
"to",
"call",
"if",
"you",
"have",
"a",
".",
"torrent",
"file",
".",
"Returns",
"the",
"infoHash",
"of",
"the",
"newly",
"added",
"torrent",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L1780-L1784 |
2,228 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClient.addTorrentWithoutMetainfo | def addTorrentWithoutMetainfo(announceUrl, infoHash, magnet = nil)
raise "addTorrentWithoutMetainfo should be called with a Magnet object, not a #{magnet.class}" if magnet && ! magnet.is_a?(MagnetURI)
trackerclient = TrackerClient.create(announceUrl, infoHash, 0, false)
addTorrent(trackerclient, infoHash, nil, magnet)
end | ruby | def addTorrentWithoutMetainfo(announceUrl, infoHash, magnet = nil)
raise "addTorrentWithoutMetainfo should be called with a Magnet object, not a #{magnet.class}" if magnet && ! magnet.is_a?(MagnetURI)
trackerclient = TrackerClient.create(announceUrl, infoHash, 0, false)
addTorrent(trackerclient, infoHash, nil, magnet)
end | [
"def",
"addTorrentWithoutMetainfo",
"(",
"announceUrl",
",",
"infoHash",
",",
"magnet",
"=",
"nil",
")",
"raise",
"\"addTorrentWithoutMetainfo should be called with a Magnet object, not a #{magnet.class}\"",
"if",
"magnet",
"&&",
"!",
"magnet",
".",
"is_a?",
"(",
"MagnetURI",
")",
"trackerclient",
"=",
"TrackerClient",
".",
"create",
"(",
"announceUrl",
",",
"infoHash",
",",
"0",
",",
"false",
")",
"addTorrent",
"(",
"trackerclient",
",",
"infoHash",
",",
"nil",
",",
"magnet",
")",
"end"
] | Add a new torrent to manage given an announceUrl and an infoHash. The announceUrl may be a list.
Returns the infoHash of the newly added torrent. | [
"Add",
"a",
"new",
"torrent",
"to",
"manage",
"given",
"an",
"announceUrl",
"and",
"an",
"infoHash",
".",
"The",
"announceUrl",
"may",
"be",
"a",
"list",
".",
"Returns",
"the",
"infoHash",
"of",
"the",
"newly",
"added",
"torrent",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L1788-L1792 |
2,229 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClient.addTorrentByMagnetURI | def addTorrentByMagnetURI(magnet)
raise "addTorrentByMagnetURI should be called with a MagnetURI object, not a #{magnet.class}" if ! magnet.is_a?(MagnetURI)
trackerUrl = magnet.trackers
raise "addTorrentByMagnetURI can't handle magnet links that don't have a tracker URL." if !trackerUrl
addTorrentWithoutMetainfo(trackerUrl, magnet.btInfoHash, magnet)
end | ruby | def addTorrentByMagnetURI(magnet)
raise "addTorrentByMagnetURI should be called with a MagnetURI object, not a #{magnet.class}" if ! magnet.is_a?(MagnetURI)
trackerUrl = magnet.trackers
raise "addTorrentByMagnetURI can't handle magnet links that don't have a tracker URL." if !trackerUrl
addTorrentWithoutMetainfo(trackerUrl, magnet.btInfoHash, magnet)
end | [
"def",
"addTorrentByMagnetURI",
"(",
"magnet",
")",
"raise",
"\"addTorrentByMagnetURI should be called with a MagnetURI object, not a #{magnet.class}\"",
"if",
"!",
"magnet",
".",
"is_a?",
"(",
"MagnetURI",
")",
"trackerUrl",
"=",
"magnet",
".",
"trackers",
"raise",
"\"addTorrentByMagnetURI can't handle magnet links that don't have a tracker URL.\"",
"if",
"!",
"trackerUrl",
"addTorrentWithoutMetainfo",
"(",
"trackerUrl",
",",
"magnet",
".",
"btInfoHash",
",",
"magnet",
")",
"end"
] | Add a new torrent to manage given a MagnetURI object. This is generally the
method to call if you have a magnet link.
Returns the infoHash of the newly added torrent. | [
"Add",
"a",
"new",
"torrent",
"to",
"manage",
"given",
"a",
"MagnetURI",
"object",
".",
"This",
"is",
"generally",
"the",
"method",
"to",
"call",
"if",
"you",
"have",
"a",
"magnet",
"link",
".",
"Returns",
"the",
"infoHash",
"of",
"the",
"newly",
"added",
"torrent",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L1797-L1804 |
2,230 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClient.adjustBytesDownloaded | def adjustBytesDownloaded(infoHash, adjustment)
return if ! adjustment
raise "Bytes downloaded adjustment must be an Integer, not a #{adjustment.class}" if !adjustment.is_a?(Integer)
@handler.adjustBytesDownloaded(infoHash, adjustment)
end | ruby | def adjustBytesDownloaded(infoHash, adjustment)
return if ! adjustment
raise "Bytes downloaded adjustment must be an Integer, not a #{adjustment.class}" if !adjustment.is_a?(Integer)
@handler.adjustBytesDownloaded(infoHash, adjustment)
end | [
"def",
"adjustBytesDownloaded",
"(",
"infoHash",
",",
"adjustment",
")",
"return",
"if",
"!",
"adjustment",
"raise",
"\"Bytes downloaded adjustment must be an Integer, not a #{adjustment.class}\"",
"if",
"!",
"adjustment",
".",
"is_a?",
"(",
"Integer",
")",
"@handler",
".",
"adjustBytesDownloaded",
"(",
"infoHash",
",",
"adjustment",
")",
"end"
] | Adjust the bytesDownloaded property of the specified torrent by the passed amount.
Adjustment should be an integer. It is added to the current bytesUploaded amount. | [
"Adjust",
"the",
"bytesDownloaded",
"property",
"of",
"the",
"specified",
"torrent",
"by",
"the",
"passed",
"amount",
".",
"Adjustment",
"should",
"be",
"an",
"integer",
".",
"It",
"is",
"added",
"to",
"the",
"current",
"bytesUploaded",
"amount",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L1854-L1858 |
2,231 | jeffwilliams/quartz-torrent | lib/quartz_torrent/peerclient.rb | QuartzTorrent.PeerClient.addTorrent | def addTorrent(trackerclient, infoHash, info, magnet = nil)
trackerclient.port = @port
torrentData = @handler.addTrackerClient(infoHash, info, trackerclient)
torrentData.magnet = magnet
trackerclient.dynamicRequestParamsBuilder = Proc.new do
torrentData = @handler.torrentData[infoHash]
dataLength = (info ? info.dataLength : nil)
result = TrackerDynamicRequestParams.new(dataLength)
if torrentData && torrentData.blockState
result.left = torrentData.blockState.totalLength - torrentData.blockState.completedLength
result.downloaded = torrentData.bytesDownloadedDataOnly
result.uploaded = torrentData.bytesUploadedDataOnly
end
result
end
# If we haven't started yet then add this trackerclient to a queue of
# trackerclients to start once we are started. If we start too soon we
# will connect to the tracker, and it will try to connect back to us before we are listening.
if ! trackerclient.started?
if @stopped
@toStart.push trackerclient
else
trackerclient.start
end
end
torrentData.infoHash
end | ruby | def addTorrent(trackerclient, infoHash, info, magnet = nil)
trackerclient.port = @port
torrentData = @handler.addTrackerClient(infoHash, info, trackerclient)
torrentData.magnet = magnet
trackerclient.dynamicRequestParamsBuilder = Proc.new do
torrentData = @handler.torrentData[infoHash]
dataLength = (info ? info.dataLength : nil)
result = TrackerDynamicRequestParams.new(dataLength)
if torrentData && torrentData.blockState
result.left = torrentData.blockState.totalLength - torrentData.blockState.completedLength
result.downloaded = torrentData.bytesDownloadedDataOnly
result.uploaded = torrentData.bytesUploadedDataOnly
end
result
end
# If we haven't started yet then add this trackerclient to a queue of
# trackerclients to start once we are started. If we start too soon we
# will connect to the tracker, and it will try to connect back to us before we are listening.
if ! trackerclient.started?
if @stopped
@toStart.push trackerclient
else
trackerclient.start
end
end
torrentData.infoHash
end | [
"def",
"addTorrent",
"(",
"trackerclient",
",",
"infoHash",
",",
"info",
",",
"magnet",
"=",
"nil",
")",
"trackerclient",
".",
"port",
"=",
"@port",
"torrentData",
"=",
"@handler",
".",
"addTrackerClient",
"(",
"infoHash",
",",
"info",
",",
"trackerclient",
")",
"torrentData",
".",
"magnet",
"=",
"magnet",
"trackerclient",
".",
"dynamicRequestParamsBuilder",
"=",
"Proc",
".",
"new",
"do",
"torrentData",
"=",
"@handler",
".",
"torrentData",
"[",
"infoHash",
"]",
"dataLength",
"=",
"(",
"info",
"?",
"info",
".",
"dataLength",
":",
"nil",
")",
"result",
"=",
"TrackerDynamicRequestParams",
".",
"new",
"(",
"dataLength",
")",
"if",
"torrentData",
"&&",
"torrentData",
".",
"blockState",
"result",
".",
"left",
"=",
"torrentData",
".",
"blockState",
".",
"totalLength",
"-",
"torrentData",
".",
"blockState",
".",
"completedLength",
"result",
".",
"downloaded",
"=",
"torrentData",
".",
"bytesDownloadedDataOnly",
"result",
".",
"uploaded",
"=",
"torrentData",
".",
"bytesUploadedDataOnly",
"end",
"result",
"end",
"# If we haven't started yet then add this trackerclient to a queue of ",
"# trackerclients to start once we are started. If we start too soon we ",
"# will connect to the tracker, and it will try to connect back to us before we are listening.",
"if",
"!",
"trackerclient",
".",
"started?",
"if",
"@stopped",
"@toStart",
".",
"push",
"trackerclient",
"else",
"trackerclient",
".",
"start",
"end",
"end",
"torrentData",
".",
"infoHash",
"end"
] | Helper method for adding a torrent. | [
"Helper",
"method",
"for",
"adding",
"a",
"torrent",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/peerclient.rb#L1867-L1897 |
2,232 | rjurado01/rapidoc | lib/rapidoc/config.rb | Rapidoc.Config.target_dir | def target_dir( f = nil )
if File.exists?( config_file_path )
form_file_name( target_dir_from_config, f )
else
form_file_name( File.join( ::Rails.root.to_s, 'public/docs' ), f )
end
end | ruby | def target_dir( f = nil )
if File.exists?( config_file_path )
form_file_name( target_dir_from_config, f )
else
form_file_name( File.join( ::Rails.root.to_s, 'public/docs' ), f )
end
end | [
"def",
"target_dir",
"(",
"f",
"=",
"nil",
")",
"if",
"File",
".",
"exists?",
"(",
"config_file_path",
")",
"form_file_name",
"(",
"target_dir_from_config",
",",
"f",
")",
"else",
"form_file_name",
"(",
"File",
".",
"join",
"(",
"::",
"Rails",
".",
"root",
".",
"to_s",
",",
"'public/docs'",
")",
",",
"f",
")",
"end",
"end"
] | return the directory where rapidoc generates the doc | [
"return",
"the",
"directory",
"where",
"rapidoc",
"generates",
"the",
"doc"
] | 03b7a8f29a37dd03f4ed5036697b48551d3b4ae6 | https://github.com/rjurado01/rapidoc/blob/03b7a8f29a37dd03f4ed5036697b48551d3b4ae6/lib/rapidoc/config.rb#L79-L85 |
2,233 | rjurado01/rapidoc | lib/rapidoc/config.rb | Rapidoc.Config.examples_dir | def examples_dir( f = nil )
if File.exists?( config_file_path )
form_file_name( examples_dir_from_config_file, f )
else
form_file_name( config_dir( '/examples' ), f )
end
end | ruby | def examples_dir( f = nil )
if File.exists?( config_file_path )
form_file_name( examples_dir_from_config_file, f )
else
form_file_name( config_dir( '/examples' ), f )
end
end | [
"def",
"examples_dir",
"(",
"f",
"=",
"nil",
")",
"if",
"File",
".",
"exists?",
"(",
"config_file_path",
")",
"form_file_name",
"(",
"examples_dir_from_config_file",
",",
"f",
")",
"else",
"form_file_name",
"(",
"config_dir",
"(",
"'/examples'",
")",
",",
"f",
")",
"end",
"end"
] | returns the directory where rapidoc searches for examples | [
"returns",
"the",
"directory",
"where",
"rapidoc",
"searches",
"for",
"examples"
] | 03b7a8f29a37dd03f4ed5036697b48551d3b4ae6 | https://github.com/rjurado01/rapidoc/blob/03b7a8f29a37dd03f4ed5036697b48551d3b4ae6/lib/rapidoc/config.rb#L93-L99 |
2,234 | philm/twilio | lib/twilio/verb.rb | Twilio.Verb.say | def say(*args)
options = {:voice => 'man', :language => 'en', :loop => 1}
args.each do |arg|
case arg
when String
options[:text_to_speak] = arg
when Hash
options.merge!(arg)
else
raise ArgumentError, 'say expects String or Hash argument'
end
end
output {
if options[:pause]
loop_with_pause(options[:loop], @xml) do
@xml.Say(options[:text_to_speak], :voice => options[:voice], :language => options[:language])
end
else
@xml.Say(options[:text_to_speak], :voice => options[:voice], :language => options[:language], :loop => options[:loop])
end
}
end | ruby | def say(*args)
options = {:voice => 'man', :language => 'en', :loop => 1}
args.each do |arg|
case arg
when String
options[:text_to_speak] = arg
when Hash
options.merge!(arg)
else
raise ArgumentError, 'say expects String or Hash argument'
end
end
output {
if options[:pause]
loop_with_pause(options[:loop], @xml) do
@xml.Say(options[:text_to_speak], :voice => options[:voice], :language => options[:language])
end
else
@xml.Say(options[:text_to_speak], :voice => options[:voice], :language => options[:language], :loop => options[:loop])
end
}
end | [
"def",
"say",
"(",
"*",
"args",
")",
"options",
"=",
"{",
":voice",
"=>",
"'man'",
",",
":language",
"=>",
"'en'",
",",
":loop",
"=>",
"1",
"}",
"args",
".",
"each",
"do",
"|",
"arg",
"|",
"case",
"arg",
"when",
"String",
"options",
"[",
":text_to_speak",
"]",
"=",
"arg",
"when",
"Hash",
"options",
".",
"merge!",
"(",
"arg",
")",
"else",
"raise",
"ArgumentError",
",",
"'say expects String or Hash argument'",
"end",
"end",
"output",
"{",
"if",
"options",
"[",
":pause",
"]",
"loop_with_pause",
"(",
"options",
"[",
":loop",
"]",
",",
"@xml",
")",
"do",
"@xml",
".",
"Say",
"(",
"options",
"[",
":text_to_speak",
"]",
",",
":voice",
"=>",
"options",
"[",
":voice",
"]",
",",
":language",
"=>",
"options",
"[",
":language",
"]",
")",
"end",
"else",
"@xml",
".",
"Say",
"(",
"options",
"[",
":text_to_speak",
"]",
",",
":voice",
"=>",
"options",
"[",
":voice",
"]",
",",
":language",
"=>",
"options",
"[",
":language",
"]",
",",
":loop",
"=>",
"options",
"[",
":loop",
"]",
")",
"end",
"}",
"end"
] | The Say verb converts text to speech that is read back to the caller.
Say is useful for dynamic text that is difficult to prerecord.
Examples:
Twilio::Verb.say 'The time is 9:35 PM.'
Twilio::Verb.say 'The time is 9:35 PM.', :loop => 3
With numbers, 12345 will be spoken as "twelve thousand three hundred forty five" while
1 2 3 4 5 will be spoken as "one two three four five."
Twilio::Verb.say 'Your PIN is 1234', :loop => 4
Twilio::Verb.say 'Your PIN is 1 2 3 4', :loop => 4
If you need a longer pause between each loop, instead of explicitly calling the Pause
verb within a block, you can set the convenient pause option:
Twilio::Verb.say 'Your PIN is 1 2 3 4', :loop => 4, :pause => true
Options (see http://www.twilio.com/docs/api_reference/TwiML/say) are passed in as a hash:
Twilio::Verb.say 'The time is 9:35 PM.', :voice => 'woman'
Twilio::Verb.say 'The time is 9:35 PM.', :voice => 'woman', :language => 'es' | [
"The",
"Say",
"verb",
"converts",
"text",
"to",
"speech",
"that",
"is",
"read",
"back",
"to",
"the",
"caller",
".",
"Say",
"is",
"useful",
"for",
"dynamic",
"text",
"that",
"is",
"difficult",
"to",
"prerecord",
"."
] | 81c05795924bbfa780ea44efd52d7ca5670bcb55 | https://github.com/philm/twilio/blob/81c05795924bbfa780ea44efd52d7ca5670bcb55/lib/twilio/verb.rb#L62-L84 |
2,235 | philm/twilio | lib/twilio/verb.rb | Twilio.Verb.gather | def gather(*args, &block)
options = args.shift || {}
output {
if block_given?
@xml.Gather(options) { block.call}
else
@xml.Gather(options)
end
}
end | ruby | def gather(*args, &block)
options = args.shift || {}
output {
if block_given?
@xml.Gather(options) { block.call}
else
@xml.Gather(options)
end
}
end | [
"def",
"gather",
"(",
"*",
"args",
",",
"&",
"block",
")",
"options",
"=",
"args",
".",
"shift",
"||",
"{",
"}",
"output",
"{",
"if",
"block_given?",
"@xml",
".",
"Gather",
"(",
"options",
")",
"{",
"block",
".",
"call",
"}",
"else",
"@xml",
".",
"Gather",
"(",
"options",
")",
"end",
"}",
"end"
] | The Gather verb collects digits entered by a caller into their telephone keypad.
When the caller is done entering data, Twilio submits that data to a provided URL,
as either a HTTP GET or POST request, just like a web browser submits data from an HTML form.
Options (see http://www.twilio.com/docs/api_reference/TwiML/gather) are passed in as a hash
Examples:
Twilio::Verb.gather
Twilio::Verb.gather :action => 'http://foobar.com'
Twilio::Verb.gather :finishOnKey => '*'
Twilio::Verb.gather :action => 'http://foobar.com', :finishOnKey => '*'
Gather also lets you nest the Play, Say, and Pause verbs:
verb = Twilio::Verb.new { |v|
v.gather(:action => '/process_gather', :method => 'GET) {
v.say 'Please enter your account number followed by the pound sign'
}
v.say "We didn't receive any input. Goodbye!"
}
verb.response # represents the final xml output | [
"The",
"Gather",
"verb",
"collects",
"digits",
"entered",
"by",
"a",
"caller",
"into",
"their",
"telephone",
"keypad",
".",
"When",
"the",
"caller",
"is",
"done",
"entering",
"data",
"Twilio",
"submits",
"that",
"data",
"to",
"a",
"provided",
"URL",
"as",
"either",
"a",
"HTTP",
"GET",
"or",
"POST",
"request",
"just",
"like",
"a",
"web",
"browser",
"submits",
"data",
"from",
"an",
"HTML",
"form",
"."
] | 81c05795924bbfa780ea44efd52d7ca5670bcb55 | https://github.com/philm/twilio/blob/81c05795924bbfa780ea44efd52d7ca5670bcb55/lib/twilio/verb.rb#L143-L152 |
2,236 | philm/twilio | lib/twilio/verb.rb | Twilio.Verb.dial | def dial(*args, &block)
number_to_dial = ''
options = {}
args.each do |arg|
case arg
when String
number_to_dial = arg
when Hash
options.merge!(arg)
else
raise ArgumentError, 'dial expects String or Hash argument'
end
end
output {
if block_given?
@xml.Dial(options) { block.call }
else
@xml.Dial(number_to_dial, options)
end
}
end | ruby | def dial(*args, &block)
number_to_dial = ''
options = {}
args.each do |arg|
case arg
when String
number_to_dial = arg
when Hash
options.merge!(arg)
else
raise ArgumentError, 'dial expects String or Hash argument'
end
end
output {
if block_given?
@xml.Dial(options) { block.call }
else
@xml.Dial(number_to_dial, options)
end
}
end | [
"def",
"dial",
"(",
"*",
"args",
",",
"&",
"block",
")",
"number_to_dial",
"=",
"''",
"options",
"=",
"{",
"}",
"args",
".",
"each",
"do",
"|",
"arg",
"|",
"case",
"arg",
"when",
"String",
"number_to_dial",
"=",
"arg",
"when",
"Hash",
"options",
".",
"merge!",
"(",
"arg",
")",
"else",
"raise",
"ArgumentError",
",",
"'dial expects String or Hash argument'",
"end",
"end",
"output",
"{",
"if",
"block_given?",
"@xml",
".",
"Dial",
"(",
"options",
")",
"{",
"block",
".",
"call",
"}",
"else",
"@xml",
".",
"Dial",
"(",
"number_to_dial",
",",
"options",
")",
"end",
"}",
"end"
] | The Dial verb connects the current caller to an another phone. If the called party picks up,
the two parties are connected and can communicate until one hangs up. If the called party does
not pick up, if a busy signal is received, or the number doesn't exist, the dial verb will finish.
If an action verb is provided, Twilio will submit the outcome of the call attempt to the action URL.
If no action is provided, Dial will fall through to the next verb in the document.
Note: this is different than the behavior of Record and Gather. Dial does not submit back to the
current document URL if no action is provided.
Options (see http://www.twilio.com/docs/api_reference/TwiML/dial) are passed in as a hash
Examples:
Twilio::Verb.dial '415-123-4567'
Twilio::Verb.dial '415-123-4567', :action => 'http://foobar.com'
Twilio::Verb.dial '415-123-4567', :timeout => 10, :callerId => '858-987-6543'
Twilio also supports an alternate form in which a Number object is nested inside Dial:
verb = Twilio::Verb.new { |v|
v.dial { |v|
v.number '415-123-4567'
v.number '415-123-4568'
v.number '415-123-4569'
}
}
verb.response # represents the final xml output | [
"The",
"Dial",
"verb",
"connects",
"the",
"current",
"caller",
"to",
"an",
"another",
"phone",
".",
"If",
"the",
"called",
"party",
"picks",
"up",
"the",
"two",
"parties",
"are",
"connected",
"and",
"can",
"communicate",
"until",
"one",
"hangs",
"up",
".",
"If",
"the",
"called",
"party",
"does",
"not",
"pick",
"up",
"if",
"a",
"busy",
"signal",
"is",
"received",
"or",
"the",
"number",
"doesn",
"t",
"exist",
"the",
"dial",
"verb",
"will",
"finish",
"."
] | 81c05795924bbfa780ea44efd52d7ca5670bcb55 | https://github.com/philm/twilio/blob/81c05795924bbfa780ea44efd52d7ca5670bcb55/lib/twilio/verb.rb#L198-L219 |
2,237 | rjurado01/rapidoc | lib/rapidoc/resource_doc.rb | Rapidoc.ResourceDoc.generate_info | def generate_info( routes_info )
if routes_info
extractor = get_controller_extractor
@description = extractor.get_resource_info['description'] if extractor
@actions_doc = get_actions_doc( routes_info, extractor )
# template need that description will be an array
@description = [ @description ] unless @description.class == Array
end
end | ruby | def generate_info( routes_info )
if routes_info
extractor = get_controller_extractor
@description = extractor.get_resource_info['description'] if extractor
@actions_doc = get_actions_doc( routes_info, extractor )
# template need that description will be an array
@description = [ @description ] unless @description.class == Array
end
end | [
"def",
"generate_info",
"(",
"routes_info",
")",
"if",
"routes_info",
"extractor",
"=",
"get_controller_extractor",
"@description",
"=",
"extractor",
".",
"get_resource_info",
"[",
"'description'",
"]",
"if",
"extractor",
"@actions_doc",
"=",
"get_actions_doc",
"(",
"routes_info",
",",
"extractor",
")",
"# template need that description will be an array",
"@description",
"=",
"[",
"@description",
"]",
"unless",
"@description",
".",
"class",
"==",
"Array",
"end",
"end"
] | Create description and actions_doc | [
"Create",
"description",
"and",
"actions_doc"
] | 03b7a8f29a37dd03f4ed5036697b48551d3b4ae6 | https://github.com/rjurado01/rapidoc/blob/03b7a8f29a37dd03f4ed5036697b48551d3b4ae6/lib/rapidoc/resource_doc.rb#L36-L45 |
2,238 | jeffwilliams/quartz-torrent | lib/quartz_torrent/filemanager.rb | QuartzTorrent.PieceMapper.findBlock | def findBlock(pieceIndex, offset, length)
leftOffset = @pieceSize*pieceIndex + offset
rightOffset = leftOffset + length-1
findPart(leftOffset, rightOffset)
end | ruby | def findBlock(pieceIndex, offset, length)
leftOffset = @pieceSize*pieceIndex + offset
rightOffset = leftOffset + length-1
findPart(leftOffset, rightOffset)
end | [
"def",
"findBlock",
"(",
"pieceIndex",
",",
"offset",
",",
"length",
")",
"leftOffset",
"=",
"@pieceSize",
"pieceIndex",
"+",
"offset",
"rightOffset",
"=",
"leftOffset",
"+",
"length",
"-",
"1",
"findPart",
"(",
"leftOffset",
",",
"rightOffset",
")",
"end"
] | Return a list of FileRegion objects. The FileRegion offsets specify
in order which regions of files the piece covers. | [
"Return",
"a",
"list",
"of",
"FileRegion",
"objects",
".",
"The",
"FileRegion",
"offsets",
"specify",
"in",
"order",
"which",
"regions",
"of",
"files",
"the",
"piece",
"covers",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/filemanager.rb#L75-L80 |
2,239 | jeffwilliams/quartz-torrent | lib/quartz_torrent/filemanager.rb | QuartzTorrent.PieceIO.writeBlock | def writeBlock(pieceIndex, offset, block)
regions = @pieceMapper.findBlock(pieceIndex, offset, block.length)
indexInBlock = 0
regions.each do |region|
# Get the IO for the file with path 'path'. If we are being used in a reactor, this is the IO facade. If we
# are not then this is a real IO.
io = @ioManager.get(region.path)
if ! io
# No IO for this file.
raise "This process doesn't have write permission for the file #{region.path}" if File.exists?(region.path) && ! File.writable?(region.path)
# Ensure parent directories exist.
dir = File.dirname region.path
FileUtils.mkdir_p dir if ! File.directory?(dir)
begin
io = @ioManager.open(region.path)
rescue
@logger.error "Opening file #{region.path} failed: #{$!}"
raise "Opening file #{region.path} failed"
end
end
io.seek region.offset, IO::SEEK_SET
begin
io.write(block[indexInBlock, region.length])
indexInBlock += region.length
rescue
# Error when writing...
@logger.error "Writing block to file #{region.path} failed: #{$!}"
piece = nil
break
end
break if indexInBlock >= block.length
end
end | ruby | def writeBlock(pieceIndex, offset, block)
regions = @pieceMapper.findBlock(pieceIndex, offset, block.length)
indexInBlock = 0
regions.each do |region|
# Get the IO for the file with path 'path'. If we are being used in a reactor, this is the IO facade. If we
# are not then this is a real IO.
io = @ioManager.get(region.path)
if ! io
# No IO for this file.
raise "This process doesn't have write permission for the file #{region.path}" if File.exists?(region.path) && ! File.writable?(region.path)
# Ensure parent directories exist.
dir = File.dirname region.path
FileUtils.mkdir_p dir if ! File.directory?(dir)
begin
io = @ioManager.open(region.path)
rescue
@logger.error "Opening file #{region.path} failed: #{$!}"
raise "Opening file #{region.path} failed"
end
end
io.seek region.offset, IO::SEEK_SET
begin
io.write(block[indexInBlock, region.length])
indexInBlock += region.length
rescue
# Error when writing...
@logger.error "Writing block to file #{region.path} failed: #{$!}"
piece = nil
break
end
break if indexInBlock >= block.length
end
end | [
"def",
"writeBlock",
"(",
"pieceIndex",
",",
"offset",
",",
"block",
")",
"regions",
"=",
"@pieceMapper",
".",
"findBlock",
"(",
"pieceIndex",
",",
"offset",
",",
"block",
".",
"length",
")",
"indexInBlock",
"=",
"0",
"regions",
".",
"each",
"do",
"|",
"region",
"|",
"# Get the IO for the file with path 'path'. If we are being used in a reactor, this is the IO facade. If we",
"# are not then this is a real IO.",
"io",
"=",
"@ioManager",
".",
"get",
"(",
"region",
".",
"path",
")",
"if",
"!",
"io",
"# No IO for this file. ",
"raise",
"\"This process doesn't have write permission for the file #{region.path}\"",
"if",
"File",
".",
"exists?",
"(",
"region",
".",
"path",
")",
"&&",
"!",
"File",
".",
"writable?",
"(",
"region",
".",
"path",
")",
"# Ensure parent directories exist.",
"dir",
"=",
"File",
".",
"dirname",
"region",
".",
"path",
"FileUtils",
".",
"mkdir_p",
"dir",
"if",
"!",
"File",
".",
"directory?",
"(",
"dir",
")",
"begin",
"io",
"=",
"@ioManager",
".",
"open",
"(",
"region",
".",
"path",
")",
"rescue",
"@logger",
".",
"error",
"\"Opening file #{region.path} failed: #{$!}\"",
"raise",
"\"Opening file #{region.path} failed\"",
"end",
"end",
"io",
".",
"seek",
"region",
".",
"offset",
",",
"IO",
"::",
"SEEK_SET",
"begin",
"io",
".",
"write",
"(",
"block",
"[",
"indexInBlock",
",",
"region",
".",
"length",
"]",
")",
"indexInBlock",
"+=",
"region",
".",
"length",
"rescue",
"# Error when writing...",
"@logger",
".",
"error",
"\"Writing block to file #{region.path} failed: #{$!}\"",
"piece",
"=",
"nil",
"break",
"end",
"break",
"if",
"indexInBlock",
">=",
"block",
".",
"length",
"end",
"end"
] | Write a block to an in-progress piece. The block is written to
piece 'peiceIndex', at offset 'offset'. The block data is in block.
Throws exceptions on failure. | [
"Write",
"a",
"block",
"to",
"an",
"in",
"-",
"progress",
"piece",
".",
"The",
"block",
"is",
"written",
"to",
"piece",
"peiceIndex",
"at",
"offset",
"offset",
".",
"The",
"block",
"data",
"is",
"in",
"block",
".",
"Throws",
"exceptions",
"on",
"failure",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/filemanager.rb#L163-L199 |
2,240 | jeffwilliams/quartz-torrent | lib/quartz_torrent/filemanager.rb | QuartzTorrent.PieceIO.readRegions | def readRegions(regions)
piece = ""
regions.each do |region|
# Get the IO for the file with path 'path'. If we are being used in a reactor, this is the IO facade. If we
# are not then this is a real IO.
io = @ioManager.get(region.path)
if ! io
# No IO for this file.
if ! File.exists?(region.path)
# This file hasn't been created yet by having blocks written to it.
piece = nil
break
end
raise "This process doesn't have read permission for the file #{region.path}" if ! File.readable?(region.path)
begin
io = @ioManager.open(region.path)
rescue
@logger.error "Opening file #{region.path} failed: #{$!}"
raise "Opening file #{region.path} failed"
end
end
io.seek region.offset, IO::SEEK_SET
begin
piece << io.read(region.length)
rescue
# Error when reading. Likely EOF, meaning this peice isn't all there yet.
piece = nil
break
end
end
piece
end | ruby | def readRegions(regions)
piece = ""
regions.each do |region|
# Get the IO for the file with path 'path'. If we are being used in a reactor, this is the IO facade. If we
# are not then this is a real IO.
io = @ioManager.get(region.path)
if ! io
# No IO for this file.
if ! File.exists?(region.path)
# This file hasn't been created yet by having blocks written to it.
piece = nil
break
end
raise "This process doesn't have read permission for the file #{region.path}" if ! File.readable?(region.path)
begin
io = @ioManager.open(region.path)
rescue
@logger.error "Opening file #{region.path} failed: #{$!}"
raise "Opening file #{region.path} failed"
end
end
io.seek region.offset, IO::SEEK_SET
begin
piece << io.read(region.length)
rescue
# Error when reading. Likely EOF, meaning this peice isn't all there yet.
piece = nil
break
end
end
piece
end | [
"def",
"readRegions",
"(",
"regions",
")",
"piece",
"=",
"\"\"",
"regions",
".",
"each",
"do",
"|",
"region",
"|",
"# Get the IO for the file with path 'path'. If we are being used in a reactor, this is the IO facade. If we",
"# are not then this is a real IO.",
"io",
"=",
"@ioManager",
".",
"get",
"(",
"region",
".",
"path",
")",
"if",
"!",
"io",
"# No IO for this file. ",
"if",
"!",
"File",
".",
"exists?",
"(",
"region",
".",
"path",
")",
"# This file hasn't been created yet by having blocks written to it.",
"piece",
"=",
"nil",
"break",
"end",
"raise",
"\"This process doesn't have read permission for the file #{region.path}\"",
"if",
"!",
"File",
".",
"readable?",
"(",
"region",
".",
"path",
")",
"begin",
"io",
"=",
"@ioManager",
".",
"open",
"(",
"region",
".",
"path",
")",
"rescue",
"@logger",
".",
"error",
"\"Opening file #{region.path} failed: #{$!}\"",
"raise",
"\"Opening file #{region.path} failed\"",
"end",
"end",
"io",
".",
"seek",
"region",
".",
"offset",
",",
"IO",
"::",
"SEEK_SET",
"begin",
"piece",
"<<",
"io",
".",
"read",
"(",
"region",
".",
"length",
")",
"rescue",
"# Error when reading. Likely EOF, meaning this peice isn't all there yet.",
"piece",
"=",
"nil",
"break",
"end",
"end",
"piece",
"end"
] | Pass an ordered list of FileRegions to load. | [
"Pass",
"an",
"ordered",
"list",
"of",
"FileRegions",
"to",
"load",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/filemanager.rb#L220-L253 |
2,241 | jeffwilliams/quartz-torrent | lib/quartz_torrent/filemanager.rb | QuartzTorrent.PieceManager.readBlock | def readBlock(pieceIndex, offset, length)
id = returnAndIncrRequestId
return id if @state == :after_stop
@requests.push [id, :read_block, pieceIndex, offset, length]
@requestsSemaphore.signal
id
end | ruby | def readBlock(pieceIndex, offset, length)
id = returnAndIncrRequestId
return id if @state == :after_stop
@requests.push [id, :read_block, pieceIndex, offset, length]
@requestsSemaphore.signal
id
end | [
"def",
"readBlock",
"(",
"pieceIndex",
",",
"offset",
",",
"length",
")",
"id",
"=",
"returnAndIncrRequestId",
"return",
"id",
"if",
"@state",
"==",
":after_stop",
"@requests",
".",
"push",
"[",
"id",
",",
":read_block",
",",
"pieceIndex",
",",
"offset",
",",
"length",
"]",
"@requestsSemaphore",
".",
"signal",
"id",
"end"
] | Read a block from the torrent asynchronously. When the operation
is complete the result is stored in the 'results' list.
This method returns an id that can be used to match the response
to the request.
The readBlock and writeBlock methods are not threadsafe with respect to callers;
they shouldn't be called by multiple threads concurrently. | [
"Read",
"a",
"block",
"from",
"the",
"torrent",
"asynchronously",
".",
"When",
"the",
"operation",
"is",
"complete",
"the",
"result",
"is",
"stored",
"in",
"the",
"results",
"list",
".",
"This",
"method",
"returns",
"an",
"id",
"that",
"can",
"be",
"used",
"to",
"match",
"the",
"response",
"to",
"the",
"request",
".",
"The",
"readBlock",
"and",
"writeBlock",
"methods",
"are",
"not",
"threadsafe",
"with",
"respect",
"to",
"callers",
";",
"they",
"shouldn",
"t",
"be",
"called",
"by",
"multiple",
"threads",
"concurrently",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/filemanager.rb#L319-L325 |
2,242 | jeffwilliams/quartz-torrent | lib/quartz_torrent/filemanager.rb | QuartzTorrent.PieceManager.writeBlock | def writeBlock(pieceIndex, offset, block)
id = returnAndIncrRequestId
return id if @state == :after_stop
@requests.push [id, :write_block, pieceIndex, offset, block]
@requestsSemaphore.signal
id
end | ruby | def writeBlock(pieceIndex, offset, block)
id = returnAndIncrRequestId
return id if @state == :after_stop
@requests.push [id, :write_block, pieceIndex, offset, block]
@requestsSemaphore.signal
id
end | [
"def",
"writeBlock",
"(",
"pieceIndex",
",",
"offset",
",",
"block",
")",
"id",
"=",
"returnAndIncrRequestId",
"return",
"id",
"if",
"@state",
"==",
":after_stop",
"@requests",
".",
"push",
"[",
"id",
",",
":write_block",
",",
"pieceIndex",
",",
"offset",
",",
"block",
"]",
"@requestsSemaphore",
".",
"signal",
"id",
"end"
] | Write a block to the torrent asynchronously. | [
"Write",
"a",
"block",
"to",
"the",
"torrent",
"asynchronously",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/filemanager.rb#L328-L334 |
2,243 | jeffwilliams/quartz-torrent | lib/quartz_torrent/filemanager.rb | QuartzTorrent.PieceManager.readPiece | def readPiece(pieceIndex)
id = returnAndIncrRequestId
return id if @state == :after_stop
@requests.push [id, :read_piece, pieceIndex]
@requestsSemaphore.signal
id
end | ruby | def readPiece(pieceIndex)
id = returnAndIncrRequestId
return id if @state == :after_stop
@requests.push [id, :read_piece, pieceIndex]
@requestsSemaphore.signal
id
end | [
"def",
"readPiece",
"(",
"pieceIndex",
")",
"id",
"=",
"returnAndIncrRequestId",
"return",
"id",
"if",
"@state",
"==",
":after_stop",
"@requests",
".",
"push",
"[",
"id",
",",
":read_piece",
",",
"pieceIndex",
"]",
"@requestsSemaphore",
".",
"signal",
"id",
"end"
] | Read a block of the torrent asynchronously. | [
"Read",
"a",
"block",
"of",
"the",
"torrent",
"asynchronously",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/filemanager.rb#L337-L343 |
2,244 | jeffwilliams/quartz-torrent | lib/quartz_torrent/filemanager.rb | QuartzTorrent.PieceManager.checkPieceHash | def checkPieceHash(pieceIndex)
id = returnAndIncrRequestId
return id if @state == :after_stop
@requests.push [id, :hash_piece, pieceIndex]
@requestsSemaphore.signal
id
end | ruby | def checkPieceHash(pieceIndex)
id = returnAndIncrRequestId
return id if @state == :after_stop
@requests.push [id, :hash_piece, pieceIndex]
@requestsSemaphore.signal
id
end | [
"def",
"checkPieceHash",
"(",
"pieceIndex",
")",
"id",
"=",
"returnAndIncrRequestId",
"return",
"id",
"if",
"@state",
"==",
":after_stop",
"@requests",
".",
"push",
"[",
"id",
",",
":hash_piece",
",",
"pieceIndex",
"]",
"@requestsSemaphore",
".",
"signal",
"id",
"end"
] | Validate that the hash of the downloaded piece matches the hash from the metainfo.
The result is successful? if the hash matches, false otherwise. The data of the result is
set to the piece index. | [
"Validate",
"that",
"the",
"hash",
"of",
"the",
"downloaded",
"piece",
"matches",
"the",
"hash",
"from",
"the",
"metainfo",
".",
"The",
"result",
"is",
"successful?",
"if",
"the",
"hash",
"matches",
"false",
"otherwise",
".",
"The",
"data",
"of",
"the",
"result",
"is",
"set",
"to",
"the",
"piece",
"index",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/filemanager.rb#L360-L366 |
2,245 | poise/halite | lib/halite/gem.rb | Halite.Gem.license_header | def license_header
IO.readlines(spec_file).take_while { |line| line.strip.empty? || line.strip.start_with?('#') }.join('')
end | ruby | def license_header
IO.readlines(spec_file).take_while { |line| line.strip.empty? || line.strip.start_with?('#') }.join('')
end | [
"def",
"license_header",
"IO",
".",
"readlines",
"(",
"spec_file",
")",
".",
"take_while",
"{",
"|",
"line",
"|",
"line",
".",
"strip",
".",
"empty?",
"||",
"line",
".",
"strip",
".",
"start_with?",
"(",
"'#'",
")",
"}",
".",
"join",
"(",
"''",
")",
"end"
] | License header extacted from the gemspec. Suitable for inclusion in other
Ruby source files.
@return [String] | [
"License",
"header",
"extacted",
"from",
"the",
"gemspec",
".",
"Suitable",
"for",
"inclusion",
"in",
"other",
"Ruby",
"source",
"files",
"."
] | 9ae174e6b7c5d4674f3301394e14567fa89a8b3e | https://github.com/poise/halite/blob/9ae174e6b7c5d4674f3301394e14567fa89a8b3e/lib/halite/gem.rb#L104-L106 |
2,246 | poise/halite | lib/halite/gem.rb | Halite.Gem.issues_url | def issues_url
if spec.metadata['issues_url']
spec.metadata['issues_url']
elsif spec.homepage =~ /^http(s)?:\/\/(www\.)?github\.com/
spec.homepage.chomp('/') + '/issues'
end
end | ruby | def issues_url
if spec.metadata['issues_url']
spec.metadata['issues_url']
elsif spec.homepage =~ /^http(s)?:\/\/(www\.)?github\.com/
spec.homepage.chomp('/') + '/issues'
end
end | [
"def",
"issues_url",
"if",
"spec",
".",
"metadata",
"[",
"'issues_url'",
"]",
"spec",
".",
"metadata",
"[",
"'issues_url'",
"]",
"elsif",
"spec",
".",
"homepage",
"=~",
"/",
"\\/",
"\\/",
"\\.",
"\\.",
"/",
"spec",
".",
"homepage",
".",
"chomp",
"(",
"'/'",
")",
"+",
"'/issues'",
"end",
"end"
] | URL to the issue tracker for this project.
@return [String, nil] | [
"URL",
"to",
"the",
"issue",
"tracker",
"for",
"this",
"project",
"."
] | 9ae174e6b7c5d4674f3301394e14567fa89a8b3e | https://github.com/poise/halite/blob/9ae174e6b7c5d4674f3301394e14567fa89a8b3e/lib/halite/gem.rb#L111-L117 |
2,247 | 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'",
",",
"'*'",
"# 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"
] | 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 |
2,248 | 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",
"# Didn't find anything",
"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 |
2,249 | 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",
")",
"# #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"
] | 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 |
2,250 | 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",
"# Force an integer",
"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 |
2,251 | 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 |
2,252 | 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",
"# 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"
] | 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 |
2,253 | 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 |
2,254 | 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 |
2,255 | 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 |
2,256 | 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",
"# Hex-encoded info hash. Convert to binary.",
"result",
"=",
"[",
"hash",
"]",
".",
"pack",
"\"H*\"",
"else",
"# Base32 encoded",
"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 |
2,257 | 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 |
2,258 | 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 |
2,259 | 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 |
2,260 | 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 |
2,261 | 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 |
2,262 | 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 = 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"
] | 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 |
2,263 | 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",
"\\/",
"/",
"# /users/:id (users)",
"return",
"$1",
"if",
"new_url",
"=~",
"/",
"\\/",
"\\w",
"\\/",
"\\/",
"/",
"# /users/:id/edit (users)",
"return",
"$1",
"if",
"new_url",
"=~",
"/",
"\\/",
"\\w",
"/",
"# /users (users)",
"return",
"$1",
"if",
"new_url",
"=~",
"/",
"\\/",
"\\w",
"\\/",
"\\w",
"/",
"# /users/:id/images (images)",
"return",
"$1",
"if",
"new_url",
"=~",
"/",
"\\/",
"\\w",
"\\/",
"\\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"
] | 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 |
2,264 | 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",
"# 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"
] | 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 |
2,265 | 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 |
2,266 | 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",
")",
"# 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",
"&&",
"!",
"@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 |
2,267 | 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 |
2,268 | 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 |
2,269 | 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",
"# Last block may be smaller",
"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 |
2,270 | 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",
")",
"# 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"
] | 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 |
2,271 | 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",
")",
"# 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"
] | 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 |
2,272 | 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 |
2,273 | 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 |
2,274 | 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 |
2,275 | 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 |
2,276 | 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 |
2,277 | 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 |
2,278 | 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 |
2,279 | 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\"",
")",
"# Reserved. 0x10 means we support extensions (BEP 10).",
"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 |
2,280 | 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",
"# 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"
] | Start the worker thread | [
"Start",
"the",
"worker",
"thread"
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/trackerclient.rb#L262-L348 |
2,281 | 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 |
2,282 | 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 |
2,283 | 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 |
2,284 | 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?",
"# 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"
] | 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 |
2,285 | 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 |
2,286 | 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 |
2,287 | 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 |
2,288 | 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 |
2,289 | 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 |
2,290 | 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 |
2,291 | 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 |
2,292 | 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 with new response host",
"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 |
2,293 | 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 |
2,294 | 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 |
2,295 | 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",
")",
"# customize size ",
"{",
":alt",
"=>",
"''",
"}",
".",
"merge!",
"(",
"options",
")",
"# to ensure validity merge with :alt => ''!",
"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 |
2,296 | 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 |
2,297 | 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 |
2,298 | 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 |
2,299 | 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",
")",
"# 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"
] | 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 |
Subsets and Splits