repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
sugaryourcoffee/syc-svpro | lib/sycsvpro/spread_sheet.rb | Sycsvpro.SpreadSheet.to_s | def to_s
col_label_sizes = col_labels.collect { |c| c.to_s.size + 2 }
row_label_size = row_labels.collect { |r| r.to_s.size + 2 }.max
row_col_sizes = rows.transpose.collect { |r| r.collect { |c| c.to_s.size } }
i = -1
col_sizes = col_label_sizes.collect do |s|
i += 1
[row_col_sizes[i],s].flatten.max + 1
end
s = (sprintf("%#{row_label_size}s", " "))
col_labels.each_with_index { |l,i| s << (sprintf("%#{col_sizes[i]}s",
"[#{l}]")) }
s << "\n"
rows.each_with_index do |row, i|
s << (sprintf("%#{row_label_size}s", "[#{row_labels[i]}]"))
row.each_with_index { |c,j| s << (sprintf("%#{col_sizes[j]}s", c)) }
s << "\n"
end
s
end | ruby | def to_s
col_label_sizes = col_labels.collect { |c| c.to_s.size + 2 }
row_label_size = row_labels.collect { |r| r.to_s.size + 2 }.max
row_col_sizes = rows.transpose.collect { |r| r.collect { |c| c.to_s.size } }
i = -1
col_sizes = col_label_sizes.collect do |s|
i += 1
[row_col_sizes[i],s].flatten.max + 1
end
s = (sprintf("%#{row_label_size}s", " "))
col_labels.each_with_index { |l,i| s << (sprintf("%#{col_sizes[i]}s",
"[#{l}]")) }
s << "\n"
rows.each_with_index do |row, i|
s << (sprintf("%#{row_label_size}s", "[#{row_labels[i]}]"))
row.each_with_index { |c,j| s << (sprintf("%#{col_sizes[j]}s", c)) }
s << "\n"
end
s
end | [
"def",
"to_s",
"col_label_sizes",
"=",
"col_labels",
".",
"collect",
"{",
"|",
"c",
"|",
"c",
".",
"to_s",
".",
"size",
"+",
"2",
"}",
"row_label_size",
"=",
"row_labels",
".",
"collect",
"{",
"|",
"r",
"|",
"r",
".",
"to_s",
".",
"size",
"+",
"2",... | Prints the spread sheet in a matrix with column labels and row labels. If
no labels are available the column number and row number is printed | [
"Prints",
"the",
"spread",
"sheet",
"in",
"a",
"matrix",
"with",
"column",
"labels",
"and",
"row",
"labels",
".",
"If",
"no",
"labels",
"are",
"available",
"the",
"column",
"number",
"and",
"row",
"number",
"is",
"printed"
] | a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3 | https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/spread_sheet.rb#L370-L394 | valid |
sugaryourcoffee/syc-svpro | lib/sycsvpro/spread_sheet.rb | Sycsvpro.SpreadSheet.rows_from_params | def rows_from_params(opts)
col_count = opts[:cols]
row_count = opts[:rows]
size = row_count * col_count if row_count && col_count
rows = []
if values = opts[:values]
if size
values += [NotAvailable] * (size - values.size)
elsif col_count
values += [NotAvailable] * ((col_count - values.size) % col_count)
elsif row_count
values += [NotAvailable] * ((row_count - values.size) % row_count)
col_count = values.size / row_count
else
col_count = Math.sqrt(values.size).ceil
values += [NotAvailable] * ((col_count - values.size) % col_count)
end
values.each_slice(col_count) { |row| rows << row }
elsif opts[:file]
File.foreach(opts[:file]) do |line|
next if line.chomp.empty?
values = line.split(SEMICOLON) rescue str2utf8(line).split(SEMICOLON)
rows << values.collect { |v|
v.strip.empty? ? NotAvailable : str2num(v.chomp, opts[:ds])
}
end
end
rows
end | ruby | def rows_from_params(opts)
col_count = opts[:cols]
row_count = opts[:rows]
size = row_count * col_count if row_count && col_count
rows = []
if values = opts[:values]
if size
values += [NotAvailable] * (size - values.size)
elsif col_count
values += [NotAvailable] * ((col_count - values.size) % col_count)
elsif row_count
values += [NotAvailable] * ((row_count - values.size) % row_count)
col_count = values.size / row_count
else
col_count = Math.sqrt(values.size).ceil
values += [NotAvailable] * ((col_count - values.size) % col_count)
end
values.each_slice(col_count) { |row| rows << row }
elsif opts[:file]
File.foreach(opts[:file]) do |line|
next if line.chomp.empty?
values = line.split(SEMICOLON) rescue str2utf8(line).split(SEMICOLON)
rows << values.collect { |v|
v.strip.empty? ? NotAvailable : str2num(v.chomp, opts[:ds])
}
end
end
rows
end | [
"def",
"rows_from_params",
"(",
"opts",
")",
"col_count",
"=",
"opts",
"[",
":cols",
"]",
"row_count",
"=",
"opts",
"[",
":rows",
"]",
"size",
"=",
"row_count",
"*",
"col_count",
"if",
"row_count",
"&&",
"col_count",
"rows",
"=",
"[",
"]",
"if",
"values"... | Creates rows from provided array or file. If array doesn't provide
equal column sizes the array is extended with NotAvailable values | [
"Creates",
"rows",
"from",
"provided",
"array",
"or",
"file",
".",
"If",
"array",
"doesn",
"t",
"provide",
"equal",
"column",
"sizes",
"the",
"array",
"is",
"extended",
"with",
"NotAvailable",
"values"
] | a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3 | https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/spread_sheet.rb#L400-L432 | valid |
sugaryourcoffee/syc-svpro | lib/sycsvpro/spread_sheet.rb | Sycsvpro.SpreadSheet.equalize_rows | def equalize_rows(rows)
column_sizes = rows.collect { |r| r.size }
return rows if column_sizes.uniq.size == 1
max_size = column_sizes.max
small_rows = []
column_sizes.each_with_index { |c,i| small_rows << i if c < max_size }
small_rows.each do |i|
rows[i] += [NotAvailable] * (max_size - rows[i].size)
end
rows
end | ruby | def equalize_rows(rows)
column_sizes = rows.collect { |r| r.size }
return rows if column_sizes.uniq.size == 1
max_size = column_sizes.max
small_rows = []
column_sizes.each_with_index { |c,i| small_rows << i if c < max_size }
small_rows.each do |i|
rows[i] += [NotAvailable] * (max_size - rows[i].size)
end
rows
end | [
"def",
"equalize_rows",
"(",
"rows",
")",
"column_sizes",
"=",
"rows",
".",
"collect",
"{",
"|",
"r",
"|",
"r",
".",
"size",
"}",
"return",
"rows",
"if",
"column_sizes",
".",
"uniq",
".",
"size",
"==",
"1",
"max_size",
"=",
"column_sizes",
".",
"max",
... | If rows are of different column size the rows are equalized in column
size by filling missing columns with NA | [
"If",
"rows",
"are",
"of",
"different",
"column",
"size",
"the",
"rows",
"are",
"equalized",
"in",
"column",
"size",
"by",
"filling",
"missing",
"columns",
"with",
"NA"
] | a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3 | https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/spread_sheet.rb#L436-L450 | valid |
sugaryourcoffee/syc-svpro | lib/sycsvpro/spread_sheet.rb | Sycsvpro.SpreadSheet.same_column_size? | def same_column_size?(rows)
offset = opts[:c] ? 1 : 0
return true if rows.size == 1 + offset
(0 + offset).upto(rows.size - 2) do |i|
return false unless rows[i].size == rows[i+1].size
end
true
end | ruby | def same_column_size?(rows)
offset = opts[:c] ? 1 : 0
return true if rows.size == 1 + offset
(0 + offset).upto(rows.size - 2) do |i|
return false unless rows[i].size == rows[i+1].size
end
true
end | [
"def",
"same_column_size?",
"(",
"rows",
")",
"offset",
"=",
"opts",
"[",
":c",
"]",
"?",
"1",
":",
"0",
"return",
"true",
"if",
"rows",
".",
"size",
"==",
"1",
"+",
"offset",
"(",
"0",
"+",
"offset",
")",
".",
"upto",
"(",
"rows",
".",
"size",
... | Checks whether all rows have the same column size. Returns true if
all columns have the same column size | [
"Checks",
"whether",
"all",
"rows",
"have",
"the",
"same",
"column",
"size",
".",
"Returns",
"true",
"if",
"all",
"columns",
"have",
"the",
"same",
"column",
"size"
] | a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3 | https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/spread_sheet.rb#L465-L472 | valid |
sugaryourcoffee/syc-svpro | lib/sycsvpro/spread_sheet.rb | Sycsvpro.SpreadSheet.coerce | def coerce(value)
return SpreadSheet.new([value]) if value.is_a?(Numeric)
return SpreadSheet.new(value) if value.is_a?(Array)
end | ruby | def coerce(value)
return SpreadSheet.new([value]) if value.is_a?(Numeric)
return SpreadSheet.new(value) if value.is_a?(Array)
end | [
"def",
"coerce",
"(",
"value",
")",
"return",
"SpreadSheet",
".",
"new",
"(",
"[",
"value",
"]",
")",
"if",
"value",
".",
"is_a?",
"(",
"Numeric",
")",
"return",
"SpreadSheet",
".",
"new",
"(",
"value",
")",
"if",
"value",
".",
"is_a?",
"(",
"Array",... | Coerces a number or an array to a spread sheet | [
"Coerces",
"a",
"number",
"or",
"an",
"array",
"to",
"a",
"spread",
"sheet"
] | a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3 | https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/spread_sheet.rb#L534-L537 | valid |
sugaryourcoffee/syc-svpro | lib/sycsvpro/spread_sheet.rb | Sycsvpro.SpreadSheet.process | def process(operator, s)
s = coerce(s) || s
raise "operand needs to be a SpreadSheet, "+
"Numeric or Array" unless s.is_a?(SpreadSheet)
result = []
rlabel = []
clabel = []
s1_row_count, s1_col_count = dim
s2_row_count, s2_col_count = s.dim
row_count = [s1_row_count, s2_row_count].max
col_count = [s1_col_count, s2_col_count].max
0.upto(row_count - 1) do |r|
r1 = r % s1_row_count
r2 = r % s2_row_count
rlabel << "#{row_labels[r1]}#{operator}#{s.row_labels[r2]}"
element = []
0.upto(col_count - 1) do |c|
c1 = c % s1_col_count
c2 = c % s2_col_count
clabel << "#{col_labels[c1]}#{operator}#{s.col_labels[c2]}"
element << rows[r1][c1].send(operator, s.rows[r2][c2])
end
result << element
end
SpreadSheet.new(*result, row_labels: rlabel, col_labels: clabel)
end | ruby | def process(operator, s)
s = coerce(s) || s
raise "operand needs to be a SpreadSheet, "+
"Numeric or Array" unless s.is_a?(SpreadSheet)
result = []
rlabel = []
clabel = []
s1_row_count, s1_col_count = dim
s2_row_count, s2_col_count = s.dim
row_count = [s1_row_count, s2_row_count].max
col_count = [s1_col_count, s2_col_count].max
0.upto(row_count - 1) do |r|
r1 = r % s1_row_count
r2 = r % s2_row_count
rlabel << "#{row_labels[r1]}#{operator}#{s.row_labels[r2]}"
element = []
0.upto(col_count - 1) do |c|
c1 = c % s1_col_count
c2 = c % s2_col_count
clabel << "#{col_labels[c1]}#{operator}#{s.col_labels[c2]}"
element << rows[r1][c1].send(operator, s.rows[r2][c2])
end
result << element
end
SpreadSheet.new(*result, row_labels: rlabel, col_labels: clabel)
end | [
"def",
"process",
"(",
"operator",
",",
"s",
")",
"s",
"=",
"coerce",
"(",
"s",
")",
"||",
"s",
"raise",
"\"operand needs to be a SpreadSheet, \"",
"+",
"\"Numeric or Array\"",
"unless",
"s",
".",
"is_a?",
"(",
"SpreadSheet",
")",
"result",
"=",
"[",
"]",
... | Conducts the calculation of this spread sheet with the provided value
based on the operator. It s is a number or an array it is coerced into
a spread sheet | [
"Conducts",
"the",
"calculation",
"of",
"this",
"spread",
"sheet",
"with",
"the",
"provided",
"value",
"based",
"on",
"the",
"operator",
".",
"It",
"s",
"is",
"a",
"number",
"or",
"an",
"array",
"it",
"is",
"coerced",
"into",
"a",
"spread",
"sheet"
] | a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3 | https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/spread_sheet.rb#L542-L567 | valid |
sugaryourcoffee/syc-svpro | lib/sycsvpro/counter.rb | Sycsvpro.Counter.process_count | def process_count
File.new(infile).each_with_index do |line, index|
result = col_filter.process(row_filter.process(line.chomp, row: index))
unless result.nil? or result.empty?
key = unstring(line).split(';').values_at(*key_columns)
key_value = key_values[key] || key_values[key] = { name: key,
elements: Hash.new(0),
sum: 0 }
result.chomp.split(';').each do |column|
heading << column if heading.index(column).nil?
key_value[:elements][column] += 1
key_value[:sum] += 1
sums[column] += 1
end
end
end
end | ruby | def process_count
File.new(infile).each_with_index do |line, index|
result = col_filter.process(row_filter.process(line.chomp, row: index))
unless result.nil? or result.empty?
key = unstring(line).split(';').values_at(*key_columns)
key_value = key_values[key] || key_values[key] = { name: key,
elements: Hash.new(0),
sum: 0 }
result.chomp.split(';').each do |column|
heading << column if heading.index(column).nil?
key_value[:elements][column] += 1
key_value[:sum] += 1
sums[column] += 1
end
end
end
end | [
"def",
"process_count",
"File",
".",
"new",
"(",
"infile",
")",
".",
"each_with_index",
"do",
"|",
"line",
",",
"index",
"|",
"result",
"=",
"col_filter",
".",
"process",
"(",
"row_filter",
".",
"process",
"(",
"line",
".",
"chomp",
",",
"row",
":",
"i... | Processes the counting on the in file | [
"Processes",
"the",
"counting",
"on",
"the",
"in",
"file"
] | a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3 | https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/counter.rb#L63-L79 | valid |
sugaryourcoffee/syc-svpro | lib/sycsvpro/counter.rb | Sycsvpro.Counter.write_result | def write_result
sum_line = [sum_row_title] + [''] * (key_titles.size - 1)
headline = heading_sort ? heading.sort : original_pivot_sequence_heading
headline << add_sum_col unless sum_col_title.nil?
headline.each do |h|
sum_line << sums[h]
end
row = 0;
File.open(outfile, 'w') do |out|
out.puts sum_line.join(';') if row == sum_row ; row += 1
out.puts (key_titles + headline).join(';')
key_values.each do |k,v|
out.puts sum_line.join(';') if row == sum_row ; row += 1
line = [k]
headline.each do |h|
line << v[:elements][h] unless h == sum_col_title
end
line << v[:sum] unless sum_col_title.nil?
out.puts line.join(';')
end
end
end | ruby | def write_result
sum_line = [sum_row_title] + [''] * (key_titles.size - 1)
headline = heading_sort ? heading.sort : original_pivot_sequence_heading
headline << add_sum_col unless sum_col_title.nil?
headline.each do |h|
sum_line << sums[h]
end
row = 0;
File.open(outfile, 'w') do |out|
out.puts sum_line.join(';') if row == sum_row ; row += 1
out.puts (key_titles + headline).join(';')
key_values.each do |k,v|
out.puts sum_line.join(';') if row == sum_row ; row += 1
line = [k]
headline.each do |h|
line << v[:elements][h] unless h == sum_col_title
end
line << v[:sum] unless sum_col_title.nil?
out.puts line.join(';')
end
end
end | [
"def",
"write_result",
"sum_line",
"=",
"[",
"sum_row_title",
"]",
"+",
"[",
"''",
"]",
"*",
"(",
"key_titles",
".",
"size",
"-",
"1",
")",
"headline",
"=",
"heading_sort",
"?",
"heading",
".",
"sort",
":",
"original_pivot_sequence_heading",
"headline",
"<<"... | Writes the count results | [
"Writes",
"the",
"count",
"results"
] | a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3 | https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/counter.rb#L82-L103 | valid |
sugaryourcoffee/syc-svpro | lib/sycsvpro/counter.rb | Sycsvpro.Counter.init_sum_scheme | def init_sum_scheme(sum_scheme)
return if sum_scheme.nil?
re = /(\w+):(\d+)|(\w+)/
sum_scheme.scan(re).each do |part|
if part.compact.size == 2
@sum_row_title = part[0]
@sum_row = part[1].to_i
else
@sum_col_title = part[2]
end
end
end | ruby | def init_sum_scheme(sum_scheme)
return if sum_scheme.nil?
re = /(\w+):(\d+)|(\w+)/
sum_scheme.scan(re).each do |part|
if part.compact.size == 2
@sum_row_title = part[0]
@sum_row = part[1].to_i
else
@sum_col_title = part[2]
end
end
end | [
"def",
"init_sum_scheme",
"(",
"sum_scheme",
")",
"return",
"if",
"sum_scheme",
".",
"nil?",
"re",
"=",
"/",
"\\w",
"\\d",
"\\w",
"/",
"sum_scheme",
".",
"scan",
"(",
"re",
")",
".",
"each",
"do",
"|",
"part",
"|",
"if",
"part",
".",
"compact",
".",
... | Initializes the sum row title an positions as well as the sum column
title | [
"Initializes",
"the",
"sum",
"row",
"title",
"an",
"positions",
"as",
"well",
"as",
"the",
"sum",
"column",
"title"
] | a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3 | https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/counter.rb#L109-L124 | valid |
sugaryourcoffee/syc-svpro | lib/sycsvpro/counter.rb | Sycsvpro.Counter.init_key_columns | def init_key_columns(key_scheme)
@key_titles = []
@key_columns = []
keys = key_scheme.scan(/(\d+):(\w+)/)
keys.each do |key|
@key_titles << key[1]
@key_columns << key[0].to_i
end
end | ruby | def init_key_columns(key_scheme)
@key_titles = []
@key_columns = []
keys = key_scheme.scan(/(\d+):(\w+)/)
keys.each do |key|
@key_titles << key[1]
@key_columns << key[0].to_i
end
end | [
"def",
"init_key_columns",
"(",
"key_scheme",
")",
"@key_titles",
"=",
"[",
"]",
"@key_columns",
"=",
"[",
"]",
"keys",
"=",
"key_scheme",
".",
"scan",
"(",
"/",
"\\d",
"\\w",
"/",
")",
"keys",
".",
"each",
"do",
"|",
"key",
"|",
"@key_titles",
"<<",
... | Initialize the key columns and headers | [
"Initialize",
"the",
"key",
"columns",
"and",
"headers"
] | a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3 | https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/counter.rb#L127-L139 | valid |
sugaryourcoffee/syc-svpro | lib/sycsvpro/counter.rb | Sycsvpro.Counter.original_pivot_sequence_heading | def original_pivot_sequence_heading
(heading.sort - col_filter.pivot.keys << col_filter.pivot.keys).flatten
end | ruby | def original_pivot_sequence_heading
(heading.sort - col_filter.pivot.keys << col_filter.pivot.keys).flatten
end | [
"def",
"original_pivot_sequence_heading",
"(",
"heading",
".",
"sort",
"-",
"col_filter",
".",
"pivot",
".",
"keys",
"<<",
"col_filter",
".",
"pivot",
".",
"keys",
")",
".",
"flatten",
"end"
] | Arrange heading in the original sequence regarding conditional column
filters | [
"Arrange",
"heading",
"in",
"the",
"original",
"sequence",
"regarding",
"conditional",
"column",
"filters"
] | a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3 | https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/counter.rb#L143-L145 | valid |
sugaryourcoffee/syc-svpro | lib/sycsvpro/row_filter.rb | Sycsvpro.RowFilter.process | def process(object, options={})
object = unstring(object)
return object unless has_filter?
filtered = !filter.flatten.uniq.index(options[:row]).nil?
pattern.each do |p|
filtered = (filtered or !(object =~ Regexp.new(p)).nil?)
end
filtered = (filtered or match_boolean_filter?(object.split(';')))
filtered ? object : nil
end | ruby | def process(object, options={})
object = unstring(object)
return object unless has_filter?
filtered = !filter.flatten.uniq.index(options[:row]).nil?
pattern.each do |p|
filtered = (filtered or !(object =~ Regexp.new(p)).nil?)
end
filtered = (filtered or match_boolean_filter?(object.split(';')))
filtered ? object : nil
end | [
"def",
"process",
"(",
"object",
",",
"options",
"=",
"{",
"}",
")",
"object",
"=",
"unstring",
"(",
"object",
")",
"return",
"object",
"unless",
"has_filter?",
"filtered",
"=",
"!",
"filter",
".",
"flatten",
".",
"uniq",
".",
"index",
"(",
"options",
... | Processes the filter on the given row | [
"Processes",
"the",
"filter",
"on",
"the",
"given",
"row"
] | a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3 | https://github.com/sugaryourcoffee/syc-svpro/blob/a8f8b97283ee593b4e8d5092da46a1b0e39fc8e3/lib/sycsvpro/row_filter.rb#L13-L22 | valid |
obrie/turntabler | lib/turntabler/user.rb | Turntabler.User.messages | def messages
data = api('pm.history', :receiverid => id)
data['history'].map {|attrs| Message.new(client, attrs)}
end | ruby | def messages
data = api('pm.history', :receiverid => id)
data['history'].map {|attrs| Message.new(client, attrs)}
end | [
"def",
"messages",
"data",
"=",
"api",
"(",
"'pm.history'",
",",
":receiverid",
"=>",
"id",
")",
"data",
"[",
"'history'",
"]",
".",
"map",
"{",
"|",
"attrs",
"|",
"Message",
".",
"new",
"(",
"client",
",",
"attrs",
")",
"}",
"end"
] | Gets the private conversation history with this user.
@return [Array<Turntabler::Message>]
@raise [Turntabler::Error] if the command fails
@example
user.messages # => [#<Turntabler::Message ...>, ...] | [
"Gets",
"the",
"private",
"conversation",
"history",
"with",
"this",
"user",
"."
] | e2240f1a5d210a33c05c5b2261d291089cdcf1c6 | https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/user.rb#L153-L156 | valid |
obrie/turntabler | lib/turntabler/user.rb | Turntabler.User.stalk | def stalk
become_fan unless client.user.fan_of.include?(self)
client.rooms.with_friends.detect do |room|
room.listener(id)
end
end | ruby | def stalk
become_fan unless client.user.fan_of.include?(self)
client.rooms.with_friends.detect do |room|
room.listener(id)
end
end | [
"def",
"stalk",
"become_fan",
"unless",
"client",
".",
"user",
".",
"fan_of",
".",
"include?",
"(",
"self",
")",
"client",
".",
"rooms",
".",
"with_friends",
".",
"detect",
"do",
"|",
"room",
"|",
"room",
".",
"listener",
"(",
"id",
")",
"end",
"end"
] | Gets the location of the user.
@note This will make the current user a fan of this user
@return [Turntabler::Room]
@raise [Turntabler::Error] if the command fails
@example
user.stalk # => #<Turntabler::Room ...> | [
"Gets",
"the",
"location",
"of",
"the",
"user",
"."
] | e2240f1a5d210a33c05c5b2261d291089cdcf1c6 | https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/user.rb#L222-L227 | valid |
obrie/turntabler | lib/turntabler/user.rb | Turntabler.User.boot | def boot(reason = '')
api('room.boot_user', :roomid => room.id, :section => room.section, :target_userid => id, :reason => reason)
true
end | ruby | def boot(reason = '')
api('room.boot_user', :roomid => room.id, :section => room.section, :target_userid => id, :reason => reason)
true
end | [
"def",
"boot",
"(",
"reason",
"=",
"''",
")",
"api",
"(",
"'room.boot_user'",
",",
":roomid",
"=>",
"room",
".",
"id",
",",
":section",
"=>",
"room",
".",
"section",
",",
":target_userid",
"=>",
"id",
",",
":reason",
"=>",
"reason",
")",
"true",
"end"
... | Boots the user for the specified reason.
@param [String] reason The reason why the user is being booted
@return [true]
@raise [Turntabler::Error] if the command fails
@example
user.boot('Broke rules') # => true | [
"Boots",
"the",
"user",
"for",
"the",
"specified",
"reason",
"."
] | e2240f1a5d210a33c05c5b2261d291089cdcf1c6 | https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/user.rb#L258-L261 | valid |
obrie/turntabler | lib/turntabler/user.rb | Turntabler.User.report | def report(reason = '')
api('room.report_user', :roomid => room.id, :section => room.section, :reported => id, :reason => reason)
true
end | ruby | def report(reason = '')
api('room.report_user', :roomid => room.id, :section => room.section, :reported => id, :reason => reason)
true
end | [
"def",
"report",
"(",
"reason",
"=",
"''",
")",
"api",
"(",
"'room.report_user'",
",",
":roomid",
"=>",
"room",
".",
"id",
",",
":section",
"=>",
"room",
".",
"section",
",",
":reported",
"=>",
"id",
",",
":reason",
"=>",
"reason",
")",
"true",
"end"
] | Reports abuse by a user.
@param [String] reason The reason the user is being reported
@return [true]
@raise [Turntabler::Error] if the command fails
@example
user.report('Verbal abuse ...') # => true | [
"Reports",
"abuse",
"by",
"a",
"user",
"."
] | e2240f1a5d210a33c05c5b2261d291089cdcf1c6 | https://github.com/obrie/turntabler/blob/e2240f1a5d210a33c05c5b2261d291089cdcf1c6/lib/turntabler/user.rb#L270-L273 | valid |
caruby/tissue | lib/catissue/domain/abstract_specimen.rb | CaTissue.AbstractSpecimen.default_derived_characteristics | def default_derived_characteristics
chrs = specimen_characteristics || return
pas = chrs.class.nondomain_attributes.reject { |pa| pa == :identifier }
chrs.copy(pas)
end | ruby | def default_derived_characteristics
chrs = specimen_characteristics || return
pas = chrs.class.nondomain_attributes.reject { |pa| pa == :identifier }
chrs.copy(pas)
end | [
"def",
"default_derived_characteristics",
"chrs",
"=",
"specimen_characteristics",
"||",
"return",
"pas",
"=",
"chrs",
".",
"class",
".",
"nondomain_attributes",
".",
"reject",
"{",
"|",
"pa",
"|",
"pa",
"==",
":identifier",
"}",
"chrs",
".",
"copy",
"(",
"pas... | Returns characteristics to use for a derived specimen. The new characteristics is copied from this
parent specimen's characteristics, without the identifier.
@return [CaTissue::SpecimenCharacteristics, nil] a copy of this Specimen's specimen_characteristics, or nil if none | [
"Returns",
"characteristics",
"to",
"use",
"for",
"a",
"derived",
"specimen",
".",
"The",
"new",
"characteristics",
"is",
"copied",
"from",
"this",
"parent",
"specimen",
"s",
"characteristics",
"without",
"the",
"identifier",
"."
] | 08d99aabf4801c89842ce6dee138ccb1e4f5f56b | https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/abstract_specimen.rb#L289-L293 | valid |
weibel/MapKitWrapper | lib/map-kit-wrapper/map_view.rb | MapKit.MapView.region= | def region=(args)
case args
when Hash
self.setRegion(CoordinateRegion.new(args[:region]).api, animated: args[:animated])
else
self.setRegion(CoordinateRegion.new(args).api, animated: false)
end
end | ruby | def region=(args)
case args
when Hash
self.setRegion(CoordinateRegion.new(args[:region]).api, animated: args[:animated])
else
self.setRegion(CoordinateRegion.new(args).api, animated: false)
end
end | [
"def",
"region",
"=",
"(",
"args",
")",
"case",
"args",
"when",
"Hash",
"self",
".",
"setRegion",
"(",
"CoordinateRegion",
".",
"new",
"(",
"args",
"[",
":region",
"]",
")",
".",
"api",
",",
"animated",
":",
"args",
"[",
":animated",
"]",
")",
"else"... | Set the maps region
* *Args* :
region = CoordinateRegion.new([56, 10.6], [3.1, 3.1])
region = {:region => CoordinateRegion.new([56, 10.6], [3.1, 3.1]), :animated => false} | [
"Set",
"the",
"maps",
"region"
] | 6ad3579b77e4d9be1c23ebab6a624a7dbc4ed2e6 | https://github.com/weibel/MapKitWrapper/blob/6ad3579b77e4d9be1c23ebab6a624a7dbc4ed2e6/lib/map-kit-wrapper/map_view.rb#L110-L117 | valid |
caruby/tissue | lib/catissue/domain/participant.rb | CaTissue.Participant.collection_site | def collection_site
return unless medical_identifiers.size == 1
site = medical_identifiers.first.site
return if site.nil?
site.site_type == Site::SiteType::COLLECTION ? site : nil
end | ruby | def collection_site
return unless medical_identifiers.size == 1
site = medical_identifiers.first.site
return if site.nil?
site.site_type == Site::SiteType::COLLECTION ? site : nil
end | [
"def",
"collection_site",
"return",
"unless",
"medical_identifiers",
".",
"size",
"==",
"1",
"site",
"=",
"medical_identifiers",
".",
"first",
".",
"site",
"return",
"if",
"site",
".",
"nil?",
"site",
".",
"site_type",
"==",
"Site",
"::",
"SiteType",
"::",
"... | Returns the collection site for which this participant has a MRN. If there is not exactly one
such site, then this method returns nil. This method is a convenience for the common situation
where a participant is enrolled at one site.
@return [CaTissue::Site] the collection site | [
"Returns",
"the",
"collection",
"site",
"for",
"which",
"this",
"participant",
"has",
"a",
"MRN",
".",
"If",
"there",
"is",
"not",
"exactly",
"one",
"such",
"site",
"then",
"this",
"method",
"returns",
"nil",
".",
"This",
"method",
"is",
"a",
"convenience"... | 08d99aabf4801c89842ce6dee138ccb1e4f5f56b | https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/participant.rb#L110-L115 | valid |
caruby/tissue | lib/catissue/domain/specimen_requirement.rb | CaTissue.SpecimenRequirement.match_characteristics | def match_characteristics(other)
chr = characteristics
ochr = other.characteristics
chr and ochr and chr.tissue_side == ochr.tissue_side and chr.tissue_site == ochr.tissue_site
end | ruby | def match_characteristics(other)
chr = characteristics
ochr = other.characteristics
chr and ochr and chr.tissue_side == ochr.tissue_side and chr.tissue_site == ochr.tissue_site
end | [
"def",
"match_characteristics",
"(",
"other",
")",
"chr",
"=",
"characteristics",
"ochr",
"=",
"other",
".",
"characteristics",
"chr",
"and",
"ochr",
"and",
"chr",
".",
"tissue_side",
"==",
"ochr",
".",
"tissue_side",
"and",
"chr",
".",
"tissue_site",
"==",
... | Returns whether this SpecimenRequirement characteristics matches the other SpecimenRequirement characteristics
on the tissue site and tissue side. | [
"Returns",
"whether",
"this",
"SpecimenRequirement",
"characteristics",
"matches",
"the",
"other",
"SpecimenRequirement",
"characteristics",
"on",
"the",
"tissue",
"site",
"and",
"tissue",
"side",
"."
] | 08d99aabf4801c89842ce6dee138ccb1e4f5f56b | https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/specimen_requirement.rb#L60-L64 | valid |
caruby/tissue | lib/catissue/domain/received_event_parameters.rb | CaTissue.ReceivedEventParameters.default_user | def default_user
scg = specimen_collection_group || (specimen.specimen_collection_group if specimen) || return
cp = scg.collection_protocol || return
cp.coordinators.first || (cp.sites.first.coordinator if cp.sites.size === 1)
end | ruby | def default_user
scg = specimen_collection_group || (specimen.specimen_collection_group if specimen) || return
cp = scg.collection_protocol || return
cp.coordinators.first || (cp.sites.first.coordinator if cp.sites.size === 1)
end | [
"def",
"default_user",
"scg",
"=",
"specimen_collection_group",
"||",
"(",
"specimen",
".",
"specimen_collection_group",
"if",
"specimen",
")",
"||",
"return",
"cp",
"=",
"scg",
".",
"collection_protocol",
"||",
"return",
"cp",
".",
"coordinators",
".",
"first",
... | Returns the first SCG CP coordinator, if any. | [
"Returns",
"the",
"first",
"SCG",
"CP",
"coordinator",
"if",
"any",
"."
] | 08d99aabf4801c89842ce6dee138ccb1e4f5f56b | https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/domain/received_event_parameters.rb#L19-L23 | valid |
FromUte/dune-dashboard | lib/dune/dashboard/i18n.rb | Dune::Dashboard.I18n.export! | def export!
puts "Exporting translations:\n"
if config[:split]
translations.keys.each do |locale|
if translations[:en].nil?
puts 'Missing english translation'
exit
end
puts "\nLocale: #{locale}"
fallback_english_hash = flat_hash(translations[:en])
translations_hash = flat_hash(translations[locale])
if locale != :en
translations_hash.each do |key, value|
english_fallback = fallback_english_hash[key]
if value == nil || value == ""
puts " #{key} missing!"
puts " taking english default: '#{english_fallback}'"
translations_hash[key] = english_fallback
end
end
end
save(translations_hash, File.join(export_dir, "translations_#{locale}.js"))
end
else
save(flat_hash(translations), File.join(export_dir, 'translations.js'))
end
end | ruby | def export!
puts "Exporting translations:\n"
if config[:split]
translations.keys.each do |locale|
if translations[:en].nil?
puts 'Missing english translation'
exit
end
puts "\nLocale: #{locale}"
fallback_english_hash = flat_hash(translations[:en])
translations_hash = flat_hash(translations[locale])
if locale != :en
translations_hash.each do |key, value|
english_fallback = fallback_english_hash[key]
if value == nil || value == ""
puts " #{key} missing!"
puts " taking english default: '#{english_fallback}'"
translations_hash[key] = english_fallback
end
end
end
save(translations_hash, File.join(export_dir, "translations_#{locale}.js"))
end
else
save(flat_hash(translations), File.join(export_dir, 'translations.js'))
end
end | [
"def",
"export!",
"puts",
"\"Exporting translations:\\n\"",
"if",
"config",
"[",
":split",
"]",
"translations",
".",
"keys",
".",
"each",
"do",
"|",
"locale",
"|",
"if",
"translations",
"[",
":en",
"]",
".",
"nil?",
"puts",
"'Missing english translation'",
"exit... | Export translations to JavaScript, considering settings
from configuration file | [
"Export",
"translations",
"to",
"JavaScript",
"considering",
"settings",
"from",
"configuration",
"file"
] | 4438fb6d9f83867fb22469ebde000a589cdde3f1 | https://github.com/FromUte/dune-dashboard/blob/4438fb6d9f83867fb22469ebde000a589cdde3f1/lib/dune/dashboard/i18n.rb#L23-L49 | valid |
FromUte/dune-dashboard | lib/dune/dashboard/i18n.rb | Dune::Dashboard.I18n.save | def save(translations, file)
file = ::Rails.root.join(file)
FileUtils.mkdir_p File.dirname(file)
variable_to_assign = config.fetch(:variable, 'Ember.I18n.translations')
File.open(file, 'w+') do |f|
f << variable_to_assign
f << ' = '
f << JSON.pretty_generate(translations).html_safe
f << ';'
end
end | ruby | def save(translations, file)
file = ::Rails.root.join(file)
FileUtils.mkdir_p File.dirname(file)
variable_to_assign = config.fetch(:variable, 'Ember.I18n.translations')
File.open(file, 'w+') do |f|
f << variable_to_assign
f << ' = '
f << JSON.pretty_generate(translations).html_safe
f << ';'
end
end | [
"def",
"save",
"(",
"translations",
",",
"file",
")",
"file",
"=",
"::",
"Rails",
".",
"root",
".",
"join",
"(",
"file",
")",
"FileUtils",
".",
"mkdir_p",
"File",
".",
"dirname",
"(",
"file",
")",
"variable_to_assign",
"=",
"config",
".",
"fetch",
"(",... | Convert translations to JSON string and save file. | [
"Convert",
"translations",
"to",
"JSON",
"string",
"and",
"save",
"file",
"."
] | 4438fb6d9f83867fb22469ebde000a589cdde3f1 | https://github.com/FromUte/dune-dashboard/blob/4438fb6d9f83867fb22469ebde000a589cdde3f1/lib/dune/dashboard/i18n.rb#L81-L93 | valid |
FromUte/dune-dashboard | lib/dune/dashboard/i18n.rb | Dune::Dashboard.I18n.translations | def translations
::I18n.load_path = default_locales_path
::I18n.backend.instance_eval do
init_translations unless initialized?
translations
end
end | ruby | def translations
::I18n.load_path = default_locales_path
::I18n.backend.instance_eval do
init_translations unless initialized?
translations
end
end | [
"def",
"translations",
"::",
"I18n",
".",
"load_path",
"=",
"default_locales_path",
"::",
"I18n",
".",
"backend",
".",
"instance_eval",
"do",
"init_translations",
"unless",
"initialized?",
"translations",
"end",
"end"
] | Initialize and return translations | [
"Initialize",
"and",
"return",
"translations"
] | 4438fb6d9f83867fb22469ebde000a589cdde3f1 | https://github.com/FromUte/dune-dashboard/blob/4438fb6d9f83867fb22469ebde000a589cdde3f1/lib/dune/dashboard/i18n.rb#L96-L102 | valid |
caruby/tissue | lib/catissue/helpers/properties_loader.rb | CaTissue.PropertiesLoader.load_properties | def load_properties
# the properties file
file = default_properties_file
# the access properties
props = file && File.exists?(file) ? load_properties_file(file) : {}
# Load the Java application jar path.
path = props[:classpath] || props[:path] || infer_classpath
Java.expand_to_class_path(path) if path
# Get the application login properties from the remoteService.xml, if necessary.
unless props.has_key?(:host) or props.has_key?(:port) then
url = remote_service_url
if url then
host, port = url.split(':')
props[:host] = host
props[:port] = port
end
end
unless props.has_key?(:database) then
props.merge(infer_database_properties)
end
props
end | ruby | def load_properties
# the properties file
file = default_properties_file
# the access properties
props = file && File.exists?(file) ? load_properties_file(file) : {}
# Load the Java application jar path.
path = props[:classpath] || props[:path] || infer_classpath
Java.expand_to_class_path(path) if path
# Get the application login properties from the remoteService.xml, if necessary.
unless props.has_key?(:host) or props.has_key?(:port) then
url = remote_service_url
if url then
host, port = url.split(':')
props[:host] = host
props[:port] = port
end
end
unless props.has_key?(:database) then
props.merge(infer_database_properties)
end
props
end | [
"def",
"load_properties",
"file",
"=",
"default_properties_file",
"props",
"=",
"file",
"&&",
"File",
".",
"exists?",
"(",
"file",
")",
"?",
"load_properties_file",
"(",
"file",
")",
":",
"{",
"}",
"path",
"=",
"props",
"[",
":classpath",
"]",
"||",
"props... | Loads the caTissue classpath and connection properties. | [
"Loads",
"the",
"caTissue",
"classpath",
"and",
"connection",
"properties",
"."
] | 08d99aabf4801c89842ce6dee138ccb1e4f5f56b | https://github.com/caruby/tissue/blob/08d99aabf4801c89842ce6dee138ccb1e4f5f56b/lib/catissue/helpers/properties_loader.rb#L44-L65 | valid |
tdawe/vatsim | lib/vatsim/data.rb | Vatsim.Data.parse | def parse
download_files
parsing_clients = false
parsing_prefile = false
parsing_general = false
parsing_servers = false
parsing_voice_servers = false
File.open(DATA_FILE_PATH, 'r:ascii-8bit').each { |line|
if line.start_with? ";"
parsing_clients = false
parsing_prefile = false
parsing_general = false
parsing_servers = false
parsing_voice_servers = false
elsif parsing_clients
clienttype = line.split(":")[3]
if clienttype.eql? "PILOT"
@pilots << Pilot.new(line)
elsif clienttype.eql? "ATC"
@atc << ATC.new(line)
end
elsif parsing_prefile
@prefiles << Prefile.new(line)
elsif parsing_general
line_split = line.split("=")
@general[line_split[0].strip.downcase.gsub(" ", "_")] = line_split[1].strip
elsif parsing_servers
@servers << Server.new(line)
elsif parsing_voice_servers
@voice_servers << VoiceServer.new(line) if line.length > 2 # ignore last, empty line for voice server that contains 2 characters
end
parsing_clients = true if line.start_with? "!CLIENTS:"
parsing_prefile = true if line.start_with? "!PREFILE:"
parsing_general = true if line.start_with? "!GENERAL:"
parsing_servers = true if line.start_with? "!SERVERS:"
parsing_voice_servers = true if line.start_with? "!VOICE SERVERS:"
}
end | ruby | def parse
download_files
parsing_clients = false
parsing_prefile = false
parsing_general = false
parsing_servers = false
parsing_voice_servers = false
File.open(DATA_FILE_PATH, 'r:ascii-8bit').each { |line|
if line.start_with? ";"
parsing_clients = false
parsing_prefile = false
parsing_general = false
parsing_servers = false
parsing_voice_servers = false
elsif parsing_clients
clienttype = line.split(":")[3]
if clienttype.eql? "PILOT"
@pilots << Pilot.new(line)
elsif clienttype.eql? "ATC"
@atc << ATC.new(line)
end
elsif parsing_prefile
@prefiles << Prefile.new(line)
elsif parsing_general
line_split = line.split("=")
@general[line_split[0].strip.downcase.gsub(" ", "_")] = line_split[1].strip
elsif parsing_servers
@servers << Server.new(line)
elsif parsing_voice_servers
@voice_servers << VoiceServer.new(line) if line.length > 2 # ignore last, empty line for voice server that contains 2 characters
end
parsing_clients = true if line.start_with? "!CLIENTS:"
parsing_prefile = true if line.start_with? "!PREFILE:"
parsing_general = true if line.start_with? "!GENERAL:"
parsing_servers = true if line.start_with? "!SERVERS:"
parsing_voice_servers = true if line.start_with? "!VOICE SERVERS:"
}
end | [
"def",
"parse",
"download_files",
"parsing_clients",
"=",
"false",
"parsing_prefile",
"=",
"false",
"parsing_general",
"=",
"false",
"parsing_servers",
"=",
"false",
"parsing_voice_servers",
"=",
"false",
"File",
".",
"open",
"(",
"DATA_FILE_PATH",
",",
"'r:ascii-8bit... | Parse the vatsim data file and store output as necessary | [
"Parse",
"the",
"vatsim",
"data",
"file",
"and",
"store",
"output",
"as",
"necessary"
] | 79be6099ec808f983ed8f377b7b50feb450d77c9 | https://github.com/tdawe/vatsim/blob/79be6099ec808f983ed8f377b7b50feb450d77c9/lib/vatsim/data.rb#L31-L72 | valid |
tdawe/vatsim | lib/vatsim/data.rb | Vatsim.Data.download_files | def download_files
if !File.exists?(STATUS_FILE_PATH) or File.mtime(STATUS_FILE_PATH) < Time.now - STATUS_DOWNLOAD_INTERVAL
download_to_file STATUS_URL, STATUS_FILE_PATH
end
if !File.exists?(DATA_FILE_PATH) or File.mtime(DATA_FILE_PATH) < Time.now - DATA_DOWNLOAD_INTERVAL
download_to_file random_data_url, DATA_FILE_PATH
end
end | ruby | def download_files
if !File.exists?(STATUS_FILE_PATH) or File.mtime(STATUS_FILE_PATH) < Time.now - STATUS_DOWNLOAD_INTERVAL
download_to_file STATUS_URL, STATUS_FILE_PATH
end
if !File.exists?(DATA_FILE_PATH) or File.mtime(DATA_FILE_PATH) < Time.now - DATA_DOWNLOAD_INTERVAL
download_to_file random_data_url, DATA_FILE_PATH
end
end | [
"def",
"download_files",
"if",
"!",
"File",
".",
"exists?",
"(",
"STATUS_FILE_PATH",
")",
"or",
"File",
".",
"mtime",
"(",
"STATUS_FILE_PATH",
")",
"<",
"Time",
".",
"now",
"-",
"STATUS_DOWNLOAD_INTERVAL",
"download_to_file",
"STATUS_URL",
",",
"STATUS_FILE_PATH",... | Initialize the system by downloading status and vatsim data files | [
"Initialize",
"the",
"system",
"by",
"downloading",
"status",
"and",
"vatsim",
"data",
"files"
] | 79be6099ec808f983ed8f377b7b50feb450d77c9 | https://github.com/tdawe/vatsim/blob/79be6099ec808f983ed8f377b7b50feb450d77c9/lib/vatsim/data.rb#L75-L83 | valid |
tdawe/vatsim | lib/vatsim/data.rb | Vatsim.Data.download_to_file | def download_to_file url, file
url = URI.parse(URI.encode(url.strip))
File.new(file, File::CREAT)
Net::HTTP.start(url.host) { |http|
resp = http.get(url.path)
open(file, "wb") { |file|
file.write(resp.body)
}
}
end | ruby | def download_to_file url, file
url = URI.parse(URI.encode(url.strip))
File.new(file, File::CREAT)
Net::HTTP.start(url.host) { |http|
resp = http.get(url.path)
open(file, "wb") { |file|
file.write(resp.body)
}
}
end | [
"def",
"download_to_file",
"url",
",",
"file",
"url",
"=",
"URI",
".",
"parse",
"(",
"URI",
".",
"encode",
"(",
"url",
".",
"strip",
")",
")",
"File",
".",
"new",
"(",
"file",
",",
"File",
"::",
"CREAT",
")",
"Net",
"::",
"HTTP",
".",
"start",
"(... | Download a url to a file path | [
"Download",
"a",
"url",
"to",
"a",
"file",
"path"
] | 79be6099ec808f983ed8f377b7b50feb450d77c9 | https://github.com/tdawe/vatsim/blob/79be6099ec808f983ed8f377b7b50feb450d77c9/lib/vatsim/data.rb#L86-L97 | valid |
tdawe/vatsim | lib/vatsim/data.rb | Vatsim.Data.random_data_url | def random_data_url
url0s = Array.new
file = File.open(STATUS_FILE_PATH)
file.each {|line|
if line.start_with? "url0"
url0s << line.split("=").last
end
}
return url0s[rand(url0s.length)]
end | ruby | def random_data_url
url0s = Array.new
file = File.open(STATUS_FILE_PATH)
file.each {|line|
if line.start_with? "url0"
url0s << line.split("=").last
end
}
return url0s[rand(url0s.length)]
end | [
"def",
"random_data_url",
"url0s",
"=",
"Array",
".",
"new",
"file",
"=",
"File",
".",
"open",
"(",
"STATUS_FILE_PATH",
")",
"file",
".",
"each",
"{",
"|",
"line",
"|",
"if",
"line",
".",
"start_with?",
"\"url0\"",
"url0s",
"<<",
"line",
".",
"split",
... | Return random vatsim data url from status file | [
"Return",
"random",
"vatsim",
"data",
"url",
"from",
"status",
"file"
] | 79be6099ec808f983ed8f377b7b50feb450d77c9 | https://github.com/tdawe/vatsim/blob/79be6099ec808f983ed8f377b7b50feb450d77c9/lib/vatsim/data.rb#L100-L109 | valid |
bdwyertech/newrelic-management | lib/newrelic-management/util.rb | NewRelicManagement.Util.cachier! | def cachier!(var = nil)
if var && instance_variable_get("@#{var}")
# => Clear the Single Variable
remove_instance_variable("@#{var}")
else
# => Clear the Whole Damned Cache
instance_variables.each { |x| remove_instance_variable(x) }
end
end | ruby | def cachier!(var = nil)
if var && instance_variable_get("@#{var}")
# => Clear the Single Variable
remove_instance_variable("@#{var}")
else
# => Clear the Whole Damned Cache
instance_variables.each { |x| remove_instance_variable(x) }
end
end | [
"def",
"cachier!",
"(",
"var",
"=",
"nil",
")",
"if",
"var",
"&&",
"instance_variable_get",
"(",
"\"@#{var}\"",
")",
"remove_instance_variable",
"(",
"\"@#{var}\"",
")",
"else",
"instance_variables",
".",
"each",
"{",
"|",
"x",
"|",
"remove_instance_variable",
"... | => Clear Cache | [
"=",
">",
"Clear",
"Cache"
] | 265f0024b52d1fed476f35448b6b518453b4b1a6 | https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/util.rb#L35-L43 | valid |
bdwyertech/newrelic-management | lib/newrelic-management/util.rb | NewRelicManagement.Util.write_json | def write_json(file, object)
return unless file && object
begin
File.open(file, 'w') { |f| f.write(JSON.pretty_generate(object)) }
end
end | ruby | def write_json(file, object)
return unless file && object
begin
File.open(file, 'w') { |f| f.write(JSON.pretty_generate(object)) }
end
end | [
"def",
"write_json",
"(",
"file",
",",
"object",
")",
"return",
"unless",
"file",
"&&",
"object",
"begin",
"File",
".",
"open",
"(",
"file",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"JSON",
".",
"pretty_generate",
"(",
"object",
... | => Define JSON Writer | [
"=",
">",
"Define",
"JSON",
"Writer"
] | 265f0024b52d1fed476f35448b6b518453b4b1a6 | https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/util.rb#L60-L65 | valid |
bdwyertech/newrelic-management | lib/newrelic-management/util.rb | NewRelicManagement.Util.filestring | def filestring(file, size = 8192)
return unless file
return file unless file.is_a?(String) && File.file?(file) && File.size(file) <= size
File.read(file)
end | ruby | def filestring(file, size = 8192)
return unless file
return file unless file.is_a?(String) && File.file?(file) && File.size(file) <= size
File.read(file)
end | [
"def",
"filestring",
"(",
"file",
",",
"size",
"=",
"8192",
")",
"return",
"unless",
"file",
"return",
"file",
"unless",
"file",
".",
"is_a?",
"(",
"String",
")",
"&&",
"File",
".",
"file?",
"(",
"file",
")",
"&&",
"File",
".",
"size",
"(",
"file",
... | => Check if a string is an existing file, and return it's content | [
"=",
">",
"Check",
"if",
"a",
"string",
"is",
"an",
"existing",
"file",
"and",
"return",
"it",
"s",
"content"
] | 265f0024b52d1fed476f35448b6b518453b4b1a6 | https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/util.rb#L68-L72 | valid |
bdwyertech/newrelic-management | lib/newrelic-management/util.rb | NewRelicManagement.Util.common_array | def common_array(ary) # rubocop: disable AbcSize
return ary unless ary.is_a? Array
count = ary.count
return ary if count.zero?
return ary.flatten.uniq if count == 1
common = ary[0] & ary[1]
return common if count == 2
(count - 2).times { |x| common &= ary[x + 2] } if count > 2
common
end | ruby | def common_array(ary) # rubocop: disable AbcSize
return ary unless ary.is_a? Array
count = ary.count
return ary if count.zero?
return ary.flatten.uniq if count == 1
common = ary[0] & ary[1]
return common if count == 2
(count - 2).times { |x| common &= ary[x + 2] } if count > 2
common
end | [
"def",
"common_array",
"(",
"ary",
")",
"return",
"ary",
"unless",
"ary",
".",
"is_a?",
"Array",
"count",
"=",
"ary",
".",
"count",
"return",
"ary",
"if",
"count",
".",
"zero?",
"return",
"ary",
".",
"flatten",
".",
"uniq",
"if",
"count",
"==",
"1",
... | => Return Common Elements of an Array | [
"=",
">",
"Return",
"Common",
"Elements",
"of",
"an",
"Array"
] | 265f0024b52d1fed476f35448b6b518453b4b1a6 | https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/util.rb#L90-L99 | valid |
KeasInc/isimud | lib/isimud/event_listener.rb | Isimud.EventListener.run | def run
bind_queues and return if test_env?
start_shutdown_thread
start_error_counter_thread
client.on_exception do |e|
count_error(e)
end
client.connect
start_event_thread
puts 'EventListener started. Hit Ctrl-C to exit'
Thread.stop
puts 'Main thread wakeup - exiting.'
client.close
end | ruby | def run
bind_queues and return if test_env?
start_shutdown_thread
start_error_counter_thread
client.on_exception do |e|
count_error(e)
end
client.connect
start_event_thread
puts 'EventListener started. Hit Ctrl-C to exit'
Thread.stop
puts 'Main thread wakeup - exiting.'
client.close
end | [
"def",
"run",
"bind_queues",
"and",
"return",
"if",
"test_env?",
"start_shutdown_thread",
"start_error_counter_thread",
"client",
".",
"on_exception",
"do",
"|",
"e",
"|",
"count_error",
"(",
"e",
")",
"end",
"client",
".",
"connect",
"start_event_thread",
"puts",
... | Initialize a new EventListener daemon instance
@param [Hash] options daemon options
@option options [Integer] :error_limit (10) maximum number of errors that are allowed to occur within error_interval
before the process terminates
@option options [Integer] :error_interval (3600) time interval, in seconds, before the error counter is cleared
@option options [String] :events_exchange ('events') name of AMQP exchange used for listening to event messages
@option options [String] :models_exchange ('models') name of AMQP exchange used for listening to EventObserver
instance create, update, and destroy messages
@option options [String] :name ("#{Rails.application.class.parent_name.downcase}-listener") daemon instance name.
Run the daemon process. This creates the event, error counter, and shutdown threads | [
"Initialize",
"a",
"new",
"EventListener",
"daemon",
"instance"
] | 20b66d4d981e39d2c69cb04385551436cda32c67 | https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/event_listener.rb#L93-L107 | valid |
KeasInc/isimud | lib/isimud/event_listener.rb | Isimud.EventListener.register_observer_class | def register_observer_class(observer_class)
@observer_mutex.synchronize do
return if @observed_models.include?(observer_class)
@observed_models << observer_class
log "EventListener: registering observer class #{observer_class}"
observer_queue.bind(models_exchange, routing_key: "#{Isimud.model_watcher_schema}.#{observer_class.base_class.name}.*")
end
end | ruby | def register_observer_class(observer_class)
@observer_mutex.synchronize do
return if @observed_models.include?(observer_class)
@observed_models << observer_class
log "EventListener: registering observer class #{observer_class}"
observer_queue.bind(models_exchange, routing_key: "#{Isimud.model_watcher_schema}.#{observer_class.base_class.name}.*")
end
end | [
"def",
"register_observer_class",
"(",
"observer_class",
")",
"@observer_mutex",
".",
"synchronize",
"do",
"return",
"if",
"@observed_models",
".",
"include?",
"(",
"observer_class",
")",
"@observed_models",
"<<",
"observer_class",
"log",
"\"EventListener: registering obser... | Register the observer class watcher | [
"Register",
"the",
"observer",
"class",
"watcher"
] | 20b66d4d981e39d2c69cb04385551436cda32c67 | https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/event_listener.rb#L236-L243 | valid |
KeasInc/isimud | lib/isimud/event_listener.rb | Isimud.EventListener.register_observer | def register_observer(observer)
@observer_mutex.synchronize do
log "EventListener: registering observer #{observer.class} #{observer.id}"
@observers[observer_key_for(observer.class, observer.id)] = observer.observe_events(client)
end
end | ruby | def register_observer(observer)
@observer_mutex.synchronize do
log "EventListener: registering observer #{observer.class} #{observer.id}"
@observers[observer_key_for(observer.class, observer.id)] = observer.observe_events(client)
end
end | [
"def",
"register_observer",
"(",
"observer",
")",
"@observer_mutex",
".",
"synchronize",
"do",
"log",
"\"EventListener: registering observer #{observer.class} #{observer.id}\"",
"@observers",
"[",
"observer_key_for",
"(",
"observer",
".",
"class",
",",
"observer",
".",
"id"... | Register an observer instance, and start listening for events on its associated queue.
Also ensure that we are listening for observer class update events | [
"Register",
"an",
"observer",
"instance",
"and",
"start",
"listening",
"for",
"events",
"on",
"its",
"associated",
"queue",
".",
"Also",
"ensure",
"that",
"we",
"are",
"listening",
"for",
"observer",
"class",
"update",
"events"
] | 20b66d4d981e39d2c69cb04385551436cda32c67 | https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/event_listener.rb#L247-L252 | valid |
KeasInc/isimud | lib/isimud/event_listener.rb | Isimud.EventListener.unregister_observer | def unregister_observer(observer_class, observer_id)
@observer_mutex.synchronize do
log "EventListener: un-registering observer #{observer_class} #{observer_id}"
if (consumer = @observers.delete(observer_key_for(observer_class, observer_id)))
consumer.cancel
end
end
end | ruby | def unregister_observer(observer_class, observer_id)
@observer_mutex.synchronize do
log "EventListener: un-registering observer #{observer_class} #{observer_id}"
if (consumer = @observers.delete(observer_key_for(observer_class, observer_id)))
consumer.cancel
end
end
end | [
"def",
"unregister_observer",
"(",
"observer_class",
",",
"observer_id",
")",
"@observer_mutex",
".",
"synchronize",
"do",
"log",
"\"EventListener: un-registering observer #{observer_class} #{observer_id}\"",
"if",
"(",
"consumer",
"=",
"@observers",
".",
"delete",
"(",
"ob... | Unregister an observer instance, and cancel consumption of messages. Any pre-fetched messages will be returned to the queue. | [
"Unregister",
"an",
"observer",
"instance",
"and",
"cancel",
"consumption",
"of",
"messages",
".",
"Any",
"pre",
"-",
"fetched",
"messages",
"will",
"be",
"returned",
"to",
"the",
"queue",
"."
] | 20b66d4d981e39d2c69cb04385551436cda32c67 | https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/event_listener.rb#L255-L262 | valid |
KeasInc/isimud | lib/isimud/event_listener.rb | Isimud.EventListener.observer_queue | def observer_queue
@observer_queue ||= client.create_queue([name, 'listener', Socket.gethostname, Process.pid].join('.'),
models_exchange,
queue_options: {exclusive: true},
subscribe_options: {manual_ack: true})
end | ruby | def observer_queue
@observer_queue ||= client.create_queue([name, 'listener', Socket.gethostname, Process.pid].join('.'),
models_exchange,
queue_options: {exclusive: true},
subscribe_options: {manual_ack: true})
end | [
"def",
"observer_queue",
"@observer_queue",
"||=",
"client",
".",
"create_queue",
"(",
"[",
"name",
",",
"'listener'",
",",
"Socket",
".",
"gethostname",
",",
"Process",
".",
"pid",
"]",
".",
"join",
"(",
"'.'",
")",
",",
"models_exchange",
",",
"queue_optio... | Create or return the observer queue which listens for ModelWatcher events | [
"Create",
"or",
"return",
"the",
"observer",
"queue",
"which",
"listens",
"for",
"ModelWatcher",
"events"
] | 20b66d4d981e39d2c69cb04385551436cda32c67 | https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/event_listener.rb#L265-L270 | valid |
KeasInc/isimud | lib/isimud/event.rb | Isimud.Event.as_json | def as_json(options = {})
session_id = parameters.delete(:session_id) || Thread.current[:keas_session_id]
data = {type: type,
action: action,
user_id: user_id,
occurred_at: occurred_at,
eventful_type: eventful_type,
eventful_id: eventful_id,
session_id: session_id}
unless options[:omit_parameters]
data[:parameters] = parameters
data[:attributes] = attributes
end
data
end | ruby | def as_json(options = {})
session_id = parameters.delete(:session_id) || Thread.current[:keas_session_id]
data = {type: type,
action: action,
user_id: user_id,
occurred_at: occurred_at,
eventful_type: eventful_type,
eventful_id: eventful_id,
session_id: session_id}
unless options[:omit_parameters]
data[:parameters] = parameters
data[:attributes] = attributes
end
data
end | [
"def",
"as_json",
"(",
"options",
"=",
"{",
"}",
")",
"session_id",
"=",
"parameters",
".",
"delete",
"(",
":session_id",
")",
"||",
"Thread",
".",
"current",
"[",
":keas_session_id",
"]",
"data",
"=",
"{",
"type",
":",
"type",
",",
"action",
":",
"act... | Return hash of data to be serialized to JSON
@option options [Boolean] :omit_parameters when set, do not include attributes or parameters in data
@return [Hash] data to serialize | [
"Return",
"hash",
"of",
"data",
"to",
"be",
"serialized",
"to",
"JSON"
] | 20b66d4d981e39d2c69cb04385551436cda32c67 | https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/event.rb#L87-L102 | valid |
mmcclimon/mr_poole | lib/mr_poole/cli.rb | MrPoole.CLI.do_create | def do_create(action)
options = do_creation_options
options.title ||= @params.first
@helper.send("#{action}_usage") unless options.title
fn = @commands.send(action, options)
puts "#{@src_dir}/#{fn}"
end | ruby | def do_create(action)
options = do_creation_options
options.title ||= @params.first
@helper.send("#{action}_usage") unless options.title
fn = @commands.send(action, options)
puts "#{@src_dir}/#{fn}"
end | [
"def",
"do_create",
"(",
"action",
")",
"options",
"=",
"do_creation_options",
"options",
".",
"title",
"||=",
"@params",
".",
"first",
"@helper",
".",
"send",
"(",
"\"#{action}_usage\"",
")",
"unless",
"options",
".",
"title",
"fn",
"=",
"@commands",
".",
"... | action is a string, either 'post' or 'draft' | [
"action",
"is",
"a",
"string",
"either",
"post",
"or",
"draft"
] | 442404c64dd931185ddf2e2345ce2e76994c910f | https://github.com/mmcclimon/mr_poole/blob/442404c64dd931185ddf2e2345ce2e76994c910f/lib/mr_poole/cli.rb#L51-L58 | valid |
mmcclimon/mr_poole | lib/mr_poole/cli.rb | MrPoole.CLI.do_move | def do_move(action)
options = do_move_options(action)
path = @params.first
@helper.send("#{action}_usage") unless path
fn = @commands.send(action, path, options)
puts "#{@src_dir}/#{fn}"
end | ruby | def do_move(action)
options = do_move_options(action)
path = @params.first
@helper.send("#{action}_usage") unless path
fn = @commands.send(action, path, options)
puts "#{@src_dir}/#{fn}"
end | [
"def",
"do_move",
"(",
"action",
")",
"options",
"=",
"do_move_options",
"(",
"action",
")",
"path",
"=",
"@params",
".",
"first",
"@helper",
".",
"send",
"(",
"\"#{action}_usage\"",
")",
"unless",
"path",
"fn",
"=",
"@commands",
".",
"send",
"(",
"action"... | action is a string, either 'publish' or 'unpublish' | [
"action",
"is",
"a",
"string",
"either",
"publish",
"or",
"unpublish"
] | 442404c64dd931185ddf2e2345ce2e76994c910f | https://github.com/mmcclimon/mr_poole/blob/442404c64dd931185ddf2e2345ce2e76994c910f/lib/mr_poole/cli.rb#L61-L68 | valid |
mmcclimon/mr_poole | lib/mr_poole/cli.rb | MrPoole.CLI.do_move_options | def do_move_options(type)
options = OpenStruct.new
opt_parser = OptionParser.new do |opts|
if type == 'publish'
opts.on('-d', '--keep-draft', "Keep draft post") do |d|
options.keep_draft = d
end
else
opts.on('-p', '--keep-post', "Do not delete post") do |p|
options.keep_post = p
end
end
opts.on('-t', '--keep-timestamp', "Keep existing timestamp") do |t|
options.keep_timestamp = t
end
end
opt_parser.parse! @params
options
end | ruby | def do_move_options(type)
options = OpenStruct.new
opt_parser = OptionParser.new do |opts|
if type == 'publish'
opts.on('-d', '--keep-draft', "Keep draft post") do |d|
options.keep_draft = d
end
else
opts.on('-p', '--keep-post', "Do not delete post") do |p|
options.keep_post = p
end
end
opts.on('-t', '--keep-timestamp', "Keep existing timestamp") do |t|
options.keep_timestamp = t
end
end
opt_parser.parse! @params
options
end | [
"def",
"do_move_options",
"(",
"type",
")",
"options",
"=",
"OpenStruct",
".",
"new",
"opt_parser",
"=",
"OptionParser",
".",
"new",
"do",
"|",
"opts",
"|",
"if",
"type",
"==",
"'publish'",
"opts",
".",
"on",
"(",
"'-d'",
",",
"'--keep-draft'",
",",
"\"K... | pass a string, either publish or unpublish | [
"pass",
"a",
"string",
"either",
"publish",
"or",
"unpublish"
] | 442404c64dd931185ddf2e2345ce2e76994c910f | https://github.com/mmcclimon/mr_poole/blob/442404c64dd931185ddf2e2345ce2e76994c910f/lib/mr_poole/cli.rb#L97-L117 | valid |
haines/yard-relative_markdown_links | lib/yard/relative_markdown_links.rb | YARD.RelativeMarkdownLinks.resolve_links | def resolve_links(text)
html = Nokogiri::HTML.fragment(text)
html.css("a[href]").each do |link|
href = URI(link["href"])
next unless href.relative? && markup_for_file(nil, href.path) == :markdown
link.replace "{file:#{href} #{link.inner_html}}"
end
super(html.to_s)
end | ruby | def resolve_links(text)
html = Nokogiri::HTML.fragment(text)
html.css("a[href]").each do |link|
href = URI(link["href"])
next unless href.relative? && markup_for_file(nil, href.path) == :markdown
link.replace "{file:#{href} #{link.inner_html}}"
end
super(html.to_s)
end | [
"def",
"resolve_links",
"(",
"text",
")",
"html",
"=",
"Nokogiri",
"::",
"HTML",
".",
"fragment",
"(",
"text",
")",
"html",
".",
"css",
"(",
"\"a[href]\"",
")",
".",
"each",
"do",
"|",
"link",
"|",
"href",
"=",
"URI",
"(",
"link",
"[",
"\"href\"",
... | Resolves relative links to Markdown files.
@param [String] text the HTML fragment in which to resolve links.
@return [String] HTML with relative links to Markdown files converted to `{file:}` links. | [
"Resolves",
"relative",
"links",
"to",
"Markdown",
"files",
"."
] | b8952b8f60d47cbfc8879081c61ddd9b844c7edf | https://github.com/haines/yard-relative_markdown_links/blob/b8952b8f60d47cbfc8879081c61ddd9b844c7edf/lib/yard/relative_markdown_links.rb#L19-L27 | valid |
bdwyertech/newrelic-management | lib/newrelic-management/client.rb | NewRelicManagement.Client.nr_api | def nr_api
# => Build the Faraday Connection
@conn ||= Faraday::Connection.new('https://api.newrelic.com', conn_opts) do |client|
client.use Faraday::Response::RaiseError
client.use FaradayMiddleware::EncodeJson
client.use FaradayMiddleware::ParseJson, content_type: /\bjson$/
client.response :logger if Config.environment.to_s.casecmp('development').zero? # => Log Requests to STDOUT
client.adapter Faraday.default_adapter #:net_http_persistent
end
end | ruby | def nr_api
# => Build the Faraday Connection
@conn ||= Faraday::Connection.new('https://api.newrelic.com', conn_opts) do |client|
client.use Faraday::Response::RaiseError
client.use FaradayMiddleware::EncodeJson
client.use FaradayMiddleware::ParseJson, content_type: /\bjson$/
client.response :logger if Config.environment.to_s.casecmp('development').zero? # => Log Requests to STDOUT
client.adapter Faraday.default_adapter #:net_http_persistent
end
end | [
"def",
"nr_api",
"@conn",
"||=",
"Faraday",
"::",
"Connection",
".",
"new",
"(",
"'https://api.newrelic.com'",
",",
"conn_opts",
")",
"do",
"|",
"client",
"|",
"client",
".",
"use",
"Faraday",
"::",
"Response",
"::",
"RaiseError",
"client",
".",
"use",
"Fara... | => Build the HTTP Connection | [
"=",
">",
"Build",
"the",
"HTTP",
"Connection"
] | 265f0024b52d1fed476f35448b6b518453b4b1a6 | https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/client.rb#L23-L32 | valid |
bdwyertech/newrelic-management | lib/newrelic-management/client.rb | NewRelicManagement.Client.alert_add_entity | def alert_add_entity(entity_id, condition_id, entity_type = 'Server')
nr_api.put do |req|
req.url url('alerts_entity_conditions', entity_id)
req.params['entity_type'] = entity_type
req.params['condition_id'] = condition_id
end
end | ruby | def alert_add_entity(entity_id, condition_id, entity_type = 'Server')
nr_api.put do |req|
req.url url('alerts_entity_conditions', entity_id)
req.params['entity_type'] = entity_type
req.params['condition_id'] = condition_id
end
end | [
"def",
"alert_add_entity",
"(",
"entity_id",
",",
"condition_id",
",",
"entity_type",
"=",
"'Server'",
")",
"nr_api",
".",
"put",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"url",
"(",
"'alerts_entity_conditions'",
",",
"entity_id",
")",
"req",
".",
"params",... | => Add an Entitity to an Existing Alert Policy | [
"=",
">",
"Add",
"an",
"Entitity",
"to",
"an",
"Existing",
"Alert",
"Policy"
] | 265f0024b52d1fed476f35448b6b518453b4b1a6 | https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/client.rb#L62-L68 | valid |
bdwyertech/newrelic-management | lib/newrelic-management/client.rb | NewRelicManagement.Client.alert_delete_entity | def alert_delete_entity(entity_id, condition_id, entity_type = 'Server')
nr_api.delete do |req|
req.url url('alerts_entity_conditions', entity_id)
req.params['entity_type'] = entity_type
req.params['condition_id'] = condition_id
end
end | ruby | def alert_delete_entity(entity_id, condition_id, entity_type = 'Server')
nr_api.delete do |req|
req.url url('alerts_entity_conditions', entity_id)
req.params['entity_type'] = entity_type
req.params['condition_id'] = condition_id
end
end | [
"def",
"alert_delete_entity",
"(",
"entity_id",
",",
"condition_id",
",",
"entity_type",
"=",
"'Server'",
")",
"nr_api",
".",
"delete",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"url",
"(",
"'alerts_entity_conditions'",
",",
"entity_id",
")",
"req",
".",
"pa... | => Delete an Entitity from an Existing Alert Policy | [
"=",
">",
"Delete",
"an",
"Entitity",
"from",
"an",
"Existing",
"Alert",
"Policy"
] | 265f0024b52d1fed476f35448b6b518453b4b1a6 | https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/client.rb#L71-L77 | valid |
bdwyertech/newrelic-management | lib/newrelic-management/client.rb | NewRelicManagement.Client.get_server_id | def get_server_id(server_id)
return nil unless server_id =~ /^[0-9]+$/
ret = nr_api.get(url('servers', server_id)).body
ret['server']
rescue Faraday::ResourceNotFound, NoMethodError
nil
end | ruby | def get_server_id(server_id)
return nil unless server_id =~ /^[0-9]+$/
ret = nr_api.get(url('servers', server_id)).body
ret['server']
rescue Faraday::ResourceNotFound, NoMethodError
nil
end | [
"def",
"get_server_id",
"(",
"server_id",
")",
"return",
"nil",
"unless",
"server_id",
"=~",
"/",
"/",
"ret",
"=",
"nr_api",
".",
"get",
"(",
"url",
"(",
"'servers'",
",",
"server_id",
")",
")",
".",
"body",
"ret",
"[",
"'server'",
"]",
"rescue",
"Fara... | => Get a Server based on ID | [
"=",
">",
"Get",
"a",
"Server",
"based",
"on",
"ID"
] | 265f0024b52d1fed476f35448b6b518453b4b1a6 | https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/client.rb#L104-L110 | valid |
bdwyertech/newrelic-management | lib/newrelic-management/client.rb | NewRelicManagement.Client.get_server_name | def get_server_name(server, exact = true)
ret = nr_api.get(url('servers'), 'filter[name]' => server).body
return ret['servers'] unless exact
ret['servers'].find { |x| x['name'].casecmp(server).zero? }
rescue NoMethodError
nil
end | ruby | def get_server_name(server, exact = true)
ret = nr_api.get(url('servers'), 'filter[name]' => server).body
return ret['servers'] unless exact
ret['servers'].find { |x| x['name'].casecmp(server).zero? }
rescue NoMethodError
nil
end | [
"def",
"get_server_name",
"(",
"server",
",",
"exact",
"=",
"true",
")",
"ret",
"=",
"nr_api",
".",
"get",
"(",
"url",
"(",
"'servers'",
")",
",",
"'filter[name]'",
"=>",
"server",
")",
".",
"body",
"return",
"ret",
"[",
"'servers'",
"]",
"unless",
"ex... | => Get a Server based on Name | [
"=",
">",
"Get",
"a",
"Server",
"based",
"on",
"Name"
] | 265f0024b52d1fed476f35448b6b518453b4b1a6 | https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/client.rb#L113-L119 | valid |
bdwyertech/newrelic-management | lib/newrelic-management/client.rb | NewRelicManagement.Client.get_servers_labeled | def get_servers_labeled(labels)
label_query = Array(labels).reject { |x| !x.include?(':') }.join(';')
return [] unless label_query
nr_api.get(url('servers'), 'filter[labels]' => label_query).body
end | ruby | def get_servers_labeled(labels)
label_query = Array(labels).reject { |x| !x.include?(':') }.join(';')
return [] unless label_query
nr_api.get(url('servers'), 'filter[labels]' => label_query).body
end | [
"def",
"get_servers_labeled",
"(",
"labels",
")",
"label_query",
"=",
"Array",
"(",
"labels",
")",
".",
"reject",
"{",
"|",
"x",
"|",
"!",
"x",
".",
"include?",
"(",
"':'",
")",
"}",
".",
"join",
"(",
"';'",
")",
"return",
"[",
"]",
"unless",
"labe... | => List the Servers with a Label | [
"=",
">",
"List",
"the",
"Servers",
"with",
"a",
"Label"
] | 265f0024b52d1fed476f35448b6b518453b4b1a6 | https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/client.rb#L122-L126 | valid |
KeasInc/isimud | lib/isimud/event_observer.rb | Isimud.EventObserver.observe_events | def observe_events(client)
return unless enable_listener?
queue = create_queue(client)
client.subscribe(queue) do |message|
event = Event.parse(message)
handle_event(event)
end
end | ruby | def observe_events(client)
return unless enable_listener?
queue = create_queue(client)
client.subscribe(queue) do |message|
event = Event.parse(message)
handle_event(event)
end
end | [
"def",
"observe_events",
"(",
"client",
")",
"return",
"unless",
"enable_listener?",
"queue",
"=",
"create_queue",
"(",
"client",
")",
"client",
".",
"subscribe",
"(",
"queue",
")",
"do",
"|",
"message",
"|",
"event",
"=",
"Event",
".",
"parse",
"(",
"mess... | Create or attach to a queue on the specified exchange. When an event message that matches the observer's routing keys
is received, parse the event and call handle_event on same.
@param [Isimud::Client] client client instance
@return queue or consumer object
@see BunnyClient#subscribe
@see TestClient#subscribe | [
"Create",
"or",
"attach",
"to",
"a",
"queue",
"on",
"the",
"specified",
"exchange",
".",
"When",
"an",
"event",
"message",
"that",
"matches",
"the",
"observer",
"s",
"routing",
"keys",
"is",
"received",
"parse",
"the",
"event",
"and",
"call",
"handle_event",... | 20b66d4d981e39d2c69cb04385551436cda32c67 | https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/event_observer.rb#L59-L66 | valid |
KeasInc/isimud | lib/isimud/bunny_client.rb | Isimud.BunnyClient.bind | def bind(queue_name, exchange_name, *routing_keys, &block)
queue = create_queue(queue_name, exchange_name,
queue_options: {durable: true},
routing_keys: routing_keys)
subscribe(queue, &block) if block_given?
end | ruby | def bind(queue_name, exchange_name, *routing_keys, &block)
queue = create_queue(queue_name, exchange_name,
queue_options: {durable: true},
routing_keys: routing_keys)
subscribe(queue, &block) if block_given?
end | [
"def",
"bind",
"(",
"queue_name",
",",
"exchange_name",
",",
"*",
"routing_keys",
",",
"&",
"block",
")",
"queue",
"=",
"create_queue",
"(",
"queue_name",
",",
"exchange_name",
",",
"queue_options",
":",
"{",
"durable",
":",
"true",
"}",
",",
"routing_keys",... | Initialize a new BunnyClient instance. Note that a connection is not established until any other method is called
@param [String, Hash] _url Server URL or options hash
@param [Hash] _bunny_options optional Bunny connection options
@see Bunny.new for connection options
Convenience method that finds or creates a named queue, binds to an exchange, and subscribes to messages.
If a block is provided, it will be called by the consumer each time a message is received.
@param [String] queue_name name of the queue
@param [String] exchange_name name of the AMQP exchange. Note that existing exchanges must be declared as Topic
exchanges; otherwise, an error will occur
@param [Array<String>] routing_keys list of routing keys to be bound to the queue for the specified exchange.
@yieldparam [String] payload message text
@return [Bunny::Consumer] Bunny consumer interface | [
"Initialize",
"a",
"new",
"BunnyClient",
"instance",
".",
"Note",
"that",
"a",
"connection",
"is",
"not",
"established",
"until",
"any",
"other",
"method",
"is",
"called"
] | 20b66d4d981e39d2c69cb04385551436cda32c67 | https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/bunny_client.rb#L35-L40 | valid |
KeasInc/isimud | lib/isimud/bunny_client.rb | Isimud.BunnyClient.create_queue | def create_queue(queue_name, exchange_name, options = {})
queue_options = options[:queue_options] || {durable: true}
routing_keys = options[:routing_keys] || []
log "Isimud::BunnyClient: create_queue #{queue_name}: queue_options=#{queue_options.inspect}"
queue = find_queue(queue_name, queue_options)
bind_routing_keys(queue, exchange_name, routing_keys) if routing_keys.any?
queue
end | ruby | def create_queue(queue_name, exchange_name, options = {})
queue_options = options[:queue_options] || {durable: true}
routing_keys = options[:routing_keys] || []
log "Isimud::BunnyClient: create_queue #{queue_name}: queue_options=#{queue_options.inspect}"
queue = find_queue(queue_name, queue_options)
bind_routing_keys(queue, exchange_name, routing_keys) if routing_keys.any?
queue
end | [
"def",
"create_queue",
"(",
"queue_name",
",",
"exchange_name",
",",
"options",
"=",
"{",
"}",
")",
"queue_options",
"=",
"options",
"[",
":queue_options",
"]",
"||",
"{",
"durable",
":",
"true",
"}",
"routing_keys",
"=",
"options",
"[",
":routing_keys",
"]"... | Find or create a named queue and bind it to the specified exchange
@param [String] queue_name name of the queue
@param [String] exchange_name name of the AMQP exchange. Note that pre-existing exchanges must be declared as Topic
exchanges; otherwise, an error will occur
@param [Hash] options queue declaration options
@option options [Boolean] :queue_options ({durable: true}) queue declaration options -- @see Bunny::Channel#queue
@option options [Array<String>] :routing_keys ([]) routing keys to be bound to the queue. Use "*" to match any 1 word
in a route segment. Use "#" to match 0 or more words in a segment.
@return [Bunny::Queue] Bunny queue | [
"Find",
"or",
"create",
"a",
"named",
"queue",
"and",
"bind",
"it",
"to",
"the",
"specified",
"exchange"
] | 20b66d4d981e39d2c69cb04385551436cda32c67 | https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/bunny_client.rb#L52-L59 | valid |
KeasInc/isimud | lib/isimud/bunny_client.rb | Isimud.BunnyClient.subscribe | def subscribe(queue, options = {}, &block)
queue.subscribe(options.merge(manual_ack: true)) do |delivery_info, properties, payload|
current_channel = delivery_info.channel
begin
log "Isimud: queue #{queue.name} received #{properties[:message_id]} routing_key: #{delivery_info.routing_key}", :debug
Thread.current['isimud_queue_name'] = queue.name
Thread.current['isimud_delivery_info'] = delivery_info
Thread.current['isimud_properties'] = properties
block.call(payload)
if current_channel.open?
log "Isimud: queue #{queue.name} finished with #{properties[:message_id]}, acknowledging", :debug
current_channel.ack(delivery_info.delivery_tag)
else
log "Isimud: queue #{queue.name} unable to acknowledge #{properties[:message_id]}", :warn
end
rescue => e
log("Isimud: queue #{queue.name} error processing #{properties[:message_id]} payload #{payload.inspect}: #{e.class.name} #{e.message}\n #{e.backtrace.join("\n ")}", :warn)
retry_status = run_exception_handlers(e)
log "Isimud: rejecting #{properties[:message_id]} requeue=#{retry_status}", :warn
current_channel.open? && current_channel.reject(delivery_info.delivery_tag, retry_status)
end
end
end | ruby | def subscribe(queue, options = {}, &block)
queue.subscribe(options.merge(manual_ack: true)) do |delivery_info, properties, payload|
current_channel = delivery_info.channel
begin
log "Isimud: queue #{queue.name} received #{properties[:message_id]} routing_key: #{delivery_info.routing_key}", :debug
Thread.current['isimud_queue_name'] = queue.name
Thread.current['isimud_delivery_info'] = delivery_info
Thread.current['isimud_properties'] = properties
block.call(payload)
if current_channel.open?
log "Isimud: queue #{queue.name} finished with #{properties[:message_id]}, acknowledging", :debug
current_channel.ack(delivery_info.delivery_tag)
else
log "Isimud: queue #{queue.name} unable to acknowledge #{properties[:message_id]}", :warn
end
rescue => e
log("Isimud: queue #{queue.name} error processing #{properties[:message_id]} payload #{payload.inspect}: #{e.class.name} #{e.message}\n #{e.backtrace.join("\n ")}", :warn)
retry_status = run_exception_handlers(e)
log "Isimud: rejecting #{properties[:message_id]} requeue=#{retry_status}", :warn
current_channel.open? && current_channel.reject(delivery_info.delivery_tag, retry_status)
end
end
end | [
"def",
"subscribe",
"(",
"queue",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"queue",
".",
"subscribe",
"(",
"options",
".",
"merge",
"(",
"manual_ack",
":",
"true",
")",
")",
"do",
"|",
"delivery_info",
",",
"properties",
",",
"payload",
... | Subscribe to messages on the Bunny queue. The provided block will be called each time a message is received.
The message will be acknowledged and deleted from the queue unless an exception is raised from the block.
In the case that an uncaught exception is raised, the message is rejected, and any declared exception handlers
will be called.
@param [Bunny::Queue] queue Bunny queue
@param [Hash] options {} subscription options -- @see Bunny::Queue#subscribe
@yieldparam [String] payload message text | [
"Subscribe",
"to",
"messages",
"on",
"the",
"Bunny",
"queue",
".",
"The",
"provided",
"block",
"will",
"be",
"called",
"each",
"time",
"a",
"message",
"is",
"received",
".",
"The",
"message",
"will",
"be",
"acknowledged",
"and",
"deleted",
"from",
"the",
"... | 20b66d4d981e39d2c69cb04385551436cda32c67 | https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/bunny_client.rb#L69-L91 | valid |
KeasInc/isimud | lib/isimud/bunny_client.rb | Isimud.BunnyClient.channel | def channel
if (channel = Thread.current[CHANNEL_KEY]).try(:open?)
channel
else
new_channel = connection.channel
new_channel.confirm_select
new_channel.prefetch(Isimud.prefetch_count) if Isimud.prefetch_count
Thread.current[CHANNEL_KEY] = new_channel
end
end | ruby | def channel
if (channel = Thread.current[CHANNEL_KEY]).try(:open?)
channel
else
new_channel = connection.channel
new_channel.confirm_select
new_channel.prefetch(Isimud.prefetch_count) if Isimud.prefetch_count
Thread.current[CHANNEL_KEY] = new_channel
end
end | [
"def",
"channel",
"if",
"(",
"channel",
"=",
"Thread",
".",
"current",
"[",
"CHANNEL_KEY",
"]",
")",
".",
"try",
"(",
":open?",
")",
"channel",
"else",
"new_channel",
"=",
"connection",
".",
"channel",
"new_channel",
".",
"confirm_select",
"new_channel",
"."... | Open a new, thread-specific AMQP connection channel, or return the current channel for this thread if it exists
and is currently open. New channels are created with publisher confirms enabled. Messages will be prefetched
according to Isimud.prefetch_count when declared.
@return [Bunny::Channel] channel instance. | [
"Open",
"a",
"new",
"thread",
"-",
"specific",
"AMQP",
"connection",
"channel",
"or",
"return",
"the",
"current",
"channel",
"for",
"this",
"thread",
"if",
"it",
"exists",
"and",
"is",
"currently",
"open",
".",
"New",
"channels",
"are",
"created",
"with",
... | 20b66d4d981e39d2c69cb04385551436cda32c67 | https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/bunny_client.rb#L114-L123 | valid |
KeasInc/isimud | lib/isimud/bunny_client.rb | Isimud.BunnyClient.publish | def publish(exchange, routing_key, payload, options = {})
log "Isimud::BunnyClient#publish: exchange=#{exchange} routing_key=#{routing_key}", :debug
channel.topic(exchange, durable: true).publish(payload, options.merge(routing_key: routing_key, persistent: true))
end | ruby | def publish(exchange, routing_key, payload, options = {})
log "Isimud::BunnyClient#publish: exchange=#{exchange} routing_key=#{routing_key}", :debug
channel.topic(exchange, durable: true).publish(payload, options.merge(routing_key: routing_key, persistent: true))
end | [
"def",
"publish",
"(",
"exchange",
",",
"routing_key",
",",
"payload",
",",
"options",
"=",
"{",
"}",
")",
"log",
"\"Isimud::BunnyClient#publish: exchange=#{exchange} routing_key=#{routing_key}\"",
",",
":debug",
"channel",
".",
"topic",
"(",
"exchange",
",",
"durable... | Publish a message to the specified exchange, which is declared as a durable, topic exchange. Note that message
is always persisted.
@param [String] exchange AMQP exchange name
@param [String] routing_key message routing key. This should always be in the form of words separated by dots
e.g. "user.goal.complete"
@param [String] payload message payload
@param [Hash] options additional message options
@see Bunny::Exchange#publish
@see http://rubybunny.info/articles/exchanges.html | [
"Publish",
"a",
"message",
"to",
"the",
"specified",
"exchange",
"which",
"is",
"declared",
"as",
"a",
"durable",
"topic",
"exchange",
".",
"Note",
"that",
"message",
"is",
"always",
"persisted",
"."
] | 20b66d4d981e39d2c69cb04385551436cda32c67 | https://github.com/KeasInc/isimud/blob/20b66d4d981e39d2c69cb04385551436cda32c67/lib/isimud/bunny_client.rb#L154-L157 | valid |
mmcclimon/mr_poole | lib/mr_poole/commands.rb | MrPoole.Commands.post | def post(opts)
opts = @helper.ensure_open_struct(opts)
date = @helper.get_date_stamp
# still want to escape any garbage in the slug
slug = if opts.slug.nil? || opts.slug.empty?
opts.title
else
opts.slug
end
slug = @helper.get_slug_for(slug)
# put the metadata into the layout header
head, ext = @helper.get_layout(opts.layout)
head.sub!(/^title:\s*$/, "title: #{opts.title}")
head.sub!(/^date:\s*$/, "date: #{date}")
ext ||= @ext
path = File.join(POSTS_FOLDER, "#{date}-#{slug}.#{ext}")
f = File.open(path, "w")
f.write(head)
f.close
@helper.open_in_editor(path) # open file if config key set
path # return the path, in case we want to do anything useful
end | ruby | def post(opts)
opts = @helper.ensure_open_struct(opts)
date = @helper.get_date_stamp
# still want to escape any garbage in the slug
slug = if opts.slug.nil? || opts.slug.empty?
opts.title
else
opts.slug
end
slug = @helper.get_slug_for(slug)
# put the metadata into the layout header
head, ext = @helper.get_layout(opts.layout)
head.sub!(/^title:\s*$/, "title: #{opts.title}")
head.sub!(/^date:\s*$/, "date: #{date}")
ext ||= @ext
path = File.join(POSTS_FOLDER, "#{date}-#{slug}.#{ext}")
f = File.open(path, "w")
f.write(head)
f.close
@helper.open_in_editor(path) # open file if config key set
path # return the path, in case we want to do anything useful
end | [
"def",
"post",
"(",
"opts",
")",
"opts",
"=",
"@helper",
".",
"ensure_open_struct",
"(",
"opts",
")",
"date",
"=",
"@helper",
".",
"get_date_stamp",
"slug",
"=",
"if",
"opts",
".",
"slug",
".",
"nil?",
"||",
"opts",
".",
"slug",
".",
"empty?",
"opts",
... | Generate a timestamped post | [
"Generate",
"a",
"timestamped",
"post"
] | 442404c64dd931185ddf2e2345ce2e76994c910f | https://github.com/mmcclimon/mr_poole/blob/442404c64dd931185ddf2e2345ce2e76994c910f/lib/mr_poole/commands.rb#L15-L39 | valid |
mmcclimon/mr_poole | lib/mr_poole/commands.rb | MrPoole.Commands.draft | def draft(opts)
opts = @helper.ensure_open_struct(opts)
# the drafts folder might not exist yet...create it just in case
FileUtils.mkdir_p(DRAFTS_FOLDER)
slug = if opts.slug.nil? || opts.slug.empty?
opts.title
else
opts.slug
end
slug = @helper.get_slug_for(slug)
# put the metadata into the layout header
head, ext = @helper.get_layout(opts.layout)
head.sub!(/^title:\s*$/, "title: #{opts.title}")
head.sub!(/^date:\s*$/, "date: #{@helper.get_date_stamp}")
ext ||= @ext
path = File.join(DRAFTS_FOLDER, "#{slug}.#{ext}")
f = File.open(path, "w")
f.write(head)
f.close
@helper.open_in_editor(path) # open file if config key set
path # return the path, in case we want to do anything useful
end | ruby | def draft(opts)
opts = @helper.ensure_open_struct(opts)
# the drafts folder might not exist yet...create it just in case
FileUtils.mkdir_p(DRAFTS_FOLDER)
slug = if opts.slug.nil? || opts.slug.empty?
opts.title
else
opts.slug
end
slug = @helper.get_slug_for(slug)
# put the metadata into the layout header
head, ext = @helper.get_layout(opts.layout)
head.sub!(/^title:\s*$/, "title: #{opts.title}")
head.sub!(/^date:\s*$/, "date: #{@helper.get_date_stamp}")
ext ||= @ext
path = File.join(DRAFTS_FOLDER, "#{slug}.#{ext}")
f = File.open(path, "w")
f.write(head)
f.close
@helper.open_in_editor(path) # open file if config key set
path # return the path, in case we want to do anything useful
end | [
"def",
"draft",
"(",
"opts",
")",
"opts",
"=",
"@helper",
".",
"ensure_open_struct",
"(",
"opts",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"DRAFTS_FOLDER",
")",
"slug",
"=",
"if",
"opts",
".",
"slug",
".",
"nil?",
"||",
"opts",
".",
"slug",
".",
"empty?"... | Generate a non-timestamped draft | [
"Generate",
"a",
"non",
"-",
"timestamped",
"draft"
] | 442404c64dd931185ddf2e2345ce2e76994c910f | https://github.com/mmcclimon/mr_poole/blob/442404c64dd931185ddf2e2345ce2e76994c910f/lib/mr_poole/commands.rb#L42-L67 | valid |
mmcclimon/mr_poole | lib/mr_poole/commands.rb | MrPoole.Commands.publish | def publish(draftpath, opts={})
opts = @helper.ensure_open_struct(opts)
tail = File.basename(draftpath)
begin
infile = File.open(draftpath, "r")
rescue Errno::ENOENT
@helper.bad_path(draftpath)
end
date = @helper.get_date_stamp
time = @helper.get_time_stamp
outpath = File.join(POSTS_FOLDER, "#{date}-#{tail}")
outfile = File.open(outpath, "w")
infile.each_line do |line|
line.sub!(/^date:.*$/, "date: #{date} #{time}\n") unless opts.keep_timestamp
outfile.write(line)
end
infile.close
outfile.close
FileUtils.rm(draftpath) unless opts.keep_draft
outpath
end | ruby | def publish(draftpath, opts={})
opts = @helper.ensure_open_struct(opts)
tail = File.basename(draftpath)
begin
infile = File.open(draftpath, "r")
rescue Errno::ENOENT
@helper.bad_path(draftpath)
end
date = @helper.get_date_stamp
time = @helper.get_time_stamp
outpath = File.join(POSTS_FOLDER, "#{date}-#{tail}")
outfile = File.open(outpath, "w")
infile.each_line do |line|
line.sub!(/^date:.*$/, "date: #{date} #{time}\n") unless opts.keep_timestamp
outfile.write(line)
end
infile.close
outfile.close
FileUtils.rm(draftpath) unless opts.keep_draft
outpath
end | [
"def",
"publish",
"(",
"draftpath",
",",
"opts",
"=",
"{",
"}",
")",
"opts",
"=",
"@helper",
".",
"ensure_open_struct",
"(",
"opts",
")",
"tail",
"=",
"File",
".",
"basename",
"(",
"draftpath",
")",
"begin",
"infile",
"=",
"File",
".",
"open",
"(",
"... | Todo make this take a path instead?
@param draftpath [String] path to the draft, relative to source directory
@option options :keep_draft [Boolean] if true, keep the draft file
@option options :keep_timestamp [Boolean] if true, don't change the timestamp | [
"Todo",
"make",
"this",
"take",
"a",
"path",
"instead?"
] | 442404c64dd931185ddf2e2345ce2e76994c910f | https://github.com/mmcclimon/mr_poole/blob/442404c64dd931185ddf2e2345ce2e76994c910f/lib/mr_poole/commands.rb#L74-L100 | valid |
danopia/luck | lib/luck/ansi.rb | Luck.ANSIDriver.terminal_size | def terminal_size
rows, cols = 25, 80
buf = [0, 0, 0, 0].pack("SSSS")
if $stdout.ioctl(TIOCGWINSZ, buf) >= 0 then
rows, cols, row_pixels, col_pixels = buf.unpack("SSSS")
end
return [rows, cols]
end | ruby | def terminal_size
rows, cols = 25, 80
buf = [0, 0, 0, 0].pack("SSSS")
if $stdout.ioctl(TIOCGWINSZ, buf) >= 0 then
rows, cols, row_pixels, col_pixels = buf.unpack("SSSS")
end
return [rows, cols]
end | [
"def",
"terminal_size",
"rows",
",",
"cols",
"=",
"25",
",",
"80",
"buf",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
".",
"pack",
"(",
"\"SSSS\"",
")",
"if",
"$stdout",
".",
"ioctl",
"(",
"TIOCGWINSZ",
",",
"buf",
")",
">=",
"0",
"then",... | 0000002
thanks google for all of this | [
"0000002",
"thanks",
"google",
"for",
"all",
"of",
"this"
] | 70ffc07cfffc3c2cc81a4586198295ba13983212 | https://github.com/danopia/luck/blob/70ffc07cfffc3c2cc81a4586198295ba13983212/lib/luck/ansi.rb#L185-L192 | valid |
danopia/luck | lib/luck/ansi.rb | Luck.ANSIDriver.prepare_modes | def prepare_modes
buf = [0, 0, 0, 0, 0, 0, ''].pack("IIIICCA*")
$stdout.ioctl(TCGETS, buf)
@old_modes = buf.unpack("IIIICCA*")
new_modes = @old_modes.clone
new_modes[3] &= ~ECHO # echo off
new_modes[3] &= ~ICANON # one char @ a time
$stdout.ioctl(TCSETS, new_modes.pack("IIIICCA*"))
print "\e[2J" # clear screen
print "\e[H" # go home
print "\e[?47h" # kick xterm into the alt screen
print "\e[?1000h" # kindly ask for mouse positions to make up for it
self.cursor = false
flush
end | ruby | def prepare_modes
buf = [0, 0, 0, 0, 0, 0, ''].pack("IIIICCA*")
$stdout.ioctl(TCGETS, buf)
@old_modes = buf.unpack("IIIICCA*")
new_modes = @old_modes.clone
new_modes[3] &= ~ECHO # echo off
new_modes[3] &= ~ICANON # one char @ a time
$stdout.ioctl(TCSETS, new_modes.pack("IIIICCA*"))
print "\e[2J" # clear screen
print "\e[H" # go home
print "\e[?47h" # kick xterm into the alt screen
print "\e[?1000h" # kindly ask for mouse positions to make up for it
self.cursor = false
flush
end | [
"def",
"prepare_modes",
"buf",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"''",
"]",
".",
"pack",
"(",
"\"IIIICCA*\"",
")",
"$stdout",
".",
"ioctl",
"(",
"TCGETS",
",",
"buf",
")",
"@old_modes",
"=",
"buf",
".",
"unpa... | had to convert these from C... fun | [
"had",
"to",
"convert",
"these",
"from",
"C",
"...",
"fun"
] | 70ffc07cfffc3c2cc81a4586198295ba13983212 | https://github.com/danopia/luck/blob/70ffc07cfffc3c2cc81a4586198295ba13983212/lib/luck/ansi.rb#L195-L209 | valid |
chall8908/cancancan_masquerade | lib/cancancan/masquerade.rb | CanCanCan.Masquerade.extract_subjects | def extract_subjects(subject)
return extract_subjects(subject.to_permission_instance) if subject.respond_to? :to_permission_instance
return subject[:any] if subject.is_a? Hash and subject.key? :any
[subject]
end | ruby | def extract_subjects(subject)
return extract_subjects(subject.to_permission_instance) if subject.respond_to? :to_permission_instance
return subject[:any] if subject.is_a? Hash and subject.key? :any
[subject]
end | [
"def",
"extract_subjects",
"(",
"subject",
")",
"return",
"extract_subjects",
"(",
"subject",
".",
"to_permission_instance",
")",
"if",
"subject",
".",
"respond_to?",
":to_permission_instance",
"return",
"subject",
"[",
":any",
"]",
"if",
"subject",
".",
"is_a?",
... | Override functionality from CanCan to allow objects to masquerade as other objects | [
"Override",
"functionality",
"from",
"CanCan",
"to",
"allow",
"objects",
"to",
"masquerade",
"as",
"other",
"objects"
] | 60640f241e142639f90d88224cac84b3ea381a31 | https://github.com/chall8908/cancancan_masquerade/blob/60640f241e142639f90d88224cac84b3ea381a31/lib/cancancan/masquerade.rb#L4-L10 | valid |
bdwyertech/newrelic-management | lib/newrelic-management/controller.rb | NewRelicManagement.Controller.daemon | def daemon # rubocop: disable AbcSize, MethodLength
# => Windows Workaround (https://github.com/bdwyertech/newrelic-management/issues/1)
ENV['TZ'] = 'UTC' if OS.windows? && !ENV['TZ']
scheduler = Rufus::Scheduler.new
Notifier.msg('Daemonizing Process')
# => Alerts Management
alerts_interval = Config.alert_management_interval
scheduler.every alerts_interval, overlap: false do
Manager.manage_alerts
end
# => Cleanup Stale Servers
if Config.cleanup
cleanup_interval = Config.cleanup_interval
cleanup_age = Config.cleanup_age
scheduler.every cleanup_interval, overlap: false do
Manager.remove_nonreporting_servers(cleanup_age)
end
end
# => Join the Current Thread to the Scheduler Thread
scheduler.join
end | ruby | def daemon # rubocop: disable AbcSize, MethodLength
# => Windows Workaround (https://github.com/bdwyertech/newrelic-management/issues/1)
ENV['TZ'] = 'UTC' if OS.windows? && !ENV['TZ']
scheduler = Rufus::Scheduler.new
Notifier.msg('Daemonizing Process')
# => Alerts Management
alerts_interval = Config.alert_management_interval
scheduler.every alerts_interval, overlap: false do
Manager.manage_alerts
end
# => Cleanup Stale Servers
if Config.cleanup
cleanup_interval = Config.cleanup_interval
cleanup_age = Config.cleanup_age
scheduler.every cleanup_interval, overlap: false do
Manager.remove_nonreporting_servers(cleanup_age)
end
end
# => Join the Current Thread to the Scheduler Thread
scheduler.join
end | [
"def",
"daemon",
"ENV",
"[",
"'TZ'",
"]",
"=",
"'UTC'",
"if",
"OS",
".",
"windows?",
"&&",
"!",
"ENV",
"[",
"'TZ'",
"]",
"scheduler",
"=",
"Rufus",
"::",
"Scheduler",
".",
"new",
"Notifier",
".",
"msg",
"(",
"'Daemonizing Process'",
")",
"alerts_interval... | => Daemonization for Periodic Management | [
"=",
">",
"Daemonization",
"for",
"Periodic",
"Management"
] | 265f0024b52d1fed476f35448b6b518453b4b1a6 | https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/controller.rb#L23-L48 | valid |
bdwyertech/newrelic-management | lib/newrelic-management/controller.rb | NewRelicManagement.Controller.run | def run
daemon if Config.daemonize
# => Manage Alerts
Manager.manage_alerts
# => Manage
Manager.remove_nonreporting_servers(Config.cleanup_age) if Config.cleanup
end | ruby | def run
daemon if Config.daemonize
# => Manage Alerts
Manager.manage_alerts
# => Manage
Manager.remove_nonreporting_servers(Config.cleanup_age) if Config.cleanup
end | [
"def",
"run",
"daemon",
"if",
"Config",
".",
"daemonize",
"Manager",
".",
"manage_alerts",
"Manager",
".",
"remove_nonreporting_servers",
"(",
"Config",
".",
"cleanup_age",
")",
"if",
"Config",
".",
"cleanup",
"end"
] | => Run the Application | [
"=",
">",
"Run",
"the",
"Application"
] | 265f0024b52d1fed476f35448b6b518453b4b1a6 | https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/controller.rb#L51-L59 | valid |
mmcclimon/mr_poole | lib/mr_poole/helper.rb | MrPoole.Helper.ensure_jekyll_dir | def ensure_jekyll_dir
@orig_dir = Dir.pwd
start_path = Pathname.new(@orig_dir)
ok = File.exists?('./_posts')
new_path = nil
# if it doesn't exist, check for a custom source dir in _config.yml
if !ok
check_custom_src_dir!
ok = File.exists?('./_posts')
new_path = Pathname.new(Dir.pwd)
end
if ok
return (new_path ? new_path.relative_path_from(start_path) : '.')
else
puts 'ERROR: Cannot locate _posts directory. Double check to make sure'
puts ' that you are in a jekyll directory.'
exit
end
end | ruby | def ensure_jekyll_dir
@orig_dir = Dir.pwd
start_path = Pathname.new(@orig_dir)
ok = File.exists?('./_posts')
new_path = nil
# if it doesn't exist, check for a custom source dir in _config.yml
if !ok
check_custom_src_dir!
ok = File.exists?('./_posts')
new_path = Pathname.new(Dir.pwd)
end
if ok
return (new_path ? new_path.relative_path_from(start_path) : '.')
else
puts 'ERROR: Cannot locate _posts directory. Double check to make sure'
puts ' that you are in a jekyll directory.'
exit
end
end | [
"def",
"ensure_jekyll_dir",
"@orig_dir",
"=",
"Dir",
".",
"pwd",
"start_path",
"=",
"Pathname",
".",
"new",
"(",
"@orig_dir",
")",
"ok",
"=",
"File",
".",
"exists?",
"(",
"'./_posts'",
")",
"new_path",
"=",
"nil",
"if",
"!",
"ok",
"check_custom_src_dir!",
... | Check for a _posts directory in current directory. If there's not one,
check for a _config.yml and look for a custom src directory. If we
don't find one, puke an error message and die. If we do, return the name
of the directory | [
"Check",
"for",
"a",
"_posts",
"directory",
"in",
"current",
"directory",
".",
"If",
"there",
"s",
"not",
"one",
"check",
"for",
"a",
"_config",
".",
"yml",
"and",
"look",
"for",
"a",
"custom",
"src",
"directory",
".",
"If",
"we",
"don",
"t",
"find",
... | 442404c64dd931185ddf2e2345ce2e76994c910f | https://github.com/mmcclimon/mr_poole/blob/442404c64dd931185ddf2e2345ce2e76994c910f/lib/mr_poole/helper.rb#L17-L38 | valid |
mmcclimon/mr_poole | lib/mr_poole/helper.rb | MrPoole.Helper.get_layout | def get_layout(layout_path)
if layout_path.nil?
contents = "---\n"
contents << "title:\n"
contents << "layout: post\n"
contents << "date:\n"
contents << "---\n"
ext = nil
else
begin
contents = File.open(layout_path, "r").read()
ext = layout_path.match(/\.(.*?)$/)[1]
rescue Errno::ENOENT
bad_path(layout_path)
end
end
return contents, ext
end | ruby | def get_layout(layout_path)
if layout_path.nil?
contents = "---\n"
contents << "title:\n"
contents << "layout: post\n"
contents << "date:\n"
contents << "---\n"
ext = nil
else
begin
contents = File.open(layout_path, "r").read()
ext = layout_path.match(/\.(.*?)$/)[1]
rescue Errno::ENOENT
bad_path(layout_path)
end
end
return contents, ext
end | [
"def",
"get_layout",
"(",
"layout_path",
")",
"if",
"layout_path",
".",
"nil?",
"contents",
"=",
"\"---\\n\"",
"contents",
"<<",
"\"title:\\n\"",
"contents",
"<<",
"\"layout: post\\n\"",
"contents",
"<<",
"\"date:\\n\"",
"contents",
"<<",
"\"---\\n\"",
"ext",
"=",
... | Get a layout as a string. If layout_path is non-nil, will open that
file and read it, otherwise will return a default one, and a file
extension to use | [
"Get",
"a",
"layout",
"as",
"a",
"string",
".",
"If",
"layout_path",
"is",
"non",
"-",
"nil",
"will",
"open",
"that",
"file",
"and",
"read",
"it",
"otherwise",
"will",
"return",
"a",
"default",
"one",
"and",
"a",
"file",
"extension",
"to",
"use"
] | 442404c64dd931185ddf2e2345ce2e76994c910f | https://github.com/mmcclimon/mr_poole/blob/442404c64dd931185ddf2e2345ce2e76994c910f/lib/mr_poole/helper.rb#L51-L70 | valid |
mmcclimon/mr_poole | lib/mr_poole/helper.rb | MrPoole.Helper.gen_usage | def gen_usage
puts 'Usage:'
puts ' poole [ACTION] [ARG]'
puts ''
puts 'Actions:'
puts ' draft Create a new draft in _drafts with title SLUG'
puts ' post Create a new timestamped post in _posts with title SLUG'
puts ' publish Publish the draft with SLUG, timestamping appropriately'
puts ' unpublish Move a post to _drafts, untimestamping appropriately'
exit
end | ruby | def gen_usage
puts 'Usage:'
puts ' poole [ACTION] [ARG]'
puts ''
puts 'Actions:'
puts ' draft Create a new draft in _drafts with title SLUG'
puts ' post Create a new timestamped post in _posts with title SLUG'
puts ' publish Publish the draft with SLUG, timestamping appropriately'
puts ' unpublish Move a post to _drafts, untimestamping appropriately'
exit
end | [
"def",
"gen_usage",
"puts",
"'Usage:'",
"puts",
"' poole [ACTION] [ARG]'",
"puts",
"''",
"puts",
"'Actions:'",
"puts",
"' draft Create a new draft in _drafts with title SLUG'",
"puts",
"' post Create a new timestamped post in _posts with title SLUG'",
"puts",
"' publish ... | Print a usage message and exit | [
"Print",
"a",
"usage",
"message",
"and",
"exit"
] | 442404c64dd931185ddf2e2345ce2e76994c910f | https://github.com/mmcclimon/mr_poole/blob/442404c64dd931185ddf2e2345ce2e76994c910f/lib/mr_poole/helper.rb#L120-L130 | valid |
bdwyertech/newrelic-management | lib/newrelic-management/notifier.rb | NewRelicManagement.Notifier.msg | def msg(message, subtitle = message, title = 'NewRelic Management')
# => Stdout Messages
terminal_notification(message, subtitle)
return if Config.silent
# => Pretty GUI Messages
osx_notification(message, subtitle, title) if OS.x?
end | ruby | def msg(message, subtitle = message, title = 'NewRelic Management')
# => Stdout Messages
terminal_notification(message, subtitle)
return if Config.silent
# => Pretty GUI Messages
osx_notification(message, subtitle, title) if OS.x?
end | [
"def",
"msg",
"(",
"message",
",",
"subtitle",
"=",
"message",
",",
"title",
"=",
"'NewRelic Management'",
")",
"terminal_notification",
"(",
"message",
",",
"subtitle",
")",
"return",
"if",
"Config",
".",
"silent",
"osx_notification",
"(",
"message",
",",
"su... | => Primary Notification Message Controller | [
"=",
">",
"Primary",
"Notification",
"Message",
"Controller"
] | 265f0024b52d1fed476f35448b6b518453b4b1a6 | https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/notifier.rb#L23-L31 | valid |
bdwyertech/newrelic-management | lib/newrelic-management/notifier.rb | NewRelicManagement.Notifier.osx_notification | def osx_notification(message, subtitle, title)
TerminalNotifier.notify(message, title: title, subtitle: subtitle)
end | ruby | def osx_notification(message, subtitle, title)
TerminalNotifier.notify(message, title: title, subtitle: subtitle)
end | [
"def",
"osx_notification",
"(",
"message",
",",
"subtitle",
",",
"title",
")",
"TerminalNotifier",
".",
"notify",
"(",
"message",
",",
"title",
":",
"title",
",",
"subtitle",
":",
"subtitle",
")",
"end"
] | => OS X Cocoa Messages | [
"=",
">",
"OS",
"X",
"Cocoa",
"Messages"
] | 265f0024b52d1fed476f35448b6b518453b4b1a6 | https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/notifier.rb#L40-L42 | valid |
mlj/ruby-sfst | lib/sfst.rb | SFST.RegularTransducer.analyze | def analyze(string, options = {})
x = []
@fst._analyze(string) do |a|
if options[:symbol_sequence]
x << a.map { |s| s.match(/^<(.*)>$/) ? $1.to_sym : s }
else
x << a.join
end
end
x
end | ruby | def analyze(string, options = {})
x = []
@fst._analyze(string) do |a|
if options[:symbol_sequence]
x << a.map { |s| s.match(/^<(.*)>$/) ? $1.to_sym : s }
else
x << a.join
end
end
x
end | [
"def",
"analyze",
"(",
"string",
",",
"options",
"=",
"{",
"}",
")",
"x",
"=",
"[",
"]",
"@fst",
".",
"_analyze",
"(",
"string",
")",
"do",
"|",
"a",
"|",
"if",
"options",
"[",
":symbol_sequence",
"]",
"x",
"<<",
"a",
".",
"map",
"{",
"|",
"s",... | Analyses a string +string+. Returns an array of analysed
strings if the string is accepted, or an empty array if not.
==== Options
* +symbol_sequence+ - Return each analysis as a sequence of symbols.
Multicharacter symbols will be strings on the form +<symbol>+. | [
"Analyses",
"a",
"string",
"+",
"string",
"+",
".",
"Returns",
"an",
"array",
"of",
"analysed",
"strings",
"if",
"the",
"string",
"is",
"accepted",
"or",
"an",
"empty",
"array",
"if",
"not",
"."
] | f3e1bc83d702f91d3d4792d622538938188af997 | https://github.com/mlj/ruby-sfst/blob/f3e1bc83d702f91d3d4792d622538938188af997/lib/sfst.rb#L35-L45 | valid |
mlj/ruby-sfst | lib/sfst.rb | SFST.RegularTransducer.generate | def generate(string)
x = []
@fst._generate(string) { |a| x << a.join }
x
end | ruby | def generate(string)
x = []
@fst._generate(string) { |a| x << a.join }
x
end | [
"def",
"generate",
"(",
"string",
")",
"x",
"=",
"[",
"]",
"@fst",
".",
"_generate",
"(",
"string",
")",
"{",
"|",
"a",
"|",
"x",
"<<",
"a",
".",
"join",
"}",
"x",
"end"
] | Generates a string +string+. Returns an array of generated
strings if the string is accepted or an empty array if not. | [
"Generates",
"a",
"string",
"+",
"string",
"+",
".",
"Returns",
"an",
"array",
"of",
"generated",
"strings",
"if",
"the",
"string",
"is",
"accepted",
"or",
"an",
"empty",
"array",
"if",
"not",
"."
] | f3e1bc83d702f91d3d4792d622538938188af997 | https://github.com/mlj/ruby-sfst/blob/f3e1bc83d702f91d3d4792d622538938188af997/lib/sfst.rb#L54-L58 | valid |
bdwyertech/newrelic-management | lib/newrelic-management/cli.rb | NewRelicManagement.CLI.configure | def configure(argv = ARGV)
# => Parse CLI Configuration
cli = Options.new
cli.parse_options(argv)
# => Parse JSON Config File (If Specified and Exists)
json_config = Util.parse_json(cli.config[:config_file] || Config.config_file)
# => Merge Configuration (CLI Wins)
config = [json_config, cli.config].compact.reduce(:merge)
# => Apply Configuration
config.each { |k, v| Config.send("#{k}=", v) }
end | ruby | def configure(argv = ARGV)
# => Parse CLI Configuration
cli = Options.new
cli.parse_options(argv)
# => Parse JSON Config File (If Specified and Exists)
json_config = Util.parse_json(cli.config[:config_file] || Config.config_file)
# => Merge Configuration (CLI Wins)
config = [json_config, cli.config].compact.reduce(:merge)
# => Apply Configuration
config.each { |k, v| Config.send("#{k}=", v) }
end | [
"def",
"configure",
"(",
"argv",
"=",
"ARGV",
")",
"cli",
"=",
"Options",
".",
"new",
"cli",
".",
"parse_options",
"(",
"argv",
")",
"json_config",
"=",
"Util",
".",
"parse_json",
"(",
"cli",
".",
"config",
"[",
":config_file",
"]",
"||",
"Config",
"."... | => Configure the CLI | [
"=",
">",
"Configure",
"the",
"CLI"
] | 265f0024b52d1fed476f35448b6b518453b4b1a6 | https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/cli.rb#L67-L80 | valid |
robertodecurnex/spectro | lib/spectro/compiler.rb | Spectro.Compiler.missing_specs_from_file | def missing_specs_from_file(path)
Spectro::Spec::Parser.parse(path).select do |spec|
index_spec = Spectro::Database.index[path] && Spectro::Database.index[path][spec.signature.name]
index_spec.nil? || index_spec['spec_md5'] != spec.md5
end
end | ruby | def missing_specs_from_file(path)
Spectro::Spec::Parser.parse(path).select do |spec|
index_spec = Spectro::Database.index[path] && Spectro::Database.index[path][spec.signature.name]
index_spec.nil? || index_spec['spec_md5'] != spec.md5
end
end | [
"def",
"missing_specs_from_file",
"(",
"path",
")",
"Spectro",
"::",
"Spec",
"::",
"Parser",
".",
"parse",
"(",
"path",
")",
".",
"select",
"do",
"|",
"spec",
"|",
"index_spec",
"=",
"Spectro",
"::",
"Database",
".",
"index",
"[",
"path",
"]",
"&&",
"S... | Parse the specs on the given file path and return those
that have not been fulfilled or need to be updated.
@param [String] path target file path
@return [<Spectro::Spec>] collection of specs not fulfilled or out of date | [
"Parse",
"the",
"specs",
"on",
"the",
"given",
"file",
"path",
"and",
"return",
"those",
"that",
"have",
"not",
"been",
"fulfilled",
"or",
"need",
"to",
"be",
"updated",
"."
] | 0c9945659e6eb00c7ff026a5065cdbd9a74f119f | https://github.com/robertodecurnex/spectro/blob/0c9945659e6eb00c7ff026a5065cdbd9a74f119f/lib/spectro/compiler.rb#L87-L92 | valid |
bdwyertech/newrelic-management | lib/newrelic-management/manager.rb | NewRelicManagement.Manager.remove_nonreporting_servers | def remove_nonreporting_servers(keeptime = nil)
list_nonreporting_servers.each do |server|
next if keeptime && Time.parse(server[:last_reported_at]) >= Time.now - ChronicDuration.parse(keeptime)
Notifier.msg(server[:name], 'Removing Stale, Non-Reporting Server')
Client.delete_server(server[:id])
end
end | ruby | def remove_nonreporting_servers(keeptime = nil)
list_nonreporting_servers.each do |server|
next if keeptime && Time.parse(server[:last_reported_at]) >= Time.now - ChronicDuration.parse(keeptime)
Notifier.msg(server[:name], 'Removing Stale, Non-Reporting Server')
Client.delete_server(server[:id])
end
end | [
"def",
"remove_nonreporting_servers",
"(",
"keeptime",
"=",
"nil",
")",
"list_nonreporting_servers",
".",
"each",
"do",
"|",
"server",
"|",
"next",
"if",
"keeptime",
"&&",
"Time",
".",
"parse",
"(",
"server",
"[",
":last_reported_at",
"]",
")",
">=",
"Time",
... | => Remove Non-Reporting Servers | [
"=",
">",
"Remove",
"Non",
"-",
"Reporting",
"Servers"
] | 265f0024b52d1fed476f35448b6b518453b4b1a6 | https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/manager.rb#L119-L125 | valid |
bdwyertech/newrelic-management | lib/newrelic-management/manager.rb | NewRelicManagement.Manager.find_excluded | def find_excluded(excluded)
result = []
Array(excluded).each do |exclude|
if exclude.include?(':')
find_labeled(exclude).each { |x| result << x }
next
end
res = Client.get_server(exclude)
result << res['id'] if res
end
result
end | ruby | def find_excluded(excluded)
result = []
Array(excluded).each do |exclude|
if exclude.include?(':')
find_labeled(exclude).each { |x| result << x }
next
end
res = Client.get_server(exclude)
result << res['id'] if res
end
result
end | [
"def",
"find_excluded",
"(",
"excluded",
")",
"result",
"=",
"[",
"]",
"Array",
"(",
"excluded",
")",
".",
"each",
"do",
"|",
"exclude",
"|",
"if",
"exclude",
".",
"include?",
"(",
"':'",
")",
"find_labeled",
"(",
"exclude",
")",
".",
"each",
"{",
"|... | => Find Servers which should be excluded from Management | [
"=",
">",
"Find",
"Servers",
"which",
"should",
"be",
"excluded",
"from",
"Management"
] | 265f0024b52d1fed476f35448b6b518453b4b1a6 | https://github.com/bdwyertech/newrelic-management/blob/265f0024b52d1fed476f35448b6b518453b4b1a6/lib/newrelic-management/manager.rb#L128-L139 | valid |
JackDanger/twilio_contactable | lib/contactable.rb | TwilioContactable.Contactable.send_sms_confirmation! | def send_sms_confirmation!
return false if _TC_sms_blocked
return true if sms_confirmed?
return false if _TC_phone_number.blank?
format_phone_number
confirmation_code = TwilioContactable.confirmation_code(self, :sms)
# Use this class' confirmation_message method if it
# exists, otherwise use the generic message
message = (self.class.respond_to?(:confirmation_message) ?
self.class :
TwilioContactable).confirmation_message(confirmation_code)
if message.to_s.size > 160
raise ArgumentError, "SMS Confirmation Message is too long. Limit it to 160 characters of unescaped text."
end
response = TwilioContactable::Gateway.deliver_sms(message, _TC_formatted_phone_number)
if response.success?
update_twilio_contactable_sms_confirmation confirmation_code
end
response
end | ruby | def send_sms_confirmation!
return false if _TC_sms_blocked
return true if sms_confirmed?
return false if _TC_phone_number.blank?
format_phone_number
confirmation_code = TwilioContactable.confirmation_code(self, :sms)
# Use this class' confirmation_message method if it
# exists, otherwise use the generic message
message = (self.class.respond_to?(:confirmation_message) ?
self.class :
TwilioContactable).confirmation_message(confirmation_code)
if message.to_s.size > 160
raise ArgumentError, "SMS Confirmation Message is too long. Limit it to 160 characters of unescaped text."
end
response = TwilioContactable::Gateway.deliver_sms(message, _TC_formatted_phone_number)
if response.success?
update_twilio_contactable_sms_confirmation confirmation_code
end
response
end | [
"def",
"send_sms_confirmation!",
"return",
"false",
"if",
"_TC_sms_blocked",
"return",
"true",
"if",
"sms_confirmed?",
"return",
"false",
"if",
"_TC_phone_number",
".",
"blank?",
"format_phone_number",
"confirmation_code",
"=",
"TwilioContactable",
".",
"confirmation_code",... | Sends an SMS validation request through the gateway | [
"Sends",
"an",
"SMS",
"validation",
"request",
"through",
"the",
"gateway"
] | a3ec81c6d9c34dec767642d1dfb76a65ce0929db | https://github.com/JackDanger/twilio_contactable/blob/a3ec81c6d9c34dec767642d1dfb76a65ce0929db/lib/contactable.rb#L86-L111 | valid |
JackDanger/twilio_contactable | lib/contactable.rb | TwilioContactable.Contactable.send_voice_confirmation! | def send_voice_confirmation!
return false if _TC_voice_blocked
return true if voice_confirmed?
return false if _TC_phone_number.blank?
format_phone_number
confirmation_code = TwilioContactable.confirmation_code(self, :voice)
response = TwilioContactable::Gateway.initiate_voice_call(self, _TC_formatted_phone_number)
if response.success?
update_twilio_contactable_voice_confirmation confirmation_code
end
response
end | ruby | def send_voice_confirmation!
return false if _TC_voice_blocked
return true if voice_confirmed?
return false if _TC_phone_number.blank?
format_phone_number
confirmation_code = TwilioContactable.confirmation_code(self, :voice)
response = TwilioContactable::Gateway.initiate_voice_call(self, _TC_formatted_phone_number)
if response.success?
update_twilio_contactable_voice_confirmation confirmation_code
end
response
end | [
"def",
"send_voice_confirmation!",
"return",
"false",
"if",
"_TC_voice_blocked",
"return",
"true",
"if",
"voice_confirmed?",
"return",
"false",
"if",
"_TC_phone_number",
".",
"blank?",
"format_phone_number",
"confirmation_code",
"=",
"TwilioContactable",
".",
"confirmation_... | Begins a phone call to the user where they'll need to type
their confirmation code | [
"Begins",
"a",
"phone",
"call",
"to",
"the",
"user",
"where",
"they",
"ll",
"need",
"to",
"type",
"their",
"confirmation",
"code"
] | a3ec81c6d9c34dec767642d1dfb76a65ce0929db | https://github.com/JackDanger/twilio_contactable/blob/a3ec81c6d9c34dec767642d1dfb76a65ce0929db/lib/contactable.rb#L115-L130 | valid |
sosedoff/terminal_helpers | lib/terminal_helpers/validations.rb | TerminalHelpers.Validations.validate | def validate(value, format, raise_error=false)
unless FORMATS.key?(format)
raise FormatError, "Invalid data format: #{format}"
end
result = value =~ FORMATS[format] ? true : false
if raise_error && !result
raise ValidationError, "Invalid value \"#{value}\" for #{format}"
end
result
end | ruby | def validate(value, format, raise_error=false)
unless FORMATS.key?(format)
raise FormatError, "Invalid data format: #{format}"
end
result = value =~ FORMATS[format] ? true : false
if raise_error && !result
raise ValidationError, "Invalid value \"#{value}\" for #{format}"
end
result
end | [
"def",
"validate",
"(",
"value",
",",
"format",
",",
"raise_error",
"=",
"false",
")",
"unless",
"FORMATS",
".",
"key?",
"(",
"format",
")",
"raise",
"FormatError",
",",
"\"Invalid data format: #{format}\"",
"end",
"result",
"=",
"value",
"=~",
"FORMATS",
"[",... | Validate data against provided format | [
"Validate",
"data",
"against",
"provided",
"format"
] | 7822b28b4f97b31786a149599514a0bc5c8f3cce | https://github.com/sosedoff/terminal_helpers/blob/7822b28b4f97b31786a149599514a0bc5c8f3cce/lib/terminal_helpers/validations.rb#L14-L23 | valid |
vyorkin-personal/xftp | lib/xftp/client.rb | XFTP.Client.call | def call(url, settings, &block)
uri = URI.parse(url)
klass = adapter_class(uri.scheme)
session = klass.new(uri, settings.deep_dup)
session.start(&block)
end | ruby | def call(url, settings, &block)
uri = URI.parse(url)
klass = adapter_class(uri.scheme)
session = klass.new(uri, settings.deep_dup)
session.start(&block)
end | [
"def",
"call",
"(",
"url",
",",
"settings",
",",
"&",
"block",
")",
"uri",
"=",
"URI",
".",
"parse",
"(",
"url",
")",
"klass",
"=",
"adapter_class",
"(",
"uri",
".",
"scheme",
")",
"session",
"=",
"klass",
".",
"new",
"(",
"uri",
",",
"settings",
... | Initiates a new session
@see XFTP::Validator::Settings | [
"Initiates",
"a",
"new",
"session"
] | 91a3185f60b02d5db951d5c3c0ae18c86a131a79 | https://github.com/vyorkin-personal/xftp/blob/91a3185f60b02d5db951d5c3c0ae18c86a131a79/lib/xftp/client.rb#L23-L28 | valid |
bkerley/miami_dade_geo | lib/miami_dade_geo/geo_attribute_client.rb | MiamiDadeGeo.GeoAttributeClient.all_fields | def all_fields(table, field_name, value)
body = savon.
call(:get_all_fields_records_given_a_field_name_and_value,
message: {
'strFeatureClassOrTableName' => table,
'strFieldNameToSearchOn' => field_name,
'strValueOfFieldToSearchOn' => value
}).
body
resp = body[:get_all_fields_records_given_a_field_name_and_value_response]
rslt = resp[:get_all_fields_records_given_a_field_name_and_value_result]
polys = rslt[:diffgram][:document_element][:municipality_poly]
poly = if polys.is_a? Array
polys.first
elsif polys.is_a? Hash
polys
else
fail "Unexpected polys #{polys.class.name}, wanted Array or Hash"
end
end | ruby | def all_fields(table, field_name, value)
body = savon.
call(:get_all_fields_records_given_a_field_name_and_value,
message: {
'strFeatureClassOrTableName' => table,
'strFieldNameToSearchOn' => field_name,
'strValueOfFieldToSearchOn' => value
}).
body
resp = body[:get_all_fields_records_given_a_field_name_and_value_response]
rslt = resp[:get_all_fields_records_given_a_field_name_and_value_result]
polys = rslt[:diffgram][:document_element][:municipality_poly]
poly = if polys.is_a? Array
polys.first
elsif polys.is_a? Hash
polys
else
fail "Unexpected polys #{polys.class.name}, wanted Array or Hash"
end
end | [
"def",
"all_fields",
"(",
"table",
",",
"field_name",
",",
"value",
")",
"body",
"=",
"savon",
".",
"call",
"(",
":get_all_fields_records_given_a_field_name_and_value",
",",
"message",
":",
"{",
"'strFeatureClassOrTableName'",
"=>",
"table",
",",
"'strFieldNameToSearc... | Performs a search for geo-attributes.
@param [String] table the table to search
@param [String] field_name the field/column to search in the given table
@param [String] value string value to search in the given field and table
@return [Hash] search results | [
"Performs",
"a",
"search",
"for",
"geo",
"-",
"attributes",
"."
] | 024478a898dca2c6f07c312cfc531112e88daa0b | https://github.com/bkerley/miami_dade_geo/blob/024478a898dca2c6f07c312cfc531112e88daa0b/lib/miami_dade_geo/geo_attribute_client.rb#L22-L43 | valid |
kachick/validation | lib/validation/adjustment.rb | Validation.Adjustment.WHEN | def WHEN(condition, adjuster)
unless Validation.conditionable? condition
raise TypeError, 'wrong object for condition'
end
unless Validation.adjustable? adjuster
raise TypeError, 'wrong object for adjuster'
end
->v{_valid?(condition, v) ? adjuster.call(v) : v}
end | ruby | def WHEN(condition, adjuster)
unless Validation.conditionable? condition
raise TypeError, 'wrong object for condition'
end
unless Validation.adjustable? adjuster
raise TypeError, 'wrong object for adjuster'
end
->v{_valid?(condition, v) ? adjuster.call(v) : v}
end | [
"def",
"WHEN",
"(",
"condition",
",",
"adjuster",
")",
"unless",
"Validation",
".",
"conditionable?",
"condition",
"raise",
"TypeError",
",",
"'wrong object for condition'",
"end",
"unless",
"Validation",
".",
"adjustable?",
"adjuster",
"raise",
"TypeError",
",",
"'... | Adjuster Builders
Apply adjuster when passed condition.
@param condition [Proc, Method, #===]
@param adjuster [Proc, #to_proc]
@return [lambda] | [
"Adjuster",
"Builders",
"Apply",
"adjuster",
"when",
"passed",
"condition",
"."
] | 43390cb6d9adc45c2f040d59f22ee514629309e6 | https://github.com/kachick/validation/blob/43390cb6d9adc45c2f040d59f22ee514629309e6/lib/validation/adjustment.rb#L29-L39 | valid |
kachick/validation | lib/validation/adjustment.rb | Validation.Adjustment.INJECT | def INJECT(adjuster1, adjuster2, *adjusters)
adjusters = [adjuster1, adjuster2, *adjusters]
unless adjusters.all?{|f|adjustable? f}
raise TypeError, 'wrong object for adjuster'
end
->v{
adjusters.reduce(v){|ret, adjuster|adjuster.call ret}
}
end | ruby | def INJECT(adjuster1, adjuster2, *adjusters)
adjusters = [adjuster1, adjuster2, *adjusters]
unless adjusters.all?{|f|adjustable? f}
raise TypeError, 'wrong object for adjuster'
end
->v{
adjusters.reduce(v){|ret, adjuster|adjuster.call ret}
}
end | [
"def",
"INJECT",
"(",
"adjuster1",
",",
"adjuster2",
",",
"*",
"adjusters",
")",
"adjusters",
"=",
"[",
"adjuster1",
",",
"adjuster2",
",",
"*",
"adjusters",
"]",
"unless",
"adjusters",
".",
"all?",
"{",
"|",
"f",
"|",
"adjustable?",
"f",
"}",
"raise",
... | Sequencial apply all adjusters.
@param adjuster1 [Proc, #to_proc]
@param adjuster2 [Proc, #to_proc]
@param adjusters [Proc, #to_proc]
@return [lambda] | [
"Sequencial",
"apply",
"all",
"adjusters",
"."
] | 43390cb6d9adc45c2f040d59f22ee514629309e6 | https://github.com/kachick/validation/blob/43390cb6d9adc45c2f040d59f22ee514629309e6/lib/validation/adjustment.rb#L46-L56 | valid |
kachick/validation | lib/validation/adjustment.rb | Validation.Adjustment.PARSE | def PARSE(parser)
if !::Integer.equal?(parser) and !parser.respond_to?(:parse)
raise TypeError, 'wrong object for parser'
end
->v{
if ::Integer.equal? parser
::Kernel.Integer v
else
parser.parse(
case v
when String
v
when ->_{v.respond_to? :to_str}
v.to_str
when ->_{v.respond_to? :read}
v.read
else
raise TypeError, 'wrong object for parsing source'
end
)
end
}
end | ruby | def PARSE(parser)
if !::Integer.equal?(parser) and !parser.respond_to?(:parse)
raise TypeError, 'wrong object for parser'
end
->v{
if ::Integer.equal? parser
::Kernel.Integer v
else
parser.parse(
case v
when String
v
when ->_{v.respond_to? :to_str}
v.to_str
when ->_{v.respond_to? :read}
v.read
else
raise TypeError, 'wrong object for parsing source'
end
)
end
}
end | [
"def",
"PARSE",
"(",
"parser",
")",
"if",
"!",
"::",
"Integer",
".",
"equal?",
"(",
"parser",
")",
"and",
"!",
"parser",
".",
"respond_to?",
"(",
":parse",
")",
"raise",
"TypeError",
",",
"'wrong object for parser'",
"end",
"->",
"v",
"{",
"if",
"::",
... | Accept any parser when that resopond to parse method.
@param parser [#parse]
@return [lambda] | [
"Accept",
"any",
"parser",
"when",
"that",
"resopond",
"to",
"parse",
"method",
"."
] | 43390cb6d9adc45c2f040d59f22ee514629309e6 | https://github.com/kachick/validation/blob/43390cb6d9adc45c2f040d59f22ee514629309e6/lib/validation/adjustment.rb#L61-L84 | valid |
zhimin/rformspec | lib/rformspec/window.rb | RFormSpec.Window.get_class | def get_class(name)
@class_list = get_class_list
@class_list.select {|x| x.include?(name)}.collect{|y| y.strip}
end | ruby | def get_class(name)
@class_list = get_class_list
@class_list.select {|x| x.include?(name)}.collect{|y| y.strip}
end | [
"def",
"get_class",
"(",
"name",
")",
"@class_list",
"=",
"get_class_list",
"@class_list",
".",
"select",
"{",
"|",
"x",
"|",
"x",
".",
"include?",
"(",
"name",
")",
"}",
".",
"collect",
"{",
"|",
"y",
"|",
"y",
".",
"strip",
"}",
"end"
] | return the class match by name | [
"return",
"the",
"class",
"match",
"by",
"name"
] | 756e89cb730b2ec25564c6243fdcd3e81bd93649 | https://github.com/zhimin/rformspec/blob/756e89cb730b2ec25564c6243fdcd3e81bd93649/lib/rformspec/window.rb#L121-L124 | valid |
megamsys/megam_scmmanager.rb | lib/megam/scmmanager.rb | Megam.Scmmanager.connection | def connection
@options[:path] =API_REST + @options[:path]
@options[:headers] = HEADERS.merge({
'X-Megam-Date' => Time.now.strftime("%Y-%m-%d %H:%M")
}).merge(@options[:headers])
text.info("HTTP Request Data:")
text.msg("> HTTP #{@options[:scheme]}://#{@options[:host]}")
@options.each do |key, value|
text.msg("> #{key}: #{value}")
end
text.info("End HTTP Request Data.")
http = Net::HTTP.new(@options[:host], @options[:port])
http
end | ruby | def connection
@options[:path] =API_REST + @options[:path]
@options[:headers] = HEADERS.merge({
'X-Megam-Date' => Time.now.strftime("%Y-%m-%d %H:%M")
}).merge(@options[:headers])
text.info("HTTP Request Data:")
text.msg("> HTTP #{@options[:scheme]}://#{@options[:host]}")
@options.each do |key, value|
text.msg("> #{key}: #{value}")
end
text.info("End HTTP Request Data.")
http = Net::HTTP.new(@options[:host], @options[:port])
http
end | [
"def",
"connection",
"@options",
"[",
":path",
"]",
"=",
"API_REST",
"+",
"@options",
"[",
":path",
"]",
"@options",
"[",
":headers",
"]",
"=",
"HEADERS",
".",
"merge",
"(",
"{",
"'X-Megam-Date'",
"=>",
"Time",
".",
"now",
".",
"strftime",
"(",
"\"%Y-%m-... | Make a lazy connection. | [
"Make",
"a",
"lazy",
"connection",
"."
] | fae0fe0f9519dabd3625e5fdc0b24006de5746fb | https://github.com/megamsys/megam_scmmanager.rb/blob/fae0fe0f9519dabd3625e5fdc0b24006de5746fb/lib/megam/scmmanager.rb#L78-L92 | valid |
robfors/quack_concurrency | lib/quack_concurrency/safe_sleeper.rb | QuackConcurrency.SafeSleeper.wake_deadline | def wake_deadline(start_time, timeout)
timeout = process_timeout(timeout)
deadline = start_time + timeout if timeout
end | ruby | def wake_deadline(start_time, timeout)
timeout = process_timeout(timeout)
deadline = start_time + timeout if timeout
end | [
"def",
"wake_deadline",
"(",
"start_time",
",",
"timeout",
")",
"timeout",
"=",
"process_timeout",
"(",
"timeout",
")",
"deadline",
"=",
"start_time",
"+",
"timeout",
"if",
"timeout",
"end"
] | Calculate the desired time to wake up.
@api private
@param start_time [nil,Time] time when the thread is put to sleep
@param timeout [Numeric] desired time to sleep in seconds, +nil+ for forever
@raise [TypeError] if +start_time+ is not +nil+ or a +Numeric+
@raise [ArgumentError] if +start_time+ is negative
@return [Time] | [
"Calculate",
"the",
"desired",
"time",
"to",
"wake",
"up",
"."
] | fb42bbd48b4e4994297431e926bbbcc777a3cd08 | https://github.com/robfors/quack_concurrency/blob/fb42bbd48b4e4994297431e926bbbcc777a3cd08/lib/quack_concurrency/safe_sleeper.rb#L74-L77 | valid |
CoralineAda/mir_extensions | lib/mir_extensions.rb | MirExtensions.HelperExtensions.crud_links | def crud_links(model, instance_name, actions, args={})
_html = ""
_options = args.keys.empty? ? '' : ", #{args.map{|k,v| ":#{k} => #{v}"}}"
if use_crud_icons
if actions.include?(:show)
_html << eval("link_to image_tag('/images/icons/view.png', :class => 'crud_icon'), model, :title => 'View'#{_options}")
end
if actions.include?(:edit)
_html << eval("link_to image_tag('/images/icons/edit.png', :class => 'crud_icon'), edit_#{instance_name}_path(model), :title => 'Edit'#{_options}")
end
if actions.include?(:delete)
_html << eval("link_to image_tag('/images/icons/delete.png', :class => 'crud_icon'), model, :confirm => 'Are you sure? This action cannot be undone.', :method => :delete, :title => 'Delete'#{_options}")
end
else
if actions.include?(:show)
_html << eval("link_to 'View', model, :title => 'View', :class => 'crud_link'#{_options}")
end
if actions.include?(:edit)
_html << eval("link_to 'Edit', edit_#{instance_name}_path(model), :title => 'Edit', :class => 'crud_link'#{_options}")
end
if actions.include?(:delete)
_html << eval("link_to 'Delete', model, :confirm => 'Are you sure? This action cannot be undone.', :method => :delete, :title => 'Delete', :class => 'crud_link'#{_options}")
end
end
_html
end | ruby | def crud_links(model, instance_name, actions, args={})
_html = ""
_options = args.keys.empty? ? '' : ", #{args.map{|k,v| ":#{k} => #{v}"}}"
if use_crud_icons
if actions.include?(:show)
_html << eval("link_to image_tag('/images/icons/view.png', :class => 'crud_icon'), model, :title => 'View'#{_options}")
end
if actions.include?(:edit)
_html << eval("link_to image_tag('/images/icons/edit.png', :class => 'crud_icon'), edit_#{instance_name}_path(model), :title => 'Edit'#{_options}")
end
if actions.include?(:delete)
_html << eval("link_to image_tag('/images/icons/delete.png', :class => 'crud_icon'), model, :confirm => 'Are you sure? This action cannot be undone.', :method => :delete, :title => 'Delete'#{_options}")
end
else
if actions.include?(:show)
_html << eval("link_to 'View', model, :title => 'View', :class => 'crud_link'#{_options}")
end
if actions.include?(:edit)
_html << eval("link_to 'Edit', edit_#{instance_name}_path(model), :title => 'Edit', :class => 'crud_link'#{_options}")
end
if actions.include?(:delete)
_html << eval("link_to 'Delete', model, :confirm => 'Are you sure? This action cannot be undone.', :method => :delete, :title => 'Delete', :class => 'crud_link'#{_options}")
end
end
_html
end | [
"def",
"crud_links",
"(",
"model",
",",
"instance_name",
",",
"actions",
",",
"args",
"=",
"{",
"}",
")",
"_html",
"=",
"\"\"",
"_options",
"=",
"args",
".",
"keys",
".",
"empty?",
"?",
"''",
":",
"\", #{args.map{|k,v| \":#{k} => #{v}\"}}\"",
"if",
"use_crud... | Display CRUD icons or links, according to setting in use_crud_icons method.
In application_helper.rb:
def use_crud_icons
true
end
Then use in index views like this:
<td class="crud_links"><%= crud_links(my_model, 'my_model', [:show, :edit, :delete]) -%></td> | [
"Display",
"CRUD",
"icons",
"or",
"links",
"according",
"to",
"setting",
"in",
"use_crud_icons",
"method",
"."
] | 640c0807afe2015b7912ab3dd90fcd1aa7ad07a3 | https://github.com/CoralineAda/mir_extensions/blob/640c0807afe2015b7912ab3dd90fcd1aa7ad07a3/lib/mir_extensions.rb#L68-L94 | valid |
CoralineAda/mir_extensions | lib/mir_extensions.rb | MirExtensions.HelperExtensions.obfuscated_link_to | def obfuscated_link_to(path, image, label, args={})
_html = %{<form action="#{path}" method="get" class="obfuscated_link">}
_html << %{ <fieldset><input alt="#{label}" src="#{image}" type="image" /></fieldset>}
args.each{ |k,v| _html << %{ <div><input id="#{k.to_s}" name="#{k}" type="hidden" value="#{v}" /></div>} }
_html << %{</form>}
_html
end | ruby | def obfuscated_link_to(path, image, label, args={})
_html = %{<form action="#{path}" method="get" class="obfuscated_link">}
_html << %{ <fieldset><input alt="#{label}" src="#{image}" type="image" /></fieldset>}
args.each{ |k,v| _html << %{ <div><input id="#{k.to_s}" name="#{k}" type="hidden" value="#{v}" /></div>} }
_html << %{</form>}
_html
end | [
"def",
"obfuscated_link_to",
"(",
"path",
",",
"image",
",",
"label",
",",
"args",
"=",
"{",
"}",
")",
"_html",
"=",
"%{<form action=\"#{path}\" method=\"get\" class=\"obfuscated_link\">}",
"_html",
"<<",
"%{ <fieldset><input alt=\"#{label}\" src=\"#{image}\" type=\"image\" /><... | Create a link that is opaque to search engine spiders. | [
"Create",
"a",
"link",
"that",
"is",
"opaque",
"to",
"search",
"engine",
"spiders",
"."
] | 640c0807afe2015b7912ab3dd90fcd1aa7ad07a3 | https://github.com/CoralineAda/mir_extensions/blob/640c0807afe2015b7912ab3dd90fcd1aa7ad07a3/lib/mir_extensions.rb#L161-L167 | valid |
CoralineAda/mir_extensions | lib/mir_extensions.rb | MirExtensions.HelperExtensions.required_field_helper | def required_field_helper( model, element, html )
if model && ! model.errors.empty? && element.is_required
return content_tag( :div, html, :class => 'fieldWithErrors' )
else
return html
end
end | ruby | def required_field_helper( model, element, html )
if model && ! model.errors.empty? && element.is_required
return content_tag( :div, html, :class => 'fieldWithErrors' )
else
return html
end
end | [
"def",
"required_field_helper",
"(",
"model",
",",
"element",
",",
"html",
")",
"if",
"model",
"&&",
"!",
"model",
".",
"errors",
".",
"empty?",
"&&",
"element",
".",
"is_required",
"return",
"content_tag",
"(",
":div",
",",
"html",
",",
":class",
"=>",
... | Wraps the given HTML in Rails' default style to highlight validation errors, if any. | [
"Wraps",
"the",
"given",
"HTML",
"in",
"Rails",
"default",
"style",
"to",
"highlight",
"validation",
"errors",
"if",
"any",
"."
] | 640c0807afe2015b7912ab3dd90fcd1aa7ad07a3 | https://github.com/CoralineAda/mir_extensions/blob/640c0807afe2015b7912ab3dd90fcd1aa7ad07a3/lib/mir_extensions.rb#L170-L176 | valid |
CoralineAda/mir_extensions | lib/mir_extensions.rb | MirExtensions.HelperExtensions.select_tag_for_filter | def select_tag_for_filter(model, nvpairs, params)
return unless model && nvpairs && ! nvpairs.empty?
options = { :query => params[:query] }
_url = url_for(eval("#{model}_url(options)"))
_html = %{<label for="show">Show:</label><br />}
_html << %{<select name="show" id="show" onchange="window.location='#{_url}' + '?show=' + this.value">}
nvpairs.each do |pair|
_html << %{<option value="#{pair[:scope]}"}
if params[:show] == pair[:scope] || ((params[:show].nil? || params[:show].empty?) && pair[:scope] == "all")
_html << %{ selected="selected"}
end
_html << %{>#{pair[:label]}}
_html << %{</option>}
end
_html << %{</select>}
end | ruby | def select_tag_for_filter(model, nvpairs, params)
return unless model && nvpairs && ! nvpairs.empty?
options = { :query => params[:query] }
_url = url_for(eval("#{model}_url(options)"))
_html = %{<label for="show">Show:</label><br />}
_html << %{<select name="show" id="show" onchange="window.location='#{_url}' + '?show=' + this.value">}
nvpairs.each do |pair|
_html << %{<option value="#{pair[:scope]}"}
if params[:show] == pair[:scope] || ((params[:show].nil? || params[:show].empty?) && pair[:scope] == "all")
_html << %{ selected="selected"}
end
_html << %{>#{pair[:label]}}
_html << %{</option>}
end
_html << %{</select>}
end | [
"def",
"select_tag_for_filter",
"(",
"model",
",",
"nvpairs",
",",
"params",
")",
"return",
"unless",
"model",
"&&",
"nvpairs",
"&&",
"!",
"nvpairs",
".",
"empty?",
"options",
"=",
"{",
":query",
"=>",
"params",
"[",
":query",
"]",
"}",
"_url",
"=",
"url... | Use on index pages to create dropdown list of filtering criteria.
Populate the filter list using a constant in the model corresponding to named scopes.
Usage:
- item.rb:
scope :active, :conditions => { :is_active => true }
scope :inactive, :conditions => { :is_active => false }
FILTERS = [
{:scope => "all", :label => "All"},
{:scope => "active", :label => "Active Only"},
{:scope => "inactive", :label => "Inactive Only"}
]
- items/index.html.erb:
<%= select_tag_for_filter("items", @filters, params) -%>
- items_controller.rb:
def index
@filters = Item::FILTERS
if params[:show] && params[:show] != "all" && @filters.collect{|f| f[:scope]}.include?(params[:show])
@items = eval("@items.#{params[:show]}.order_by(params[:by], params[:dir])")
else
@items = @items.order_by(params[:by], params[:dir])
end
...
end | [
"Use",
"on",
"index",
"pages",
"to",
"create",
"dropdown",
"list",
"of",
"filtering",
"criteria",
".",
"Populate",
"the",
"filter",
"list",
"using",
"a",
"constant",
"in",
"the",
"model",
"corresponding",
"to",
"named",
"scopes",
"."
] | 640c0807afe2015b7912ab3dd90fcd1aa7ad07a3 | https://github.com/CoralineAda/mir_extensions/blob/640c0807afe2015b7912ab3dd90fcd1aa7ad07a3/lib/mir_extensions.rb#L218-L233 | valid |
CoralineAda/mir_extensions | lib/mir_extensions.rb | MirExtensions.HelperExtensions.sort_link | def sort_link(model, field, params, html_options={})
if (field.to_sym == params[:by] || field == params[:by]) && params[:dir] == "ASC"
classname = "arrow-asc"
dir = "DESC"
elsif (field.to_sym == params[:by] || field == params[:by])
classname = "arrow-desc"
dir = "ASC"
else
dir = "ASC"
end
options = {
:anchor => html_options[:anchor] || nil,
:by => field,
:dir => dir,
:query => params[:query],
:show => params[:show]
}
options[:show] = params[:show] unless params[:show].blank? || params[:show] == 'all'
html_options = {
:class => "#{classname} #{html_options[:class]}",
:style => "color: white; font-weight: #{params[:by] == field ? "bold" : "normal"}; #{html_options[:style]}",
:title => "Sort by this field"
}
field_name = params[:labels] && params[:labels][field] ? params[:labels][field] : field.titleize
_link = model.is_a?(Symbol) ? eval("#{model}_url(options)") : "/#{model}?#{options.to_params}"
link_to(field_name, _link, html_options)
end | ruby | def sort_link(model, field, params, html_options={})
if (field.to_sym == params[:by] || field == params[:by]) && params[:dir] == "ASC"
classname = "arrow-asc"
dir = "DESC"
elsif (field.to_sym == params[:by] || field == params[:by])
classname = "arrow-desc"
dir = "ASC"
else
dir = "ASC"
end
options = {
:anchor => html_options[:anchor] || nil,
:by => field,
:dir => dir,
:query => params[:query],
:show => params[:show]
}
options[:show] = params[:show] unless params[:show].blank? || params[:show] == 'all'
html_options = {
:class => "#{classname} #{html_options[:class]}",
:style => "color: white; font-weight: #{params[:by] == field ? "bold" : "normal"}; #{html_options[:style]}",
:title => "Sort by this field"
}
field_name = params[:labels] && params[:labels][field] ? params[:labels][field] : field.titleize
_link = model.is_a?(Symbol) ? eval("#{model}_url(options)") : "/#{model}?#{options.to_params}"
link_to(field_name, _link, html_options)
end | [
"def",
"sort_link",
"(",
"model",
",",
"field",
",",
"params",
",",
"html_options",
"=",
"{",
"}",
")",
"if",
"(",
"field",
".",
"to_sym",
"==",
"params",
"[",
":by",
"]",
"||",
"field",
"==",
"params",
"[",
":by",
"]",
")",
"&&",
"params",
"[",
... | Returns a link_to tag with sorting parameters that can be used with ActiveRecord.order_by.
To use standard resources, specify the resources as a plural symbol:
sort_link(:users, 'email', params)
To use resources aliased with :as (in routes.rb), specify the aliased route as a string.
sort_link('users_admin', 'email', params)
You can override the link's label by adding a labels hash to your params in the controller:
params[:labels] = {'user_id' => 'User'} | [
"Returns",
"a",
"link_to",
"tag",
"with",
"sorting",
"parameters",
"that",
"can",
"be",
"used",
"with",
"ActiveRecord",
".",
"order_by",
"."
] | 640c0807afe2015b7912ab3dd90fcd1aa7ad07a3 | https://github.com/CoralineAda/mir_extensions/blob/640c0807afe2015b7912ab3dd90fcd1aa7ad07a3/lib/mir_extensions.rb#L245-L276 | valid |
CoralineAda/mir_extensions | lib/mir_extensions.rb | MirExtensions.HelperExtensions.tag_for_label_with_inline_help | def tag_for_label_with_inline_help( label_text, field_id, help_text )
_html = ""
_html << %{<label for="#{field_id}">#{label_text}}
_html << %{<img src="/images/icons/help_icon.png" onclick="$('#{field_id}_help').toggle();" class='inline_icon' />}
_html << %{</label><br />}
_html << %{<div class="inline_help" id="#{field_id}_help" style="display: none;">}
_html << %{<p>#{help_text}</p>}
_html << %{</div>}
_html
end | ruby | def tag_for_label_with_inline_help( label_text, field_id, help_text )
_html = ""
_html << %{<label for="#{field_id}">#{label_text}}
_html << %{<img src="/images/icons/help_icon.png" onclick="$('#{field_id}_help').toggle();" class='inline_icon' />}
_html << %{</label><br />}
_html << %{<div class="inline_help" id="#{field_id}_help" style="display: none;">}
_html << %{<p>#{help_text}</p>}
_html << %{</div>}
_html
end | [
"def",
"tag_for_label_with_inline_help",
"(",
"label_text",
",",
"field_id",
",",
"help_text",
")",
"_html",
"=",
"\"\"",
"_html",
"<<",
"%{<label for=\"#{field_id}\">#{label_text}}",
"_html",
"<<",
"%{<img src=\"/images/icons/help_icon.png\" onclick=\"$('#{field_id}_help').toggle(... | Create a set of tags for displaying a field label with inline help.
Field label text is appended with a ? icon, which responds to a click
by showing or hiding the provided help text.
Sample usage:
<%= tag_for_label_with_inline_help 'Relative Frequency', 'rel_frequency', 'Relative frequency of search traffic for this keyword across multiple search engines, as measured by WordTracker.' %>
Yields:
<label for="rel_frequency">Relative Frequency: <%= image_tag "/images/help_icon.png", :onclick => "$('rel_frequency_help').toggle();", :class => 'inline_icon' %></label><br />
<div class="inline_help" id="rel_frequency_help" style="display: none;">
<p>Relative frequency of search traffic for this keyword across multiple search engines, as measured by WordTracker.</p>
</div> | [
"Create",
"a",
"set",
"of",
"tags",
"for",
"displaying",
"a",
"field",
"label",
"with",
"inline",
"help",
".",
"Field",
"label",
"text",
"is",
"appended",
"with",
"a",
"?",
"icon",
"which",
"responds",
"to",
"a",
"click",
"by",
"showing",
"or",
"hiding",... | 640c0807afe2015b7912ab3dd90fcd1aa7ad07a3 | https://github.com/CoralineAda/mir_extensions/blob/640c0807afe2015b7912ab3dd90fcd1aa7ad07a3/lib/mir_extensions.rb#L385-L394 | valid |
zhimin/rformspec | lib/rformspec/driver.rb | RFormSpec.Driver.key_press | def key_press(keys)
dump_caller_stack
if keys =~ /^Ctrl\+([A-Z])$/
filtered_keys = "^+#{$1}"
elsif keys =~ /^Ctrl\+Shift\+([A-Z])$/
filtered_keys = "^+#{$1.downcase}"
elsif keys =~ /^Alt+([A-Z])$/
filtered_keys = "!+#{$1}"
elsif keys =~ /^Alt\+Shift\+([a-z])$/
filtered_keys = "!+#{$1.downcase}"
else
filtered_keys = keys
end
filtered_keys = keys.gsub("Alt+", "!+").gsub("Ctrl+", "^+")
RFormSpec::Keyboard.press(filtered_keys)
sleep 0.5
end | ruby | def key_press(keys)
dump_caller_stack
if keys =~ /^Ctrl\+([A-Z])$/
filtered_keys = "^+#{$1}"
elsif keys =~ /^Ctrl\+Shift\+([A-Z])$/
filtered_keys = "^+#{$1.downcase}"
elsif keys =~ /^Alt+([A-Z])$/
filtered_keys = "!+#{$1}"
elsif keys =~ /^Alt\+Shift\+([a-z])$/
filtered_keys = "!+#{$1.downcase}"
else
filtered_keys = keys
end
filtered_keys = keys.gsub("Alt+", "!+").gsub("Ctrl+", "^+")
RFormSpec::Keyboard.press(filtered_keys)
sleep 0.5
end | [
"def",
"key_press",
"(",
"keys",
")",
"dump_caller_stack",
"if",
"keys",
"=~",
"/",
"\\+",
"/",
"filtered_keys",
"=",
"\"^+#{$1}\"",
"elsif",
"keys",
"=~",
"/",
"\\+",
"\\+",
"/",
"filtered_keys",
"=",
"\"^+#{$1.downcase}\"",
"elsif",
"keys",
"=~",
"/",
"/",... | wrapper of keyboard operations | [
"wrapper",
"of",
"keyboard",
"operations"
] | 756e89cb730b2ec25564c6243fdcd3e81bd93649 | https://github.com/zhimin/rformspec/blob/756e89cb730b2ec25564c6243fdcd3e81bd93649/lib/rformspec/driver.rb#L51-L68 | valid |
zhimin/rformspec | lib/rformspec/driver.rb | RFormSpec.Driver.open_file_dialog | def open_file_dialog(title, filepath, text="")
wait_and_focus_window(title)
dialog = RFormSpec::OpenFileDialog.new(title, text)
dialog.enter_filepath(filepath)
sleep 1
dialog.click_open
end | ruby | def open_file_dialog(title, filepath, text="")
wait_and_focus_window(title)
dialog = RFormSpec::OpenFileDialog.new(title, text)
dialog.enter_filepath(filepath)
sleep 1
dialog.click_open
end | [
"def",
"open_file_dialog",
"(",
"title",
",",
"filepath",
",",
"text",
"=",
"\"\"",
")",
"wait_and_focus_window",
"(",
"title",
")",
"dialog",
"=",
"RFormSpec",
"::",
"OpenFileDialog",
".",
"new",
"(",
"title",
",",
"text",
")",
"dialog",
".",
"enter_filepat... | standard open file dialog | [
"standard",
"open",
"file",
"dialog"
] | 756e89cb730b2ec25564c6243fdcd3e81bd93649 | https://github.com/zhimin/rformspec/blob/756e89cb730b2ec25564c6243fdcd3e81bd93649/lib/rformspec/driver.rb#L81-L87 | valid |
IlyasValiullov/byebug-cleaner | lib/byebug/cleaner/parser.rb | ByebugCleaner.ArgumentParser.parse | def parse(args)
# The options specified on the command line will be collected in
# *options*.
@options = Options.new
opt_parser = OptionParser.new do |parser|
@options.define_options(parser)
end
opt_parser.parse!(args)
@options
end | ruby | def parse(args)
# The options specified on the command line will be collected in
# *options*.
@options = Options.new
opt_parser = OptionParser.new do |parser|
@options.define_options(parser)
end
opt_parser.parse!(args)
@options
end | [
"def",
"parse",
"(",
"args",
")",
"@options",
"=",
"Options",
".",
"new",
"opt_parser",
"=",
"OptionParser",
".",
"new",
"do",
"|",
"parser",
"|",
"@options",
".",
"define_options",
"(",
"parser",
")",
"end",
"opt_parser",
".",
"parse!",
"(",
"args",
")"... | Return a structure describing the options. | [
"Return",
"a",
"structure",
"describing",
"the",
"options",
"."
] | abee2b84f6569823bc8cb21e355e55aeb9bc7c89 | https://github.com/IlyasValiullov/byebug-cleaner/blob/abee2b84f6569823bc8cb21e355e55aeb9bc7c89/lib/byebug/cleaner/parser.rb#L67-L77 | valid |
JiriChara/rgc | lib/rgc/git_attributes.rb | Rgc.GitAttributes.add | def add(path)
str = "#{path} filter=rgc diff=rgc"
if content.include?(str)
abort "`#{str}\n` is already included in #{@location}."
end
File.open(@location, 'a') do |f|
f.write("#{str}\n")
end
rescue Errno::ENOENT
abort "File #{@location} does not exists."
rescue Errno::EACCES
abort "File #{@location} is not accessible for writing."
end | ruby | def add(path)
str = "#{path} filter=rgc diff=rgc"
if content.include?(str)
abort "`#{str}\n` is already included in #{@location}."
end
File.open(@location, 'a') do |f|
f.write("#{str}\n")
end
rescue Errno::ENOENT
abort "File #{@location} does not exists."
rescue Errno::EACCES
abort "File #{@location} is not accessible for writing."
end | [
"def",
"add",
"(",
"path",
")",
"str",
"=",
"\"#{path} filter=rgc diff=rgc\"",
"if",
"content",
".",
"include?",
"(",
"str",
")",
"abort",
"\"`#{str}\\n` is already included in #{@location}.\"",
"end",
"File",
".",
"open",
"(",
"@location",
",",
"'a'",
")",
"do",
... | Add new path to the gitattributes file | [
"Add",
"new",
"path",
"to",
"the",
"gitattributes",
"file"
] | b8fccdd073f76224d15381c2bdec00df83766a6b | https://github.com/JiriChara/rgc/blob/b8fccdd073f76224d15381c2bdec00df83766a6b/lib/rgc/git_attributes.rb#L23-L36 | valid |
mlins/active_migration | lib/active_migration/base.rb | ActiveMigration.Base.run | def run
logger.info("#{self.class.to_s} is starting.")
count_options = self.class.legacy_find_options.dup
count_options.delete(:order)
count_options.delete(:group)
count_options.delete(:limit)
count_options.delete(:offset)
@num_of_records = self.class.legacy_model.count(count_options)
if self.class.legacy_find_options[:limit] && (@num_of_records > self.class.legacy_find_options[:limit])
run_in_batches @num_of_records
else
run_normal
end
logger.info("#{self.class.to_s} migrated all #{@num_of_records} records successfully.")
end | ruby | def run
logger.info("#{self.class.to_s} is starting.")
count_options = self.class.legacy_find_options.dup
count_options.delete(:order)
count_options.delete(:group)
count_options.delete(:limit)
count_options.delete(:offset)
@num_of_records = self.class.legacy_model.count(count_options)
if self.class.legacy_find_options[:limit] && (@num_of_records > self.class.legacy_find_options[:limit])
run_in_batches @num_of_records
else
run_normal
end
logger.info("#{self.class.to_s} migrated all #{@num_of_records} records successfully.")
end | [
"def",
"run",
"logger",
".",
"info",
"(",
"\"#{self.class.to_s} is starting.\"",
")",
"count_options",
"=",
"self",
".",
"class",
".",
"legacy_find_options",
".",
"dup",
"count_options",
".",
"delete",
"(",
":order",
")",
"count_options",
".",
"delete",
"(",
":g... | Runs the migration.
MyMigration.new.run | [
"Runs",
"the",
"migration",
"."
] | 0a24d700d1b750c97fb00f3cf185848c32993eba | https://github.com/mlins/active_migration/blob/0a24d700d1b750c97fb00f3cf185848c32993eba/lib/active_migration/base.rb#L91-L105 | valid |
nearapogee/simplec | app/models/simplec/page.rb | Simplec.Page.parents | def parents
page, parents = self, Array.new
while page.parent
page = page.parent
parents << page
end
parents
end | ruby | def parents
page, parents = self, Array.new
while page.parent
page = page.parent
parents << page
end
parents
end | [
"def",
"parents",
"page",
",",
"parents",
"=",
"self",
",",
"Array",
".",
"new",
"while",
"page",
".",
"parent",
"page",
"=",
"page",
".",
"parent",
"parents",
"<<",
"page",
"end",
"parents",
"end"
] | List parents, closest to furthest.
This is a recursive, expensive call. | [
"List",
"parents",
"closest",
"to",
"furthest",
"."
] | c1096505e0323aaf2f19a36c2ff05053a8f4062c | https://github.com/nearapogee/simplec/blob/c1096505e0323aaf2f19a36c2ff05053a8f4062c/app/models/simplec/page.rb#L268-L275 | valid |
nearapogee/simplec | app/models/simplec/page.rb | Simplec.Page.extract_search_text | def extract_search_text(*attributes)
Array(attributes).map { |meth|
Nokogiri::HTML(self.send(meth)).xpath("//text()").
map {|node| text = node.text; text.try(:strip!); text}.join(" ")
}.reject(&:blank?).join("\n")
end | ruby | def extract_search_text(*attributes)
Array(attributes).map { |meth|
Nokogiri::HTML(self.send(meth)).xpath("//text()").
map {|node| text = node.text; text.try(:strip!); text}.join(" ")
}.reject(&:blank?).join("\n")
end | [
"def",
"extract_search_text",
"(",
"*",
"attributes",
")",
"Array",
"(",
"attributes",
")",
".",
"map",
"{",
"|",
"meth",
"|",
"Nokogiri",
"::",
"HTML",
"(",
"self",
".",
"send",
"(",
"meth",
")",
")",
".",
"xpath",
"(",
"\"//text()\"",
")",
".",
"ma... | Extract text out of HTML or plain strings. Basically removes html
formatting.
@param attributes [Symbol, String]
variable list of attributes or methods to be extracted for search
@return [String] content of each attribute separated by new lines | [
"Extract",
"text",
"out",
"of",
"HTML",
"or",
"plain",
"strings",
".",
"Basically",
"removes",
"html",
"formatting",
"."
] | c1096505e0323aaf2f19a36c2ff05053a8f4062c | https://github.com/nearapogee/simplec/blob/c1096505e0323aaf2f19a36c2ff05053a8f4062c/app/models/simplec/page.rb#L355-L360 | valid |
nearapogee/simplec | app/models/simplec/page.rb | Simplec.Page.set_query_attributes! | def set_query_attributes!
attr_names = self.class.search_query_attributes.map(&:to_s)
self.query = attr_names.inject({}) { |memo, attr|
memo[attr] = self.send(attr)
memo
}
end | ruby | def set_query_attributes!
attr_names = self.class.search_query_attributes.map(&:to_s)
self.query = attr_names.inject({}) { |memo, attr|
memo[attr] = self.send(attr)
memo
}
end | [
"def",
"set_query_attributes!",
"attr_names",
"=",
"self",
".",
"class",
".",
"search_query_attributes",
".",
"map",
"(",
"&",
":to_s",
")",
"self",
".",
"query",
"=",
"attr_names",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"memo",
",",
"attr",
"|",
... | Build query attribute hash.
Internally stored as JSONB.
@return [Hash] to be set for query attribute | [
"Build",
"query",
"attribute",
"hash",
"."
] | c1096505e0323aaf2f19a36c2ff05053a8f4062c | https://github.com/nearapogee/simplec/blob/c1096505e0323aaf2f19a36c2ff05053a8f4062c/app/models/simplec/page.rb#L384-L390 | valid |
chetan/bixby-agent | lib/bixby-agent/agent.rb | Bixby.Agent.manager_ws_uri | def manager_ws_uri
# convert manager uri to websocket
uri = URI.parse(manager_uri)
uri.scheme = (uri.scheme == "https" ? "wss" : "ws")
uri.path = "/wsapi"
return uri.to_s
end | ruby | def manager_ws_uri
# convert manager uri to websocket
uri = URI.parse(manager_uri)
uri.scheme = (uri.scheme == "https" ? "wss" : "ws")
uri.path = "/wsapi"
return uri.to_s
end | [
"def",
"manager_ws_uri",
"uri",
"=",
"URI",
".",
"parse",
"(",
"manager_uri",
")",
"uri",
".",
"scheme",
"=",
"(",
"uri",
".",
"scheme",
"==",
"\"https\"",
"?",
"\"wss\"",
":",
"\"ws\"",
")",
"uri",
".",
"path",
"=",
"\"/wsapi\"",
"return",
"uri",
".",... | Get the WebSocket API URI
@return [String] uri | [
"Get",
"the",
"WebSocket",
"API",
"URI"
] | cb79b001570118b5b5e2a50674df7691e906a6cd | https://github.com/chetan/bixby-agent/blob/cb79b001570118b5b5e2a50674df7691e906a6cd/lib/bixby-agent/agent.rb#L88-L94 | valid |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.