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,100 | flamontagne/rrschedule | lib/rrschedule.rb | RRSchedule.Schedule.face_to_face | def face_to_face(team_a,team_b)
res=[]
self.gamedays.each do |gd|
res << gd.games.select {|g| (g.team_a == team_a && g.team_b == team_b) || (g.team_a == team_b && g.team_b == team_a)}
end
res.flatten
end | ruby | def face_to_face(team_a,team_b)
res=[]
self.gamedays.each do |gd|
res << gd.games.select {|g| (g.team_a == team_a && g.team_b == team_b) || (g.team_a == team_b && g.team_b == team_a)}
end
res.flatten
end | [
"def",
"face_to_face",
"(",
"team_a",
",",
"team_b",
")",
"res",
"=",
"[",
"]",
"self",
".",
"gamedays",
".",
"each",
"do",
"|",
"gd",
"|",
"res",
"<<",
"gd",
".",
"games",
".",
"select",
"{",
"|",
"g",
"|",
"(",
"g",
".",
"team_a",
"==",
"team_a",
"&&",
"g",
".",
"team_b",
"==",
"team_b",
")",
"||",
"(",
"g",
".",
"team_a",
"==",
"team_b",
"&&",
"g",
".",
"team_b",
"==",
"team_a",
")",
"}",
"end",
"res",
".",
"flatten",
"end"
] | return matchups between two teams | [
"return",
"matchups",
"between",
"two",
"teams"
] | 7b334205e38901786a7569a6e96e49c24f9b425e | https://github.com/flamontagne/rrschedule/blob/7b334205e38901786a7569a6e96e49c24f9b425e/lib/rrschedule.rb#L316-L322 |
2,101 | flamontagne/rrschedule | lib/rrschedule.rb | RRSchedule.Rule.gt= | def gt=(gt)
@gt = Array(gt).empty? ? ["7:00 PM"] : Array(gt)
@gt.collect! do |gt|
begin
DateTime.parse(gt)
rescue
raise "game times must be valid time representations in the string form (e.g. 3:00 PM, 11:00 AM, 18:20, etc)"
end
end
end | ruby | def gt=(gt)
@gt = Array(gt).empty? ? ["7:00 PM"] : Array(gt)
@gt.collect! do |gt|
begin
DateTime.parse(gt)
rescue
raise "game times must be valid time representations in the string form (e.g. 3:00 PM, 11:00 AM, 18:20, etc)"
end
end
end | [
"def",
"gt",
"=",
"(",
"gt",
")",
"@gt",
"=",
"Array",
"(",
"gt",
")",
".",
"empty?",
"?",
"[",
"\"7:00 PM\"",
"]",
":",
"Array",
"(",
"gt",
")",
"@gt",
".",
"collect!",
"do",
"|",
"gt",
"|",
"begin",
"DateTime",
".",
"parse",
"(",
"gt",
")",
"rescue",
"raise",
"\"game times must be valid time representations in the string form (e.g. 3:00 PM, 11:00 AM, 18:20, etc)\"",
"end",
"end",
"end"
] | Array of game times where games are played. Must be valid DateTime objects in the string form | [
"Array",
"of",
"game",
"times",
"where",
"games",
"are",
"played",
".",
"Must",
"be",
"valid",
"DateTime",
"objects",
"in",
"the",
"string",
"form"
] | 7b334205e38901786a7569a6e96e49c24f9b425e | https://github.com/flamontagne/rrschedule/blob/7b334205e38901786a7569a6e96e49c24f9b425e/lib/rrschedule.rb#L369-L378 |
2,102 | dilcom/gnuplotrb | lib/gnuplotrb/staff/terminal.rb | GnuplotRB.Terminal.options_hash_to_string | def options_hash_to_string(options)
result = ''
options.sort_by { |key, _| OPTION_ORDER.find_index(key) || -1 }.each do |key, value|
if value
result += "set #{OptionHandling.option_to_string(key, value)}\n"
else
result += "unset #{key}\n"
end
end
result
end | ruby | def options_hash_to_string(options)
result = ''
options.sort_by { |key, _| OPTION_ORDER.find_index(key) || -1 }.each do |key, value|
if value
result += "set #{OptionHandling.option_to_string(key, value)}\n"
else
result += "unset #{key}\n"
end
end
result
end | [
"def",
"options_hash_to_string",
"(",
"options",
")",
"result",
"=",
"''",
"options",
".",
"sort_by",
"{",
"|",
"key",
",",
"_",
"|",
"OPTION_ORDER",
".",
"find_index",
"(",
"key",
")",
"||",
"-",
"1",
"}",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"value",
"result",
"+=",
"\"set #{OptionHandling.option_to_string(key, value)}\\n\"",
"else",
"result",
"+=",
"\"unset #{key}\\n\"",
"end",
"end",
"result",
"end"
] | Convert given options to gnuplot format.
For "{ opt1: val1, .. , optN: valN }" it returns
set opt1 val1
..
set optN valN
@param ptions [Hash] options to convert
@return [String] options in Gnuplot format | [
"Convert",
"given",
"options",
"to",
"gnuplot",
"format",
"."
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/staff/terminal.rb#L91-L101 |
2,103 | cfis/proj4rb | lib/proj4.rb | Proj4.Projection.forwardDeg! | def forwardDeg!(point)
point.x *= Proj4::DEG_TO_RAD
point.y *= Proj4::DEG_TO_RAD
forward!(point)
end | ruby | def forwardDeg!(point)
point.x *= Proj4::DEG_TO_RAD
point.y *= Proj4::DEG_TO_RAD
forward!(point)
end | [
"def",
"forwardDeg!",
"(",
"point",
")",
"point",
".",
"x",
"*=",
"Proj4",
"::",
"DEG_TO_RAD",
"point",
".",
"y",
"*=",
"Proj4",
"::",
"DEG_TO_RAD",
"forward!",
"(",
"point",
")",
"end"
] | Convenience function for calculating a forward projection with degrees instead of radians.
This version works in-place, i.e. the point objects content is overwritten.
call-seq: forwardDeg!(point) -> point | [
"Convenience",
"function",
"for",
"calculating",
"a",
"forward",
"projection",
"with",
"degrees",
"instead",
"of",
"radians",
".",
"This",
"version",
"works",
"in",
"-",
"place",
"i",
".",
"e",
".",
"the",
"point",
"objects",
"content",
"is",
"overwritten",
"."
] | 97a14b5d6884506795953f7c69b8ede73bb84e0f | https://github.com/cfis/proj4rb/blob/97a14b5d6884506795953f7c69b8ede73bb84e0f/lib/proj4.rb#L196-L200 |
2,104 | cfis/proj4rb | lib/proj4.rb | Proj4.Projection.inverseDeg! | def inverseDeg!(point)
inverse!(point)
point.x *= Proj4::RAD_TO_DEG
point.y *= Proj4::RAD_TO_DEG
point
end | ruby | def inverseDeg!(point)
inverse!(point)
point.x *= Proj4::RAD_TO_DEG
point.y *= Proj4::RAD_TO_DEG
point
end | [
"def",
"inverseDeg!",
"(",
"point",
")",
"inverse!",
"(",
"point",
")",
"point",
".",
"x",
"*=",
"Proj4",
"::",
"RAD_TO_DEG",
"point",
".",
"y",
"*=",
"Proj4",
"::",
"RAD_TO_DEG",
"point",
"end"
] | Convenience function for calculating an inverse projection with the result in degrees instead of radians.
This version works in-place, i.e. the point objects content is overwritten.
call-seq: inverseDeg!(point) -> point | [
"Convenience",
"function",
"for",
"calculating",
"an",
"inverse",
"projection",
"with",
"the",
"result",
"in",
"degrees",
"instead",
"of",
"radians",
".",
"This",
"version",
"works",
"in",
"-",
"place",
"i",
".",
"e",
".",
"the",
"point",
"objects",
"content",
"is",
"overwritten",
"."
] | 97a14b5d6884506795953f7c69b8ede73bb84e0f | https://github.com/cfis/proj4rb/blob/97a14b5d6884506795953f7c69b8ede73bb84e0f/lib/proj4.rb#L250-L255 |
2,105 | cfis/proj4rb | lib/proj4.rb | Proj4.Projection.transform_all! | def transform_all!(otherProjection, collection)
collection.each do |point|
transform!(otherProjection, point)
end
collection
end | ruby | def transform_all!(otherProjection, collection)
collection.each do |point|
transform!(otherProjection, point)
end
collection
end | [
"def",
"transform_all!",
"(",
"otherProjection",
",",
"collection",
")",
"collection",
".",
"each",
"do",
"|",
"point",
"|",
"transform!",
"(",
"otherProjection",
",",
"point",
")",
"end",
"collection",
"end"
] | Transforms all points in a collection 'in place' from one projection
to another. The +collection+ object must implement the +each+
method for this to work.
call-seq: transform_all!(destinationProjection, collection) -> collection | [
"Transforms",
"all",
"points",
"in",
"a",
"collection",
"in",
"place",
"from",
"one",
"projection",
"to",
"another",
".",
"The",
"+",
"collection",
"+",
"object",
"must",
"implement",
"the",
"+",
"each",
"+",
"method",
"for",
"this",
"to",
"work",
"."
] | 97a14b5d6884506795953f7c69b8ede73bb84e0f | https://github.com/cfis/proj4rb/blob/97a14b5d6884506795953f7c69b8ede73bb84e0f/lib/proj4.rb#L298-L303 |
2,106 | wework/faraday-sunset | lib/faraday/sunset.rb | Faraday.Sunset.call | def call(env)
@app.call(env).on_complete do |response_env|
datetime = sunset_header(response_env.response_headers)
report_deprecated_usage(env, datetime) unless datetime.nil?
end
end | ruby | def call(env)
@app.call(env).on_complete do |response_env|
datetime = sunset_header(response_env.response_headers)
report_deprecated_usage(env, datetime) unless datetime.nil?
end
end | [
"def",
"call",
"(",
"env",
")",
"@app",
".",
"call",
"(",
"env",
")",
".",
"on_complete",
"do",
"|",
"response_env",
"|",
"datetime",
"=",
"sunset_header",
"(",
"response_env",
".",
"response_headers",
")",
"report_deprecated_usage",
"(",
"env",
",",
"datetime",
")",
"unless",
"datetime",
".",
"nil?",
"end",
"end"
] | Initialize the middleware
@param [Type] app describe app
@param [Hash] options = {}
@return void
@param [Faraday::Env] no idea what this does
@return [Faraday::Response] response from the middleware | [
"Initialize",
"the",
"middleware"
] | aac1e1ac5828ae7d2bed173e5d03fd2c63b5ce6a | https://github.com/wework/faraday-sunset/blob/aac1e1ac5828ae7d2bed173e5d03fd2c63b5ce6a/lib/faraday/sunset.rb#L21-L26 |
2,107 | dilcom/gnuplotrb | lib/gnuplotrb/staff/dataset.rb | GnuplotRB.Dataset.update | def update(data = nil, **options)
if data && @type == :datablock
new_datablock = @data.update(data)
if new_datablock == @data
update_options(options)
else
self.class.new(new_datablock, options)
end
else
update_options(options)
end
end | ruby | def update(data = nil, **options)
if data && @type == :datablock
new_datablock = @data.update(data)
if new_datablock == @data
update_options(options)
else
self.class.new(new_datablock, options)
end
else
update_options(options)
end
end | [
"def",
"update",
"(",
"data",
"=",
"nil",
",",
"**",
"options",
")",
"if",
"data",
"&&",
"@type",
"==",
":datablock",
"new_datablock",
"=",
"@data",
".",
"update",
"(",
"data",
")",
"if",
"new_datablock",
"==",
"@data",
"update_options",
"(",
"options",
")",
"else",
"self",
".",
"class",
".",
"new",
"(",
"new_datablock",
",",
"options",
")",
"end",
"else",
"update_options",
"(",
"options",
")",
"end",
"end"
] | Create new dataset with updated data and merged options.
Given data is appended to existing.
Data is updated only if Dataset stores it in Datablock.
Method does nothing if no options given and data isn't stored
in in-memory Datablock.
@param data [#to_gnuplot_points] data to append to existing
@param options [Hash] new options to merge with existing options
@return self if dataset corresponds to math formula or file
(filename or temporary file if datablock)
@return [Dataset] new dataset if data is stored in 'in-memory' Datablock
@example Updating dataset with Math formula or filename given:
dataset = Dataset.new('file.data')
dataset.update(data: 'asd')
#=> nothing updated
dataset.update(data: 'asd', title: 'File')
#=> Dataset.new('file.data', title: 'File')
@example Updating dataset with data stored in Datablock (in-memory):
in_memory_points = Dataset.new(points, title: 'Old one')
in_memory_points.update(data: some_update, title: 'Updated')
#=> Dataset.new(points + some_update, title: 'Updated')
@example Updating dataset with data stored in Datablock (in-file):
temp_file_points = Dataset.new(points, title: 'Old one', file: true)
temp_file_points.update(data: some_update)
#=> data updated but no new dataset created
temp_file_points.update(data: some_update, title: 'Updated')
#=> data updated and new dataset with title 'Updated' returned | [
"Create",
"new",
"dataset",
"with",
"updated",
"data",
"and",
"merged",
"options",
"."
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/staff/dataset.rb#L119-L130 |
2,108 | dilcom/gnuplotrb | lib/gnuplotrb/staff/dataset.rb | GnuplotRB.Dataset.options_to_string | def options_to_string
options.sort_by { |key, _| OPTION_ORDER.find_index(key.to_s) || 999 }
.map { |key, value| OptionHandling.option_to_string(key, value) }
.join(' ')
end | ruby | def options_to_string
options.sort_by { |key, _| OPTION_ORDER.find_index(key.to_s) || 999 }
.map { |key, value| OptionHandling.option_to_string(key, value) }
.join(' ')
end | [
"def",
"options_to_string",
"options",
".",
"sort_by",
"{",
"|",
"key",
",",
"_",
"|",
"OPTION_ORDER",
".",
"find_index",
"(",
"key",
".",
"to_s",
")",
"||",
"999",
"}",
".",
"map",
"{",
"|",
"key",
",",
"value",
"|",
"OptionHandling",
".",
"option_to_string",
"(",
"key",
",",
"value",
")",
"}",
".",
"join",
"(",
"' '",
")",
"end"
] | Create string from own options
@return [String] options converted to Gnuplot format | [
"Create",
"string",
"from",
"own",
"options"
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/staff/dataset.rb#L221-L225 |
2,109 | dilcom/gnuplotrb | lib/gnuplotrb/staff/dataset.rb | GnuplotRB.Dataset.init_string | def init_string(data, options)
@type, @data = File.exist?(data) ? [:datafile, "'#{data}'"] : [:math_function, data.clone]
@options = Hamster.hash(options)
end | ruby | def init_string(data, options)
@type, @data = File.exist?(data) ? [:datafile, "'#{data}'"] : [:math_function, data.clone]
@options = Hamster.hash(options)
end | [
"def",
"init_string",
"(",
"data",
",",
"options",
")",
"@type",
",",
"@data",
"=",
"File",
".",
"exist?",
"(",
"data",
")",
"?",
"[",
":datafile",
",",
"\"'#{data}'\"",
"]",
":",
"[",
":math_function",
",",
"data",
".",
"clone",
"]",
"@options",
"=",
"Hamster",
".",
"hash",
"(",
"options",
")",
"end"
] | Initialize Dataset from given String | [
"Initialize",
"Dataset",
"from",
"given",
"String"
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/staff/dataset.rb#L235-L238 |
2,110 | dilcom/gnuplotrb | lib/gnuplotrb/staff/dataset.rb | GnuplotRB.Dataset.get_daru_columns | def get_daru_columns(data, cnt)
new_opt = (2..cnt).to_a.join(':')
if data.index[0].is_a?(DateTime) || data.index[0].is_a?(Numeric)
"1:#{new_opt}"
else
"#{new_opt}:xtic(1)"
end
end | ruby | def get_daru_columns(data, cnt)
new_opt = (2..cnt).to_a.join(':')
if data.index[0].is_a?(DateTime) || data.index[0].is_a?(Numeric)
"1:#{new_opt}"
else
"#{new_opt}:xtic(1)"
end
end | [
"def",
"get_daru_columns",
"(",
"data",
",",
"cnt",
")",
"new_opt",
"=",
"(",
"2",
"..",
"cnt",
")",
".",
"to_a",
".",
"join",
"(",
"':'",
")",
"if",
"data",
".",
"index",
"[",
"0",
"]",
".",
"is_a?",
"(",
"DateTime",
")",
"||",
"data",
".",
"index",
"[",
"0",
"]",
".",
"is_a?",
"(",
"Numeric",
")",
"\"1:#{new_opt}\"",
"else",
"\"#{new_opt}:xtic(1)\"",
"end",
"end"
] | Create new value for 'using' option based on column count | [
"Create",
"new",
"value",
"for",
"using",
"option",
"based",
"on",
"column",
"count"
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/staff/dataset.rb#L250-L257 |
2,111 | dilcom/gnuplotrb | lib/gnuplotrb/plot.rb | GnuplotRB.Plot.provide_with_datetime_format | def provide_with_datetime_format(data, using)
return unless defined?(Daru)
return unless data.is_a?(Daru::DataFrame) || data.is_a?(Daru::Vector)
return unless data.index.first.is_a?(DateTime)
return if using[0..1] != '1:'
@options = Hamster::Hash.new(
xdata: 'time',
timefmt: '%Y-%m-%dT%H:%M:%S',
format_x: '%d\n%b\n%Y'
).merge(@options)
end | ruby | def provide_with_datetime_format(data, using)
return unless defined?(Daru)
return unless data.is_a?(Daru::DataFrame) || data.is_a?(Daru::Vector)
return unless data.index.first.is_a?(DateTime)
return if using[0..1] != '1:'
@options = Hamster::Hash.new(
xdata: 'time',
timefmt: '%Y-%m-%dT%H:%M:%S',
format_x: '%d\n%b\n%Y'
).merge(@options)
end | [
"def",
"provide_with_datetime_format",
"(",
"data",
",",
"using",
")",
"return",
"unless",
"defined?",
"(",
"Daru",
")",
"return",
"unless",
"data",
".",
"is_a?",
"(",
"Daru",
"::",
"DataFrame",
")",
"||",
"data",
".",
"is_a?",
"(",
"Daru",
"::",
"Vector",
")",
"return",
"unless",
"data",
".",
"index",
".",
"first",
".",
"is_a?",
"(",
"DateTime",
")",
"return",
"if",
"using",
"[",
"0",
"..",
"1",
"]",
"!=",
"'1:'",
"@options",
"=",
"Hamster",
"::",
"Hash",
".",
"new",
"(",
"xdata",
":",
"'time'",
",",
"timefmt",
":",
"'%Y-%m-%dT%H:%M:%S'",
",",
"format_x",
":",
"'%d\\n%b\\n%Y'",
")",
".",
"merge",
"(",
"@options",
")",
"end"
] | Checks several conditions and set options needed
to handle DateTime indexes properly. | [
"Checks",
"several",
"conditions",
"and",
"set",
"options",
"needed",
"to",
"handle",
"DateTime",
"indexes",
"properly",
"."
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/plot.rb#L250-L260 |
2,112 | dilcom/gnuplotrb | lib/gnuplotrb/plot.rb | GnuplotRB.Plot.dataset_from_any | def dataset_from_any(source)
ds = case source
# when initialized with dataframe (it passes here several vectors)
when (defined?(Daru) ? Daru::Vector : nil)
Dataset.new(source)
when Dataset
source.clone
else
Dataset.new(*source)
end
data = source.is_a?(Array) ? source[0] : source
provide_with_datetime_format(data, ds.using)
ds
end | ruby | def dataset_from_any(source)
ds = case source
# when initialized with dataframe (it passes here several vectors)
when (defined?(Daru) ? Daru::Vector : nil)
Dataset.new(source)
when Dataset
source.clone
else
Dataset.new(*source)
end
data = source.is_a?(Array) ? source[0] : source
provide_with_datetime_format(data, ds.using)
ds
end | [
"def",
"dataset_from_any",
"(",
"source",
")",
"ds",
"=",
"case",
"source",
"# when initialized with dataframe (it passes here several vectors)",
"when",
"(",
"defined?",
"(",
"Daru",
")",
"?",
"Daru",
"::",
"Vector",
":",
"nil",
")",
"Dataset",
".",
"new",
"(",
"source",
")",
"when",
"Dataset",
"source",
".",
"clone",
"else",
"Dataset",
".",
"new",
"(",
"source",
")",
"end",
"data",
"=",
"source",
".",
"is_a?",
"(",
"Array",
")",
"?",
"source",
"[",
"0",
"]",
":",
"source",
"provide_with_datetime_format",
"(",
"data",
",",
"ds",
".",
"using",
")",
"ds",
"end"
] | Check if given args is a dataset and returns it. Creates
new dataset from given args otherwise. | [
"Check",
"if",
"given",
"args",
"is",
"a",
"dataset",
"and",
"returns",
"it",
".",
"Creates",
"new",
"dataset",
"from",
"given",
"args",
"otherwise",
"."
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/plot.rb#L265-L278 |
2,113 | alor/em-http-server | lib/em-http-server/response.rb | EventMachine.HttpResponse.send_headers | def send_headers
raise "sent headers already" if @sent_headers
@sent_headers = true
fixup_headers
ary = []
ary << "HTTP/1.1 #{@status || 200} #{@status_string || '...'}\r\n"
ary += generate_header_lines(@headers)
ary << "\r\n"
send_data ary.join
end | ruby | def send_headers
raise "sent headers already" if @sent_headers
@sent_headers = true
fixup_headers
ary = []
ary << "HTTP/1.1 #{@status || 200} #{@status_string || '...'}\r\n"
ary += generate_header_lines(@headers)
ary << "\r\n"
send_data ary.join
end | [
"def",
"send_headers",
"raise",
"\"sent headers already\"",
"if",
"@sent_headers",
"@sent_headers",
"=",
"true",
"fixup_headers",
"ary",
"=",
"[",
"]",
"ary",
"<<",
"\"HTTP/1.1 #{@status || 200} #{@status_string || '...'}\\r\\n\"",
"ary",
"+=",
"generate_header_lines",
"(",
"@headers",
")",
"ary",
"<<",
"\"\\r\\n\"",
"send_data",
"ary",
".",
"join",
"end"
] | Send the headers out in alpha-sorted order. This will degrade performance to some
degree, and is intended only to simplify the construction of unit tests. | [
"Send",
"the",
"headers",
"out",
"in",
"alpha",
"-",
"sorted",
"order",
".",
"This",
"will",
"degrade",
"performance",
"to",
"some",
"degree",
"and",
"is",
"intended",
"only",
"to",
"simplify",
"the",
"construction",
"of",
"unit",
"tests",
"."
] | 4c5050b376e5765572e074db7a92f65f882b24a2 | https://github.com/alor/em-http-server/blob/4c5050b376e5765572e074db7a92f65f882b24a2/lib/em-http-server/response.rb#L108-L120 |
2,114 | iron-io/rest | lib/rest/wrappers/base_wrapper.rb | Rest.BaseResponseWrapper.headers | def headers
new_h = {}
headers_orig.each_pair do |k, v|
if v.is_a?(Array) && v.size == 1
v = v[0]
end
new_h[k.downcase] = v
end
new_h
end | ruby | def headers
new_h = {}
headers_orig.each_pair do |k, v|
if v.is_a?(Array) && v.size == 1
v = v[0]
end
new_h[k.downcase] = v
end
new_h
end | [
"def",
"headers",
"new_h",
"=",
"{",
"}",
"headers_orig",
".",
"each_pair",
"do",
"|",
"k",
",",
"v",
"|",
"if",
"v",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"v",
".",
"size",
"==",
"1",
"v",
"=",
"v",
"[",
"0",
"]",
"end",
"new_h",
"[",
"k",
".",
"downcase",
"]",
"=",
"v",
"end",
"new_h",
"end"
] | Provide a headers_orig method in your wrapper to allow this to work | [
"Provide",
"a",
"headers_orig",
"method",
"in",
"your",
"wrapper",
"to",
"allow",
"this",
"to",
"work"
] | 7775483f775a4b0560a1687fee48149b52fa5c51 | https://github.com/iron-io/rest/blob/7775483f775a4b0560a1687fee48149b52fa5c51/lib/rest/wrappers/base_wrapper.rb#L42-L51 |
2,115 | dilcom/gnuplotrb | lib/gnuplotrb/animation.rb | GnuplotRB.Animation.plot | def plot(path = nil, **options)
options[:output] ||= path
plot_options = mix_options(options) do |plot_opts, anim_opts|
plot_opts.merge(term: ['gif', anim_opts])
end.to_h
need_output = plot_options[:output].nil?
plot_options[:output] = Dir::Tmpname.make_tmpname('anim', 0) if need_output
terminal = Terminal.new
multiplot(terminal, plot_options)
# guaranteed wait for plotting to finish
terminal.close
if need_output
result = File.binread(plot_options[:output])
File.delete(plot_options[:output])
else
result = nil
end
result
end | ruby | def plot(path = nil, **options)
options[:output] ||= path
plot_options = mix_options(options) do |plot_opts, anim_opts|
plot_opts.merge(term: ['gif', anim_opts])
end.to_h
need_output = plot_options[:output].nil?
plot_options[:output] = Dir::Tmpname.make_tmpname('anim', 0) if need_output
terminal = Terminal.new
multiplot(terminal, plot_options)
# guaranteed wait for plotting to finish
terminal.close
if need_output
result = File.binread(plot_options[:output])
File.delete(plot_options[:output])
else
result = nil
end
result
end | [
"def",
"plot",
"(",
"path",
"=",
"nil",
",",
"**",
"options",
")",
"options",
"[",
":output",
"]",
"||=",
"path",
"plot_options",
"=",
"mix_options",
"(",
"options",
")",
"do",
"|",
"plot_opts",
",",
"anim_opts",
"|",
"plot_opts",
".",
"merge",
"(",
"term",
":",
"[",
"'gif'",
",",
"anim_opts",
"]",
")",
"end",
".",
"to_h",
"need_output",
"=",
"plot_options",
"[",
":output",
"]",
".",
"nil?",
"plot_options",
"[",
":output",
"]",
"=",
"Dir",
"::",
"Tmpname",
".",
"make_tmpname",
"(",
"'anim'",
",",
"0",
")",
"if",
"need_output",
"terminal",
"=",
"Terminal",
".",
"new",
"multiplot",
"(",
"terminal",
",",
"plot_options",
")",
"# guaranteed wait for plotting to finish",
"terminal",
".",
"close",
"if",
"need_output",
"result",
"=",
"File",
".",
"binread",
"(",
"plot_options",
"[",
":output",
"]",
")",
"File",
".",
"delete",
"(",
"plot_options",
"[",
":output",
"]",
")",
"else",
"result",
"=",
"nil",
"end",
"result",
"end"
] | This method creates a gif animation where frames are plots
already contained by Animation object.
Options passed in #plot have priority over those which were set before.
Inner options of Plots have the highest priority (except
:term and :output which are ignored).
@param path [String] path to new gif file that will be created as a result
@param options [Hash] see note about available options in top class documentation
@return [nil] if path to output file given
@return [String] gif file contents if no path to output file given | [
"This",
"method",
"creates",
"a",
"gif",
"animation",
"where",
"frames",
"are",
"plots",
"already",
"contained",
"by",
"Animation",
"object",
"."
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/animation.rb#L55-L73 |
2,116 | dilcom/gnuplotrb | lib/gnuplotrb/animation.rb | GnuplotRB.Animation.specific_keys | def specific_keys
%w(
animate
size
background
transparent
enhanced
rounded
butt
linewidth
dashlength
tiny
small
medium
large
giant
font
fontscale
crop
)
end | ruby | def specific_keys
%w(
animate
size
background
transparent
enhanced
rounded
butt
linewidth
dashlength
tiny
small
medium
large
giant
font
fontscale
crop
)
end | [
"def",
"specific_keys",
"%w(",
"animate",
"size",
"background",
"transparent",
"enhanced",
"rounded",
"butt",
"linewidth",
"dashlength",
"tiny",
"small",
"medium",
"large",
"giant",
"font",
"fontscale",
"crop",
")",
"end"
] | This plot have some specific options which
should be handled different way than others.
Here are keys of this options. | [
"This",
"plot",
"have",
"some",
"specific",
"options",
"which",
"should",
"be",
"handled",
"different",
"way",
"than",
"others",
".",
"Here",
"are",
"keys",
"of",
"this",
"options",
"."
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/animation.rb#L107-L127 |
2,117 | dilcom/gnuplotrb | lib/gnuplotrb/fit.rb | GnuplotRB.Fit.fit | def fit(data, function: 'a2*x*x+a1*x+a0', initials: { a2: 1, a1: 1, a0: 1 }, term_options: {}, **options)
dataset = data.is_a?(Dataset) ? Dataset.new(data.data) : Dataset.new(data)
opts_str = OptionHandling.ruby_class_to_gnuplot(options)
output = gnuplot_fit(function, dataset, opts_str, initials, term_options)
res = parse_output(initials.keys, function, output)
{
formula_ds: Dataset.new(res[2], title: 'Fit formula'),
coefficients: res[0],
deltas: res[1],
data: dataset
}
end | ruby | def fit(data, function: 'a2*x*x+a1*x+a0', initials: { a2: 1, a1: 1, a0: 1 }, term_options: {}, **options)
dataset = data.is_a?(Dataset) ? Dataset.new(data.data) : Dataset.new(data)
opts_str = OptionHandling.ruby_class_to_gnuplot(options)
output = gnuplot_fit(function, dataset, opts_str, initials, term_options)
res = parse_output(initials.keys, function, output)
{
formula_ds: Dataset.new(res[2], title: 'Fit formula'),
coefficients: res[0],
deltas: res[1],
data: dataset
}
end | [
"def",
"fit",
"(",
"data",
",",
"function",
":",
"'a2*x*x+a1*x+a0'",
",",
"initials",
":",
"{",
"a2",
":",
"1",
",",
"a1",
":",
"1",
",",
"a0",
":",
"1",
"}",
",",
"term_options",
":",
"{",
"}",
",",
"**",
"options",
")",
"dataset",
"=",
"data",
".",
"is_a?",
"(",
"Dataset",
")",
"?",
"Dataset",
".",
"new",
"(",
"data",
".",
"data",
")",
":",
"Dataset",
".",
"new",
"(",
"data",
")",
"opts_str",
"=",
"OptionHandling",
".",
"ruby_class_to_gnuplot",
"(",
"options",
")",
"output",
"=",
"gnuplot_fit",
"(",
"function",
",",
"dataset",
",",
"opts_str",
",",
"initials",
",",
"term_options",
")",
"res",
"=",
"parse_output",
"(",
"initials",
".",
"keys",
",",
"function",
",",
"output",
")",
"{",
"formula_ds",
":",
"Dataset",
".",
"new",
"(",
"res",
"[",
"2",
"]",
",",
"title",
":",
"'Fit formula'",
")",
",",
"coefficients",
":",
"res",
"[",
"0",
"]",
",",
"deltas",
":",
"res",
"[",
"1",
"]",
",",
"data",
":",
"dataset",
"}",
"end"
] | Fit given data with function.
Fit waits for output from gnuplot Settings.max_fit_delay and throw exception if gets nothing.
One can change this value in order to wait longer (if huge datasets is fitted).
@param data [#to_gnuplot_points] method accepts the same sources as Dataset.new
and Dataset object
@param :function [String] function to fit data with
@param :initials [Hash] initial values for coefficients used in fitting
@param :term_options [Hash] terminal options that should be setted to terminal before fit.
You can see them in Plot's documentation (or even better in gnuplot doc)
Most useful here are ranges (xrange, yrange etc) and fit option which tunes fit parameters
(see {gnuplot doc}[http://www.gnuplot.info/docs_5.0/gnuplot.pdf] p. 122)
@param options [Hash] options passed to Gnuplot's fit such as *using*. They are covered in
{gnuplot doc}[http://www.gnuplot.info/docs_5.0/gnuplot.pdf] (pp. 69-74)
@return [Hash] hash with four elements:
- :formula_ds - dataset with best fit curve as data
- :coefficients - hash of calculated coefficients. So if you gave
``{ initials: {a: 1, b: 1, c: 1} }`` it will return hash with keys :a, :b, :c and its values
- :deltas - Gnuplot calculates possible deltas for coefficients during fitting and
deltas hash contains this deltas
- :data - pointer to Datablock with given data
@example
fit(some_data, function: 'exp(a/x)', initials: {a: 10}, term_option: { xrange: 1..100 })
fit(some_dataset, using: '1:2:3') | [
"Fit",
"given",
"data",
"with",
"function",
"."
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/fit.rb#L36-L47 |
2,118 | dilcom/gnuplotrb | lib/gnuplotrb/fit.rb | GnuplotRB.Fit.wait_for_output | def wait_for_output(term, variables)
# now we should catch 'error' from terminal: it will contain approximation data
# but we can get a real error instead of output, so lets wait for limited time
start = Time.now
output = ''
until output_ready?(output, variables)
begin
term.check_errors(raw: true)
rescue GnuplotRB::GnuplotError => e
output += e.message
end
if Time.now - start > Settings.max_fit_delay
fail GnuplotError, "Seems like there is an error in gnuplotrb: #{output}"
end
end
output
end | ruby | def wait_for_output(term, variables)
# now we should catch 'error' from terminal: it will contain approximation data
# but we can get a real error instead of output, so lets wait for limited time
start = Time.now
output = ''
until output_ready?(output, variables)
begin
term.check_errors(raw: true)
rescue GnuplotRB::GnuplotError => e
output += e.message
end
if Time.now - start > Settings.max_fit_delay
fail GnuplotError, "Seems like there is an error in gnuplotrb: #{output}"
end
end
output
end | [
"def",
"wait_for_output",
"(",
"term",
",",
"variables",
")",
"# now we should catch 'error' from terminal: it will contain approximation data",
"# but we can get a real error instead of output, so lets wait for limited time",
"start",
"=",
"Time",
".",
"now",
"output",
"=",
"''",
"until",
"output_ready?",
"(",
"output",
",",
"variables",
")",
"begin",
"term",
".",
"check_errors",
"(",
"raw",
":",
"true",
")",
"rescue",
"GnuplotRB",
"::",
"GnuplotError",
"=>",
"e",
"output",
"+=",
"e",
".",
"message",
"end",
"if",
"Time",
".",
"now",
"-",
"start",
">",
"Settings",
".",
"max_fit_delay",
"fail",
"GnuplotError",
",",
"\"Seems like there is an error in gnuplotrb: #{output}\"",
"end",
"end",
"output",
"end"
] | It takes some time to produce output so here we need
to wait for it.
Max time to wait is stored in Settings.max_fit_delay, so one
can change it in order to wait longer. | [
"It",
"takes",
"some",
"time",
"to",
"produce",
"output",
"so",
"here",
"we",
"need",
"to",
"wait",
"for",
"it",
"."
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/fit.rb#L140-L156 |
2,119 | dilcom/gnuplotrb | lib/gnuplotrb/fit.rb | GnuplotRB.Fit.gnuplot_fit | def gnuplot_fit(function, data, options, initials, term_options)
variables = initials.keys
term = Terminal.new
term.set(term_options)
initials.each { |var_name, value| term.stream_puts "#{var_name} = #{value}" }
command = "fit #{function} #{data.to_s(term, without_options: true)} " \
"#{options} via #{variables.join(',')}"
term.stream_puts(command)
output = wait_for_output(term, variables)
begin
term.close
rescue GnuplotError
# Nothing interesting here.
# If we had an error, we never reach this line.
# Error here may be only additional information
# such as correlation matrix.
end
output
end | ruby | def gnuplot_fit(function, data, options, initials, term_options)
variables = initials.keys
term = Terminal.new
term.set(term_options)
initials.each { |var_name, value| term.stream_puts "#{var_name} = #{value}" }
command = "fit #{function} #{data.to_s(term, without_options: true)} " \
"#{options} via #{variables.join(',')}"
term.stream_puts(command)
output = wait_for_output(term, variables)
begin
term.close
rescue GnuplotError
# Nothing interesting here.
# If we had an error, we never reach this line.
# Error here may be only additional information
# such as correlation matrix.
end
output
end | [
"def",
"gnuplot_fit",
"(",
"function",
",",
"data",
",",
"options",
",",
"initials",
",",
"term_options",
")",
"variables",
"=",
"initials",
".",
"keys",
"term",
"=",
"Terminal",
".",
"new",
"term",
".",
"set",
"(",
"term_options",
")",
"initials",
".",
"each",
"{",
"|",
"var_name",
",",
"value",
"|",
"term",
".",
"stream_puts",
"\"#{var_name} = #{value}\"",
"}",
"command",
"=",
"\"fit #{function} #{data.to_s(term, without_options: true)} \"",
"\"#{options} via #{variables.join(',')}\"",
"term",
".",
"stream_puts",
"(",
"command",
")",
"output",
"=",
"wait_for_output",
"(",
"term",
",",
"variables",
")",
"begin",
"term",
".",
"close",
"rescue",
"GnuplotError",
"# Nothing interesting here.",
"# If we had an error, we never reach this line.",
"# Error here may be only additional information",
"# such as correlation matrix.",
"end",
"output",
"end"
] | Make fit command and send it to gnuplot | [
"Make",
"fit",
"command",
"and",
"send",
"it",
"to",
"gnuplot"
] | 0a3146386ae28fcbe2c09cb6e266fe40ebb659f4 | https://github.com/dilcom/gnuplotrb/blob/0a3146386ae28fcbe2c09cb6e266fe40ebb659f4/lib/gnuplotrb/fit.rb#L184-L202 |
2,120 | namick/scatter_swap | lib/scatter_swap/hasher.rb | ScatterSwap.Hasher.swapper_map | def swapper_map(index)
array = (0..9).to_a
10.times.collect.with_index do |i|
array.rotate!(index + i ^ spin).pop
end
end | ruby | def swapper_map(index)
array = (0..9).to_a
10.times.collect.with_index do |i|
array.rotate!(index + i ^ spin).pop
end
end | [
"def",
"swapper_map",
"(",
"index",
")",
"array",
"=",
"(",
"0",
"..",
"9",
")",
".",
"to_a",
"10",
".",
"times",
".",
"collect",
".",
"with_index",
"do",
"|",
"i",
"|",
"array",
".",
"rotate!",
"(",
"index",
"+",
"i",
"^",
"spin",
")",
".",
"pop",
"end",
"end"
] | We want a unique map for each place in the original number | [
"We",
"want",
"a",
"unique",
"map",
"for",
"each",
"place",
"in",
"the",
"original",
"number"
] | 0ae5a936482752e4f2220f0e54d7647b5953d80e | https://github.com/namick/scatter_swap/blob/0ae5a936482752e4f2220f0e54d7647b5953d80e/lib/scatter_swap/hasher.rb#L31-L36 |
2,121 | namick/scatter_swap | lib/scatter_swap/hasher.rb | ScatterSwap.Hasher.unscatter | def unscatter
scattered_array = @working_array
sum_of_digits = scattered_array.inject(:+).to_i
@working_array = []
@working_array.tap do |unscatter|
10.times do
unscatter.push scattered_array.pop
unscatter.rotate! (sum_of_digits ^ spin) * -1
end
end
end | ruby | def unscatter
scattered_array = @working_array
sum_of_digits = scattered_array.inject(:+).to_i
@working_array = []
@working_array.tap do |unscatter|
10.times do
unscatter.push scattered_array.pop
unscatter.rotate! (sum_of_digits ^ spin) * -1
end
end
end | [
"def",
"unscatter",
"scattered_array",
"=",
"@working_array",
"sum_of_digits",
"=",
"scattered_array",
".",
"inject",
"(",
":+",
")",
".",
"to_i",
"@working_array",
"=",
"[",
"]",
"@working_array",
".",
"tap",
"do",
"|",
"unscatter",
"|",
"10",
".",
"times",
"do",
"unscatter",
".",
"push",
"scattered_array",
".",
"pop",
"unscatter",
".",
"rotate!",
"(",
"sum_of_digits",
"^",
"spin",
")",
"*",
"-",
"1",
"end",
"end",
"end"
] | Reverse the scatter | [
"Reverse",
"the",
"scatter"
] | 0ae5a936482752e4f2220f0e54d7647b5953d80e | https://github.com/namick/scatter_swap/blob/0ae5a936482752e4f2220f0e54d7647b5953d80e/lib/scatter_swap/hasher.rb#L64-L74 |
2,122 | futurechimp/awrence | lib/awrence/methods.rb | Awrence.Methods.to_camelback_keys | def to_camelback_keys(value = self)
case value
when Array
value.map { |v| to_camelback_keys(v) }
when Hash
Hash[value.map { |k, v| [camelize_key(k, false), to_camelback_keys(v)] }]
else
value
end
end | ruby | def to_camelback_keys(value = self)
case value
when Array
value.map { |v| to_camelback_keys(v) }
when Hash
Hash[value.map { |k, v| [camelize_key(k, false), to_camelback_keys(v)] }]
else
value
end
end | [
"def",
"to_camelback_keys",
"(",
"value",
"=",
"self",
")",
"case",
"value",
"when",
"Array",
"value",
".",
"map",
"{",
"|",
"v",
"|",
"to_camelback_keys",
"(",
"v",
")",
"}",
"when",
"Hash",
"Hash",
"[",
"value",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"camelize_key",
"(",
"k",
",",
"false",
")",
",",
"to_camelback_keys",
"(",
"v",
")",
"]",
"}",
"]",
"else",
"value",
"end",
"end"
] | Recursively converts Rubyish snake_case hash keys to camelBack JSON-style
hash keys suitable for use with a JSON API. | [
"Recursively",
"converts",
"Rubyish",
"snake_case",
"hash",
"keys",
"to",
"camelBack",
"JSON",
"-",
"style",
"hash",
"keys",
"suitable",
"for",
"use",
"with",
"a",
"JSON",
"API",
"."
] | f040f70b82828a6d803f3552b267eb9aec194c57 | https://github.com/futurechimp/awrence/blob/f040f70b82828a6d803f3552b267eb9aec194c57/lib/awrence/methods.rb#L8-L17 |
2,123 | futurechimp/awrence | lib/awrence/methods.rb | Awrence.Methods.to_camel_keys | def to_camel_keys(value = self)
case value
when Array
value.map { |v| to_camel_keys(v) }
when Hash
Hash[value.map { |k, v| [camelize_key(k), to_camel_keys(v)] }]
else
value
end
end | ruby | def to_camel_keys(value = self)
case value
when Array
value.map { |v| to_camel_keys(v) }
when Hash
Hash[value.map { |k, v| [camelize_key(k), to_camel_keys(v)] }]
else
value
end
end | [
"def",
"to_camel_keys",
"(",
"value",
"=",
"self",
")",
"case",
"value",
"when",
"Array",
"value",
".",
"map",
"{",
"|",
"v",
"|",
"to_camel_keys",
"(",
"v",
")",
"}",
"when",
"Hash",
"Hash",
"[",
"value",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"camelize_key",
"(",
"k",
")",
",",
"to_camel_keys",
"(",
"v",
")",
"]",
"}",
"]",
"else",
"value",
"end",
"end"
] | Recursively converts Rubyish snake_case hash keys to CamelCase JSON-style
hash keys suitable for use with a JSON API. | [
"Recursively",
"converts",
"Rubyish",
"snake_case",
"hash",
"keys",
"to",
"CamelCase",
"JSON",
"-",
"style",
"hash",
"keys",
"suitable",
"for",
"use",
"with",
"a",
"JSON",
"API",
"."
] | f040f70b82828a6d803f3552b267eb9aec194c57 | https://github.com/futurechimp/awrence/blob/f040f70b82828a6d803f3552b267eb9aec194c57/lib/awrence/methods.rb#L22-L31 |
2,124 | mdh/ssm | lib/simple_state_machine/state_machine.rb | SimpleStateMachine.StateMachine.next_state | def next_state(event_name)
transition = transitions.select{|t| t.is_transition_for?(event_name, @subject.send(state_method))}.first
transition ? transition.to : nil
end | ruby | def next_state(event_name)
transition = transitions.select{|t| t.is_transition_for?(event_name, @subject.send(state_method))}.first
transition ? transition.to : nil
end | [
"def",
"next_state",
"(",
"event_name",
")",
"transition",
"=",
"transitions",
".",
"select",
"{",
"|",
"t",
"|",
"t",
".",
"is_transition_for?",
"(",
"event_name",
",",
"@subject",
".",
"send",
"(",
"state_method",
")",
")",
"}",
".",
"first",
"transition",
"?",
"transition",
".",
"to",
":",
"nil",
"end"
] | Returns the next state for the subject for event_name | [
"Returns",
"the",
"next",
"state",
"for",
"the",
"subject",
"for",
"event_name"
] | 81f82c44cf75f444ee720f83fb3a5d3e570247f9 | https://github.com/mdh/ssm/blob/81f82c44cf75f444ee720f83fb3a5d3e570247f9/lib/simple_state_machine/state_machine.rb#L15-L18 |
2,125 | mdh/ssm | lib/simple_state_machine/state_machine.rb | SimpleStateMachine.StateMachine.error_state | def error_state(event_name, error)
transition = transitions.select{|t| t.is_error_transition_for?(event_name, error) }.first
transition ? transition.to : nil
end | ruby | def error_state(event_name, error)
transition = transitions.select{|t| t.is_error_transition_for?(event_name, error) }.first
transition ? transition.to : nil
end | [
"def",
"error_state",
"(",
"event_name",
",",
"error",
")",
"transition",
"=",
"transitions",
".",
"select",
"{",
"|",
"t",
"|",
"t",
".",
"is_error_transition_for?",
"(",
"event_name",
",",
"error",
")",
"}",
".",
"first",
"transition",
"?",
"transition",
".",
"to",
":",
"nil",
"end"
] | Returns the error state for the subject for event_name and error | [
"Returns",
"the",
"error",
"state",
"for",
"the",
"subject",
"for",
"event_name",
"and",
"error"
] | 81f82c44cf75f444ee720f83fb3a5d3e570247f9 | https://github.com/mdh/ssm/blob/81f82c44cf75f444ee720f83fb3a5d3e570247f9/lib/simple_state_machine/state_machine.rb#L21-L24 |
2,126 | mdh/ssm | lib/simple_state_machine/state_machine.rb | SimpleStateMachine.StateMachine.transition | def transition(event_name)
clear_raised_error
if to = next_state(event_name)
begin
result = yield
rescue => e
error_state = error_state(event_name, e) ||
state_machine_definition.default_error_state
if error_state
@raised_error = e
@subject.send("#{state_method}=", error_state)
return result
else
raise
end
end
# TODO refactor out to AR module
if defined?(::ActiveRecord) && @subject.is_a?(::ActiveRecord::Base)
if @subject.errors.entries.empty?
@subject.send("#{state_method}=", to)
return true
else
return false
end
else
@subject.send("#{state_method}=", to)
return result
end
else
illegal_event_callback event_name
end
end | ruby | def transition(event_name)
clear_raised_error
if to = next_state(event_name)
begin
result = yield
rescue => e
error_state = error_state(event_name, e) ||
state_machine_definition.default_error_state
if error_state
@raised_error = e
@subject.send("#{state_method}=", error_state)
return result
else
raise
end
end
# TODO refactor out to AR module
if defined?(::ActiveRecord) && @subject.is_a?(::ActiveRecord::Base)
if @subject.errors.entries.empty?
@subject.send("#{state_method}=", to)
return true
else
return false
end
else
@subject.send("#{state_method}=", to)
return result
end
else
illegal_event_callback event_name
end
end | [
"def",
"transition",
"(",
"event_name",
")",
"clear_raised_error",
"if",
"to",
"=",
"next_state",
"(",
"event_name",
")",
"begin",
"result",
"=",
"yield",
"rescue",
"=>",
"e",
"error_state",
"=",
"error_state",
"(",
"event_name",
",",
"e",
")",
"||",
"state_machine_definition",
".",
"default_error_state",
"if",
"error_state",
"@raised_error",
"=",
"e",
"@subject",
".",
"send",
"(",
"\"#{state_method}=\"",
",",
"error_state",
")",
"return",
"result",
"else",
"raise",
"end",
"end",
"# TODO refactor out to AR module",
"if",
"defined?",
"(",
"::",
"ActiveRecord",
")",
"&&",
"@subject",
".",
"is_a?",
"(",
"::",
"ActiveRecord",
"::",
"Base",
")",
"if",
"@subject",
".",
"errors",
".",
"entries",
".",
"empty?",
"@subject",
".",
"send",
"(",
"\"#{state_method}=\"",
",",
"to",
")",
"return",
"true",
"else",
"return",
"false",
"end",
"else",
"@subject",
".",
"send",
"(",
"\"#{state_method}=\"",
",",
"to",
")",
"return",
"result",
"end",
"else",
"illegal_event_callback",
"event_name",
"end",
"end"
] | Transitions to the next state if next_state exists.
When an error occurs, it uses the error to determine next state.
If no next state can be determined it transitions to the default error
state if defined, otherwise the error is re-raised.
Calls illegal_event_callback event_name if no next_state is found | [
"Transitions",
"to",
"the",
"next",
"state",
"if",
"next_state",
"exists",
".",
"When",
"an",
"error",
"occurs",
"it",
"uses",
"the",
"error",
"to",
"determine",
"next",
"state",
".",
"If",
"no",
"next",
"state",
"can",
"be",
"determined",
"it",
"transitions",
"to",
"the",
"default",
"error",
"state",
"if",
"defined",
"otherwise",
"the",
"error",
"is",
"re",
"-",
"raised",
".",
"Calls",
"illegal_event_callback",
"event_name",
"if",
"no",
"next_state",
"is",
"found"
] | 81f82c44cf75f444ee720f83fb3a5d3e570247f9 | https://github.com/mdh/ssm/blob/81f82c44cf75f444ee720f83fb3a5d3e570247f9/lib/simple_state_machine/state_machine.rb#L31-L62 |
2,127 | alfa-jpn/inum | lib/inum/active_record_mixin.rb | Inum.ActiveRecordMixin.bind_inum | def bind_inum(column, enum_class, options = {})
options = { prefix: column }.merge(options)
options[:prefix] = options[:prefix] ? "#{options[:prefix]}_" : ''
self.class_eval do
define_method(column) do
enum_class.parse(read_attribute(column))
end
define_method("#{column}=") do |value|
enum_class.parse(value).tap do |enum|
if enum
write_attribute(column, enum.to_i)
else
write_attribute(column, nil)
end
end
end
enum_class.each do |enum|
define_method("#{options[:prefix]}#{enum.to_s.underscore}?") do
enum.eql?(read_attribute(column))
end
end
end
end | ruby | def bind_inum(column, enum_class, options = {})
options = { prefix: column }.merge(options)
options[:prefix] = options[:prefix] ? "#{options[:prefix]}_" : ''
self.class_eval do
define_method(column) do
enum_class.parse(read_attribute(column))
end
define_method("#{column}=") do |value|
enum_class.parse(value).tap do |enum|
if enum
write_attribute(column, enum.to_i)
else
write_attribute(column, nil)
end
end
end
enum_class.each do |enum|
define_method("#{options[:prefix]}#{enum.to_s.underscore}?") do
enum.eql?(read_attribute(column))
end
end
end
end | [
"def",
"bind_inum",
"(",
"column",
",",
"enum_class",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"prefix",
":",
"column",
"}",
".",
"merge",
"(",
"options",
")",
"options",
"[",
":prefix",
"]",
"=",
"options",
"[",
":prefix",
"]",
"?",
"\"#{options[:prefix]}_\"",
":",
"''",
"self",
".",
"class_eval",
"do",
"define_method",
"(",
"column",
")",
"do",
"enum_class",
".",
"parse",
"(",
"read_attribute",
"(",
"column",
")",
")",
"end",
"define_method",
"(",
"\"#{column}=\"",
")",
"do",
"|",
"value",
"|",
"enum_class",
".",
"parse",
"(",
"value",
")",
".",
"tap",
"do",
"|",
"enum",
"|",
"if",
"enum",
"write_attribute",
"(",
"column",
",",
"enum",
".",
"to_i",
")",
"else",
"write_attribute",
"(",
"column",
",",
"nil",
")",
"end",
"end",
"end",
"enum_class",
".",
"each",
"do",
"|",
"enum",
"|",
"define_method",
"(",
"\"#{options[:prefix]}#{enum.to_s.underscore}?\"",
")",
"do",
"enum",
".",
"eql?",
"(",
"read_attribute",
"(",
"column",
")",
")",
"end",
"end",
"end",
"end"
] | Define compare method in class.
@param column [Symbol] Binding column name.
@param enum_class [Inum::Base] Binding Enum.
@param options [Hash] option
@option options [Symbol] :prefix Prefix. (default: column) | [
"Define",
"compare",
"method",
"in",
"class",
"."
] | 41a504aaebaf5523a9d895b1173bdbd6f02ac86d | https://github.com/alfa-jpn/inum/blob/41a504aaebaf5523a9d895b1173bdbd6f02ac86d/lib/inum/active_record_mixin.rb#L16-L41 |
2,128 | veelenga/i3ipc-ruby | lib/i3ipc/protocol.rb | I3Ipc.Protocol.receive | def receive(type = nil)
check_connected
# length of "i3-ipc" + 4 bytes length + 4 bytes type
data = @socket.read 14
magic, len, recv_type = unpack_header(data)
raise WrongMagicString.new(magic) unless MAGIC_STRING.eql? magic
type && (raise WrongType.new(type, recv_type) unless type == recv_type)
@socket.read(len)
end | ruby | def receive(type = nil)
check_connected
# length of "i3-ipc" + 4 bytes length + 4 bytes type
data = @socket.read 14
magic, len, recv_type = unpack_header(data)
raise WrongMagicString.new(magic) unless MAGIC_STRING.eql? magic
type && (raise WrongType.new(type, recv_type) unless type == recv_type)
@socket.read(len)
end | [
"def",
"receive",
"(",
"type",
"=",
"nil",
")",
"check_connected",
"# length of \"i3-ipc\" + 4 bytes length + 4 bytes type",
"data",
"=",
"@socket",
".",
"read",
"14",
"magic",
",",
"len",
",",
"recv_type",
"=",
"unpack_header",
"(",
"data",
")",
"raise",
"WrongMagicString",
".",
"new",
"(",
"magic",
")",
"unless",
"MAGIC_STRING",
".",
"eql?",
"magic",
"type",
"&&",
"(",
"raise",
"WrongType",
".",
"new",
"(",
"type",
",",
"recv_type",
")",
"unless",
"type",
"==",
"recv_type",
")",
"@socket",
".",
"read",
"(",
"len",
")",
"end"
] | Receives message from i3-ipc server socket.
@param [Integer] type expected type of the message.
@return [String] unpacked response from i3 server.
@raise [NotConnected] if protocol is not connected.
@raise [WrongMagicString] if got message with wrong magic string.
@raise [WrongType] if got message with not expected type. | [
"Receives",
"message",
"from",
"i3",
"-",
"ipc",
"server",
"socket",
"."
] | 0c3a2a76d3c264c634a0d94cc31b8be2639d9ec6 | https://github.com/veelenga/i3ipc-ruby/blob/0c3a2a76d3c264c634a0d94cc31b8be2639d9ec6/lib/i3ipc/protocol.rb#L84-L94 |
2,129 | mdh/ssm | lib/simple_state_machine/transition.rb | SimpleStateMachine.Transition.is_error_transition_for? | def is_error_transition_for?(event_name, error)
is_same_event?(event_name) && from.is_a?(Class) && error.is_a?(from)
end | ruby | def is_error_transition_for?(event_name, error)
is_same_event?(event_name) && from.is_a?(Class) && error.is_a?(from)
end | [
"def",
"is_error_transition_for?",
"(",
"event_name",
",",
"error",
")",
"is_same_event?",
"(",
"event_name",
")",
"&&",
"from",
".",
"is_a?",
"(",
"Class",
")",
"&&",
"error",
".",
"is_a?",
"(",
"from",
")",
"end"
] | returns true if it's a error transition for event_name and error | [
"returns",
"true",
"if",
"it",
"s",
"a",
"error",
"transition",
"for",
"event_name",
"and",
"error"
] | 81f82c44cf75f444ee720f83fb3a5d3e570247f9 | https://github.com/mdh/ssm/blob/81f82c44cf75f444ee720f83fb3a5d3e570247f9/lib/simple_state_machine/transition.rb#L17-L19 |
2,130 | fantasticfears/ffi-icu | lib/ffi-icu/normalizer.rb | ICU.Normalizer.normalize | def normalize(input)
input_length = input.jlength
in_ptr = UCharPointer.from_string(input)
needed_length = capacity = 0
out_ptr = UCharPointer.new(needed_length)
retried = false
begin
Lib.check_error do |error|
needed_length = Lib.unorm2_normalize(@instance, in_ptr, input_length, out_ptr, capacity, error)
end
rescue BufferOverflowError
raise BufferOverflowError, "needed: #{needed_length}" if retried
capacity = needed_length
out_ptr = out_ptr.resized_to needed_length
retried = true
retry
end
out_ptr.string
end | ruby | def normalize(input)
input_length = input.jlength
in_ptr = UCharPointer.from_string(input)
needed_length = capacity = 0
out_ptr = UCharPointer.new(needed_length)
retried = false
begin
Lib.check_error do |error|
needed_length = Lib.unorm2_normalize(@instance, in_ptr, input_length, out_ptr, capacity, error)
end
rescue BufferOverflowError
raise BufferOverflowError, "needed: #{needed_length}" if retried
capacity = needed_length
out_ptr = out_ptr.resized_to needed_length
retried = true
retry
end
out_ptr.string
end | [
"def",
"normalize",
"(",
"input",
")",
"input_length",
"=",
"input",
".",
"jlength",
"in_ptr",
"=",
"UCharPointer",
".",
"from_string",
"(",
"input",
")",
"needed_length",
"=",
"capacity",
"=",
"0",
"out_ptr",
"=",
"UCharPointer",
".",
"new",
"(",
"needed_length",
")",
"retried",
"=",
"false",
"begin",
"Lib",
".",
"check_error",
"do",
"|",
"error",
"|",
"needed_length",
"=",
"Lib",
".",
"unorm2_normalize",
"(",
"@instance",
",",
"in_ptr",
",",
"input_length",
",",
"out_ptr",
",",
"capacity",
",",
"error",
")",
"end",
"rescue",
"BufferOverflowError",
"raise",
"BufferOverflowError",
",",
"\"needed: #{needed_length}\"",
"if",
"retried",
"capacity",
"=",
"needed_length",
"out_ptr",
"=",
"out_ptr",
".",
"resized_to",
"needed_length",
"retried",
"=",
"true",
"retry",
"end",
"out_ptr",
".",
"string",
"end"
] | support for newer ICU normalization API | [
"support",
"for",
"newer",
"ICU",
"normalization",
"API"
] | 9694d97b5a700b613c8d3c9ce9e0d0e9dcbf4a30 | https://github.com/fantasticfears/ffi-icu/blob/9694d97b5a700b613c8d3c9ce9e0d0e9dcbf4a30/lib/ffi-icu/normalizer.rb#L11-L33 |
2,131 | mdespuits/validates_formatting_of | lib/validates_formatting_of/model_additions.rb | ValidatesFormattingOf.ModelAdditions.validates_formatting_of | def validates_formatting_of(attribute, options = {})
validation = Method.find(attribute, options)
options.reverse_merge!(:with => validation.regex, :message => validation.message)
self.validates_format_of(attribute, options)
end | ruby | def validates_formatting_of(attribute, options = {})
validation = Method.find(attribute, options)
options.reverse_merge!(:with => validation.regex, :message => validation.message)
self.validates_format_of(attribute, options)
end | [
"def",
"validates_formatting_of",
"(",
"attribute",
",",
"options",
"=",
"{",
"}",
")",
"validation",
"=",
"Method",
".",
"find",
"(",
"attribute",
",",
"options",
")",
"options",
".",
"reverse_merge!",
"(",
":with",
"=>",
"validation",
".",
"regex",
",",
":message",
"=>",
"validation",
".",
"message",
")",
"self",
".",
"validates_format_of",
"(",
"attribute",
",",
"options",
")",
"end"
] | Using validates_formatting_of is as simple as using Rails' built-in
validation methods in models.
class User < ActiveRecord::Base
validates_formatting_of :email, :using => :email
end
If your column name is idencital to any of the built-in methods, you
may leave off the `:using` option and validates_formatting_of will
automatically use the validation with the matching name.
class User < ActiveRecord::Base
validates_formatting_of :email
end
You can also pass conditions and options for Rails to use
* :if
* :unless
* :allow_nil
* :allow_blank
* :on | [
"Using",
"validates_formatting_of",
"is",
"as",
"simple",
"as",
"using",
"Rails",
"built",
"-",
"in",
"validation",
"methods",
"in",
"models",
"."
] | 664b7c8b1ae8c9016549944fc833737c74f1d752 | https://github.com/mdespuits/validates_formatting_of/blob/664b7c8b1ae8c9016549944fc833737c74f1d752/lib/validates_formatting_of/model_additions.rb#L27-L31 |
2,132 | phstc/sidekiq-statsd | lib/sidekiq/statsd/server_middleware.rb | Sidekiq::Statsd.ServerMiddleware.call | def call worker, msg, queue
@statsd.batch do |b|
begin
# colon causes invalid metric names
worker_name = worker.class.name.gsub('::', '.')
b.time prefix(worker_name, 'processing_time') do
yield
end
b.increment prefix(worker_name, 'success')
rescue => e
b.increment prefix(worker_name, 'failure')
raise e
ensure
if @options[:sidekiq_stats]
# Queue sizes
b.gauge prefix('enqueued'), @sidekiq_stats.enqueued
if @sidekiq_stats.respond_to?(:retry_size)
# 2.6.0 doesn't have `retry_size`
b.gauge prefix('retry_set_size'), @sidekiq_stats.retry_size
end
# All-time counts
b.gauge prefix('processed'), @sidekiq_stats.processed
b.gauge prefix('failed'), @sidekiq_stats.failed
end
# Queue metrics
queue_name = msg['queue']
sidekiq_queue = Sidekiq::Queue.new(queue_name)
b.gauge prefix('queues', queue_name, 'enqueued'), sidekiq_queue.size
if sidekiq_queue.respond_to?(:latency)
b.gauge prefix('queues', queue_name, 'latency'), sidekiq_queue.latency
end
end
end
end | ruby | def call worker, msg, queue
@statsd.batch do |b|
begin
# colon causes invalid metric names
worker_name = worker.class.name.gsub('::', '.')
b.time prefix(worker_name, 'processing_time') do
yield
end
b.increment prefix(worker_name, 'success')
rescue => e
b.increment prefix(worker_name, 'failure')
raise e
ensure
if @options[:sidekiq_stats]
# Queue sizes
b.gauge prefix('enqueued'), @sidekiq_stats.enqueued
if @sidekiq_stats.respond_to?(:retry_size)
# 2.6.0 doesn't have `retry_size`
b.gauge prefix('retry_set_size'), @sidekiq_stats.retry_size
end
# All-time counts
b.gauge prefix('processed'), @sidekiq_stats.processed
b.gauge prefix('failed'), @sidekiq_stats.failed
end
# Queue metrics
queue_name = msg['queue']
sidekiq_queue = Sidekiq::Queue.new(queue_name)
b.gauge prefix('queues', queue_name, 'enqueued'), sidekiq_queue.size
if sidekiq_queue.respond_to?(:latency)
b.gauge prefix('queues', queue_name, 'latency'), sidekiq_queue.latency
end
end
end
end | [
"def",
"call",
"worker",
",",
"msg",
",",
"queue",
"@statsd",
".",
"batch",
"do",
"|",
"b",
"|",
"begin",
"# colon causes invalid metric names",
"worker_name",
"=",
"worker",
".",
"class",
".",
"name",
".",
"gsub",
"(",
"'::'",
",",
"'.'",
")",
"b",
".",
"time",
"prefix",
"(",
"worker_name",
",",
"'processing_time'",
")",
"do",
"yield",
"end",
"b",
".",
"increment",
"prefix",
"(",
"worker_name",
",",
"'success'",
")",
"rescue",
"=>",
"e",
"b",
".",
"increment",
"prefix",
"(",
"worker_name",
",",
"'failure'",
")",
"raise",
"e",
"ensure",
"if",
"@options",
"[",
":sidekiq_stats",
"]",
"# Queue sizes",
"b",
".",
"gauge",
"prefix",
"(",
"'enqueued'",
")",
",",
"@sidekiq_stats",
".",
"enqueued",
"if",
"@sidekiq_stats",
".",
"respond_to?",
"(",
":retry_size",
")",
"# 2.6.0 doesn't have `retry_size`",
"b",
".",
"gauge",
"prefix",
"(",
"'retry_set_size'",
")",
",",
"@sidekiq_stats",
".",
"retry_size",
"end",
"# All-time counts",
"b",
".",
"gauge",
"prefix",
"(",
"'processed'",
")",
",",
"@sidekiq_stats",
".",
"processed",
"b",
".",
"gauge",
"prefix",
"(",
"'failed'",
")",
",",
"@sidekiq_stats",
".",
"failed",
"end",
"# Queue metrics",
"queue_name",
"=",
"msg",
"[",
"'queue'",
"]",
"sidekiq_queue",
"=",
"Sidekiq",
"::",
"Queue",
".",
"new",
"(",
"queue_name",
")",
"b",
".",
"gauge",
"prefix",
"(",
"'queues'",
",",
"queue_name",
",",
"'enqueued'",
")",
",",
"sidekiq_queue",
".",
"size",
"if",
"sidekiq_queue",
".",
"respond_to?",
"(",
":latency",
")",
"b",
".",
"gauge",
"prefix",
"(",
"'queues'",
",",
"queue_name",
",",
"'latency'",
")",
",",
"sidekiq_queue",
".",
"latency",
"end",
"end",
"end",
"end"
] | Initializes the middleware with options.
@param [Hash] options The options to initialize the StatsD client.
@option options [Statsd] :statsd Existing statsd client.
@option options [String] :env ("production") The env to segment the metric key (e.g. env.prefix.worker_name.success|failure).
@option options [String] :prefix ("worker") The prefix to segment the metric key (e.g. env.prefix.worker_name.success|failure).
@option options [String] :host ("localhost") The StatsD host.
@option options [String] :port ("8125") The StatsD port.
@option options [String] :sidekiq_stats ("true") Send Sidekiq global stats e.g. total enqueued, processed and failed.
Pushes the metrics in a batch.
@param worker [Sidekiq::Worker] The worker the job belongs to.
@param msg [Hash] The job message.
@param queue [String] The current queue. | [
"Initializes",
"the",
"middleware",
"with",
"options",
"."
] | 8ae212173b8860ece70e903a6a8ebd266f1f818e | https://github.com/phstc/sidekiq-statsd/blob/8ae212173b8860ece70e903a6a8ebd266f1f818e/lib/sidekiq/statsd/server_middleware.rb#L37-L74 |
2,133 | rpossan/autoit | lib/autoit/control.rb | AutoIt.Control.control_command_select_string | def control_command_select_string(title, text, control, string)
command 'ControlCommand', [title, text, control, 'SelectString', string]
end | ruby | def control_command_select_string(title, text, control, string)
command 'ControlCommand', [title, text, control, 'SelectString', string]
end | [
"def",
"control_command_select_string",
"(",
"title",
",",
"text",
",",
"control",
",",
"string",
")",
"command",
"'ControlCommand'",
",",
"[",
"title",
",",
"text",
",",
"control",
",",
"'SelectString'",
",",
"string",
"]",
"end"
] | Sets selection according to string in a ListBox or ComboBox
@param: title: The title of the window to access.
@param: text: The text of the window to access.
@param: control: The control to interact with.
@param: string: The string. | [
"Sets",
"selection",
"according",
"to",
"string",
"in",
"a",
"ListBox",
"or",
"ComboBox"
] | f24d1891dac4431830eaf9a7c6afeeada3f653f8 | https://github.com/rpossan/autoit/blob/f24d1891dac4431830eaf9a7c6afeeada3f653f8/lib/autoit/control.rb#L110-L112 |
2,134 | rpossan/autoit | lib/autoit/control.rb | AutoIt.Control.control_set_text | def control_set_text(title, text, control, value)
command_validate'ControlSetText', [title, text, control, value]
end | ruby | def control_set_text(title, text, control, value)
command_validate'ControlSetText', [title, text, control, value]
end | [
"def",
"control_set_text",
"(",
"title",
",",
"text",
",",
"control",
",",
"value",
")",
"command_validate",
"'ControlSetText'",
",",
"[",
"title",
",",
"text",
",",
"control",
",",
"value",
"]",
"end"
] | Sets text of a control.
Sends a string of characters to a control.
@param: title: The title of the window to access.
@param: text: The text of the window to access.
@param: control: The control to interact with.
@param: string: The string.
@return True if success, false otherwise | [
"Sets",
"text",
"of",
"a",
"control",
".",
"Sends",
"a",
"string",
"of",
"characters",
"to",
"a",
"control",
"."
] | f24d1891dac4431830eaf9a7c6afeeada3f653f8 | https://github.com/rpossan/autoit/blob/f24d1891dac4431830eaf9a7c6afeeada3f653f8/lib/autoit/control.rb#L137-L139 |
2,135 | rpossan/autoit | lib/autoit/control.rb | AutoIt.Control.control_click | def control_click(title, text, control, button, clicks, x, y)
command_validate('ControlClick', [title, text, control, button, clicks, x, y])
end | ruby | def control_click(title, text, control, button, clicks, x, y)
command_validate('ControlClick', [title, text, control, button, clicks, x, y])
end | [
"def",
"control_click",
"(",
"title",
",",
"text",
",",
"control",
",",
"button",
",",
"clicks",
",",
"x",
",",
"y",
")",
"command_validate",
"(",
"'ControlClick'",
",",
"[",
"title",
",",
"text",
",",
"control",
",",
"button",
",",
"clicks",
",",
"x",
",",
"y",
"]",
")",
"end"
] | Sends a mouse click command to a given control.
@param: title: The title of the window to access.
@param: text: The text of the window to access.
@param: controlID: The control to interact with.
@param: button: The button to click, "left", "right" or "middle".
@param: clicks: The number of times to click the mouse. Default is center.
@param: x: The x position to click within the control. Default is center.
@param: y: The y position to click within the control. Default is center.
@return: True if success, false otherwise. | [
"Sends",
"a",
"mouse",
"click",
"command",
"to",
"a",
"given",
"control",
"."
] | f24d1891dac4431830eaf9a7c6afeeada3f653f8 | https://github.com/rpossan/autoit/blob/f24d1891dac4431830eaf9a7c6afeeada3f653f8/lib/autoit/control.rb#L150-L152 |
2,136 | rpossan/autoit | lib/autoit/control.rb | AutoIt.Control.control_command_set_current_selection | def control_command_set_current_selection(title, text, control, occurrance)
command('ControlCommand', [title, text, control, 'SetCurrentSelection', occurrance])
end | ruby | def control_command_set_current_selection(title, text, control, occurrance)
command('ControlCommand', [title, text, control, 'SetCurrentSelection', occurrance])
end | [
"def",
"control_command_set_current_selection",
"(",
"title",
",",
"text",
",",
"control",
",",
"occurrance",
")",
"command",
"(",
"'ControlCommand'",
",",
"[",
"title",
",",
"text",
",",
"control",
",",
"'SetCurrentSelection'",
",",
"occurrance",
"]",
")",
"end"
] | Sets selection to occurrence ref in a ListBox or ComboBox.
@param: title: The title of the window to access.
@param: text: The text of the window to access.
@param: control: The control to interact with.
@param: occurrance: the value. | [
"Sets",
"selection",
"to",
"occurrence",
"ref",
"in",
"a",
"ListBox",
"or",
"ComboBox",
"."
] | f24d1891dac4431830eaf9a7c6afeeada3f653f8 | https://github.com/rpossan/autoit/blob/f24d1891dac4431830eaf9a7c6afeeada3f653f8/lib/autoit/control.rb#L159-L161 |
2,137 | stereobooster/html_press | lib/html_press/html.rb | HtmlPress.Html.process_ie_conditional_comments | def process_ie_conditional_comments (out)
out.gsub /(<!--\[[^\]]+\]>([\s\S]*?)<!\[[^\]]+\]-->)\s*/ do
m = $1
comment = $2
comment_compressed = Html.new.press(comment)
m.gsub!(comment, comment_compressed)
reserve m
end
end | ruby | def process_ie_conditional_comments (out)
out.gsub /(<!--\[[^\]]+\]>([\s\S]*?)<!\[[^\]]+\]-->)\s*/ do
m = $1
comment = $2
comment_compressed = Html.new.press(comment)
m.gsub!(comment, comment_compressed)
reserve m
end
end | [
"def",
"process_ie_conditional_comments",
"(",
"out",
")",
"out",
".",
"gsub",
"/",
"\\[",
"\\]",
"\\]",
"\\s",
"\\S",
"\\[",
"\\]",
"\\]",
"\\s",
"/",
"do",
"m",
"=",
"$1",
"comment",
"=",
"$2",
"comment_compressed",
"=",
"Html",
".",
"new",
".",
"press",
"(",
"comment",
")",
"m",
".",
"gsub!",
"(",
"comment",
",",
"comment_compressed",
")",
"reserve",
"m",
"end",
"end"
] | IE conditional comments | [
"IE",
"conditional",
"comments"
] | 4bc4599751708b6054d0d2afc76aa720973dd94f | https://github.com/stereobooster/html_press/blob/4bc4599751708b6054d0d2afc76aa720973dd94f/lib/html_press/html.rb#L57-L65 |
2,138 | stereobooster/html_press | lib/html_press/html.rb | HtmlPress.Html.process_pres | def process_pres (out)
out.gsub /(<pre\b[^>]*?>([\s\S]*?)<\/pre>)\s*/i do
pre = $2
m = $1
pre_compressed = pre.lines.map{ |l| l.gsub(/\s+$/, '') }.join("\n")
pre_compressed = HtmlPress.entities_compressor pre_compressed
m.gsub!(pre, pre_compressed)
reserve m
end
end | ruby | def process_pres (out)
out.gsub /(<pre\b[^>]*?>([\s\S]*?)<\/pre>)\s*/i do
pre = $2
m = $1
pre_compressed = pre.lines.map{ |l| l.gsub(/\s+$/, '') }.join("\n")
pre_compressed = HtmlPress.entities_compressor pre_compressed
m.gsub!(pre, pre_compressed)
reserve m
end
end | [
"def",
"process_pres",
"(",
"out",
")",
"out",
".",
"gsub",
"/",
"\\b",
"\\s",
"\\S",
"\\/",
"\\s",
"/i",
"do",
"pre",
"=",
"$2",
"m",
"=",
"$1",
"pre_compressed",
"=",
"pre",
".",
"lines",
".",
"map",
"{",
"|",
"l",
"|",
"l",
".",
"gsub",
"(",
"/",
"\\s",
"/",
",",
"''",
")",
"}",
".",
"join",
"(",
"\"\\n\"",
")",
"pre_compressed",
"=",
"HtmlPress",
".",
"entities_compressor",
"pre_compressed",
"m",
".",
"gsub!",
"(",
"pre",
",",
"pre_compressed",
")",
"reserve",
"m",
"end",
"end"
] | replace PREs with placeholders | [
"replace",
"PREs",
"with",
"placeholders"
] | 4bc4599751708b6054d0d2afc76aa720973dd94f | https://github.com/stereobooster/html_press/blob/4bc4599751708b6054d0d2afc76aa720973dd94f/lib/html_press/html.rb#L107-L116 |
2,139 | stereobooster/html_press | lib/html_press/html.rb | HtmlPress.Html.process_block_elements | def process_block_elements (out)
re = '\\s+(<\\/?(?:area|base(?:font)?|blockquote|body' +
'|caption|center|cite|col(?:group)?|dd|dir|div|dl|dt|fieldset|form' +
'|frame(?:set)?|h[1-6]|head|hr|html|legend|li|link|map|menu|meta' +
'|ol|opt(?:group|ion)|p|param|t(?:able|body|head|d|h|r|foot|itle)' +
'|ul)\\b[^>]*>)'
re = Regexp.new(re)
out.gsub!(re, '\\1')
# remove whitespaces outside of all elements
out.gsub! />([^<]+)</ do |m|
m.gsub(/^\s+|\s+$/, ' ')
end
out
end | ruby | def process_block_elements (out)
re = '\\s+(<\\/?(?:area|base(?:font)?|blockquote|body' +
'|caption|center|cite|col(?:group)?|dd|dir|div|dl|dt|fieldset|form' +
'|frame(?:set)?|h[1-6]|head|hr|html|legend|li|link|map|menu|meta' +
'|ol|opt(?:group|ion)|p|param|t(?:able|body|head|d|h|r|foot|itle)' +
'|ul)\\b[^>]*>)'
re = Regexp.new(re)
out.gsub!(re, '\\1')
# remove whitespaces outside of all elements
out.gsub! />([^<]+)</ do |m|
m.gsub(/^\s+|\s+$/, ' ')
end
out
end | [
"def",
"process_block_elements",
"(",
"out",
")",
"re",
"=",
"'\\\\s+(<\\\\/?(?:area|base(?:font)?|blockquote|body'",
"+",
"'|caption|center|cite|col(?:group)?|dd|dir|div|dl|dt|fieldset|form'",
"+",
"'|frame(?:set)?|h[1-6]|head|hr|html|legend|li|link|map|menu|meta'",
"+",
"'|ol|opt(?:group|ion)|p|param|t(?:able|body|head|d|h|r|foot|itle)'",
"+",
"'|ul)\\\\b[^>]*>)'",
"re",
"=",
"Regexp",
".",
"new",
"(",
"re",
")",
"out",
".",
"gsub!",
"(",
"re",
",",
"'\\\\1'",
")",
"# remove whitespaces outside of all elements",
"out",
".",
"gsub!",
"/",
"/",
"do",
"|",
"m",
"|",
"m",
".",
"gsub",
"(",
"/",
"\\s",
"\\s",
"/",
",",
"' '",
")",
"end",
"out",
"end"
] | remove whitespaces outside of block elements | [
"remove",
"whitespaces",
"outside",
"of",
"block",
"elements"
] | 4bc4599751708b6054d0d2afc76aa720973dd94f | https://github.com/stereobooster/html_press/blob/4bc4599751708b6054d0d2afc76aa720973dd94f/lib/html_press/html.rb#L124-L140 |
2,140 | haw-itn/openassets-ruby | lib/openassets/util.rb | OpenAssets.Util.address_to_oa_address | def address_to_oa_address(btc_address)
begin
btc_hex = decode_base58(btc_address)
btc_hex = '0' +btc_hex if btc_hex.size==47
address = btc_hex[0..-9] # bitcoin address without checksum
named_addr = OA_NAMESPACE.to_s(16) + address
oa_checksum = checksum(named_addr)
encode_base58(named_addr + oa_checksum)
rescue ArgumentError
nil # bech32 format fails to decode. TODO define OA address for segwit
end
end | ruby | def address_to_oa_address(btc_address)
begin
btc_hex = decode_base58(btc_address)
btc_hex = '0' +btc_hex if btc_hex.size==47
address = btc_hex[0..-9] # bitcoin address without checksum
named_addr = OA_NAMESPACE.to_s(16) + address
oa_checksum = checksum(named_addr)
encode_base58(named_addr + oa_checksum)
rescue ArgumentError
nil # bech32 format fails to decode. TODO define OA address for segwit
end
end | [
"def",
"address_to_oa_address",
"(",
"btc_address",
")",
"begin",
"btc_hex",
"=",
"decode_base58",
"(",
"btc_address",
")",
"btc_hex",
"=",
"'0'",
"+",
"btc_hex",
"if",
"btc_hex",
".",
"size",
"==",
"47",
"address",
"=",
"btc_hex",
"[",
"0",
"..",
"-",
"9",
"]",
"# bitcoin address without checksum",
"named_addr",
"=",
"OA_NAMESPACE",
".",
"to_s",
"(",
"16",
")",
"+",
"address",
"oa_checksum",
"=",
"checksum",
"(",
"named_addr",
")",
"encode_base58",
"(",
"named_addr",
"+",
"oa_checksum",
")",
"rescue",
"ArgumentError",
"nil",
"# bech32 format fails to decode. TODO define OA address for segwit",
"end",
"end"
] | convert bitcoin address to open assets address
@param [String] btc_address The Bitcoin address.
@return [String] The Open Assets Address. | [
"convert",
"bitcoin",
"address",
"to",
"open",
"assets",
"address"
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/util.rb#L17-L28 |
2,141 | haw-itn/openassets-ruby | lib/openassets/util.rb | OpenAssets.Util.oa_address_to_address | def oa_address_to_address(oa_address)
decode_address = decode_base58(oa_address)
btc_addr = decode_address[2..-9]
btc_checksum = checksum(btc_addr)
encode_base58(btc_addr + btc_checksum)
end | ruby | def oa_address_to_address(oa_address)
decode_address = decode_base58(oa_address)
btc_addr = decode_address[2..-9]
btc_checksum = checksum(btc_addr)
encode_base58(btc_addr + btc_checksum)
end | [
"def",
"oa_address_to_address",
"(",
"oa_address",
")",
"decode_address",
"=",
"decode_base58",
"(",
"oa_address",
")",
"btc_addr",
"=",
"decode_address",
"[",
"2",
"..",
"-",
"9",
"]",
"btc_checksum",
"=",
"checksum",
"(",
"btc_addr",
")",
"encode_base58",
"(",
"btc_addr",
"+",
"btc_checksum",
")",
"end"
] | convert open assets address to bitcoin address
@param [String] oa_address The Open Assets Address.
@return [String] The Bitcoin address. | [
"convert",
"open",
"assets",
"address",
"to",
"bitcoin",
"address"
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/util.rb#L33-L38 |
2,142 | haw-itn/openassets-ruby | lib/openassets/util.rb | OpenAssets.Util.valid_asset_id? | def valid_asset_id?(asset_id)
return false if asset_id.nil? || asset_id.length != 34
decoded = decode_base58(asset_id)
return false if decoded[0,2].to_i(16) != oa_version_byte
p2pkh_script_hash = decoded[2..-9]
address = hash160_to_address(p2pkh_script_hash)
valid_address?(address)
end | ruby | def valid_asset_id?(asset_id)
return false if asset_id.nil? || asset_id.length != 34
decoded = decode_base58(asset_id)
return false if decoded[0,2].to_i(16) != oa_version_byte
p2pkh_script_hash = decoded[2..-9]
address = hash160_to_address(p2pkh_script_hash)
valid_address?(address)
end | [
"def",
"valid_asset_id?",
"(",
"asset_id",
")",
"return",
"false",
"if",
"asset_id",
".",
"nil?",
"||",
"asset_id",
".",
"length",
"!=",
"34",
"decoded",
"=",
"decode_base58",
"(",
"asset_id",
")",
"return",
"false",
"if",
"decoded",
"[",
"0",
",",
"2",
"]",
".",
"to_i",
"(",
"16",
")",
"!=",
"oa_version_byte",
"p2pkh_script_hash",
"=",
"decoded",
"[",
"2",
"..",
"-",
"9",
"]",
"address",
"=",
"hash160_to_address",
"(",
"p2pkh_script_hash",
")",
"valid_address?",
"(",
"address",
")",
"end"
] | validate asset ID | [
"validate",
"asset",
"ID"
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/util.rb#L113-L120 |
2,143 | haw-itn/openassets-ruby | lib/openassets/util.rb | OpenAssets.Util.read_var_integer | def read_var_integer(data, offset = 0)
raise ArgumentError, "data is nil." unless data
packed = [data].pack('H*')
return [nil, 0] if packed.bytesize < 1+offset
bytes = packed.bytes[offset..(offset + 9)] # 9 is variable integer max storage length.
first_byte = bytes[0]
if first_byte < 0xfd
[first_byte, offset + 1]
elsif first_byte == 0xfd
[calc_var_integer_val(bytes[1..2]), offset + 3]
elsif first_byte == 0xfe
[calc_var_integer_val(bytes[1..4]), offset + 5]
elsif first_byte == 0xff
[calc_var_integer_val(bytes[1..8]), offset + 9]
end
end | ruby | def read_var_integer(data, offset = 0)
raise ArgumentError, "data is nil." unless data
packed = [data].pack('H*')
return [nil, 0] if packed.bytesize < 1+offset
bytes = packed.bytes[offset..(offset + 9)] # 9 is variable integer max storage length.
first_byte = bytes[0]
if first_byte < 0xfd
[first_byte, offset + 1]
elsif first_byte == 0xfd
[calc_var_integer_val(bytes[1..2]), offset + 3]
elsif first_byte == 0xfe
[calc_var_integer_val(bytes[1..4]), offset + 5]
elsif first_byte == 0xff
[calc_var_integer_val(bytes[1..8]), offset + 9]
end
end | [
"def",
"read_var_integer",
"(",
"data",
",",
"offset",
"=",
"0",
")",
"raise",
"ArgumentError",
",",
"\"data is nil.\"",
"unless",
"data",
"packed",
"=",
"[",
"data",
"]",
".",
"pack",
"(",
"'H*'",
")",
"return",
"[",
"nil",
",",
"0",
"]",
"if",
"packed",
".",
"bytesize",
"<",
"1",
"+",
"offset",
"bytes",
"=",
"packed",
".",
"bytes",
"[",
"offset",
"..",
"(",
"offset",
"+",
"9",
")",
"]",
"# 9 is variable integer max storage length.",
"first_byte",
"=",
"bytes",
"[",
"0",
"]",
"if",
"first_byte",
"<",
"0xfd",
"[",
"first_byte",
",",
"offset",
"+",
"1",
"]",
"elsif",
"first_byte",
"==",
"0xfd",
"[",
"calc_var_integer_val",
"(",
"bytes",
"[",
"1",
"..",
"2",
"]",
")",
",",
"offset",
"+",
"3",
"]",
"elsif",
"first_byte",
"==",
"0xfe",
"[",
"calc_var_integer_val",
"(",
"bytes",
"[",
"1",
"..",
"4",
"]",
")",
",",
"offset",
"+",
"5",
"]",
"elsif",
"first_byte",
"==",
"0xff",
"[",
"calc_var_integer_val",
"(",
"bytes",
"[",
"1",
"..",
"8",
"]",
")",
",",
"offset",
"+",
"9",
"]",
"end",
"end"
] | read variable integer
@param [String] data reading data
@param [Integer] offset the position when reading from data.
@return [[Integer, Integer]] decoded integer value and the reading byte length.
https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer | [
"read",
"variable",
"integer"
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/util.rb#L127-L142 |
2,144 | haw-itn/openassets-ruby | lib/openassets/util.rb | OpenAssets.Util.read_leb128 | def read_leb128(data, offset = 0)
bytes = [data].pack('H*').bytes
result = 0
shift = 0
while true
return [nil, offset] if bytes.length < 1 + offset
byte = bytes[offset..(offset + 1)][0]
result |= (byte & 0x7f) << shift
break if byte & 0x80 == 0
shift += 7
offset += 1
end
[result, offset + 1]
end | ruby | def read_leb128(data, offset = 0)
bytes = [data].pack('H*').bytes
result = 0
shift = 0
while true
return [nil, offset] if bytes.length < 1 + offset
byte = bytes[offset..(offset + 1)][0]
result |= (byte & 0x7f) << shift
break if byte & 0x80 == 0
shift += 7
offset += 1
end
[result, offset + 1]
end | [
"def",
"read_leb128",
"(",
"data",
",",
"offset",
"=",
"0",
")",
"bytes",
"=",
"[",
"data",
"]",
".",
"pack",
"(",
"'H*'",
")",
".",
"bytes",
"result",
"=",
"0",
"shift",
"=",
"0",
"while",
"true",
"return",
"[",
"nil",
",",
"offset",
"]",
"if",
"bytes",
".",
"length",
"<",
"1",
"+",
"offset",
"byte",
"=",
"bytes",
"[",
"offset",
"..",
"(",
"offset",
"+",
"1",
")",
"]",
"[",
"0",
"]",
"result",
"|=",
"(",
"byte",
"&",
"0x7f",
")",
"<<",
"shift",
"break",
"if",
"byte",
"&",
"0x80",
"==",
"0",
"shift",
"+=",
"7",
"offset",
"+=",
"1",
"end",
"[",
"result",
",",
"offset",
"+",
"1",
"]",
"end"
] | read leb128 value
@param [String] data reading data
@param [Integer] offset start position when reading from data.
@return [[Integer, Integer]] decoded integer value and the reading byte length. | [
"read",
"leb128",
"value"
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/util.rb#L148-L161 |
2,145 | mikerodrigues/arp_scan | lib/arp_scan/scan_report.rb | ARPScan.ScanReport.to_array | def to_array
self.instance_variables.map do |var|
if var == :@hosts
self.instance_variable_get(var).map {|host| host.to_array}
else
self.instance_variable_get(var)
end
end
end | ruby | def to_array
self.instance_variables.map do |var|
if var == :@hosts
self.instance_variable_get(var).map {|host| host.to_array}
else
self.instance_variable_get(var)
end
end
end | [
"def",
"to_array",
"self",
".",
"instance_variables",
".",
"map",
"do",
"|",
"var",
"|",
"if",
"var",
"==",
":@hosts",
"self",
".",
"instance_variable_get",
"(",
"var",
")",
".",
"map",
"{",
"|",
"host",
"|",
"host",
".",
"to_array",
"}",
"else",
"self",
".",
"instance_variable_get",
"(",
"var",
")",
"end",
"end",
"end"
] | Create a new scan report, passing in every attribute. The best way to do
this is with the ScanResultProcessor module.
Returns an array representation of the ScanReport. Metadata about the
scan, and an array of Host arrays comprise the array. | [
"Create",
"a",
"new",
"scan",
"report",
"passing",
"in",
"every",
"attribute",
".",
"The",
"best",
"way",
"to",
"do",
"this",
"is",
"with",
"the",
"ScanResultProcessor",
"module",
"."
] | c0fb8821ce9a08e43e74ed7d219b029c7b6c32c9 | https://github.com/mikerodrigues/arp_scan/blob/c0fb8821ce9a08e43e74ed7d219b029c7b6c32c9/lib/arp_scan/scan_report.rb#L60-L68 |
2,146 | greyblake/telebot | lib/telebot/client.rb | Telebot.Client.get_updates | def get_updates(offset: nil, limit: nil, timeout: nil)
result = call(:getUpdates, offset: offset, limit: limit, timeout: timeout)
result.map { |update_hash| Update.new(update_hash) }
end | ruby | def get_updates(offset: nil, limit: nil, timeout: nil)
result = call(:getUpdates, offset: offset, limit: limit, timeout: timeout)
result.map { |update_hash| Update.new(update_hash) }
end | [
"def",
"get_updates",
"(",
"offset",
":",
"nil",
",",
"limit",
":",
"nil",
",",
"timeout",
":",
"nil",
")",
"result",
"=",
"call",
"(",
":getUpdates",
",",
"offset",
":",
"offset",
",",
"limit",
":",
"limit",
",",
"timeout",
":",
"timeout",
")",
"result",
".",
"map",
"{",
"|",
"update_hash",
"|",
"Update",
".",
"new",
"(",
"update_hash",
")",
"}",
"end"
] | Use this method to receive incoming updates using long polling.
An Array of Update objects is returned.
Note:
1. This method will not work if an outgoing webhook is set up.
2. In order to avoid getting duplicate updates, recalculate offset after each server response.
@param offset [Integer]
Identifier of the first update to be returned.
Must be greater by one than the highest among the identifiers of
previously received updates. By default, updates starting with the
earliest unconfirmed update are returned. An update is considered
confirmed as soon as getUpdates is called with an offset higher
than its update_id.
@param limit [Integer]
Limits the number of updates to be retrieved. Values between 1—100 are accepted.
Defaults to 100
@param timeout [Integer]
Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling.
@return [Array<Telebot::Update>] | [
"Use",
"this",
"method",
"to",
"receive",
"incoming",
"updates",
"using",
"long",
"polling",
".",
"An",
"Array",
"of",
"Update",
"objects",
"is",
"returned",
"."
] | 16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a | https://github.com/greyblake/telebot/blob/16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a/lib/telebot/client.rb#L50-L53 |
2,147 | greyblake/telebot | lib/telebot/client.rb | Telebot.Client.send_message | def send_message(chat_id:, text:, disable_web_page_preview: false, reply_to_message_id: nil, reply_markup: nil, parse_mode: nil)
result = call(:sendMessage,
chat_id: chat_id,
text: text,
disable_web_page_preview: disable_web_page_preview,
reply_to_message_id: reply_to_message_id,
reply_markup: reply_markup,
parse_mode: parse_mode
)
Message.new(result)
end | ruby | def send_message(chat_id:, text:, disable_web_page_preview: false, reply_to_message_id: nil, reply_markup: nil, parse_mode: nil)
result = call(:sendMessage,
chat_id: chat_id,
text: text,
disable_web_page_preview: disable_web_page_preview,
reply_to_message_id: reply_to_message_id,
reply_markup: reply_markup,
parse_mode: parse_mode
)
Message.new(result)
end | [
"def",
"send_message",
"(",
"chat_id",
":",
",",
"text",
":",
",",
"disable_web_page_preview",
":",
"false",
",",
"reply_to_message_id",
":",
"nil",
",",
"reply_markup",
":",
"nil",
",",
"parse_mode",
":",
"nil",
")",
"result",
"=",
"call",
"(",
":sendMessage",
",",
"chat_id",
":",
"chat_id",
",",
"text",
":",
"text",
",",
"disable_web_page_preview",
":",
"disable_web_page_preview",
",",
"reply_to_message_id",
":",
"reply_to_message_id",
",",
"reply_markup",
":",
"reply_markup",
",",
"parse_mode",
":",
"parse_mode",
")",
"Message",
".",
"new",
"(",
"result",
")",
"end"
] | Send text message.
@param chat_id [Integer] Unique identifier for the message recipient - User or GroupChat id
@param text [String] Text of the message to be sent
@param disable_web_page_preview [Boolean] Disables link previews for links in this message
@param reply_to_message_id [Integer] If the message is a reply, ID of the original message
@param reply_markup [ReplyKeyboardMarkup, ReplyKeyboardHide, ForceReply] Additional interface options
@param parse_mode [String] "Markdown" or "HTML", Optional
@return [Telebot::Message] | [
"Send",
"text",
"message",
"."
] | 16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a | https://github.com/greyblake/telebot/blob/16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a/lib/telebot/client.rb#L65-L75 |
2,148 | greyblake/telebot | lib/telebot/client.rb | Telebot.Client.forward_message | def forward_message(chat_id:, from_chat_id:, message_id:)
result = call(:forwardMessage, chat_id: chat_id, from_chat_id: from_chat_id, message_id: message_id)
Message.new(result)
end | ruby | def forward_message(chat_id:, from_chat_id:, message_id:)
result = call(:forwardMessage, chat_id: chat_id, from_chat_id: from_chat_id, message_id: message_id)
Message.new(result)
end | [
"def",
"forward_message",
"(",
"chat_id",
":",
",",
"from_chat_id",
":",
",",
"message_id",
":",
")",
"result",
"=",
"call",
"(",
":forwardMessage",
",",
"chat_id",
":",
"chat_id",
",",
"from_chat_id",
":",
"from_chat_id",
",",
"message_id",
":",
"message_id",
")",
"Message",
".",
"new",
"(",
"result",
")",
"end"
] | Use this method to forward messages of any kind.
@param chat_id [Integer] Unique identifier for the message recipient - User or GroupChat id
@param from_chat_id [Integer] Unique identifier for the chat where the original message was sent - User or GroupChat id
@param message_id [Integer] Unique message identifier
@return [Telebot::Message] | [
"Use",
"this",
"method",
"to",
"forward",
"messages",
"of",
"any",
"kind",
"."
] | 16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a | https://github.com/greyblake/telebot/blob/16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a/lib/telebot/client.rb#L84-L87 |
2,149 | greyblake/telebot | lib/telebot/client.rb | Telebot.Client.send_photo | def send_photo(chat_id:, photo:, caption: nil, reply_to_message_id: nil, reply_markup: nil)
result = call(:sendPhoto, chat_id: chat_id, photo: photo, caption: caption, reply_to_message_id: reply_to_message_id, reply_markup: reply_markup)
Message.new(result)
end | ruby | def send_photo(chat_id:, photo:, caption: nil, reply_to_message_id: nil, reply_markup: nil)
result = call(:sendPhoto, chat_id: chat_id, photo: photo, caption: caption, reply_to_message_id: reply_to_message_id, reply_markup: reply_markup)
Message.new(result)
end | [
"def",
"send_photo",
"(",
"chat_id",
":",
",",
"photo",
":",
",",
"caption",
":",
"nil",
",",
"reply_to_message_id",
":",
"nil",
",",
"reply_markup",
":",
"nil",
")",
"result",
"=",
"call",
"(",
":sendPhoto",
",",
"chat_id",
":",
"chat_id",
",",
"photo",
":",
"photo",
",",
"caption",
":",
"caption",
",",
"reply_to_message_id",
":",
"reply_to_message_id",
",",
"reply_markup",
":",
"reply_markup",
")",
"Message",
".",
"new",
"(",
"result",
")",
"end"
] | Send a picture.
@param chat_id [Integer] Unique identifier for the message recipient - User or GroupChat id
@param photo [InputFile, String] Photo to send. You can either pass a
file_id as String to resend a photo that is already on the Telegram servers,
or upload a new photo using multipart/form-data.
@param caption [String] Photo caption (may also be used when resending photos by file_id)
@param reply_to_message_id [Integer] If the message is a reply, ID of the original message
@param reply_markup [ReplyKeyboardMarkup, ReplyKeyboardHide, ForceReply] Additional interface options
@return [Telebot::Message] | [
"Send",
"a",
"picture",
"."
] | 16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a | https://github.com/greyblake/telebot/blob/16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a/lib/telebot/client.rb#L100-L103 |
2,150 | greyblake/telebot | lib/telebot/client.rb | Telebot.Client.send_document | def send_document(chat_id:, document:, reply_to_message_id: nil, reply_markup: nil)
result = call(:sendDocument, chat_id: chat_id, document: document, reply_to_message_id: reply_to_message_id, reply_markup: reply_markup)
Message.new(result)
end | ruby | def send_document(chat_id:, document:, reply_to_message_id: nil, reply_markup: nil)
result = call(:sendDocument, chat_id: chat_id, document: document, reply_to_message_id: reply_to_message_id, reply_markup: reply_markup)
Message.new(result)
end | [
"def",
"send_document",
"(",
"chat_id",
":",
",",
"document",
":",
",",
"reply_to_message_id",
":",
"nil",
",",
"reply_markup",
":",
"nil",
")",
"result",
"=",
"call",
"(",
":sendDocument",
",",
"chat_id",
":",
"chat_id",
",",
"document",
":",
"document",
",",
"reply_to_message_id",
":",
"reply_to_message_id",
",",
"reply_markup",
":",
"reply_markup",
")",
"Message",
".",
"new",
"(",
"result",
")",
"end"
] | Send general file.
@param chat_id [Integer]
@param document [Telebot::InputFile, String] document to send (file or file_id)
@param reply_to_message_id [Integer] If the message is a reply, ID of the original message
@param reply_markup [ReplyKeyboardMarkup, ReplyKeyboardHide, ForceReply] Additional interface options
@return [Telebot::Message] | [
"Send",
"general",
"file",
"."
] | 16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a | https://github.com/greyblake/telebot/blob/16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a/lib/telebot/client.rb#L128-L131 |
2,151 | greyblake/telebot | lib/telebot/client.rb | Telebot.Client.send_sticker | def send_sticker(chat_id:, sticker:, reply_to_message_id: nil, reply_markup: nil)
result = call(:sendSticker, chat_id: chat_id, sticker: sticker, reply_to_message_id: reply_to_message_id, reply_markup: reply_markup)
Message.new(result)
end | ruby | def send_sticker(chat_id:, sticker:, reply_to_message_id: nil, reply_markup: nil)
result = call(:sendSticker, chat_id: chat_id, sticker: sticker, reply_to_message_id: reply_to_message_id, reply_markup: reply_markup)
Message.new(result)
end | [
"def",
"send_sticker",
"(",
"chat_id",
":",
",",
"sticker",
":",
",",
"reply_to_message_id",
":",
"nil",
",",
"reply_markup",
":",
"nil",
")",
"result",
"=",
"call",
"(",
":sendSticker",
",",
"chat_id",
":",
"chat_id",
",",
"sticker",
":",
"sticker",
",",
"reply_to_message_id",
":",
"reply_to_message_id",
",",
"reply_markup",
":",
"reply_markup",
")",
"Message",
".",
"new",
"(",
"result",
")",
"end"
] | Use this method to send .webp stickers.
@param chat_id [Integer]
@param sticker [Telebot::InputFile, String] sticker to send (file or file_id)
@param reply_to_message_id [Integer] If the message is a reply, ID of the original message
@param reply_markup [ReplyKeyboardMarkup, ReplyKeyboardHide, ForceReply] Additional interface options
@return [Telebot::Message] | [
"Use",
"this",
"method",
"to",
"send",
".",
"webp",
"stickers",
"."
] | 16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a | https://github.com/greyblake/telebot/blob/16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a/lib/telebot/client.rb#L141-L144 |
2,152 | greyblake/telebot | lib/telebot/client.rb | Telebot.Client.send_location | def send_location(chat_id:, latitude:, longitude:, reply_to_message_id: nil, reply_markup: nil)
result = call(:sendLocation, chat_id: chat_id,
latitude: latitude,
longitude: longitude,
reply_to_message_id: reply_to_message_id,
reply_markup: reply_markup)
Message.new(result)
end | ruby | def send_location(chat_id:, latitude:, longitude:, reply_to_message_id: nil, reply_markup: nil)
result = call(:sendLocation, chat_id: chat_id,
latitude: latitude,
longitude: longitude,
reply_to_message_id: reply_to_message_id,
reply_markup: reply_markup)
Message.new(result)
end | [
"def",
"send_location",
"(",
"chat_id",
":",
",",
"latitude",
":",
",",
"longitude",
":",
",",
"reply_to_message_id",
":",
"nil",
",",
"reply_markup",
":",
"nil",
")",
"result",
"=",
"call",
"(",
":sendLocation",
",",
"chat_id",
":",
"chat_id",
",",
"latitude",
":",
"latitude",
",",
"longitude",
":",
"longitude",
",",
"reply_to_message_id",
":",
"reply_to_message_id",
",",
"reply_markup",
":",
"reply_markup",
")",
"Message",
".",
"new",
"(",
"result",
")",
"end"
] | Send a point on the map.
@param chat_id [Integer]
@param latitude [Integer]
@param longitude [Integer]
@param reply_to_message_id [Integer]
@param reply_markup [ReplyKeyboardMarkup, ReplyKeyboardHide, ForceReply]
@return [Telebot::Message] | [
"Send",
"a",
"point",
"on",
"the",
"map",
"."
] | 16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a | https://github.com/greyblake/telebot/blob/16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a/lib/telebot/client.rb#L168-L175 |
2,153 | greyblake/telebot | lib/telebot/client.rb | Telebot.Client.get_user_profile_photos | def get_user_profile_photos(user_id:, offset: nil, limit: nil)
result = call(:getUserProfilePhotos, user_id: user_id, offset: offset, limit: limit)
UserProfilePhotos.new(result)
end | ruby | def get_user_profile_photos(user_id:, offset: nil, limit: nil)
result = call(:getUserProfilePhotos, user_id: user_id, offset: offset, limit: limit)
UserProfilePhotos.new(result)
end | [
"def",
"get_user_profile_photos",
"(",
"user_id",
":",
",",
"offset",
":",
"nil",
",",
"limit",
":",
"nil",
")",
"result",
"=",
"call",
"(",
":getUserProfilePhotos",
",",
"user_id",
":",
"user_id",
",",
"offset",
":",
"offset",
",",
"limit",
":",
"limit",
")",
"UserProfilePhotos",
".",
"new",
"(",
"result",
")",
"end"
] | Use this method to get a list of profile pictures for a user.
@param user_id [Integer]
@param offset [Integer]
@param limit [Integer]
@return [Telebot::UserProfilePhotos] | [
"Use",
"this",
"method",
"to",
"get",
"a",
"list",
"of",
"profile",
"pictures",
"for",
"a",
"user",
"."
] | 16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a | https://github.com/greyblake/telebot/blob/16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a/lib/telebot/client.rb#L197-L200 |
2,154 | Cimpress-MCP/LambdaWrap | lib/lambda_wrap/api_manager.rb | LambdaWrap.API.add_lambda | def add_lambda(*new_lambda)
flattened_lambdas = new_lambda.flatten
flattened_lambdas.each { |lambda| parameter_guard(lambda, LambdaWrap::Lambda, 'LambdaWrap::Lambda') }
lambdas.concat(flattened_lambdas)
end | ruby | def add_lambda(*new_lambda)
flattened_lambdas = new_lambda.flatten
flattened_lambdas.each { |lambda| parameter_guard(lambda, LambdaWrap::Lambda, 'LambdaWrap::Lambda') }
lambdas.concat(flattened_lambdas)
end | [
"def",
"add_lambda",
"(",
"*",
"new_lambda",
")",
"flattened_lambdas",
"=",
"new_lambda",
".",
"flatten",
"flattened_lambdas",
".",
"each",
"{",
"|",
"lambda",
"|",
"parameter_guard",
"(",
"lambda",
",",
"LambdaWrap",
"::",
"Lambda",
",",
"'LambdaWrap::Lambda'",
")",
"}",
"lambdas",
".",
"concat",
"(",
"flattened_lambdas",
")",
"end"
] | Constructor for the high level API Manager class.
@param [Hash] options The Options to configure the API.
@option options [String] :access_key_id The AWS Access Key Id to communicate with AWS. Will also check the
environment variables for this value.
@option options [String] :secret_access_key The AWS Secret Access Key to communicate with AWS. Also checks
environment variables for this value.
@option options [String] :region The AWS Region to deploy API to. Also checks environment variables for this
value.
@todo Allow clients to pass in a YAML file for all construction.
Add Lambda Object(s) to the API.
@param [LambdaWrap::Lambda Array<LambdaWrap::Lambda>] new_lambda Splat of LambdaWrap Lambda
objects to add to the API. Overloaded as:
add_lambda(lambda1) OR add_lambda([lambda1, lambda2]) OR add_lambda(lambda1, lambda2) | [
"Constructor",
"for",
"the",
"high",
"level",
"API",
"Manager",
"class",
"."
] | 9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8 | https://github.com/Cimpress-MCP/LambdaWrap/blob/9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8/lib/lambda_wrap/api_manager.rb#L66-L70 |
2,155 | Cimpress-MCP/LambdaWrap | lib/lambda_wrap/api_manager.rb | LambdaWrap.API.deploy | def deploy(environment_options)
environment_parameter_guard(environment_options)
if no_op?
puts 'Nothing to deploy.'
return
end
deployment_start_message = 'Deploying '
deployment_start_message += "#{dynamo_tables.length} Dynamo Tables, " unless dynamo_tables.empty?
deployment_start_message += "#{lambdas.length} Lambdas, " unless lambdas.empty?
deployment_start_message += "#{api_gateways.length} API Gateways " unless api_gateways.empty?
deployment_start_message += "to Environment: #{environment_options.name}"
puts deployment_start_message
total_time_start = Time.now
services_time_start = total_time_start
dynamo_tables.each { |table| table.deploy(environment_options, @dynamo_client, @region) }
services_time_end = Time.now
unless dynamo_tables.empty?
puts "Deploying #{dynamo_tables.length} Table(s) took: \
#{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}"
end
services_time_start = Time.now
lambdas.each { |lambda| lambda.deploy(environment_options, @lambda_client, @region) }
services_time_end = Time.now
unless lambdas.empty?
puts "Deploying #{lambdas.length} Lambda(s) took: \
#{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}"
end
services_time_start = Time.now
api_gateways.each { |apig| apig.deploy(environment_options, @api_gateway_client, @region) }
services_time_end = Time.now
unless api_gateways.empty?
puts "Deploying #{api_gateways.length} API Gateway(s) took: \
#{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}"
end
total_time_end = Time.now
puts "Total API Deployment took: \
#{Time.at(total_time_end - total_time_start).utc.strftime('%H:%M:%S')}"
puts "Successfully deployed API to #{environment_options.name}"
true
end | ruby | def deploy(environment_options)
environment_parameter_guard(environment_options)
if no_op?
puts 'Nothing to deploy.'
return
end
deployment_start_message = 'Deploying '
deployment_start_message += "#{dynamo_tables.length} Dynamo Tables, " unless dynamo_tables.empty?
deployment_start_message += "#{lambdas.length} Lambdas, " unless lambdas.empty?
deployment_start_message += "#{api_gateways.length} API Gateways " unless api_gateways.empty?
deployment_start_message += "to Environment: #{environment_options.name}"
puts deployment_start_message
total_time_start = Time.now
services_time_start = total_time_start
dynamo_tables.each { |table| table.deploy(environment_options, @dynamo_client, @region) }
services_time_end = Time.now
unless dynamo_tables.empty?
puts "Deploying #{dynamo_tables.length} Table(s) took: \
#{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}"
end
services_time_start = Time.now
lambdas.each { |lambda| lambda.deploy(environment_options, @lambda_client, @region) }
services_time_end = Time.now
unless lambdas.empty?
puts "Deploying #{lambdas.length} Lambda(s) took: \
#{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}"
end
services_time_start = Time.now
api_gateways.each { |apig| apig.deploy(environment_options, @api_gateway_client, @region) }
services_time_end = Time.now
unless api_gateways.empty?
puts "Deploying #{api_gateways.length} API Gateway(s) took: \
#{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}"
end
total_time_end = Time.now
puts "Total API Deployment took: \
#{Time.at(total_time_end - total_time_start).utc.strftime('%H:%M:%S')}"
puts "Successfully deployed API to #{environment_options.name}"
true
end | [
"def",
"deploy",
"(",
"environment_options",
")",
"environment_parameter_guard",
"(",
"environment_options",
")",
"if",
"no_op?",
"puts",
"'Nothing to deploy.'",
"return",
"end",
"deployment_start_message",
"=",
"'Deploying '",
"deployment_start_message",
"+=",
"\"#{dynamo_tables.length} Dynamo Tables, \"",
"unless",
"dynamo_tables",
".",
"empty?",
"deployment_start_message",
"+=",
"\"#{lambdas.length} Lambdas, \"",
"unless",
"lambdas",
".",
"empty?",
"deployment_start_message",
"+=",
"\"#{api_gateways.length} API Gateways \"",
"unless",
"api_gateways",
".",
"empty?",
"deployment_start_message",
"+=",
"\"to Environment: #{environment_options.name}\"",
"puts",
"deployment_start_message",
"total_time_start",
"=",
"Time",
".",
"now",
"services_time_start",
"=",
"total_time_start",
"dynamo_tables",
".",
"each",
"{",
"|",
"table",
"|",
"table",
".",
"deploy",
"(",
"environment_options",
",",
"@dynamo_client",
",",
"@region",
")",
"}",
"services_time_end",
"=",
"Time",
".",
"now",
"unless",
"dynamo_tables",
".",
"empty?",
"puts",
"\"Deploying #{dynamo_tables.length} Table(s) took: \\\n #{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}\"",
"end",
"services_time_start",
"=",
"Time",
".",
"now",
"lambdas",
".",
"each",
"{",
"|",
"lambda",
"|",
"lambda",
".",
"deploy",
"(",
"environment_options",
",",
"@lambda_client",
",",
"@region",
")",
"}",
"services_time_end",
"=",
"Time",
".",
"now",
"unless",
"lambdas",
".",
"empty?",
"puts",
"\"Deploying #{lambdas.length} Lambda(s) took: \\\n #{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}\"",
"end",
"services_time_start",
"=",
"Time",
".",
"now",
"api_gateways",
".",
"each",
"{",
"|",
"apig",
"|",
"apig",
".",
"deploy",
"(",
"environment_options",
",",
"@api_gateway_client",
",",
"@region",
")",
"}",
"services_time_end",
"=",
"Time",
".",
"now",
"unless",
"api_gateways",
".",
"empty?",
"puts",
"\"Deploying #{api_gateways.length} API Gateway(s) took: \\\n #{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}\"",
"end",
"total_time_end",
"=",
"Time",
".",
"now",
"puts",
"\"Total API Deployment took: \\\n #{Time.at(total_time_end - total_time_start).utc.strftime('%H:%M:%S')}\"",
"puts",
"\"Successfully deployed API to #{environment_options.name}\"",
"true",
"end"
] | Deploys all services to the specified environment.
@param [LambdaWrap::Environment] environment_options the Environment to deploy | [
"Deploys",
"all",
"services",
"to",
"the",
"specified",
"environment",
"."
] | 9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8 | https://github.com/Cimpress-MCP/LambdaWrap/blob/9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8/lib/lambda_wrap/api_manager.rb#L97-L147 |
2,156 | Cimpress-MCP/LambdaWrap | lib/lambda_wrap/api_manager.rb | LambdaWrap.API.delete | def delete
if dynamo_tables.empty? && lambdas.empty? && api_gateways.empty?
puts 'Nothing to Deleting.'
return
end
deployment_start_message = 'Deleting '
deployment_start_message += "#{dynamo_tables.length} Dynamo Tables, " unless dynamo_tables.empty?
deployment_start_message += "#{lambdas.length} Lambdas, " unless lambdas.empty?
deployment_start_message += "#{api_gateways.length} API Gateways " unless api_gateways.empty?
puts deployment_start_message
total_time_start = Time.now
services_time_start = total_time_start
dynamo_tables.each { |table| table.delete(@dynamo_client, @region) }
services_time_end = Time.now
unless dynamo_tables.empty?
puts "Deleting #{dynamo_tables.length} Table(s) took: \
#{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}"
end
services_time_start = Time.now
lambdas.each { |lambda| lambda.delete(@lambda_client, @region) }
services_time_end = Time.now
unless lambdas.empty?
puts "Deleting #{lambdas.length} Lambda(s) took: \
#{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}"
end
services_time_start = Time.now
api_gateways.each { |apig| apig.delete(@api_gateway_client, @region) }
services_time_end = Time.now
unless api_gateways.empty?
puts "Deleting #{api_gateways.length} API Gateway(s) took: \
#{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}"
end
total_time_end = Time.now
puts "Total API Deletion took: \
#{Time.at(total_time_end - total_time_start).utc.strftime('%H:%M:%S')}"
puts 'Successful Deletion of API'
true
end | ruby | def delete
if dynamo_tables.empty? && lambdas.empty? && api_gateways.empty?
puts 'Nothing to Deleting.'
return
end
deployment_start_message = 'Deleting '
deployment_start_message += "#{dynamo_tables.length} Dynamo Tables, " unless dynamo_tables.empty?
deployment_start_message += "#{lambdas.length} Lambdas, " unless lambdas.empty?
deployment_start_message += "#{api_gateways.length} API Gateways " unless api_gateways.empty?
puts deployment_start_message
total_time_start = Time.now
services_time_start = total_time_start
dynamo_tables.each { |table| table.delete(@dynamo_client, @region) }
services_time_end = Time.now
unless dynamo_tables.empty?
puts "Deleting #{dynamo_tables.length} Table(s) took: \
#{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}"
end
services_time_start = Time.now
lambdas.each { |lambda| lambda.delete(@lambda_client, @region) }
services_time_end = Time.now
unless lambdas.empty?
puts "Deleting #{lambdas.length} Lambda(s) took: \
#{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}"
end
services_time_start = Time.now
api_gateways.each { |apig| apig.delete(@api_gateway_client, @region) }
services_time_end = Time.now
unless api_gateways.empty?
puts "Deleting #{api_gateways.length} API Gateway(s) took: \
#{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}"
end
total_time_end = Time.now
puts "Total API Deletion took: \
#{Time.at(total_time_end - total_time_start).utc.strftime('%H:%M:%S')}"
puts 'Successful Deletion of API'
true
end | [
"def",
"delete",
"if",
"dynamo_tables",
".",
"empty?",
"&&",
"lambdas",
".",
"empty?",
"&&",
"api_gateways",
".",
"empty?",
"puts",
"'Nothing to Deleting.'",
"return",
"end",
"deployment_start_message",
"=",
"'Deleting '",
"deployment_start_message",
"+=",
"\"#{dynamo_tables.length} Dynamo Tables, \"",
"unless",
"dynamo_tables",
".",
"empty?",
"deployment_start_message",
"+=",
"\"#{lambdas.length} Lambdas, \"",
"unless",
"lambdas",
".",
"empty?",
"deployment_start_message",
"+=",
"\"#{api_gateways.length} API Gateways \"",
"unless",
"api_gateways",
".",
"empty?",
"puts",
"deployment_start_message",
"total_time_start",
"=",
"Time",
".",
"now",
"services_time_start",
"=",
"total_time_start",
"dynamo_tables",
".",
"each",
"{",
"|",
"table",
"|",
"table",
".",
"delete",
"(",
"@dynamo_client",
",",
"@region",
")",
"}",
"services_time_end",
"=",
"Time",
".",
"now",
"unless",
"dynamo_tables",
".",
"empty?",
"puts",
"\"Deleting #{dynamo_tables.length} Table(s) took: \\\n #{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}\"",
"end",
"services_time_start",
"=",
"Time",
".",
"now",
"lambdas",
".",
"each",
"{",
"|",
"lambda",
"|",
"lambda",
".",
"delete",
"(",
"@lambda_client",
",",
"@region",
")",
"}",
"services_time_end",
"=",
"Time",
".",
"now",
"unless",
"lambdas",
".",
"empty?",
"puts",
"\"Deleting #{lambdas.length} Lambda(s) took: \\\n #{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}\"",
"end",
"services_time_start",
"=",
"Time",
".",
"now",
"api_gateways",
".",
"each",
"{",
"|",
"apig",
"|",
"apig",
".",
"delete",
"(",
"@api_gateway_client",
",",
"@region",
")",
"}",
"services_time_end",
"=",
"Time",
".",
"now",
"unless",
"api_gateways",
".",
"empty?",
"puts",
"\"Deleting #{api_gateways.length} API Gateway(s) took: \\\n #{Time.at(services_time_end - services_time_start).utc.strftime('%H:%M:%S')}\"",
"end",
"total_time_end",
"=",
"Time",
".",
"now",
"puts",
"\"Total API Deletion took: \\\n #{Time.at(total_time_end - total_time_start).utc.strftime('%H:%M:%S')}\"",
"puts",
"'Successful Deletion of API'",
"true",
"end"
] | Deletes all services from the cloud. | [
"Deletes",
"all",
"services",
"from",
"the",
"cloud",
"."
] | 9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8 | https://github.com/Cimpress-MCP/LambdaWrap/blob/9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8/lib/lambda_wrap/api_manager.rb#L205-L253 |
2,157 | Cimpress-MCP/LambdaWrap | lib/lambda_wrap/lambda_manager.rb | LambdaWrap.Lambda.deploy | def deploy(environment_options, client, region = 'AWS_REGION')
super
puts "Deploying Lambda: #{@lambda_name} to Environment: #{environment_options.name}"
unless File.exist?(@path_to_zip_file)
raise ArgumentError, "Deployment Package Zip File does not exist: #{@path_to_zip_file}!"
end
lambda_details = retrieve_lambda_details
if lambda_details.nil?
function_version = create_lambda
else
update_lambda_config
function_version = update_lambda_code
end
create_alias(function_version, environment_options.name, environment_options.description)
cleanup_unused_versions if @delete_unreferenced_versions
puts "Lambda: #{@lambda_name} successfully deployed!"
true
end | ruby | def deploy(environment_options, client, region = 'AWS_REGION')
super
puts "Deploying Lambda: #{@lambda_name} to Environment: #{environment_options.name}"
unless File.exist?(@path_to_zip_file)
raise ArgumentError, "Deployment Package Zip File does not exist: #{@path_to_zip_file}!"
end
lambda_details = retrieve_lambda_details
if lambda_details.nil?
function_version = create_lambda
else
update_lambda_config
function_version = update_lambda_code
end
create_alias(function_version, environment_options.name, environment_options.description)
cleanup_unused_versions if @delete_unreferenced_versions
puts "Lambda: #{@lambda_name} successfully deployed!"
true
end | [
"def",
"deploy",
"(",
"environment_options",
",",
"client",
",",
"region",
"=",
"'AWS_REGION'",
")",
"super",
"puts",
"\"Deploying Lambda: #{@lambda_name} to Environment: #{environment_options.name}\"",
"unless",
"File",
".",
"exist?",
"(",
"@path_to_zip_file",
")",
"raise",
"ArgumentError",
",",
"\"Deployment Package Zip File does not exist: #{@path_to_zip_file}!\"",
"end",
"lambda_details",
"=",
"retrieve_lambda_details",
"if",
"lambda_details",
".",
"nil?",
"function_version",
"=",
"create_lambda",
"else",
"update_lambda_config",
"function_version",
"=",
"update_lambda_code",
"end",
"create_alias",
"(",
"function_version",
",",
"environment_options",
".",
"name",
",",
"environment_options",
".",
"description",
")",
"cleanup_unused_versions",
"if",
"@delete_unreferenced_versions",
"puts",
"\"Lambda: #{@lambda_name} successfully deployed!\"",
"true",
"end"
] | Initializes a Lambda Manager. Frontloaded configuration.
@param [Hash] options The Configuration for the Lambda
@option options [String] :lambda_name The name you want to assign to the function you are uploading. The function
names appear in the console and are returned in the ListFunctions API. Function names are used to specify
functions to other AWS Lambda API operations, such as Invoke. Note that the length constraint applies only to
the ARN. If you specify only the function name, it is limited to 64 characters in length.
@option options [String] :handler The function within your code that Lambda calls to begin execution.
@option options [String] :role_arn The Amazon Resource Name (ARN) of the IAM role that Lambda assumes when it
executes your function to access any other Amazon Web Services (AWS) resources.
@option options [String] :path_to_zip_file The absolute path to the Deployment Package zip file
@option options [String] :runtime The runtime environment for the Lambda function you are uploading.
@option options [String] :description ('Deployed with LambdaWrap') A short, user-defined function description.
Lambda does not use this value. Assign a meaningful description as you see fit.
@option options [Integer] :timeout (30) The function execution time at which Lambda should terminate the function.
@option options [Integer] :memory_size (128) The amount of memory, in MB, your Lambda function is given. Lambda
uses this memory size to infer the amount of CPU and memory allocated to your function. The value must be a
multiple of 64MB. Minimum: 128, Maximum: 3008.
@option options [Array<String>] :subnet_ids ([]) If your Lambda function accesses resources in a VPC, you provide
this parameter identifying the list of subnet IDs. These must belong to the same VPC. You must provide at least
one security group and one subnet ID to configure VPC access.
@option options [Array<String>] :security_group_ids ([]) If your Lambda function accesses resources in a VPC, you
provide this parameter identifying the list of security group IDs. These must belong to the same VPC. You must
provide at least one security group and one subnet ID.
@option options [Boolean] :delete_unreferenced_versions (true) Option to delete any Lambda Function Versions upon
deployment that do not have an alias pointing to them.
@option options [String] :dead_letter_queue_arn ('') The ARN of the SQS Queue for failed async invocations.
Deploys the Lambda to the specified Environment. Creates a Lambda Function if one didn't exist.
Updates the Lambda's configuration, Updates the Lambda's Code, publishes a new version, and creates
an alias that points to the newly published version. If the @delete_unreferenced_versions option
is enabled, all Lambda Function versions that don't have an alias pointing to them will be deleted.
@param environment_options [LambdaWrap::Environment] The target Environment to deploy
@param client [Aws::Lambda::Client] Client to use with SDK. Should be passed in by the API class.
@param region [String] AWS Region string. Should be passed in by the API class. | [
"Initializes",
"a",
"Lambda",
"Manager",
".",
"Frontloaded",
"configuration",
"."
] | 9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8 | https://github.com/Cimpress-MCP/LambdaWrap/blob/9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8/lib/lambda_wrap/lambda_manager.rb#L104-L128 |
2,158 | Cimpress-MCP/LambdaWrap | lib/lambda_wrap/lambda_manager.rb | LambdaWrap.Lambda.delete | def delete(client, region = 'AWS_REGION')
super
puts "Deleting all versions and aliases for Lambda: #{@lambda_name}"
lambda_details = retrieve_lambda_details
if lambda_details.nil?
puts 'No Lambda to delete.'
else
options = { function_name: @lambda_name }
@client.delete_function(options)
puts "Lambda #{@lambda_name} and all Versions & Aliases have been deleted."
end
true
end | ruby | def delete(client, region = 'AWS_REGION')
super
puts "Deleting all versions and aliases for Lambda: #{@lambda_name}"
lambda_details = retrieve_lambda_details
if lambda_details.nil?
puts 'No Lambda to delete.'
else
options = { function_name: @lambda_name }
@client.delete_function(options)
puts "Lambda #{@lambda_name} and all Versions & Aliases have been deleted."
end
true
end | [
"def",
"delete",
"(",
"client",
",",
"region",
"=",
"'AWS_REGION'",
")",
"super",
"puts",
"\"Deleting all versions and aliases for Lambda: #{@lambda_name}\"",
"lambda_details",
"=",
"retrieve_lambda_details",
"if",
"lambda_details",
".",
"nil?",
"puts",
"'No Lambda to delete.'",
"else",
"options",
"=",
"{",
"function_name",
":",
"@lambda_name",
"}",
"@client",
".",
"delete_function",
"(",
"options",
")",
"puts",
"\"Lambda #{@lambda_name} and all Versions & Aliases have been deleted.\"",
"end",
"true",
"end"
] | Deletes the Lambda Object with associated versions, code, configuration, and aliases.
@param client [Aws::Lambda::Client] Client to use with SDK. Should be passed in by the API class.
@param region [String] AWS Region string. Should be passed in by the API class. | [
"Deletes",
"the",
"Lambda",
"Object",
"with",
"associated",
"versions",
"code",
"configuration",
"and",
"aliases",
"."
] | 9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8 | https://github.com/Cimpress-MCP/LambdaWrap/blob/9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8/lib/lambda_wrap/lambda_manager.rb#L147-L159 |
2,159 | Cimpress-MCP/LambdaWrap | lib/lambda_wrap/api_gateway_manager.rb | LambdaWrap.ApiGateway.teardown | def teardown(environment_options, client, region = 'AWS_REGION')
super
api_id = get_id_for_api(@api_name)
if api_id
delete_stage(api_id, environment_options.name)
else
puts "API Gateway Object #{@api_name} not found. No environment to tear down."
end
true
end | ruby | def teardown(environment_options, client, region = 'AWS_REGION')
super
api_id = get_id_for_api(@api_name)
if api_id
delete_stage(api_id, environment_options.name)
else
puts "API Gateway Object #{@api_name} not found. No environment to tear down."
end
true
end | [
"def",
"teardown",
"(",
"environment_options",
",",
"client",
",",
"region",
"=",
"'AWS_REGION'",
")",
"super",
"api_id",
"=",
"get_id_for_api",
"(",
"@api_name",
")",
"if",
"api_id",
"delete_stage",
"(",
"api_id",
",",
"environment_options",
".",
"name",
")",
"else",
"puts",
"\"API Gateway Object #{@api_name} not found. No environment to tear down.\"",
"end",
"true",
"end"
] | Tearsdown environment for API Gateway. Deletes stage.
@param environment_options [LambdaWrap::Environment] The environment to teardown.
@param client [Aws::APIGateway::Client] Client to use with SDK. Should be passed in by the API class.
@param region [String] AWS Region string. Should be passed in by the API class. | [
"Tearsdown",
"environment",
"for",
"API",
"Gateway",
".",
"Deletes",
"stage",
"."
] | 9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8 | https://github.com/Cimpress-MCP/LambdaWrap/blob/9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8/lib/lambda_wrap/api_gateway_manager.rb#L77-L86 |
2,160 | Cimpress-MCP/LambdaWrap | lib/lambda_wrap/api_gateway_manager.rb | LambdaWrap.ApiGateway.delete | def delete(client, region = 'AWS_REGION')
super
api_id = get_id_for_api(@api_name)
if api_id
options = {
rest_api_id: api_id
}
@client.delete_rest_api(options)
puts "Deleted API: #{@api_name} ID:#{api_id}"
else
puts "API Gateway Object #{@api_name} not found. Nothing to delete."
end
true
end | ruby | def delete(client, region = 'AWS_REGION')
super
api_id = get_id_for_api(@api_name)
if api_id
options = {
rest_api_id: api_id
}
@client.delete_rest_api(options)
puts "Deleted API: #{@api_name} ID:#{api_id}"
else
puts "API Gateway Object #{@api_name} not found. Nothing to delete."
end
true
end | [
"def",
"delete",
"(",
"client",
",",
"region",
"=",
"'AWS_REGION'",
")",
"super",
"api_id",
"=",
"get_id_for_api",
"(",
"@api_name",
")",
"if",
"api_id",
"options",
"=",
"{",
"rest_api_id",
":",
"api_id",
"}",
"@client",
".",
"delete_rest_api",
"(",
"options",
")",
"puts",
"\"Deleted API: #{@api_name} ID:#{api_id}\"",
"else",
"puts",
"\"API Gateway Object #{@api_name} not found. Nothing to delete.\"",
"end",
"true",
"end"
] | Deletes all stages and API Gateway object.
@param client [Aws::APIGateway::Client] Client to use with SDK. Should be passed in by the API class.
@param region [String] AWS Region string. Should be passed in by the API class. | [
"Deletes",
"all",
"stages",
"and",
"API",
"Gateway",
"object",
"."
] | 9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8 | https://github.com/Cimpress-MCP/LambdaWrap/blob/9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8/lib/lambda_wrap/api_gateway_manager.rb#L91-L104 |
2,161 | Cimpress-MCP/LambdaWrap | lib/lambda_wrap/dynamo_db_manager.rb | LambdaWrap.DynamoTable.deploy | def deploy(environment_options, client, region = 'AWS_REGION')
super
puts "Deploying Table: #{@table_name} to Environment: #{environment_options.name}"
full_table_name = @table_name + (@append_environment_on_deploy ? "-#{environment_options.name}" : '')
table_details = retrieve_table_details(full_table_name)
if table_details.nil?
create_table(full_table_name)
else
wait_until_table_is_available(full_table_name) if table_details[:table_status] != 'ACTIVE'
update_table(full_table_name, table_details)
end
puts "Dynamo Table #{full_table_name} is now available."
full_table_name
end | ruby | def deploy(environment_options, client, region = 'AWS_REGION')
super
puts "Deploying Table: #{@table_name} to Environment: #{environment_options.name}"
full_table_name = @table_name + (@append_environment_on_deploy ? "-#{environment_options.name}" : '')
table_details = retrieve_table_details(full_table_name)
if table_details.nil?
create_table(full_table_name)
else
wait_until_table_is_available(full_table_name) if table_details[:table_status] != 'ACTIVE'
update_table(full_table_name, table_details)
end
puts "Dynamo Table #{full_table_name} is now available."
full_table_name
end | [
"def",
"deploy",
"(",
"environment_options",
",",
"client",
",",
"region",
"=",
"'AWS_REGION'",
")",
"super",
"puts",
"\"Deploying Table: #{@table_name} to Environment: #{environment_options.name}\"",
"full_table_name",
"=",
"@table_name",
"+",
"(",
"@append_environment_on_deploy",
"?",
"\"-#{environment_options.name}\"",
":",
"''",
")",
"table_details",
"=",
"retrieve_table_details",
"(",
"full_table_name",
")",
"if",
"table_details",
".",
"nil?",
"create_table",
"(",
"full_table_name",
")",
"else",
"wait_until_table_is_available",
"(",
"full_table_name",
")",
"if",
"table_details",
"[",
":table_status",
"]",
"!=",
"'ACTIVE'",
"update_table",
"(",
"full_table_name",
",",
"table_details",
")",
"end",
"puts",
"\"Dynamo Table #{full_table_name} is now available.\"",
"full_table_name",
"end"
] | Sets up the DynamoTable for the Dynamo DB Manager. Preloading the configuration in the constructor.
@param [Hash] options The configuration for the DynamoDB Table.
@option options [String] :table_name The name of the DynamoDB Table. A "Base Name" can be used here where the
environment name can be appended upon deployment.
@option options [Array<Hash>] :attribute_definitions ([{ attribute_name: 'Id', attribute_type: 'S' }]) An array of
attributes that describe the key schema for the table and indexes. The Hash must have symbols: :attribute_name &
:attribute_type. Please see AWS Documentation for the {http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html
Data Model}.
@option options [Array<Hash>] :key_schema ([{ attribute_name: 'Id', key_type: 'HASH' }]) Specifies the attributes
that make up the primary key for a table or an index. The attributes in key_schema must also be defined in the
AttributeDefinitions array. Please see AWS Documentation for the {http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html
Data Model}.
Each element in the array must be composed of:
* <tt>:attribute_name</tt> - The name of this key attribute.
* <tt>:key_type</tt> - The role that the key attribute will assume:
* <tt>HASH</tt> - partition key
* <tt>RANGE</tt> - sort key
The partition key of an item is also known as its hash attribute. The term "hash attribute" derives from
DynamoDB's usage of an internal hash function to evenly distribute data items across partitions, based on their
partition key values.
The sort key of an item is also known as its range attribute. The term "range attribute" derives from the way
DynamoDB stores items with the same partition key physically close together, in sorted order by the sort key
value.
For a simple primary key (partition key), you must provide exactly one element with a <tt>KeyType</tt> of
<tt>HASH</tt>.
For a composite primary key (partition key and sort key), you must provide exactly two elements, in this order:
The first element must have a <tt>KeyType</tt> of <tt>HASH</tt>, and the second element must have a
<tt>KeyType</tt> of <tt>RANGE</tt>.
For more information, see {http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.html#WorkingWithTables.primary.key
Specifying the Primary Key} in the <em>Amazon DynamoDB Developer Guide</em>.
@option options [Integer] :read_capacity_units (1) The maximum number of strongly consistent reads consumed per
second before DynamoDB returns a <tt>ThrottlingException</tt>. Must be at least 1. For current minimum and
maximum provisioned throughput values, see {http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html
Limits} in the <em>Amazon DynamoDB Developer Guide</em>.
@option options [Integer] :write_capacity_units (1) The maximum number of writes consumed per second before
DynamoDB returns a <tt>ThrottlingException</tt>. Must be at least 1. For current minimum and maximum
provisioned throughput values, see {http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html
Limits} in the <em>Amazon DynamoDB Developer Guide</em>.
@option options [Array<Hash>] :local_secondary_indexes ([]) One or more local secondary indexes (the maximum is
five) to be created on the table. Each index is scoped to a given partition key value. There is a 10 GB size
limit per partition key value; otherwise, the size of a local secondary index is unconstrained.
Each element in the array must be a Hash with these symbols:
* <tt>:index_name</tt> - The name of the local secondary index. Must be unique only for this table.
* <tt>:key_schema</tt> - Specifies the key schema for the local secondary index. The key schema must begin with
the same partition key as the table.
* <tt>:projection</tt> - Specifies attributes that are copied (projected) from the table into the index. These
are in addition to the primary key attributes and index key attributes, which are automatically projected. Each
attribute specification is composed of:
* <tt>:projection_type</tt> - One of the following:
* <tt>KEYS_ONLY</tt> - Only the index and primary keys are projected into the index.
* <tt>INCLUDE</tt> - Only the specified table attributes are projected into the index. The list of projected
attributes are in <tt>non_key_attributes</tt>.
* <tt>ALL</tt> - All of the table attributes are projected into the index.
* <tt>:non_key_attributes</tt> - A list of one or more non-key attribute names that are projected into the
secondary index. The total count of attributes provided in NonKeyAttributes, summed across all of the
secondary indexes, must not exceed 20. If you project the same attribute into two different indexes, this
counts as two distinct attributes when determining the total.
@option options [Array<Hash>] :global_secondary_indexes ([]) One or more global secondary indexes (the maximum is
five) to be created on the table. Each global secondary index (Hash) in the array includes the following:
* <tt>:index_name</tt> - The name of the global secondary index. Must be unique only for this table.
* <tt>:key_schema</tt> - Specifies the key schema for the global secondary index.
* <tt>:projection</tt> - Specifies attributes that are copied (projected) from the table into the index. These
are in addition to the primary key attributes and index key attributes, which are automatically projected. Each
attribute specification is composed of:
* <tt>:projection_type</tt> - One of the following:
* <tt>KEYS_ONLY</tt> - Only the index and primary keys are projected into the index.
* <tt>INCLUDE</tt> - Only the specified table attributes are projected into the index. The list of projected
attributes are in <tt>NonKeyAttributes</tt>.
* <tt>ALL</tt> - All of the table attributes are projected into the index.
* <tt>non_key_attributes</tt> - A list of one or more non-key attribute names that are projected into the
secondary index. The total count of attributes provided in NonKeyAttributes, summed across all of the
secondary indexes, must not exceed 20. If you project the same attribute into two different indexes, this
counts as two distinct attributes when determining the total.
* <tt>:provisioned_throughput</tt> - The provisioned throughput settings for the global secondary index,
consisting of read and write capacity units.
@option options [Boolean] :append_environment_on_deploy (false) Option to append the name of the environment to
the table name upon deployment and teardown. DynamoDB Tables cannot shard data in a similar manner as how Lambda
aliases and API Gateway Environments work. This option is supposed to help the user with naming tables instead
of managing the environment names on their own.
Deploys the DynamoDB Table to the target environment. If the @append_environment_on_deploy option is set, the
table_name will be appended with a hyphen and the environment name. This will attempt to Create or Update with
the parameters specified from the constructor. This may take a LONG time for it will wait for any new indexes to
be available.
@param environment_options [LambdaWrap::Environment] Target environment to deploy.
@param client [Aws::DynamoDB::Client] Client to use with SDK. Should be passed in by the API class.
@param region [String] AWS Region string. Should be passed in by the API class. | [
"Sets",
"up",
"the",
"DynamoTable",
"for",
"the",
"Dynamo",
"DB",
"Manager",
".",
"Preloading",
"the",
"configuration",
"in",
"the",
"constructor",
"."
] | 9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8 | https://github.com/Cimpress-MCP/LambdaWrap/blob/9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8/lib/lambda_wrap/dynamo_db_manager.rb#L158-L176 |
2,162 | Cimpress-MCP/LambdaWrap | lib/lambda_wrap/dynamo_db_manager.rb | LambdaWrap.DynamoTable.wait_until_table_is_available | def wait_until_table_is_available(full_table_name, delay = 5, max_attempts = 5)
puts "Waiting for Table #{full_table_name} to be available."
puts "Waiting with a #{delay} second delay between attempts, for a maximum of #{max_attempts} attempts."
max_time = Time.at(delay * max_attempts).utc.strftime('%H:%M:%S')
puts "Max waiting time will be: #{max_time} (approximate)."
# wait until the table has updated to being fully available
# waiting for ~2min at most; an error will be thrown afterwards
started_waiting_at = Time.now
max_attempts.times do |attempt|
puts "Attempt #{attempt + 1}/#{max_attempts}, \
#{Time.at(Time.now - started_waiting_at).utc.strftime('%H:%M:%S')}/#{max_time}"
details = retrieve_table_details(full_table_name)
if details.table_status != 'ACTIVE'
puts "Table: #{full_table_name} is not yet available. Status: #{details.table_status}. Retrying..."
else
updating_indexes = details.global_secondary_indexes.reject do |global_index|
global_index.index_status == 'ACTIVE'
end
return true if updating_indexes.empty?
puts 'Table is available, but the global indexes are not:'
puts(updating_indexes.map { |global_index| "#{global_index.index_name}, #{global_index.index_status}" })
end
Kernel.sleep(delay.seconds)
end
raise Exception, "Table #{full_table_name} did not become available after #{max_attempts} attempts. " \
'Try again later or inspect the AWS console.'
end | ruby | def wait_until_table_is_available(full_table_name, delay = 5, max_attempts = 5)
puts "Waiting for Table #{full_table_name} to be available."
puts "Waiting with a #{delay} second delay between attempts, for a maximum of #{max_attempts} attempts."
max_time = Time.at(delay * max_attempts).utc.strftime('%H:%M:%S')
puts "Max waiting time will be: #{max_time} (approximate)."
# wait until the table has updated to being fully available
# waiting for ~2min at most; an error will be thrown afterwards
started_waiting_at = Time.now
max_attempts.times do |attempt|
puts "Attempt #{attempt + 1}/#{max_attempts}, \
#{Time.at(Time.now - started_waiting_at).utc.strftime('%H:%M:%S')}/#{max_time}"
details = retrieve_table_details(full_table_name)
if details.table_status != 'ACTIVE'
puts "Table: #{full_table_name} is not yet available. Status: #{details.table_status}. Retrying..."
else
updating_indexes = details.global_secondary_indexes.reject do |global_index|
global_index.index_status == 'ACTIVE'
end
return true if updating_indexes.empty?
puts 'Table is available, but the global indexes are not:'
puts(updating_indexes.map { |global_index| "#{global_index.index_name}, #{global_index.index_status}" })
end
Kernel.sleep(delay.seconds)
end
raise Exception, "Table #{full_table_name} did not become available after #{max_attempts} attempts. " \
'Try again later or inspect the AWS console.'
end | [
"def",
"wait_until_table_is_available",
"(",
"full_table_name",
",",
"delay",
"=",
"5",
",",
"max_attempts",
"=",
"5",
")",
"puts",
"\"Waiting for Table #{full_table_name} to be available.\"",
"puts",
"\"Waiting with a #{delay} second delay between attempts, for a maximum of #{max_attempts} attempts.\"",
"max_time",
"=",
"Time",
".",
"at",
"(",
"delay",
"*",
"max_attempts",
")",
".",
"utc",
".",
"strftime",
"(",
"'%H:%M:%S'",
")",
"puts",
"\"Max waiting time will be: #{max_time} (approximate).\"",
"# wait until the table has updated to being fully available",
"# waiting for ~2min at most; an error will be thrown afterwards",
"started_waiting_at",
"=",
"Time",
".",
"now",
"max_attempts",
".",
"times",
"do",
"|",
"attempt",
"|",
"puts",
"\"Attempt #{attempt + 1}/#{max_attempts}, \\\n #{Time.at(Time.now - started_waiting_at).utc.strftime('%H:%M:%S')}/#{max_time}\"",
"details",
"=",
"retrieve_table_details",
"(",
"full_table_name",
")",
"if",
"details",
".",
"table_status",
"!=",
"'ACTIVE'",
"puts",
"\"Table: #{full_table_name} is not yet available. Status: #{details.table_status}. Retrying...\"",
"else",
"updating_indexes",
"=",
"details",
".",
"global_secondary_indexes",
".",
"reject",
"do",
"|",
"global_index",
"|",
"global_index",
".",
"index_status",
"==",
"'ACTIVE'",
"end",
"return",
"true",
"if",
"updating_indexes",
".",
"empty?",
"puts",
"'Table is available, but the global indexes are not:'",
"puts",
"(",
"updating_indexes",
".",
"map",
"{",
"|",
"global_index",
"|",
"\"#{global_index.index_name}, #{global_index.index_status}\"",
"}",
")",
"end",
"Kernel",
".",
"sleep",
"(",
"delay",
".",
"seconds",
")",
"end",
"raise",
"Exception",
",",
"\"Table #{full_table_name} did not become available after #{max_attempts} attempts. \"",
"'Try again later or inspect the AWS console.'",
"end"
] | Waits for the table to be available | [
"Waits",
"for",
"the",
"table",
"to",
"be",
"available"
] | 9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8 | https://github.com/Cimpress-MCP/LambdaWrap/blob/9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8/lib/lambda_wrap/dynamo_db_manager.rb#L228-L258 |
2,163 | Cimpress-MCP/LambdaWrap | lib/lambda_wrap/dynamo_db_manager.rb | LambdaWrap.DynamoTable.build_global_index_updates_array | def build_global_index_updates_array(current_global_indexes)
indexes_to_update = []
return indexes_to_update if current_global_indexes.empty?
current_global_indexes.each do |current_index|
@global_secondary_indexes.each do |target_index|
# Find the same named index
next unless target_index[:index_name] == current_index[:index_name]
# Skip unless a different ProvisionedThroughput is specified
break unless (target_index[:provisioned_throughput][:read_capacity_units] !=
current_index.provisioned_throughput.read_capacity_units) ||
(target_index[:provisioned_throughput][:write_capacity_units] !=
current_index.provisioned_throughput.write_capacity_units)
indexes_to_update << { index_name: target_index[:index_name],
provisioned_throughput: target_index[:provisioned_throughput] }
end
end
puts indexes_to_update
indexes_to_update
end | ruby | def build_global_index_updates_array(current_global_indexes)
indexes_to_update = []
return indexes_to_update if current_global_indexes.empty?
current_global_indexes.each do |current_index|
@global_secondary_indexes.each do |target_index|
# Find the same named index
next unless target_index[:index_name] == current_index[:index_name]
# Skip unless a different ProvisionedThroughput is specified
break unless (target_index[:provisioned_throughput][:read_capacity_units] !=
current_index.provisioned_throughput.read_capacity_units) ||
(target_index[:provisioned_throughput][:write_capacity_units] !=
current_index.provisioned_throughput.write_capacity_units)
indexes_to_update << { index_name: target_index[:index_name],
provisioned_throughput: target_index[:provisioned_throughput] }
end
end
puts indexes_to_update
indexes_to_update
end | [
"def",
"build_global_index_updates_array",
"(",
"current_global_indexes",
")",
"indexes_to_update",
"=",
"[",
"]",
"return",
"indexes_to_update",
"if",
"current_global_indexes",
".",
"empty?",
"current_global_indexes",
".",
"each",
"do",
"|",
"current_index",
"|",
"@global_secondary_indexes",
".",
"each",
"do",
"|",
"target_index",
"|",
"# Find the same named index",
"next",
"unless",
"target_index",
"[",
":index_name",
"]",
"==",
"current_index",
"[",
":index_name",
"]",
"# Skip unless a different ProvisionedThroughput is specified",
"break",
"unless",
"(",
"target_index",
"[",
":provisioned_throughput",
"]",
"[",
":read_capacity_units",
"]",
"!=",
"current_index",
".",
"provisioned_throughput",
".",
"read_capacity_units",
")",
"||",
"(",
"target_index",
"[",
":provisioned_throughput",
"]",
"[",
":write_capacity_units",
"]",
"!=",
"current_index",
".",
"provisioned_throughput",
".",
"write_capacity_units",
")",
"indexes_to_update",
"<<",
"{",
"index_name",
":",
"target_index",
"[",
":index_name",
"]",
",",
"provisioned_throughput",
":",
"target_index",
"[",
":provisioned_throughput",
"]",
"}",
"end",
"end",
"puts",
"indexes_to_update",
"indexes_to_update",
"end"
] | Looks through the list current of Global Secondary Indexes and builds an array if the Provisioned Throughput
in the intended Indexes are higher than the current Indexes. | [
"Looks",
"through",
"the",
"list",
"current",
"of",
"Global",
"Secondary",
"Indexes",
"and",
"builds",
"an",
"array",
"if",
"the",
"Provisioned",
"Throughput",
"in",
"the",
"intended",
"Indexes",
"are",
"higher",
"than",
"the",
"current",
"Indexes",
"."
] | 9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8 | https://github.com/Cimpress-MCP/LambdaWrap/blob/9c34b4ea49c86aaf9b5c998b12a61ceb065cedd8/lib/lambda_wrap/dynamo_db_manager.rb#L341-L359 |
2,164 | greyblake/telebot | lib/telebot/objects/user_profile_photos.rb | Telebot.UserProfilePhotos.photos= | def photos=(values)
@photos = values.map do |photo|
photo.map do |photo_size_attrs|
PhotoSize.new(photo_size_attrs)
end
end
end | ruby | def photos=(values)
@photos = values.map do |photo|
photo.map do |photo_size_attrs|
PhotoSize.new(photo_size_attrs)
end
end
end | [
"def",
"photos",
"=",
"(",
"values",
")",
"@photos",
"=",
"values",
".",
"map",
"do",
"|",
"photo",
"|",
"photo",
".",
"map",
"do",
"|",
"photo_size_attrs",
"|",
"PhotoSize",
".",
"new",
"(",
"photo_size_attrs",
")",
"end",
"end",
"end"
] | Assign Array of Array of PhotoSize
@param values [Array<Array<PhotoSize>>] | [
"Assign",
"Array",
"of",
"Array",
"of",
"PhotoSize"
] | 16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a | https://github.com/greyblake/telebot/blob/16c3f73ce47c2dc2480c23b3ef2cc8ee1f9cae4a/lib/telebot/objects/user_profile_photos.rb#L15-L21 |
2,165 | square/border_patrol | lib/border_patrol/polygon.rb | BorderPatrol.Polygon.contains_point? | def contains_point?(point)
return false unless inside_bounding_box?(point)
c = false
i = -1
j = size - 1
while (i += 1) < size
if (self[i].y <= point.y && point.y < self[j].y) ||
(self[j].y <= point.y && point.y < self[i].y)
if point.x < (self[j].x - self[i].x) * (point.y - self[i].y) / (self[j].y - self[i].y) + self[i].x
c = !c
end
end
j = i
end
c
end | ruby | def contains_point?(point)
return false unless inside_bounding_box?(point)
c = false
i = -1
j = size - 1
while (i += 1) < size
if (self[i].y <= point.y && point.y < self[j].y) ||
(self[j].y <= point.y && point.y < self[i].y)
if point.x < (self[j].x - self[i].x) * (point.y - self[i].y) / (self[j].y - self[i].y) + self[i].x
c = !c
end
end
j = i
end
c
end | [
"def",
"contains_point?",
"(",
"point",
")",
"return",
"false",
"unless",
"inside_bounding_box?",
"(",
"point",
")",
"c",
"=",
"false",
"i",
"=",
"-",
"1",
"j",
"=",
"size",
"-",
"1",
"while",
"(",
"i",
"+=",
"1",
")",
"<",
"size",
"if",
"(",
"self",
"[",
"i",
"]",
".",
"y",
"<=",
"point",
".",
"y",
"&&",
"point",
".",
"y",
"<",
"self",
"[",
"j",
"]",
".",
"y",
")",
"||",
"(",
"self",
"[",
"j",
"]",
".",
"y",
"<=",
"point",
".",
"y",
"&&",
"point",
".",
"y",
"<",
"self",
"[",
"i",
"]",
".",
"y",
")",
"if",
"point",
".",
"x",
"<",
"(",
"self",
"[",
"j",
"]",
".",
"x",
"-",
"self",
"[",
"i",
"]",
".",
"x",
")",
"*",
"(",
"point",
".",
"y",
"-",
"self",
"[",
"i",
"]",
".",
"y",
")",
"/",
"(",
"self",
"[",
"j",
"]",
".",
"y",
"-",
"self",
"[",
"i",
"]",
".",
"y",
")",
"+",
"self",
"[",
"i",
"]",
".",
"x",
"c",
"=",
"!",
"c",
"end",
"end",
"j",
"=",
"i",
"end",
"c",
"end"
] | Quick and dirty hash function | [
"Quick",
"and",
"dirty",
"hash",
"function"
] | 72c50ea17c89f7fa89fbaed25ad3db3fa1d8eeb1 | https://github.com/square/border_patrol/blob/72c50ea17c89f7fa89fbaed25ad3db3fa1d8eeb1/lib/border_patrol/polygon.rb#L43-L58 |
2,166 | haw-itn/openassets-ruby | lib/openassets/api.rb | OpenAssets.Api.list_unspent | def list_unspent(oa_address_list = [])
btc_address_list = oa_address_list.map { |oa_address| oa_address_to_address(oa_address)}
outputs = get_unspent_outputs(btc_address_list)
result = outputs.map{|out| out.to_hash}
result
end | ruby | def list_unspent(oa_address_list = [])
btc_address_list = oa_address_list.map { |oa_address| oa_address_to_address(oa_address)}
outputs = get_unspent_outputs(btc_address_list)
result = outputs.map{|out| out.to_hash}
result
end | [
"def",
"list_unspent",
"(",
"oa_address_list",
"=",
"[",
"]",
")",
"btc_address_list",
"=",
"oa_address_list",
".",
"map",
"{",
"|",
"oa_address",
"|",
"oa_address_to_address",
"(",
"oa_address",
")",
"}",
"outputs",
"=",
"get_unspent_outputs",
"(",
"btc_address_list",
")",
"result",
"=",
"outputs",
".",
"map",
"{",
"|",
"out",
"|",
"out",
".",
"to_hash",
"}",
"result",
"end"
] | get UTXO for colored coins.
@param [Array] oa_address_list Obtain the balance of this open assets address only, or all addresses if unspecified.
@return [Array] Return array of the unspent information Hash. | [
"get",
"UTXO",
"for",
"colored",
"coins",
"."
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/api.rb#L48-L53 |
2,167 | haw-itn/openassets-ruby | lib/openassets/api.rb | OpenAssets.Api.get_balance | def get_balance(address = nil)
outputs = get_unspent_outputs(address.nil? ? [] : [oa_address_to_address(address)])
colored_outputs = outputs.map{|o|o.output}
sorted_outputs = colored_outputs.sort_by { |o|o.script.to_string}
groups = sorted_outputs.group_by{|o| o.script.to_string}
result = groups.map{|k, v|
btc_address = script_to_address(v[0].script)
sorted_script_outputs = v.sort_by{|o|o.asset_id unless o.asset_id}
group_assets = sorted_script_outputs.group_by{|o|o.asset_id}.select{|k,v| !k.nil?}
assets = group_assets.map{|asset_id, outputs|
{
'asset_id' => asset_id,
'quantity' => outputs.inject(0) { |sum, o| sum + o.asset_quantity }.to_s,
'amount' => outputs.inject(0) { |sum, o| sum + o.asset_amount }.to_s,
'asset_definition_url' => outputs[0].asset_definition_url,
'proof_of_authenticity' => outputs[0].proof_of_authenticity
}
}
{
'address' => btc_address,
'oa_address' => (btc_address.nil? || btc_address.is_a?(Array)) ? nil : address_to_oa_address(btc_address),
'value' => satoshi_to_coin(v.inject(0) { |sum, o|sum + o.value}),
'assets' => assets,
'account' => v[0].account
}
}
address.nil? ? result : result.select{|r|r['oa_address'] == address}
end | ruby | def get_balance(address = nil)
outputs = get_unspent_outputs(address.nil? ? [] : [oa_address_to_address(address)])
colored_outputs = outputs.map{|o|o.output}
sorted_outputs = colored_outputs.sort_by { |o|o.script.to_string}
groups = sorted_outputs.group_by{|o| o.script.to_string}
result = groups.map{|k, v|
btc_address = script_to_address(v[0].script)
sorted_script_outputs = v.sort_by{|o|o.asset_id unless o.asset_id}
group_assets = sorted_script_outputs.group_by{|o|o.asset_id}.select{|k,v| !k.nil?}
assets = group_assets.map{|asset_id, outputs|
{
'asset_id' => asset_id,
'quantity' => outputs.inject(0) { |sum, o| sum + o.asset_quantity }.to_s,
'amount' => outputs.inject(0) { |sum, o| sum + o.asset_amount }.to_s,
'asset_definition_url' => outputs[0].asset_definition_url,
'proof_of_authenticity' => outputs[0].proof_of_authenticity
}
}
{
'address' => btc_address,
'oa_address' => (btc_address.nil? || btc_address.is_a?(Array)) ? nil : address_to_oa_address(btc_address),
'value' => satoshi_to_coin(v.inject(0) { |sum, o|sum + o.value}),
'assets' => assets,
'account' => v[0].account
}
}
address.nil? ? result : result.select{|r|r['oa_address'] == address}
end | [
"def",
"get_balance",
"(",
"address",
"=",
"nil",
")",
"outputs",
"=",
"get_unspent_outputs",
"(",
"address",
".",
"nil?",
"?",
"[",
"]",
":",
"[",
"oa_address_to_address",
"(",
"address",
")",
"]",
")",
"colored_outputs",
"=",
"outputs",
".",
"map",
"{",
"|",
"o",
"|",
"o",
".",
"output",
"}",
"sorted_outputs",
"=",
"colored_outputs",
".",
"sort_by",
"{",
"|",
"o",
"|",
"o",
".",
"script",
".",
"to_string",
"}",
"groups",
"=",
"sorted_outputs",
".",
"group_by",
"{",
"|",
"o",
"|",
"o",
".",
"script",
".",
"to_string",
"}",
"result",
"=",
"groups",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"btc_address",
"=",
"script_to_address",
"(",
"v",
"[",
"0",
"]",
".",
"script",
")",
"sorted_script_outputs",
"=",
"v",
".",
"sort_by",
"{",
"|",
"o",
"|",
"o",
".",
"asset_id",
"unless",
"o",
".",
"asset_id",
"}",
"group_assets",
"=",
"sorted_script_outputs",
".",
"group_by",
"{",
"|",
"o",
"|",
"o",
".",
"asset_id",
"}",
".",
"select",
"{",
"|",
"k",
",",
"v",
"|",
"!",
"k",
".",
"nil?",
"}",
"assets",
"=",
"group_assets",
".",
"map",
"{",
"|",
"asset_id",
",",
"outputs",
"|",
"{",
"'asset_id'",
"=>",
"asset_id",
",",
"'quantity'",
"=>",
"outputs",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"sum",
",",
"o",
"|",
"sum",
"+",
"o",
".",
"asset_quantity",
"}",
".",
"to_s",
",",
"'amount'",
"=>",
"outputs",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"sum",
",",
"o",
"|",
"sum",
"+",
"o",
".",
"asset_amount",
"}",
".",
"to_s",
",",
"'asset_definition_url'",
"=>",
"outputs",
"[",
"0",
"]",
".",
"asset_definition_url",
",",
"'proof_of_authenticity'",
"=>",
"outputs",
"[",
"0",
"]",
".",
"proof_of_authenticity",
"}",
"}",
"{",
"'address'",
"=>",
"btc_address",
",",
"'oa_address'",
"=>",
"(",
"btc_address",
".",
"nil?",
"||",
"btc_address",
".",
"is_a?",
"(",
"Array",
")",
")",
"?",
"nil",
":",
"address_to_oa_address",
"(",
"btc_address",
")",
",",
"'value'",
"=>",
"satoshi_to_coin",
"(",
"v",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"sum",
",",
"o",
"|",
"sum",
"+",
"o",
".",
"value",
"}",
")",
",",
"'assets'",
"=>",
"assets",
",",
"'account'",
"=>",
"v",
"[",
"0",
"]",
".",
"account",
"}",
"}",
"address",
".",
"nil?",
"?",
"result",
":",
"result",
".",
"select",
"{",
"|",
"r",
"|",
"r",
"[",
"'oa_address'",
"]",
"==",
"address",
"}",
"end"
] | Returns the balance in both bitcoin and colored coin assets for all of the addresses available in your Bitcoin Core wallet.
@param [String] address The open assets address. if unspecified nil. | [
"Returns",
"the",
"balance",
"in",
"both",
"bitcoin",
"and",
"colored",
"coin",
"assets",
"for",
"all",
"of",
"the",
"addresses",
"available",
"in",
"your",
"Bitcoin",
"Core",
"wallet",
"."
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/api.rb#L57-L84 |
2,168 | haw-itn/openassets-ruby | lib/openassets/api.rb | OpenAssets.Api.issue_asset | def issue_asset(from, amount, metadata = nil, to = nil, fees = nil, mode = 'broadcast', output_qty = 1)
to = from if to.nil?
colored_outputs = get_unspent_outputs([oa_address_to_address(from)])
issue_param = OpenAssets::Transaction::TransferParameters.new(colored_outputs, to, from, amount, output_qty)
tx = create_tx_builder.issue_asset(issue_param, metadata, fees.nil? ? @config[:default_fees]: fees)
tx = process_transaction(tx, mode)
tx
end | ruby | def issue_asset(from, amount, metadata = nil, to = nil, fees = nil, mode = 'broadcast', output_qty = 1)
to = from if to.nil?
colored_outputs = get_unspent_outputs([oa_address_to_address(from)])
issue_param = OpenAssets::Transaction::TransferParameters.new(colored_outputs, to, from, amount, output_qty)
tx = create_tx_builder.issue_asset(issue_param, metadata, fees.nil? ? @config[:default_fees]: fees)
tx = process_transaction(tx, mode)
tx
end | [
"def",
"issue_asset",
"(",
"from",
",",
"amount",
",",
"metadata",
"=",
"nil",
",",
"to",
"=",
"nil",
",",
"fees",
"=",
"nil",
",",
"mode",
"=",
"'broadcast'",
",",
"output_qty",
"=",
"1",
")",
"to",
"=",
"from",
"if",
"to",
".",
"nil?",
"colored_outputs",
"=",
"get_unspent_outputs",
"(",
"[",
"oa_address_to_address",
"(",
"from",
")",
"]",
")",
"issue_param",
"=",
"OpenAssets",
"::",
"Transaction",
"::",
"TransferParameters",
".",
"new",
"(",
"colored_outputs",
",",
"to",
",",
"from",
",",
"amount",
",",
"output_qty",
")",
"tx",
"=",
"create_tx_builder",
".",
"issue_asset",
"(",
"issue_param",
",",
"metadata",
",",
"fees",
".",
"nil?",
"?",
"@config",
"[",
":default_fees",
"]",
":",
"fees",
")",
"tx",
"=",
"process_transaction",
"(",
"tx",
",",
"mode",
")",
"tx",
"end"
] | Creates a transaction for issuing an asset.
@param[String] from The open asset address to issue the asset from.
@param[Integer] amount The amount of asset units to issue.
@param[String] to The open asset address to send the asset to; if unspecified, the assets are sent back to the issuing address.
@param[String] metadata The metadata to embed in the transaction. The asset definition pointer defined by this metadata.
@param[Integer] fees The fess in satoshis for the transaction.
@param[String] mode Specify the following mode.
'broadcast' (default) for signing and broadcasting the transaction,
'signed' for signing the transaction without broadcasting,
'unsigned' for getting the raw unsigned transaction without broadcasting"""='broadcast'
@param[Integer] output_qty The number of divides the issue output. Default value is 1.
Ex. amount = 125 and output_qty = 2, asset quantity = [62, 63] and issue TxOut is two.
@return[Bitcoin::Protocol::Tx] The Bitcoin::Protocol::Tx object. | [
"Creates",
"a",
"transaction",
"for",
"issuing",
"an",
"asset",
"."
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/api.rb#L99-L106 |
2,169 | haw-itn/openassets-ruby | lib/openassets/api.rb | OpenAssets.Api.send_asset | def send_asset(from, asset_id, amount, to, fees = nil, mode = 'broadcast', output_qty = 1)
colored_outputs = get_unspent_outputs([oa_address_to_address(from)])
asset_transfer_spec = OpenAssets::Transaction::TransferParameters.new(colored_outputs, to, from, amount, output_qty)
tx = create_tx_builder.transfer_asset(asset_id, asset_transfer_spec, from, fees.nil? ? @config[:default_fees]: fees)
tx = process_transaction(tx, mode)
tx
end | ruby | def send_asset(from, asset_id, amount, to, fees = nil, mode = 'broadcast', output_qty = 1)
colored_outputs = get_unspent_outputs([oa_address_to_address(from)])
asset_transfer_spec = OpenAssets::Transaction::TransferParameters.new(colored_outputs, to, from, amount, output_qty)
tx = create_tx_builder.transfer_asset(asset_id, asset_transfer_spec, from, fees.nil? ? @config[:default_fees]: fees)
tx = process_transaction(tx, mode)
tx
end | [
"def",
"send_asset",
"(",
"from",
",",
"asset_id",
",",
"amount",
",",
"to",
",",
"fees",
"=",
"nil",
",",
"mode",
"=",
"'broadcast'",
",",
"output_qty",
"=",
"1",
")",
"colored_outputs",
"=",
"get_unspent_outputs",
"(",
"[",
"oa_address_to_address",
"(",
"from",
")",
"]",
")",
"asset_transfer_spec",
"=",
"OpenAssets",
"::",
"Transaction",
"::",
"TransferParameters",
".",
"new",
"(",
"colored_outputs",
",",
"to",
",",
"from",
",",
"amount",
",",
"output_qty",
")",
"tx",
"=",
"create_tx_builder",
".",
"transfer_asset",
"(",
"asset_id",
",",
"asset_transfer_spec",
",",
"from",
",",
"fees",
".",
"nil?",
"?",
"@config",
"[",
":default_fees",
"]",
":",
"fees",
")",
"tx",
"=",
"process_transaction",
"(",
"tx",
",",
"mode",
")",
"tx",
"end"
] | Creates a transaction for sending an asset from an address to another.
@param[String] from The open asset address to send the asset from.
@param[String] asset_id The asset ID identifying the asset to send.
@param[Integer] amount The amount of asset units to send.
@param[String] to The open asset address to send the asset to.
@param[Integer] fees The fess in satoshis for the transaction.
@param[String] mode 'broadcast' (default) for signing and broadcasting the transaction,
'signed' for signing the transaction without broadcasting,
'unsigned' for getting the raw unsigned transaction without broadcasting"""='broadcast'
@return[Bitcoin::Protocol:Tx] The resulting transaction. | [
"Creates",
"a",
"transaction",
"for",
"sending",
"an",
"asset",
"from",
"an",
"address",
"to",
"another",
"."
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/api.rb#L118-L124 |
2,170 | haw-itn/openassets-ruby | lib/openassets/api.rb | OpenAssets.Api.send_assets | def send_assets(from, send_asset_params, fees = nil, mode = 'broadcast')
transfer_specs = send_asset_params.map{ |param|
colored_outputs = get_unspent_outputs([oa_address_to_address(param.from || from)])
[param.asset_id, OpenAssets::Transaction::TransferParameters.new(colored_outputs, param.to, param.from || from, param.amount)]
}
btc_transfer_spec = OpenAssets::Transaction::TransferParameters.new(
get_unspent_outputs([oa_address_to_address(from)]), nil, oa_address_to_address(from), 0)
tx = create_tx_builder.transfer_assets(transfer_specs, btc_transfer_spec, fees.nil? ? @config[:default_fees]: fees)
tx = process_transaction(tx, mode)
tx
end | ruby | def send_assets(from, send_asset_params, fees = nil, mode = 'broadcast')
transfer_specs = send_asset_params.map{ |param|
colored_outputs = get_unspent_outputs([oa_address_to_address(param.from || from)])
[param.asset_id, OpenAssets::Transaction::TransferParameters.new(colored_outputs, param.to, param.from || from, param.amount)]
}
btc_transfer_spec = OpenAssets::Transaction::TransferParameters.new(
get_unspent_outputs([oa_address_to_address(from)]), nil, oa_address_to_address(from), 0)
tx = create_tx_builder.transfer_assets(transfer_specs, btc_transfer_spec, fees.nil? ? @config[:default_fees]: fees)
tx = process_transaction(tx, mode)
tx
end | [
"def",
"send_assets",
"(",
"from",
",",
"send_asset_params",
",",
"fees",
"=",
"nil",
",",
"mode",
"=",
"'broadcast'",
")",
"transfer_specs",
"=",
"send_asset_params",
".",
"map",
"{",
"|",
"param",
"|",
"colored_outputs",
"=",
"get_unspent_outputs",
"(",
"[",
"oa_address_to_address",
"(",
"param",
".",
"from",
"||",
"from",
")",
"]",
")",
"[",
"param",
".",
"asset_id",
",",
"OpenAssets",
"::",
"Transaction",
"::",
"TransferParameters",
".",
"new",
"(",
"colored_outputs",
",",
"param",
".",
"to",
",",
"param",
".",
"from",
"||",
"from",
",",
"param",
".",
"amount",
")",
"]",
"}",
"btc_transfer_spec",
"=",
"OpenAssets",
"::",
"Transaction",
"::",
"TransferParameters",
".",
"new",
"(",
"get_unspent_outputs",
"(",
"[",
"oa_address_to_address",
"(",
"from",
")",
"]",
")",
",",
"nil",
",",
"oa_address_to_address",
"(",
"from",
")",
",",
"0",
")",
"tx",
"=",
"create_tx_builder",
".",
"transfer_assets",
"(",
"transfer_specs",
",",
"btc_transfer_spec",
",",
"fees",
".",
"nil?",
"?",
"@config",
"[",
":default_fees",
"]",
":",
"fees",
")",
"tx",
"=",
"process_transaction",
"(",
"tx",
",",
"mode",
")",
"tx",
"end"
] | Creates a transaction for sending multiple asset from an address to another.
@param[String] from The open asset address to send the asset from when send_asset_param hasn't from.
to send the bitcoins from, if needed. where to send bitcoin change, if any.
@param[Array[OpenAssets::SendAssetParam]] send_asset_params The send Asset information(asset_id, amount, to, from).
@param[Integer] fees The fess in satoshis for the transaction.
@param[String] mode 'broadcast' (default) for signing and broadcasting the transaction,
'signed' for signing the transaction without broadcasting,
'unsigned' for getting the raw unsigned transaction without broadcasting"""='broadcast'
@return[Bitcoin::Protocol:Tx] The resulting transaction. | [
"Creates",
"a",
"transaction",
"for",
"sending",
"multiple",
"asset",
"from",
"an",
"address",
"to",
"another",
"."
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/api.rb#L135-L145 |
2,171 | haw-itn/openassets-ruby | lib/openassets/api.rb | OpenAssets.Api.send_bitcoin | def send_bitcoin(from, amount, to, fees = nil, mode = 'broadcast', output_qty = 1)
validate_address([from, to])
colored_outputs = get_unspent_outputs([from])
btc_transfer_spec = OpenAssets::Transaction::TransferParameters.new(colored_outputs, to, from, amount, output_qty)
tx = create_tx_builder.transfer_btc(btc_transfer_spec, fees.nil? ? @config[:default_fees]: fees)
process_transaction(tx, mode)
end | ruby | def send_bitcoin(from, amount, to, fees = nil, mode = 'broadcast', output_qty = 1)
validate_address([from, to])
colored_outputs = get_unspent_outputs([from])
btc_transfer_spec = OpenAssets::Transaction::TransferParameters.new(colored_outputs, to, from, amount, output_qty)
tx = create_tx_builder.transfer_btc(btc_transfer_spec, fees.nil? ? @config[:default_fees]: fees)
process_transaction(tx, mode)
end | [
"def",
"send_bitcoin",
"(",
"from",
",",
"amount",
",",
"to",
",",
"fees",
"=",
"nil",
",",
"mode",
"=",
"'broadcast'",
",",
"output_qty",
"=",
"1",
")",
"validate_address",
"(",
"[",
"from",
",",
"to",
"]",
")",
"colored_outputs",
"=",
"get_unspent_outputs",
"(",
"[",
"from",
"]",
")",
"btc_transfer_spec",
"=",
"OpenAssets",
"::",
"Transaction",
"::",
"TransferParameters",
".",
"new",
"(",
"colored_outputs",
",",
"to",
",",
"from",
",",
"amount",
",",
"output_qty",
")",
"tx",
"=",
"create_tx_builder",
".",
"transfer_btc",
"(",
"btc_transfer_spec",
",",
"fees",
".",
"nil?",
"?",
"@config",
"[",
":default_fees",
"]",
":",
"fees",
")",
"process_transaction",
"(",
"tx",
",",
"mode",
")",
"end"
] | Creates a transaction for sending bitcoins from an address to another.
@param[String] from The address to send the bitcoins from.
@param[Integer] amount The amount of satoshis to send.
@param[String] to The address to send the bitcoins to.
@param[Integer] fees The fess in satoshis for the transaction.
@param[String] mode 'broadcast' (default) for signing and broadcasting the transaction,
'signed' for signing the transaction without broadcasting,
'unsigned' for getting the raw unsigned transaction without broadcasting"""='broadcast'
@param [Integer] output_qty The number of divides the issue output. Default value is 1.
Ex. amount = 125 and output_qty = 2, asset quantity = [62, 63] and issue TxOut is two.
@return[Bitcoin::Protocol:Tx] The resulting transaction. | [
"Creates",
"a",
"transaction",
"for",
"sending",
"bitcoins",
"from",
"an",
"address",
"to",
"another",
"."
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/api.rb#L158-L164 |
2,172 | haw-itn/openassets-ruby | lib/openassets/api.rb | OpenAssets.Api.send_bitcoins | def send_bitcoins(from, send_params, fees = nil, mode = 'broadcast')
colored_outputs = get_unspent_outputs([from])
btc_transfer_specs = send_params.map{|param|
OpenAssets::Transaction::TransferParameters.new(colored_outputs, param.to, from, param.amount)
}
tx = create_tx_builder.transfer_btcs(btc_transfer_specs, fees.nil? ? @config[:default_fees]: fees)
tx = process_transaction(tx, mode)
tx
end | ruby | def send_bitcoins(from, send_params, fees = nil, mode = 'broadcast')
colored_outputs = get_unspent_outputs([from])
btc_transfer_specs = send_params.map{|param|
OpenAssets::Transaction::TransferParameters.new(colored_outputs, param.to, from, param.amount)
}
tx = create_tx_builder.transfer_btcs(btc_transfer_specs, fees.nil? ? @config[:default_fees]: fees)
tx = process_transaction(tx, mode)
tx
end | [
"def",
"send_bitcoins",
"(",
"from",
",",
"send_params",
",",
"fees",
"=",
"nil",
",",
"mode",
"=",
"'broadcast'",
")",
"colored_outputs",
"=",
"get_unspent_outputs",
"(",
"[",
"from",
"]",
")",
"btc_transfer_specs",
"=",
"send_params",
".",
"map",
"{",
"|",
"param",
"|",
"OpenAssets",
"::",
"Transaction",
"::",
"TransferParameters",
".",
"new",
"(",
"colored_outputs",
",",
"param",
".",
"to",
",",
"from",
",",
"param",
".",
"amount",
")",
"}",
"tx",
"=",
"create_tx_builder",
".",
"transfer_btcs",
"(",
"btc_transfer_specs",
",",
"fees",
".",
"nil?",
"?",
"@config",
"[",
":default_fees",
"]",
":",
"fees",
")",
"tx",
"=",
"process_transaction",
"(",
"tx",
",",
"mode",
")",
"tx",
"end"
] | Creates a transaction for sending multiple bitcoins from an address to others.
@param[String] from The address to send the bitcoins from.
@param[Array[OpenAssets::SendBitcoinParam]] send_params The send information(amount of satoshis and to).
@param[Integer] fees The fees in satoshis for the transaction.
@param[String] mode 'broadcast' (default) for signing and broadcasting the transaction,
'signed' for signing the transaction without broadcasting,
'unsigned' for getting the raw unsigned transaction without broadcasting"""='broadcast'
@return[Bitcoin::Protocol:Tx] The resulting transaction. | [
"Creates",
"a",
"transaction",
"for",
"sending",
"multiple",
"bitcoins",
"from",
"an",
"address",
"to",
"others",
"."
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/api.rb#L174-L182 |
2,173 | haw-itn/openassets-ruby | lib/openassets/api.rb | OpenAssets.Api.burn_asset | def burn_asset(oa_address, asset_id, fees = nil, mode = 'broadcast')
unspents = get_unspent_outputs([oa_address_to_address(oa_address)])
tx = create_tx_builder.burn_asset(unspents, asset_id, fees.nil? ? @config[:default_fees]: fees)
process_transaction(tx, mode)
end | ruby | def burn_asset(oa_address, asset_id, fees = nil, mode = 'broadcast')
unspents = get_unspent_outputs([oa_address_to_address(oa_address)])
tx = create_tx_builder.burn_asset(unspents, asset_id, fees.nil? ? @config[:default_fees]: fees)
process_transaction(tx, mode)
end | [
"def",
"burn_asset",
"(",
"oa_address",
",",
"asset_id",
",",
"fees",
"=",
"nil",
",",
"mode",
"=",
"'broadcast'",
")",
"unspents",
"=",
"get_unspent_outputs",
"(",
"[",
"oa_address_to_address",
"(",
"oa_address",
")",
"]",
")",
"tx",
"=",
"create_tx_builder",
".",
"burn_asset",
"(",
"unspents",
",",
"asset_id",
",",
"fees",
".",
"nil?",
"?",
"@config",
"[",
":default_fees",
"]",
":",
"fees",
")",
"process_transaction",
"(",
"tx",
",",
"mode",
")",
"end"
] | Creates a transaction for burn asset.
@param[String] oa_address The open asset address to burn asset.
@param[String] asset_id The asset ID identifying the asset to burn.
@param[Integer] fees The fess in satoshis for the transaction.
@param[String] mode 'broadcast' (default) for signing and broadcasting the transaction,
'signed' for signing the transaction without broadcasting,
'unsigned' for getting the raw unsigned transaction without broadcasting"""='broadcast' | [
"Creates",
"a",
"transaction",
"for",
"burn",
"asset",
"."
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/api.rb#L192-L196 |
2,174 | haw-itn/openassets-ruby | lib/openassets/api.rb | OpenAssets.Api.get_unspent_outputs | def get_unspent_outputs(addresses)
validate_address(addresses)
unspent = provider.list_unspent(addresses, @config[:min_confirmation], @config[:max_confirmation])
result = unspent.map{|item|
output_result = get_output(item['txid'], item['vout'])
output_result.account = item['account']
output = OpenAssets::Transaction::SpendableOutput.new(
OpenAssets::Transaction::OutPoint.new(item['txid'], item['vout']), output_result)
output.confirmations = item['confirmations']
output.spendable = item['spendable']
output.solvable = item['solvable']
output
}
result
end | ruby | def get_unspent_outputs(addresses)
validate_address(addresses)
unspent = provider.list_unspent(addresses, @config[:min_confirmation], @config[:max_confirmation])
result = unspent.map{|item|
output_result = get_output(item['txid'], item['vout'])
output_result.account = item['account']
output = OpenAssets::Transaction::SpendableOutput.new(
OpenAssets::Transaction::OutPoint.new(item['txid'], item['vout']), output_result)
output.confirmations = item['confirmations']
output.spendable = item['spendable']
output.solvable = item['solvable']
output
}
result
end | [
"def",
"get_unspent_outputs",
"(",
"addresses",
")",
"validate_address",
"(",
"addresses",
")",
"unspent",
"=",
"provider",
".",
"list_unspent",
"(",
"addresses",
",",
"@config",
"[",
":min_confirmation",
"]",
",",
"@config",
"[",
":max_confirmation",
"]",
")",
"result",
"=",
"unspent",
".",
"map",
"{",
"|",
"item",
"|",
"output_result",
"=",
"get_output",
"(",
"item",
"[",
"'txid'",
"]",
",",
"item",
"[",
"'vout'",
"]",
")",
"output_result",
".",
"account",
"=",
"item",
"[",
"'account'",
"]",
"output",
"=",
"OpenAssets",
"::",
"Transaction",
"::",
"SpendableOutput",
".",
"new",
"(",
"OpenAssets",
"::",
"Transaction",
"::",
"OutPoint",
".",
"new",
"(",
"item",
"[",
"'txid'",
"]",
",",
"item",
"[",
"'vout'",
"]",
")",
",",
"output_result",
")",
"output",
".",
"confirmations",
"=",
"item",
"[",
"'confirmations'",
"]",
"output",
".",
"spendable",
"=",
"item",
"[",
"'spendable'",
"]",
"output",
".",
"solvable",
"=",
"item",
"[",
"'solvable'",
"]",
"output",
"}",
"result",
"end"
] | Get unspent outputs.
@param [Array] addresses The array of Bitcoin address.
@return [Array[OpenAssets::Transaction::SpendableOutput]] The array of unspent outputs. | [
"Get",
"unspent",
"outputs",
"."
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/api.rb#L201-L215 |
2,175 | haw-itn/openassets-ruby | lib/openassets/api.rb | OpenAssets.Api.get_outputs_from_txid | def get_outputs_from_txid(txid, use_cache = false)
tx = get_tx(txid, use_cache)
outputs = get_color_outputs_from_tx(tx)
outputs.map.with_index{|out, i|out.to_hash.merge({'txid' => tx.hash, 'vout' => i})}
end | ruby | def get_outputs_from_txid(txid, use_cache = false)
tx = get_tx(txid, use_cache)
outputs = get_color_outputs_from_tx(tx)
outputs.map.with_index{|out, i|out.to_hash.merge({'txid' => tx.hash, 'vout' => i})}
end | [
"def",
"get_outputs_from_txid",
"(",
"txid",
",",
"use_cache",
"=",
"false",
")",
"tx",
"=",
"get_tx",
"(",
"txid",
",",
"use_cache",
")",
"outputs",
"=",
"get_color_outputs_from_tx",
"(",
"tx",
")",
"outputs",
".",
"map",
".",
"with_index",
"{",
"|",
"out",
",",
"i",
"|",
"out",
".",
"to_hash",
".",
"merge",
"(",
"{",
"'txid'",
"=>",
"tx",
".",
"hash",
",",
"'vout'",
"=>",
"i",
"}",
")",
"}",
"end"
] | Get tx outputs.
@param[String] txid Transaction ID.
@param[Boolean] use_cache If specified true use cache.(default value is false)
@return[Array] Return array of the transaction output Hash with coloring information. | [
"Get",
"tx",
"outputs",
"."
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/api.rb#L248-L252 |
2,176 | haw-itn/openassets-ruby | lib/openassets/api.rb | OpenAssets.Api.parse_issuance_p2sh_pointer | def parse_issuance_p2sh_pointer(script_sig)
script = Bitcoin::Script.new(script_sig).chunks.last
redeem_script = Bitcoin::Script.new(script)
return nil unless redeem_script.chunks[1] == Bitcoin::Script::OP_DROP
asset_def = to_bytes(redeem_script.chunks[0].to_s.bth)[0..-1].map{|x|x.to_i(16).chr}.join
asset_def && asset_def.start_with?('u=') ? asset_def : nil
end | ruby | def parse_issuance_p2sh_pointer(script_sig)
script = Bitcoin::Script.new(script_sig).chunks.last
redeem_script = Bitcoin::Script.new(script)
return nil unless redeem_script.chunks[1] == Bitcoin::Script::OP_DROP
asset_def = to_bytes(redeem_script.chunks[0].to_s.bth)[0..-1].map{|x|x.to_i(16).chr}.join
asset_def && asset_def.start_with?('u=') ? asset_def : nil
end | [
"def",
"parse_issuance_p2sh_pointer",
"(",
"script_sig",
")",
"script",
"=",
"Bitcoin",
"::",
"Script",
".",
"new",
"(",
"script_sig",
")",
".",
"chunks",
".",
"last",
"redeem_script",
"=",
"Bitcoin",
"::",
"Script",
".",
"new",
"(",
"script",
")",
"return",
"nil",
"unless",
"redeem_script",
".",
"chunks",
"[",
"1",
"]",
"==",
"Bitcoin",
"::",
"Script",
"::",
"OP_DROP",
"asset_def",
"=",
"to_bytes",
"(",
"redeem_script",
".",
"chunks",
"[",
"0",
"]",
".",
"to_s",
".",
"bth",
")",
"[",
"0",
"..",
"-",
"1",
"]",
".",
"map",
"{",
"|",
"x",
"|",
"x",
".",
"to_i",
"(",
"16",
")",
".",
"chr",
"}",
".",
"join",
"asset_def",
"&&",
"asset_def",
".",
"start_with?",
"(",
"'u='",
")",
"?",
"asset_def",
":",
"nil",
"end"
] | parse issuance p2sh which contains asset definition pointer | [
"parse",
"issuance",
"p2sh",
"which",
"contains",
"asset",
"definition",
"pointer"
] | c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf | https://github.com/haw-itn/openassets-ruby/blob/c2171ccb7e3bf2b8c712e9ef82a3bfaef3d1f4bf/lib/openassets/api.rb#L409-L415 |
2,177 | poise/halite | lib/halite/spec_helper.rb | Halite.SpecHelper.chef_runner_options | def chef_runner_options
super.tap do |options|
options[:halite_gemspec] = halite_gemspec
# And some legacy data.
options[:default_attributes].update(default_attributes)
options[:normal_attributes].update(normal_attributes)
options[:override_attributes].update(override_attributes)
options.update(chefspec_options)
end
end | ruby | def chef_runner_options
super.tap do |options|
options[:halite_gemspec] = halite_gemspec
# And some legacy data.
options[:default_attributes].update(default_attributes)
options[:normal_attributes].update(normal_attributes)
options[:override_attributes].update(override_attributes)
options.update(chefspec_options)
end
end | [
"def",
"chef_runner_options",
"super",
".",
"tap",
"do",
"|",
"options",
"|",
"options",
"[",
":halite_gemspec",
"]",
"=",
"halite_gemspec",
"# And some legacy data.",
"options",
"[",
":default_attributes",
"]",
".",
"update",
"(",
"default_attributes",
")",
"options",
"[",
":normal_attributes",
"]",
".",
"update",
"(",
"normal_attributes",
")",
"options",
"[",
":override_attributes",
"]",
".",
"update",
"(",
"override_attributes",
")",
"options",
".",
"update",
"(",
"chefspec_options",
")",
"end",
"end"
] | Merge in extra options data. | [
"Merge",
"in",
"extra",
"options",
"data",
"."
] | 9ae174e6b7c5d4674f3301394e14567fa89a8b3e | https://github.com/poise/halite/blob/9ae174e6b7c5d4674f3301394e14567fa89a8b3e/lib/halite/spec_helper.rb#L106-L115 |
2,178 | poise/halite | lib/halite/rake_helper.rb | Halite.RakeHelper.install | def install
extend Rake::DSL
# Core Halite tasks
unless options[:no_gem]
desc "Convert #{gemspec.name}-#{gemspec.version} to a cookbook in the pkg directory"
task 'chef:build' do
build_cookbook
end
desc "Push #{gemspec.name}-#{gemspec.version} to Supermarket"
task 'chef:release' => ['chef:build'] do
release_cookbook(pkg_path)
end
# Patch the core gem tasks to run ours too
task 'build' => ['chef:build']
task 'release' => ['chef:release']
else
desc "Push #{gem_name} to Supermarket"
task 'chef:release' do
release_cookbook(base)
end
end
# Foodcritic doesn't have a config file, so just always try to add it.
unless options[:no_foodcritic]
install_foodcritic
end
# If a .kitchen.yml exists, install the Test Kitchen tasks.
unless options[:no_kitchen] || !File.exist?(File.join(@base, '.kitchen.yml'))
install_kitchen
end
end | ruby | def install
extend Rake::DSL
# Core Halite tasks
unless options[:no_gem]
desc "Convert #{gemspec.name}-#{gemspec.version} to a cookbook in the pkg directory"
task 'chef:build' do
build_cookbook
end
desc "Push #{gemspec.name}-#{gemspec.version} to Supermarket"
task 'chef:release' => ['chef:build'] do
release_cookbook(pkg_path)
end
# Patch the core gem tasks to run ours too
task 'build' => ['chef:build']
task 'release' => ['chef:release']
else
desc "Push #{gem_name} to Supermarket"
task 'chef:release' do
release_cookbook(base)
end
end
# Foodcritic doesn't have a config file, so just always try to add it.
unless options[:no_foodcritic]
install_foodcritic
end
# If a .kitchen.yml exists, install the Test Kitchen tasks.
unless options[:no_kitchen] || !File.exist?(File.join(@base, '.kitchen.yml'))
install_kitchen
end
end | [
"def",
"install",
"extend",
"Rake",
"::",
"DSL",
"# Core Halite tasks",
"unless",
"options",
"[",
":no_gem",
"]",
"desc",
"\"Convert #{gemspec.name}-#{gemspec.version} to a cookbook in the pkg directory\"",
"task",
"'chef:build'",
"do",
"build_cookbook",
"end",
"desc",
"\"Push #{gemspec.name}-#{gemspec.version} to Supermarket\"",
"task",
"'chef:release'",
"=>",
"[",
"'chef:build'",
"]",
"do",
"release_cookbook",
"(",
"pkg_path",
")",
"end",
"# Patch the core gem tasks to run ours too",
"task",
"'build'",
"=>",
"[",
"'chef:build'",
"]",
"task",
"'release'",
"=>",
"[",
"'chef:release'",
"]",
"else",
"desc",
"\"Push #{gem_name} to Supermarket\"",
"task",
"'chef:release'",
"do",
"release_cookbook",
"(",
"base",
")",
"end",
"end",
"# Foodcritic doesn't have a config file, so just always try to add it.",
"unless",
"options",
"[",
":no_foodcritic",
"]",
"install_foodcritic",
"end",
"# If a .kitchen.yml exists, install the Test Kitchen tasks.",
"unless",
"options",
"[",
":no_kitchen",
"]",
"||",
"!",
"File",
".",
"exist?",
"(",
"File",
".",
"join",
"(",
"@base",
",",
"'.kitchen.yml'",
")",
")",
"install_kitchen",
"end",
"end"
] | Install all Rake tasks.
@return [void] | [
"Install",
"all",
"Rake",
"tasks",
"."
] | 9ae174e6b7c5d4674f3301394e14567fa89a8b3e | https://github.com/poise/halite/blob/9ae174e6b7c5d4674f3301394e14567fa89a8b3e/lib/halite/rake_helper.rb#L37-L70 |
2,179 | poise/halite | lib/halite/rake_helper.rb | Halite.RakeHelper.remove_files_in_folder | def remove_files_in_folder(base_path)
existing_files = Dir.glob(File.join(base_path, '**', '*'), File::FNM_DOTMATCH).map {|path| File.expand_path(path)}.uniq.reverse # expand_path just to normalize foo/. -> foo
existing_files.delete(base_path) # Don't remove the base
# Fuck FileUtils, it is a confusing pile of fail for remove*/rm*
existing_files.each do |path|
if File.file?(path)
File.unlink(path)
elsif File.directory?(path)
Dir.unlink(path)
else
# Because paranoia
raise Error.new("Unknown type of file at '#{path}', possible symlink deletion attack")
end
end
end | ruby | def remove_files_in_folder(base_path)
existing_files = Dir.glob(File.join(base_path, '**', '*'), File::FNM_DOTMATCH).map {|path| File.expand_path(path)}.uniq.reverse # expand_path just to normalize foo/. -> foo
existing_files.delete(base_path) # Don't remove the base
# Fuck FileUtils, it is a confusing pile of fail for remove*/rm*
existing_files.each do |path|
if File.file?(path)
File.unlink(path)
elsif File.directory?(path)
Dir.unlink(path)
else
# Because paranoia
raise Error.new("Unknown type of file at '#{path}', possible symlink deletion attack")
end
end
end | [
"def",
"remove_files_in_folder",
"(",
"base_path",
")",
"existing_files",
"=",
"Dir",
".",
"glob",
"(",
"File",
".",
"join",
"(",
"base_path",
",",
"'**'",
",",
"'*'",
")",
",",
"File",
"::",
"FNM_DOTMATCH",
")",
".",
"map",
"{",
"|",
"path",
"|",
"File",
".",
"expand_path",
"(",
"path",
")",
"}",
".",
"uniq",
".",
"reverse",
"# expand_path just to normalize foo/. -> foo",
"existing_files",
".",
"delete",
"(",
"base_path",
")",
"# Don't remove the base",
"# Fuck FileUtils, it is a confusing pile of fail for remove*/rm*",
"existing_files",
".",
"each",
"do",
"|",
"path",
"|",
"if",
"File",
".",
"file?",
"(",
"path",
")",
"File",
".",
"unlink",
"(",
"path",
")",
"elsif",
"File",
".",
"directory?",
"(",
"path",
")",
"Dir",
".",
"unlink",
"(",
"path",
")",
"else",
"# Because paranoia",
"raise",
"Error",
".",
"new",
"(",
"\"Unknown type of file at '#{path}', possible symlink deletion attack\"",
")",
"end",
"end",
"end"
] | Remove everything in a path, but not the directory itself | [
"Remove",
"everything",
"in",
"a",
"path",
"but",
"not",
"the",
"directory",
"itself"
] | 9ae174e6b7c5d4674f3301394e14567fa89a8b3e | https://github.com/poise/halite/blob/9ae174e6b7c5d4674f3301394e14567fa89a8b3e/lib/halite/rake_helper.rb#L145-L159 |
2,180 | jeffwilliams/quartz-torrent | lib/quartz_torrent/udptrackerdriver.rb | QuartzTorrent.UdpTrackerDriver.readWithTimeout | def readWithTimeout(socket, length, timeout)
rc = IO.select([socket], nil, nil, timeout)
if ! rc
raise "Waiting for response from UDP tracker #{@host}:#{@trackerPort} timed out after #{@timeout} seconds"
elsif rc[0].size > 0
socket.recvfrom(length)[0]
else
raise "Error receiving response from UDP tracker #{@host}:#{@trackerPort}"
end
end | ruby | def readWithTimeout(socket, length, timeout)
rc = IO.select([socket], nil, nil, timeout)
if ! rc
raise "Waiting for response from UDP tracker #{@host}:#{@trackerPort} timed out after #{@timeout} seconds"
elsif rc[0].size > 0
socket.recvfrom(length)[0]
else
raise "Error receiving response from UDP tracker #{@host}:#{@trackerPort}"
end
end | [
"def",
"readWithTimeout",
"(",
"socket",
",",
"length",
",",
"timeout",
")",
"rc",
"=",
"IO",
".",
"select",
"(",
"[",
"socket",
"]",
",",
"nil",
",",
"nil",
",",
"timeout",
")",
"if",
"!",
"rc",
"raise",
"\"Waiting for response from UDP tracker #{@host}:#{@trackerPort} timed out after #{@timeout} seconds\"",
"elsif",
"rc",
"[",
"0",
"]",
".",
"size",
">",
"0",
"socket",
".",
"recvfrom",
"(",
"length",
")",
"[",
"0",
"]",
"else",
"raise",
"\"Error receiving response from UDP tracker #{@host}:#{@trackerPort}\"",
"end",
"end"
] | Throws exception if timeout occurs | [
"Throws",
"exception",
"if",
"timeout",
"occurs"
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/udptrackerdriver.rb#L82-L91 |
2,181 | poise/halite | lib/halite/helper_base.rb | Halite.HelperBase.find_gem_name | def find_gem_name(base)
spec = Dir[File.join(base, '*.gemspec')].first
File.basename(spec, '.gemspec') if spec
end | ruby | def find_gem_name(base)
spec = Dir[File.join(base, '*.gemspec')].first
File.basename(spec, '.gemspec') if spec
end | [
"def",
"find_gem_name",
"(",
"base",
")",
"spec",
"=",
"Dir",
"[",
"File",
".",
"join",
"(",
"base",
",",
"'*.gemspec'",
")",
"]",
".",
"first",
"File",
".",
"basename",
"(",
"spec",
",",
"'.gemspec'",
")",
"if",
"spec",
"end"
] | Search a directory for a .gemspec file to determine the gem name.
Returns nil if no gemspec is found.
@param base [String] Folder to search.
@return [String, nil] | [
"Search",
"a",
"directory",
"for",
"a",
".",
"gemspec",
"file",
"to",
"determine",
"the",
"gem",
"name",
".",
"Returns",
"nil",
"if",
"no",
"gemspec",
"is",
"found",
"."
] | 9ae174e6b7c5d4674f3301394e14567fa89a8b3e | https://github.com/poise/halite/blob/9ae174e6b7c5d4674f3301394e14567fa89a8b3e/lib/halite/helper_base.rb#L102-L105 |
2,182 | poise/halite | lib/halite/helper_base.rb | Halite.HelperBase.gemspec | def gemspec
@gemspec ||= begin
raise Error.new("Unable to automatically determine gem name from specs in #{base}. Please set the gem name via #{self.class.name}.install_tasks(gem_name: 'name')") unless gem_name
g = Bundler.load_gemspec(File.join(base, gem_name+'.gemspec'))
# This is returning the path it would be in if installed normally,
# override so we get the local path. Also for reasons that are entirely
# beyond me, #tap makes Gem::Specification flip out so do it old-school.
g.full_gem_path = base
g
end
end | ruby | def gemspec
@gemspec ||= begin
raise Error.new("Unable to automatically determine gem name from specs in #{base}. Please set the gem name via #{self.class.name}.install_tasks(gem_name: 'name')") unless gem_name
g = Bundler.load_gemspec(File.join(base, gem_name+'.gemspec'))
# This is returning the path it would be in if installed normally,
# override so we get the local path. Also for reasons that are entirely
# beyond me, #tap makes Gem::Specification flip out so do it old-school.
g.full_gem_path = base
g
end
end | [
"def",
"gemspec",
"@gemspec",
"||=",
"begin",
"raise",
"Error",
".",
"new",
"(",
"\"Unable to automatically determine gem name from specs in #{base}. Please set the gem name via #{self.class.name}.install_tasks(gem_name: 'name')\"",
")",
"unless",
"gem_name",
"g",
"=",
"Bundler",
".",
"load_gemspec",
"(",
"File",
".",
"join",
"(",
"base",
",",
"gem_name",
"+",
"'.gemspec'",
")",
")",
"# This is returning the path it would be in if installed normally,",
"# override so we get the local path. Also for reasons that are entirely",
"# beyond me, #tap makes Gem::Specification flip out so do it old-school.",
"g",
".",
"full_gem_path",
"=",
"base",
"g",
"end",
"end"
] | Gem specification for the current gem.
@return [Gem::Specification] | [
"Gem",
"specification",
"for",
"the",
"current",
"gem",
"."
] | 9ae174e6b7c5d4674f3301394e14567fa89a8b3e | https://github.com/poise/halite/blob/9ae174e6b7c5d4674f3301394e14567fa89a8b3e/lib/halite/helper_base.rb#L110-L120 |
2,183 | jeffwilliams/quartz-torrent | lib/quartz_torrent/metainfopiecestate.rb | QuartzTorrent.MetainfoPieceState.metainfoCompletedLength | def metainfoCompletedLength
num = @completePieces.countSet
# Last block may be smaller
extra = 0
if @completePieces.set?(@completePieces.length-1)
num -= 1
extra = @lastPieceLength
end
num*BlockSize + extra
end | ruby | def metainfoCompletedLength
num = @completePieces.countSet
# Last block may be smaller
extra = 0
if @completePieces.set?(@completePieces.length-1)
num -= 1
extra = @lastPieceLength
end
num*BlockSize + extra
end | [
"def",
"metainfoCompletedLength",
"num",
"=",
"@completePieces",
".",
"countSet",
"# Last block may be smaller",
"extra",
"=",
"0",
"if",
"@completePieces",
".",
"set?",
"(",
"@completePieces",
".",
"length",
"-",
"1",
")",
"num",
"-=",
"1",
"extra",
"=",
"@lastPieceLength",
"end",
"num",
"BlockSize",
"+",
"extra",
"end"
] | Return the number of bytes of the metainfo that we have downloaded so far. | [
"Return",
"the",
"number",
"of",
"bytes",
"of",
"the",
"metainfo",
"that",
"we",
"have",
"downloaded",
"so",
"far",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/metainfopiecestate.rb#L110-L119 |
2,184 | jeffwilliams/quartz-torrent | lib/quartz_torrent/metainfopiecestate.rb | QuartzTorrent.MetainfoPieceState.savePiece | def savePiece(pieceIndex, data)
id = @pieceManager.writeBlock pieceIndex, 0, data
@pieceManagerRequests[id] = PieceManagerRequestMetadata.new(:write, pieceIndex)
id
end | ruby | def savePiece(pieceIndex, data)
id = @pieceManager.writeBlock pieceIndex, 0, data
@pieceManagerRequests[id] = PieceManagerRequestMetadata.new(:write, pieceIndex)
id
end | [
"def",
"savePiece",
"(",
"pieceIndex",
",",
"data",
")",
"id",
"=",
"@pieceManager",
".",
"writeBlock",
"pieceIndex",
",",
"0",
",",
"data",
"@pieceManagerRequests",
"[",
"id",
"]",
"=",
"PieceManagerRequestMetadata",
".",
"new",
"(",
":write",
",",
"pieceIndex",
")",
"id",
"end"
] | Save the specified piece to disk asynchronously. | [
"Save",
"the",
"specified",
"piece",
"to",
"disk",
"asynchronously",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/metainfopiecestate.rb#L141-L145 |
2,185 | jeffwilliams/quartz-torrent | lib/quartz_torrent/metainfopiecestate.rb | QuartzTorrent.MetainfoPieceState.readPiece | def readPiece(pieceIndex)
length = BlockSize
length = @lastPieceLength if pieceIndex == @numPieces - 1
id = @pieceManager.readBlock pieceIndex, 0, length
#result = manager.nextResult
@pieceManagerRequests[id] = PieceManagerRequestMetadata.new(:read, pieceIndex)
id
end | ruby | def readPiece(pieceIndex)
length = BlockSize
length = @lastPieceLength if pieceIndex == @numPieces - 1
id = @pieceManager.readBlock pieceIndex, 0, length
#result = manager.nextResult
@pieceManagerRequests[id] = PieceManagerRequestMetadata.new(:read, pieceIndex)
id
end | [
"def",
"readPiece",
"(",
"pieceIndex",
")",
"length",
"=",
"BlockSize",
"length",
"=",
"@lastPieceLength",
"if",
"pieceIndex",
"==",
"@numPieces",
"-",
"1",
"id",
"=",
"@pieceManager",
".",
"readBlock",
"pieceIndex",
",",
"0",
",",
"length",
"#result = manager.nextResult",
"@pieceManagerRequests",
"[",
"id",
"]",
"=",
"PieceManagerRequestMetadata",
".",
"new",
"(",
":read",
",",
"pieceIndex",
")",
"id",
"end"
] | Read a piece from disk. This method is asynchronous; it returns a handle that can be later
used to retreive the result. | [
"Read",
"a",
"piece",
"from",
"disk",
".",
"This",
"method",
"is",
"asynchronous",
";",
"it",
"returns",
"a",
"handle",
"that",
"can",
"be",
"later",
"used",
"to",
"retreive",
"the",
"result",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/metainfopiecestate.rb#L149-L156 |
2,186 | jeffwilliams/quartz-torrent | lib/quartz_torrent/metainfopiecestate.rb | QuartzTorrent.MetainfoPieceState.checkResults | def checkResults
results = []
while true
result = @pieceManager.nextResult
break if ! result
results.push result
metaData = @pieceManagerRequests.delete(result.requestId)
if ! metaData
@logger.error "Can't find metadata for PieceManager request #{result.requestId}"
next
end
if metaData.type == :write
if result.successful?
@completePieces.set(metaData.data)
else
@requestedPieces.clear(metaData.data)
@pieceRequestTime[metaData.data] = nil
@logger.error "Writing metainfo piece failed: #{result.error}"
end
elsif metaData.type == :read
if ! result.successful?
@logger.error "Reading metainfo piece failed: #{result.error}"
end
end
end
results
end | ruby | def checkResults
results = []
while true
result = @pieceManager.nextResult
break if ! result
results.push result
metaData = @pieceManagerRequests.delete(result.requestId)
if ! metaData
@logger.error "Can't find metadata for PieceManager request #{result.requestId}"
next
end
if metaData.type == :write
if result.successful?
@completePieces.set(metaData.data)
else
@requestedPieces.clear(metaData.data)
@pieceRequestTime[metaData.data] = nil
@logger.error "Writing metainfo piece failed: #{result.error}"
end
elsif metaData.type == :read
if ! result.successful?
@logger.error "Reading metainfo piece failed: #{result.error}"
end
end
end
results
end | [
"def",
"checkResults",
"results",
"=",
"[",
"]",
"while",
"true",
"result",
"=",
"@pieceManager",
".",
"nextResult",
"break",
"if",
"!",
"result",
"results",
".",
"push",
"result",
"metaData",
"=",
"@pieceManagerRequests",
".",
"delete",
"(",
"result",
".",
"requestId",
")",
"if",
"!",
"metaData",
"@logger",
".",
"error",
"\"Can't find metadata for PieceManager request #{result.requestId}\"",
"next",
"end",
"if",
"metaData",
".",
"type",
"==",
":write",
"if",
"result",
".",
"successful?",
"@completePieces",
".",
"set",
"(",
"metaData",
".",
"data",
")",
"else",
"@requestedPieces",
".",
"clear",
"(",
"metaData",
".",
"data",
")",
"@pieceRequestTime",
"[",
"metaData",
".",
"data",
"]",
"=",
"nil",
"@logger",
".",
"error",
"\"Writing metainfo piece failed: #{result.error}\"",
"end",
"elsif",
"metaData",
".",
"type",
"==",
":read",
"if",
"!",
"result",
".",
"successful?",
"@logger",
".",
"error",
"\"Reading metainfo piece failed: #{result.error}\"",
"end",
"end",
"end",
"results",
"end"
] | Check the results of savePiece and readPiece. This method returns a list
of the PieceManager results. | [
"Check",
"the",
"results",
"of",
"savePiece",
"and",
"readPiece",
".",
"This",
"method",
"returns",
"a",
"list",
"of",
"the",
"PieceManager",
"results",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/metainfopiecestate.rb#L160-L189 |
2,187 | jeffwilliams/quartz-torrent | lib/quartz_torrent/metainfopiecestate.rb | QuartzTorrent.MetainfoPieceState.findRequestablePieces | def findRequestablePieces
piecesRequired = []
removeOldRequests
@numPieces.times do |pieceIndex|
piecesRequired.push pieceIndex if ! @completePieces.set?(pieceIndex) && ! @requestedPieces.set?(pieceIndex)
end
piecesRequired
end | ruby | def findRequestablePieces
piecesRequired = []
removeOldRequests
@numPieces.times do |pieceIndex|
piecesRequired.push pieceIndex if ! @completePieces.set?(pieceIndex) && ! @requestedPieces.set?(pieceIndex)
end
piecesRequired
end | [
"def",
"findRequestablePieces",
"piecesRequired",
"=",
"[",
"]",
"removeOldRequests",
"@numPieces",
".",
"times",
"do",
"|",
"pieceIndex",
"|",
"piecesRequired",
".",
"push",
"pieceIndex",
"if",
"!",
"@completePieces",
".",
"set?",
"(",
"pieceIndex",
")",
"&&",
"!",
"@requestedPieces",
".",
"set?",
"(",
"pieceIndex",
")",
"end",
"piecesRequired",
"end"
] | Return a list of torrent pieces that can still be requested. These are pieces that are not completed and are not requested. | [
"Return",
"a",
"list",
"of",
"torrent",
"pieces",
"that",
"can",
"still",
"be",
"requested",
".",
"These",
"are",
"pieces",
"that",
"are",
"not",
"completed",
"and",
"are",
"not",
"requested",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/metainfopiecestate.rb#L192-L202 |
2,188 | jeffwilliams/quartz-torrent | lib/quartz_torrent/metainfopiecestate.rb | QuartzTorrent.MetainfoPieceState.findRequestablePeers | def findRequestablePeers(classifiedPeers)
result = []
classifiedPeers.establishedPeers.each do |peer|
result.push peer if ! @badPeers.findByAddr(peer.trackerPeer.ip, peer.trackerPeer.port)
end
result
end | ruby | def findRequestablePeers(classifiedPeers)
result = []
classifiedPeers.establishedPeers.each do |peer|
result.push peer if ! @badPeers.findByAddr(peer.trackerPeer.ip, peer.trackerPeer.port)
end
result
end | [
"def",
"findRequestablePeers",
"(",
"classifiedPeers",
")",
"result",
"=",
"[",
"]",
"classifiedPeers",
".",
"establishedPeers",
".",
"each",
"do",
"|",
"peer",
"|",
"result",
".",
"push",
"peer",
"if",
"!",
"@badPeers",
".",
"findByAddr",
"(",
"peer",
".",
"trackerPeer",
".",
"ip",
",",
"peer",
".",
"trackerPeer",
".",
"port",
")",
"end",
"result",
"end"
] | Return a list of peers from whom we can request pieces. These are peers for whom we have an established connection, and
are not marked as bad. See markPeerBad. | [
"Return",
"a",
"list",
"of",
"peers",
"from",
"whom",
"we",
"can",
"request",
"pieces",
".",
"These",
"are",
"peers",
"for",
"whom",
"we",
"have",
"an",
"established",
"connection",
"and",
"are",
"not",
"marked",
"as",
"bad",
".",
"See",
"markPeerBad",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/metainfopiecestate.rb#L206-L214 |
2,189 | jeffwilliams/quartz-torrent | lib/quartz_torrent/metainfopiecestate.rb | QuartzTorrent.MetainfoPieceState.setPieceRequested | def setPieceRequested(pieceIndex, bool)
if bool
@requestedPieces.set pieceIndex
@pieceRequestTime[pieceIndex] = Time.new
else
@requestedPieces.clear pieceIndex
@pieceRequestTime[pieceIndex] = nil
end
end | ruby | def setPieceRequested(pieceIndex, bool)
if bool
@requestedPieces.set pieceIndex
@pieceRequestTime[pieceIndex] = Time.new
else
@requestedPieces.clear pieceIndex
@pieceRequestTime[pieceIndex] = nil
end
end | [
"def",
"setPieceRequested",
"(",
"pieceIndex",
",",
"bool",
")",
"if",
"bool",
"@requestedPieces",
".",
"set",
"pieceIndex",
"@pieceRequestTime",
"[",
"pieceIndex",
"]",
"=",
"Time",
".",
"new",
"else",
"@requestedPieces",
".",
"clear",
"pieceIndex",
"@pieceRequestTime",
"[",
"pieceIndex",
"]",
"=",
"nil",
"end",
"end"
] | Set whether the piece with the passed pieceIndex is requested or not. | [
"Set",
"whether",
"the",
"piece",
"with",
"the",
"passed",
"pieceIndex",
"is",
"requested",
"or",
"not",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/metainfopiecestate.rb#L217-L225 |
2,190 | jeffwilliams/quartz-torrent | lib/quartz_torrent/metainfopiecestate.rb | QuartzTorrent.MetainfoPieceState.removeOldRequests | def removeOldRequests
now = Time.new
@requestedPieces.length.times do |i|
if @requestedPieces.set? i
if now - @pieceRequestTime[i] > @requestTimeout
@requestedPieces.clear i
@pieceRequestTime[i] = nil
end
end
end
end | ruby | def removeOldRequests
now = Time.new
@requestedPieces.length.times do |i|
if @requestedPieces.set? i
if now - @pieceRequestTime[i] > @requestTimeout
@requestedPieces.clear i
@pieceRequestTime[i] = nil
end
end
end
end | [
"def",
"removeOldRequests",
"now",
"=",
"Time",
".",
"new",
"@requestedPieces",
".",
"length",
".",
"times",
"do",
"|",
"i",
"|",
"if",
"@requestedPieces",
".",
"set?",
"i",
"if",
"now",
"-",
"@pieceRequestTime",
"[",
"i",
"]",
">",
"@requestTimeout",
"@requestedPieces",
".",
"clear",
"i",
"@pieceRequestTime",
"[",
"i",
"]",
"=",
"nil",
"end",
"end",
"end",
"end"
] | Remove any pending requests after a timeout. | [
"Remove",
"any",
"pending",
"requests",
"after",
"a",
"timeout",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/metainfopiecestate.rb#L263-L273 |
2,191 | jeffwilliams/quartz-torrent | lib/quartz_torrent/reactor.rb | QuartzTorrent.Handler.scheduleTimer | def scheduleTimer(duration, metainfo = nil, recurring = true, immed = false)
@reactor.scheduleTimer(duration, metainfo, recurring, immed) if @reactor
end | ruby | def scheduleTimer(duration, metainfo = nil, recurring = true, immed = false)
@reactor.scheduleTimer(duration, metainfo, recurring, immed) if @reactor
end | [
"def",
"scheduleTimer",
"(",
"duration",
",",
"metainfo",
"=",
"nil",
",",
"recurring",
"=",
"true",
",",
"immed",
"=",
"false",
")",
"@reactor",
".",
"scheduleTimer",
"(",
"duration",
",",
"metainfo",
",",
"recurring",
",",
"immed",
")",
"if",
"@reactor",
"end"
] | Schedule a timer.
@param duration The duration of the timer in seconds
@param metainfo The metainfo to associate with the timer
@param recurring If true when the timer duration expires, the timer will be rescheduled. If false the timer
will not be rescheduled.
@param immed If true then the timer will expire immediately (the next pass through the event loop). If the timer
is also recurring it will then be rescheduled according to it's duratoin. | [
"Schedule",
"a",
"timer",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/reactor.rb#L75-L77 |
2,192 | jeffwilliams/quartz-torrent | lib/quartz_torrent/reactor.rb | QuartzTorrent.Handler.connect | def connect(addr, port, metainfo, timeout = nil)
@reactor.connect(addr, port, metainfo, timeout) if @reactor
end | ruby | def connect(addr, port, metainfo, timeout = nil)
@reactor.connect(addr, port, metainfo, timeout) if @reactor
end | [
"def",
"connect",
"(",
"addr",
",",
"port",
",",
"metainfo",
",",
"timeout",
"=",
"nil",
")",
"@reactor",
".",
"connect",
"(",
"addr",
",",
"port",
",",
"metainfo",
",",
"timeout",
")",
"if",
"@reactor",
"end"
] | Create a TCP connection to the specified host and port. Associate the passed metainfo with the IO representing the connection. | [
"Create",
"a",
"TCP",
"connection",
"to",
"the",
"specified",
"host",
"and",
"port",
".",
"Associate",
"the",
"passed",
"metainfo",
"with",
"the",
"IO",
"representing",
"the",
"connection",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/reactor.rb#L86-L88 |
2,193 | jeffwilliams/quartz-torrent | lib/quartz_torrent/reactor.rb | QuartzTorrent.IoFacade.read | def read(length)
data = ''
while data.length < length
begin
toRead = length-data.length
rateLimited = false
if @ioInfo.readRateLimit
avail = @ioInfo.readRateLimit.avail.to_i
if avail < toRead
toRead = avail
rateLimited = true
end
@ioInfo.readRateLimit.withdraw toRead
end
@logger.debug "IoFacade: must read: #{length} have read: #{data.length}. Reading #{toRead} bytes now" if @logger
data << @io.read_nonblock(toRead) if toRead > 0
# If we tried to read more than we are allowed to by rate limiting, yield.
Fiber.yield if rateLimited
rescue Errno::EWOULDBLOCK
# Wait for more data.
@logger.debug "IoFacade: read would block" if @logger
Fiber.yield
rescue Errno::EAGAIN, Errno::EINTR
# Wait for more data.
@logger.debug "IoFacade: read was interrupted" if @logger
Fiber.yield
rescue
@logger.debug "IoFacade: read error: #{$!}" if @logger
# Read failure occurred
@ioInfo.lastReadError = $!
if @ioInfo.useErrorhandler
@ioInfo.state = :error
Fiber.yield
else
raise $!
end
end
end
data
end | ruby | def read(length)
data = ''
while data.length < length
begin
toRead = length-data.length
rateLimited = false
if @ioInfo.readRateLimit
avail = @ioInfo.readRateLimit.avail.to_i
if avail < toRead
toRead = avail
rateLimited = true
end
@ioInfo.readRateLimit.withdraw toRead
end
@logger.debug "IoFacade: must read: #{length} have read: #{data.length}. Reading #{toRead} bytes now" if @logger
data << @io.read_nonblock(toRead) if toRead > 0
# If we tried to read more than we are allowed to by rate limiting, yield.
Fiber.yield if rateLimited
rescue Errno::EWOULDBLOCK
# Wait for more data.
@logger.debug "IoFacade: read would block" if @logger
Fiber.yield
rescue Errno::EAGAIN, Errno::EINTR
# Wait for more data.
@logger.debug "IoFacade: read was interrupted" if @logger
Fiber.yield
rescue
@logger.debug "IoFacade: read error: #{$!}" if @logger
# Read failure occurred
@ioInfo.lastReadError = $!
if @ioInfo.useErrorhandler
@ioInfo.state = :error
Fiber.yield
else
raise $!
end
end
end
data
end | [
"def",
"read",
"(",
"length",
")",
"data",
"=",
"''",
"while",
"data",
".",
"length",
"<",
"length",
"begin",
"toRead",
"=",
"length",
"-",
"data",
".",
"length",
"rateLimited",
"=",
"false",
"if",
"@ioInfo",
".",
"readRateLimit",
"avail",
"=",
"@ioInfo",
".",
"readRateLimit",
".",
"avail",
".",
"to_i",
"if",
"avail",
"<",
"toRead",
"toRead",
"=",
"avail",
"rateLimited",
"=",
"true",
"end",
"@ioInfo",
".",
"readRateLimit",
".",
"withdraw",
"toRead",
"end",
"@logger",
".",
"debug",
"\"IoFacade: must read: #{length} have read: #{data.length}. Reading #{toRead} bytes now\"",
"if",
"@logger",
"data",
"<<",
"@io",
".",
"read_nonblock",
"(",
"toRead",
")",
"if",
"toRead",
">",
"0",
"# If we tried to read more than we are allowed to by rate limiting, yield.",
"Fiber",
".",
"yield",
"if",
"rateLimited",
"rescue",
"Errno",
"::",
"EWOULDBLOCK",
"# Wait for more data.",
"@logger",
".",
"debug",
"\"IoFacade: read would block\"",
"if",
"@logger",
"Fiber",
".",
"yield",
"rescue",
"Errno",
"::",
"EAGAIN",
",",
"Errno",
"::",
"EINTR",
"# Wait for more data.",
"@logger",
".",
"debug",
"\"IoFacade: read was interrupted\"",
"if",
"@logger",
"Fiber",
".",
"yield",
"rescue",
"@logger",
".",
"debug",
"\"IoFacade: read error: #{$!}\"",
"if",
"@logger",
"# Read failure occurred",
"@ioInfo",
".",
"lastReadError",
"=",
"$!",
"if",
"@ioInfo",
".",
"useErrorhandler",
"@ioInfo",
".",
"state",
"=",
":error",
"Fiber",
".",
"yield",
"else",
"raise",
"$!",
"end",
"end",
"end",
"data",
"end"
] | Read `length` bytes. | [
"Read",
"length",
"bytes",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/reactor.rb#L230-L269 |
2,194 | jeffwilliams/quartz-torrent | lib/quartz_torrent/reactor.rb | QuartzTorrent.Reactor.connect | def connect(addr, port, metainfo, timeout = nil)
ioInfo = startConnection(port, addr, metainfo)
@ioInfo[ioInfo.io] = ioInfo
if timeout && ioInfo.state == :connecting
ioInfo.connectTimeout = timeout
ioInfo.connectTimer = scheduleTimer(timeout, InternalTimerInfo.new(:connect_timeout, ioInfo), false)
end
end | ruby | def connect(addr, port, metainfo, timeout = nil)
ioInfo = startConnection(port, addr, metainfo)
@ioInfo[ioInfo.io] = ioInfo
if timeout && ioInfo.state == :connecting
ioInfo.connectTimeout = timeout
ioInfo.connectTimer = scheduleTimer(timeout, InternalTimerInfo.new(:connect_timeout, ioInfo), false)
end
end | [
"def",
"connect",
"(",
"addr",
",",
"port",
",",
"metainfo",
",",
"timeout",
"=",
"nil",
")",
"ioInfo",
"=",
"startConnection",
"(",
"port",
",",
"addr",
",",
"metainfo",
")",
"@ioInfo",
"[",
"ioInfo",
".",
"io",
"]",
"=",
"ioInfo",
"if",
"timeout",
"&&",
"ioInfo",
".",
"state",
"==",
":connecting",
"ioInfo",
".",
"connectTimeout",
"=",
"timeout",
"ioInfo",
".",
"connectTimer",
"=",
"scheduleTimer",
"(",
"timeout",
",",
"InternalTimerInfo",
".",
"new",
"(",
":connect_timeout",
",",
"ioInfo",
")",
",",
"false",
")",
"end",
"end"
] | Create a TCP connection to the specified host.
Note that this method may raise exceptions. For example 'Too many open files' might be raised if
the process is using too many file descriptors | [
"Create",
"a",
"TCP",
"connection",
"to",
"the",
"specified",
"host",
".",
"Note",
"that",
"this",
"method",
"may",
"raise",
"exceptions",
".",
"For",
"example",
"Too",
"many",
"open",
"files",
"might",
"be",
"raised",
"if",
"the",
"process",
"is",
"using",
"too",
"many",
"file",
"descriptors"
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/reactor.rb#L422-L429 |
2,195 | jeffwilliams/quartz-torrent | lib/quartz_torrent/reactor.rb | QuartzTorrent.Reactor.listen | def listen(addr, port, metainfo)
listener = Socket.new( AF_INET, SOCK_STREAM, 0 )
sockaddr = Socket.pack_sockaddr_in( port, "0.0.0.0" )
listener.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
listener.bind( sockaddr )
@logger.debug "listening on port #{port}" if @logger
listener.listen( @listenBacklog )
info = IOInfo.new(listener, metainfo)
info.readFiberIoFacade.logger = @logger if @logger
info.state = :listening
@ioInfo[info.io] = info
end | ruby | def listen(addr, port, metainfo)
listener = Socket.new( AF_INET, SOCK_STREAM, 0 )
sockaddr = Socket.pack_sockaddr_in( port, "0.0.0.0" )
listener.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
listener.bind( sockaddr )
@logger.debug "listening on port #{port}" if @logger
listener.listen( @listenBacklog )
info = IOInfo.new(listener, metainfo)
info.readFiberIoFacade.logger = @logger if @logger
info.state = :listening
@ioInfo[info.io] = info
end | [
"def",
"listen",
"(",
"addr",
",",
"port",
",",
"metainfo",
")",
"listener",
"=",
"Socket",
".",
"new",
"(",
"AF_INET",
",",
"SOCK_STREAM",
",",
"0",
")",
"sockaddr",
"=",
"Socket",
".",
"pack_sockaddr_in",
"(",
"port",
",",
"\"0.0.0.0\"",
")",
"listener",
".",
"setsockopt",
"(",
"Socket",
"::",
"SOL_SOCKET",
",",
"Socket",
"::",
"SO_REUSEADDR",
",",
"true",
")",
"listener",
".",
"bind",
"(",
"sockaddr",
")",
"@logger",
".",
"debug",
"\"listening on port #{port}\"",
"if",
"@logger",
"listener",
".",
"listen",
"(",
"@listenBacklog",
")",
"info",
"=",
"IOInfo",
".",
"new",
"(",
"listener",
",",
"metainfo",
")",
"info",
".",
"readFiberIoFacade",
".",
"logger",
"=",
"@logger",
"if",
"@logger",
"info",
".",
"state",
"=",
":listening",
"@ioInfo",
"[",
"info",
".",
"io",
"]",
"=",
"info",
"end"
] | Create a TCP server that listens for connections on the specified
port | [
"Create",
"a",
"TCP",
"server",
"that",
"listens",
"for",
"connections",
"on",
"the",
"specified",
"port"
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/reactor.rb#L433-L445 |
2,196 | jeffwilliams/quartz-torrent | lib/quartz_torrent/reactor.rb | QuartzTorrent.Reactor.open | def open(path, mode, metainfo, useErrorhandler = true)
file = File.open(path, mode)
info = IOInfo.new(file, metainfo, true)
info.useErrorhandler = useErrorhandler
info.readFiberIoFacade.logger = @logger if @logger
info.state = :connected
@ioInfo[info.io] = info
end | ruby | def open(path, mode, metainfo, useErrorhandler = true)
file = File.open(path, mode)
info = IOInfo.new(file, metainfo, true)
info.useErrorhandler = useErrorhandler
info.readFiberIoFacade.logger = @logger if @logger
info.state = :connected
@ioInfo[info.io] = info
end | [
"def",
"open",
"(",
"path",
",",
"mode",
",",
"metainfo",
",",
"useErrorhandler",
"=",
"true",
")",
"file",
"=",
"File",
".",
"open",
"(",
"path",
",",
"mode",
")",
"info",
"=",
"IOInfo",
".",
"new",
"(",
"file",
",",
"metainfo",
",",
"true",
")",
"info",
".",
"useErrorhandler",
"=",
"useErrorhandler",
"info",
".",
"readFiberIoFacade",
".",
"logger",
"=",
"@logger",
"if",
"@logger",
"info",
".",
"state",
"=",
":connected",
"@ioInfo",
"[",
"info",
".",
"io",
"]",
"=",
"info",
"end"
] | Open the specified file for the specified mode. | [
"Open",
"the",
"specified",
"file",
"for",
"the",
"specified",
"mode",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/reactor.rb#L448-L456 |
2,197 | jeffwilliams/quartz-torrent | lib/quartz_torrent/reactor.rb | QuartzTorrent.Reactor.start | def start
while true
begin
break if eventLoopBody == :halt
rescue
@logger.error "Unexpected exception in reactor event loop: #{$!}" if @logger
@logger.error $!.backtrace.join "\n" if @logger
end
end
@logger.info "Reactor shutting down" if @logger
# Event loop finished
@ioInfo.each do |k,v|
k.close
end
end | ruby | def start
while true
begin
break if eventLoopBody == :halt
rescue
@logger.error "Unexpected exception in reactor event loop: #{$!}" if @logger
@logger.error $!.backtrace.join "\n" if @logger
end
end
@logger.info "Reactor shutting down" if @logger
# Event loop finished
@ioInfo.each do |k,v|
k.close
end
end | [
"def",
"start",
"while",
"true",
"begin",
"break",
"if",
"eventLoopBody",
"==",
":halt",
"rescue",
"@logger",
".",
"error",
"\"Unexpected exception in reactor event loop: #{$!}\"",
"if",
"@logger",
"@logger",
".",
"error",
"$!",
".",
"backtrace",
".",
"join",
"\"\\n\"",
"if",
"@logger",
"end",
"end",
"@logger",
".",
"info",
"\"Reactor shutting down\"",
"if",
"@logger",
"# Event loop finished",
"@ioInfo",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"k",
".",
"close",
"end",
"end"
] | Run event loop | [
"Run",
"event",
"loop"
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/reactor.rb#L465-L482 |
2,198 | jeffwilliams/quartz-torrent | lib/quartz_torrent/reactor.rb | QuartzTorrent.Reactor.findIoByMetainfo | def findIoByMetainfo(metainfo)
@ioInfo.each_value do |info|
if info.metainfo == metainfo
io = info.readFiberIoFacade
# Don't allow read calls from timer handlers. This is to prevent a complex situation.
# See the processTimer call in eventLoopBody for more info
io = WriteOnlyIoFacade.new(info) if @currentHandlerCallback == :timer
return io
end
end
nil
end | ruby | def findIoByMetainfo(metainfo)
@ioInfo.each_value do |info|
if info.metainfo == metainfo
io = info.readFiberIoFacade
# Don't allow read calls from timer handlers. This is to prevent a complex situation.
# See the processTimer call in eventLoopBody for more info
io = WriteOnlyIoFacade.new(info) if @currentHandlerCallback == :timer
return io
end
end
nil
end | [
"def",
"findIoByMetainfo",
"(",
"metainfo",
")",
"@ioInfo",
".",
"each_value",
"do",
"|",
"info",
"|",
"if",
"info",
".",
"metainfo",
"==",
"metainfo",
"io",
"=",
"info",
".",
"readFiberIoFacade",
"# Don't allow read calls from timer handlers. This is to prevent a complex situation.",
"# See the processTimer call in eventLoopBody for more info",
"io",
"=",
"WriteOnlyIoFacade",
".",
"new",
"(",
"info",
")",
"if",
"@currentHandlerCallback",
"==",
":timer",
"return",
"io",
"end",
"end",
"nil",
"end"
] | Meant to be called from the handler. Find an IO by metainfo. The == operator is used to
match the metainfo. | [
"Meant",
"to",
"be",
"called",
"from",
"the",
"handler",
".",
"Find",
"an",
"IO",
"by",
"metainfo",
".",
"The",
"==",
"operator",
"is",
"used",
"to",
"match",
"the",
"metainfo",
"."
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/reactor.rb#L569-L580 |
2,199 | jeffwilliams/quartz-torrent | lib/quartz_torrent/reactor.rb | QuartzTorrent.Reactor.handleAccept | def handleAccept(ioInfo)
socket, clientAddr = ioInfo.io.accept
info = IOInfo.new(socket, ioInfo.metainfo)
info.readFiberIoFacade.logger = @logger if @logger
info.state = :connected
@ioInfo[info.io] = info
if @logger
port, addr = Socket.unpack_sockaddr_in(clientAddr)
@logger.debug "Accepted connection from #{addr}:#{port}" if @logger
end
[info, addr, port]
end | ruby | def handleAccept(ioInfo)
socket, clientAddr = ioInfo.io.accept
info = IOInfo.new(socket, ioInfo.metainfo)
info.readFiberIoFacade.logger = @logger if @logger
info.state = :connected
@ioInfo[info.io] = info
if @logger
port, addr = Socket.unpack_sockaddr_in(clientAddr)
@logger.debug "Accepted connection from #{addr}:#{port}" if @logger
end
[info, addr, port]
end | [
"def",
"handleAccept",
"(",
"ioInfo",
")",
"socket",
",",
"clientAddr",
"=",
"ioInfo",
".",
"io",
".",
"accept",
"info",
"=",
"IOInfo",
".",
"new",
"(",
"socket",
",",
"ioInfo",
".",
"metainfo",
")",
"info",
".",
"readFiberIoFacade",
".",
"logger",
"=",
"@logger",
"if",
"@logger",
"info",
".",
"state",
"=",
":connected",
"@ioInfo",
"[",
"info",
".",
"io",
"]",
"=",
"info",
"if",
"@logger",
"port",
",",
"addr",
"=",
"Socket",
".",
"unpack_sockaddr_in",
"(",
"clientAddr",
")",
"@logger",
".",
"debug",
"\"Accepted connection from #{addr}:#{port}\"",
"if",
"@logger",
"end",
"[",
"info",
",",
"addr",
",",
"port",
"]",
"end"
] | Given the ioInfo for a listening socket, call accept and return the new ioInfo for the
client's socket | [
"Given",
"the",
"ioInfo",
"for",
"a",
"listening",
"socket",
"call",
"accept",
"and",
"return",
"the",
"new",
"ioInfo",
"for",
"the",
"client",
"s",
"socket"
] | 7aeb40125d886dd60d7481deb5129282fc3e3c06 | https://github.com/jeffwilliams/quartz-torrent/blob/7aeb40125d886dd60d7481deb5129282fc3e3c06/lib/quartz_torrent/reactor.rb#L813-L825 |
Subsets and Splits