id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
|
|---|---|---|---|---|---|---|---|---|---|---|---|
8,100
|
userhello/bit_magic
|
lib/bit_magic/bits_generator.rb
|
BitMagic.BitsGenerator.each_value
|
def each_value(each_bits = nil, &block)
# Warning! This has exponential complexity (time and space)
# 2**n to be precise, use sparingly
yield 0
count = 1
if @options[:default] != 0
yield @options[:default]
count += 1
end
each_bits = self.bits if each_bits == nil
1.upto(each_bits.length).each do |i|
each_bits.combination(i).each do |bits_list|
num = bits_list.reduce(0) { |m, j| m |= (1 << j) }
yield num
count += 1
end
end
count
end
|
ruby
|
def each_value(each_bits = nil, &block)
# Warning! This has exponential complexity (time and space)
# 2**n to be precise, use sparingly
yield 0
count = 1
if @options[:default] != 0
yield @options[:default]
count += 1
end
each_bits = self.bits if each_bits == nil
1.upto(each_bits.length).each do |i|
each_bits.combination(i).each do |bits_list|
num = bits_list.reduce(0) { |m, j| m |= (1 << j) }
yield num
count += 1
end
end
count
end
|
[
"def",
"each_value",
"(",
"each_bits",
"=",
"nil",
",",
"&",
"block",
")",
"# Warning! This has exponential complexity (time and space)",
"# 2**n to be precise, use sparingly",
"yield",
"0",
"count",
"=",
"1",
"if",
"@options",
"[",
":default",
"]",
"!=",
"0",
"yield",
"@options",
"[",
":default",
"]",
"count",
"+=",
"1",
"end",
"each_bits",
"=",
"self",
".",
"bits",
"if",
"each_bits",
"==",
"nil",
"1",
".",
"upto",
"(",
"each_bits",
".",
"length",
")",
".",
"each",
"do",
"|",
"i",
"|",
"each_bits",
".",
"combination",
"(",
"i",
")",
".",
"each",
"do",
"|",
"bits_list",
"|",
"num",
"=",
"bits_list",
".",
"reduce",
"(",
"0",
")",
"{",
"|",
"m",
",",
"j",
"|",
"m",
"|=",
"(",
"1",
"<<",
"j",
")",
"}",
"yield",
"num",
"count",
"+=",
"1",
"end",
"end",
"count",
"end"
] |
Iterates over the entire combination of all possible values utilizing the
list of bits we are given.
Warning: Because we are iteration over possible values, the total available
values grows exponentially with the given number of bits. For example, if
you use only 8 bits, there are 2*8 = 256 possible values, with 20 bits it
grows to 2**20 = 1048576. At 32 bits, 2**32 = 4294967296.
Warning 2: We're using combinations to generate each individual number, so
there's additional overhead causing O(n * 2^(n-1)) time complexity. Carefully
benchmark when you have large bit lists (more than 16 bits total) and
check both timing and memory for your use case.
@param [optional, Array<Integer>] each_bits a list of bits used to generate
the combination list. default: the list of bits given during initialization
@param [Proc] block a callable method to yield individual values
@yield num will yield to the given block multiple times, each time with one
of the integer values that are possible from the given bits list
@example Iterate over a list of bits
gen = BitsGenerator.new(:is_odd => 0, :amount => [1, 2, 3], :is_cool => 4)
values = []
gen.each_value { |val| values << val } #=> 32
values #=> [0, 1, 2, 4, 8, 16, 3, 5, 9, 17, 6, 10, 18, 12, 20, 24, 7, 11, 19, 13, 21, 25, 14, 22, 26, 28, 15, 23, 27, 29, 30, 31]
values2 = []
gen.each_value([0, 5]) { |val| values2 << val } #=> 4
values2 #=> [0, 1, 32, 33]
@return [Integer] total number of values yielded
|
[
"Iterates",
"over",
"the",
"entire",
"combination",
"of",
"all",
"possible",
"values",
"utilizing",
"the",
"list",
"of",
"bits",
"we",
"are",
"given",
"."
] |
78b7fc28313af9c9506220812573576d229186bb
|
https://github.com/userhello/bit_magic/blob/78b7fc28313af9c9506220812573576d229186bb/lib/bit_magic/bits_generator.rb#L111-L134
|
8,101
|
userhello/bit_magic
|
lib/bit_magic/bits_generator.rb
|
BitMagic.BitsGenerator.all_values
|
def all_values(each_bits = nil, opts = {warn_threshold: 12})
# Shuffle things around so that people can call #all_values(warn_threshold: false)
if each_bits.is_a?(Hash)
opts = each_bits
each_bits = nil
end
each_bits = self.bits if each_bits == nil
if opts[:warn_threshold] and each_bits.length > opts[:warn_threshold]
warn "There are #{each_bits.length} bits. You will have #{2**(each_bits.length)} values in the result. Please carefully benchmark the execution time and memory usage of your use-case."
warn "You can disable this warning by using #all_values(warn_threshold: false)"
end
values = []
self.each_value(each_bits) {|num| values << num }
values
end
|
ruby
|
def all_values(each_bits = nil, opts = {warn_threshold: 12})
# Shuffle things around so that people can call #all_values(warn_threshold: false)
if each_bits.is_a?(Hash)
opts = each_bits
each_bits = nil
end
each_bits = self.bits if each_bits == nil
if opts[:warn_threshold] and each_bits.length > opts[:warn_threshold]
warn "There are #{each_bits.length} bits. You will have #{2**(each_bits.length)} values in the result. Please carefully benchmark the execution time and memory usage of your use-case."
warn "You can disable this warning by using #all_values(warn_threshold: false)"
end
values = []
self.each_value(each_bits) {|num| values << num }
values
end
|
[
"def",
"all_values",
"(",
"each_bits",
"=",
"nil",
",",
"opts",
"=",
"{",
"warn_threshold",
":",
"12",
"}",
")",
"# Shuffle things around so that people can call #all_values(warn_threshold: false)",
"if",
"each_bits",
".",
"is_a?",
"(",
"Hash",
")",
"opts",
"=",
"each_bits",
"each_bits",
"=",
"nil",
"end",
"each_bits",
"=",
"self",
".",
"bits",
"if",
"each_bits",
"==",
"nil",
"if",
"opts",
"[",
":warn_threshold",
"]",
"and",
"each_bits",
".",
"length",
">",
"opts",
"[",
":warn_threshold",
"]",
"warn",
"\"There are #{each_bits.length} bits. You will have #{2**(each_bits.length)} values in the result. Please carefully benchmark the execution time and memory usage of your use-case.\"",
"warn",
"\"You can disable this warning by using #all_values(warn_threshold: false)\"",
"end",
"values",
"=",
"[",
"]",
"self",
".",
"each_value",
"(",
"each_bits",
")",
"{",
"|",
"num",
"|",
"values",
"<<",
"num",
"}",
"values",
"end"
] |
Gives you an array of all possible integer values based off the bit
combinations of the bit list.
Note: This will include all possible values from the bit list, but there
are no guarantees on their order. If you need an ordered list, sort the result.
Warning: Please see the warnings on each_value.
Warning: Memory usage grows exponentially to the number of bits! For example,
on a 64 bit platform (assuming pointers are 8 bytes) if you have 8 bits,
this array will have 256 values, taking up 2KB of memory. At 20 bits, it's
1048576 values, taking up 8MB. At 32 bits, 4294967296 values take up 34GB!
@param [optional, Array<Integer>] each_bits a list of bits used to generate
the combination list. default: the list of bits given during initialization
@param [Hash] opts additional options
@option opts [Integer] :warn_threshold will output warning messages if
the total number of bits is above this number. false to disable. default: 20
@example Get an array for all values from our bit list
gen = BitsGenerator.new(:is_odd => 0, :amount => [1, 2, 3], :is_cool => 4)
gen.all_values
@return [Array<Integer>] an array of all possible values from the bit list
Order is not guaranteed to be consistent.
|
[
"Gives",
"you",
"an",
"array",
"of",
"all",
"possible",
"integer",
"values",
"based",
"off",
"the",
"bit",
"combinations",
"of",
"the",
"bit",
"list",
"."
] |
78b7fc28313af9c9506220812573576d229186bb
|
https://github.com/userhello/bit_magic/blob/78b7fc28313af9c9506220812573576d229186bb/lib/bit_magic/bits_generator.rb#L161-L180
|
8,102
|
userhello/bit_magic
|
lib/bit_magic/bits_generator.rb
|
BitMagic.BitsGenerator.equal_to
|
def equal_to(field_values = {})
all_num, none_num = self.equal_to_numbers(field_values)
[].tap do |list|
self.each_value { |num| list << num if (num & all_num) == all_num and (num & none_num) == 0 }
end
end
|
ruby
|
def equal_to(field_values = {})
all_num, none_num = self.equal_to_numbers(field_values)
[].tap do |list|
self.each_value { |num| list << num if (num & all_num) == all_num and (num & none_num) == 0 }
end
end
|
[
"def",
"equal_to",
"(",
"field_values",
"=",
"{",
"}",
")",
"all_num",
",",
"none_num",
"=",
"self",
".",
"equal_to_numbers",
"(",
"field_values",
")",
"[",
"]",
".",
"tap",
"do",
"|",
"list",
"|",
"self",
".",
"each_value",
"{",
"|",
"num",
"|",
"list",
"<<",
"num",
"if",
"(",
"num",
"&",
"all_num",
")",
"==",
"all_num",
"and",
"(",
"num",
"&",
"none_num",
")",
"==",
"0",
"}",
"end",
"end"
] |
Gives you an array of values where the given field names are exactly
equal to their given field values.
Possible values are derived from the bits list during initialization.
Note: Order is not guaranteed. All numbers will be present, but there is
no expectation that the numbers will be in the same order every time. If
you need an ordered list, you can sort the result.
@param [Hash] one or more field names or an integer for a known bit index
as the key, and the value (integer or boolean) for that field as the hash
value. Values that have more bits than available will be truncated for
comparison. eg. a field with one bit setting value to 2 means field is 0
@example Get different amount values
gen = BitsGenerator.new(:is_odd => 0, :amount => [1, 2, 3], :is_cool => 4)
gen.equal_to(:amount => 5) #=> [10, 11, 26, 27]
gen.equal_to(:amount => 7) #=> [14, 15, 30, 31]
gen.equal_to(:amount => 7, :is_odd => 1, :is_cool => 1) #=> [31]
@return [Array<Integer>] an array of integer values where the bits and values
match the given input
|
[
"Gives",
"you",
"an",
"array",
"of",
"values",
"where",
"the",
"given",
"field",
"names",
"are",
"exactly",
"equal",
"to",
"their",
"given",
"field",
"values",
"."
] |
78b7fc28313af9c9506220812573576d229186bb
|
https://github.com/userhello/bit_magic/blob/78b7fc28313af9c9506220812573576d229186bb/lib/bit_magic/bits_generator.rb#L299-L305
|
8,103
|
userhello/bit_magic
|
lib/bit_magic/bits_generator.rb
|
BitMagic.BitsGenerator.equal_to_numbers
|
def equal_to_numbers(field_values = {})
fields = {}
field_values.each_pair do |field_name, v|
bits = self.bits_for(field_name)
fields[bits] = v if bits.length > 0
end
all_num = 0
none_num = 0
fields.each_pair { |field_bits, val|
field_bits.each_with_index do |bit, i|
if @options[:bool_caster].call(val[i])
all_num |= (1 << bit)
else
none_num |= (1 << bit)
end
end
}
[all_num, none_num]
end
|
ruby
|
def equal_to_numbers(field_values = {})
fields = {}
field_values.each_pair do |field_name, v|
bits = self.bits_for(field_name)
fields[bits] = v if bits.length > 0
end
all_num = 0
none_num = 0
fields.each_pair { |field_bits, val|
field_bits.each_with_index do |bit, i|
if @options[:bool_caster].call(val[i])
all_num |= (1 << bit)
else
none_num |= (1 << bit)
end
end
}
[all_num, none_num]
end
|
[
"def",
"equal_to_numbers",
"(",
"field_values",
"=",
"{",
"}",
")",
"fields",
"=",
"{",
"}",
"field_values",
".",
"each_pair",
"do",
"|",
"field_name",
",",
"v",
"|",
"bits",
"=",
"self",
".",
"bits_for",
"(",
"field_name",
")",
"fields",
"[",
"bits",
"]",
"=",
"v",
"if",
"bits",
".",
"length",
">",
"0",
"end",
"all_num",
"=",
"0",
"none_num",
"=",
"0",
"fields",
".",
"each_pair",
"{",
"|",
"field_bits",
",",
"val",
"|",
"field_bits",
".",
"each_with_index",
"do",
"|",
"bit",
",",
"i",
"|",
"if",
"@options",
"[",
":bool_caster",
"]",
".",
"call",
"(",
"val",
"[",
"i",
"]",
")",
"all_num",
"|=",
"(",
"1",
"<<",
"bit",
")",
"else",
"none_num",
"|=",
"(",
"1",
"<<",
"bit",
")",
"end",
"end",
"}",
"[",
"all_num",
",",
"none_num",
"]",
"end"
] |
Will return an array of two numbers, the first of which has all bits set
where the corresponding value bit is 1, and the second has all bits set
where the corresponding value bit is 0.
These numbers can be used in advanced bitwise operations to test fields
for exact equality.
@param [Hash] one or more field names or an integer for a known bit index
as the key, and the value (integer or boolean) for that field as the hash
value. Values that have more bits than available will be truncated for
comparison. eg. a field with one bit setting value to 2 means field is 0
@example Retrieve the representation for various amounts
gen = BitsGenerator.new(:is_odd => 0, :amount => [1, 2, 3], :is_cool => 4)
gen.equal_to_numbers(:amount => 5) #=> [10, 4]
# 5 is 101, 10 is 1010 and 4 is 100. (Note that amount uses bits 1, 2, 3)
gen.equal_to_numbers(:amount => 7) #=> [14, 0]
gen.equal_to_numbers(:amount => 7, :is_odd => 1) #=> [15, 0]
@return [Array<Integer>] an array of two integers, first representing bits
of given field bit values as 1 set to 1, and the second representing bits
of given field bit values as 0 set to 1. See the example.
|
[
"Will",
"return",
"an",
"array",
"of",
"two",
"numbers",
"the",
"first",
"of",
"which",
"has",
"all",
"bits",
"set",
"where",
"the",
"corresponding",
"value",
"bit",
"is",
"1",
"and",
"the",
"second",
"has",
"all",
"bits",
"set",
"where",
"the",
"corresponding",
"value",
"bit",
"is",
"0",
".",
"These",
"numbers",
"can",
"be",
"used",
"in",
"advanced",
"bitwise",
"operations",
"to",
"test",
"fields",
"for",
"exact",
"equality",
"."
] |
78b7fc28313af9c9506220812573576d229186bb
|
https://github.com/userhello/bit_magic/blob/78b7fc28313af9c9506220812573576d229186bb/lib/bit_magic/bits_generator.rb#L329-L350
|
8,104
|
ideonetwork/lato-blog
|
app/models/lato_blog/category/entity_helpers.rb
|
LatoBlog.Category::EntityHelpers.get_all_category_children
|
def get_all_category_children
direct_children = self.category_children
all_children = []
direct_children.each do |direct_child|
all_children.push(direct_child)
all_children = all_children + direct_child.get_all_category_children
end
all_children
end
|
ruby
|
def get_all_category_children
direct_children = self.category_children
all_children = []
direct_children.each do |direct_child|
all_children.push(direct_child)
all_children = all_children + direct_child.get_all_category_children
end
all_children
end
|
[
"def",
"get_all_category_children",
"direct_children",
"=",
"self",
".",
"category_children",
"all_children",
"=",
"[",
"]",
"direct_children",
".",
"each",
"do",
"|",
"direct_child",
"|",
"all_children",
".",
"push",
"(",
"direct_child",
")",
"all_children",
"=",
"all_children",
"+",
"direct_child",
".",
"get_all_category_children",
"end",
"all_children",
"end"
] |
This function return all category children of the current category.
|
[
"This",
"function",
"return",
"all",
"category",
"children",
"of",
"the",
"current",
"category",
"."
] |
a0d92de299a0e285851743b9d4a902f611187cba
|
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/category/entity_helpers.rb#L37-L47
|
8,105
|
lanvige/chinese_lunar
|
lib/chinese_lunar/lunar.rb
|
ChineseLunar.Lunar.lunar_date
|
def lunar_date()
l = convert(@date.year, @date.month, @date.day)
l[0].to_s + "-" + l[1].to_s + "-" + (/^\d+/.match(l[2].to_s)).to_s
end
|
ruby
|
def lunar_date()
l = convert(@date.year, @date.month, @date.day)
l[0].to_s + "-" + l[1].to_s + "-" + (/^\d+/.match(l[2].to_s)).to_s
end
|
[
"def",
"lunar_date",
"(",
")",
"l",
"=",
"convert",
"(",
"@date",
".",
"year",
",",
"@date",
".",
"month",
",",
"@date",
".",
"day",
")",
"l",
"[",
"0",
"]",
".",
"to_s",
"+",
"\"-\"",
"+",
"l",
"[",
"1",
"]",
".",
"to_s",
"+",
"\"-\"",
"+",
"(",
"/",
"\\d",
"/",
".",
"match",
"(",
"l",
"[",
"2",
"]",
".",
"to_s",
")",
")",
".",
"to_s",
"end"
] |
Get the Lundar date in 'xxxx-xx-xx' fromat
|
[
"Get",
"the",
"Lundar",
"date",
"in",
"xxxx",
"-",
"xx",
"-",
"xx",
"fromat"
] |
f4e4a4f19fc1a7098fabe31f41b58b0e6c86e779
|
https://github.com/lanvige/chinese_lunar/blob/f4e4a4f19fc1a7098fabe31f41b58b0e6c86e779/lib/chinese_lunar/lunar.rb#L53-L56
|
8,106
|
lanvige/chinese_lunar
|
lib/chinese_lunar/lunar.rb
|
ChineseLunar.Lunar.days_in_lunar_date
|
def days_in_lunar_date(y)
sum = 348
i = 0x8000
while i > 0x8
if ((@@lunar_info[y - 1900] & i) != 0)
sum += 1
end
i >>= 1
end
sum + leap_days(y)
end
|
ruby
|
def days_in_lunar_date(y)
sum = 348
i = 0x8000
while i > 0x8
if ((@@lunar_info[y - 1900] & i) != 0)
sum += 1
end
i >>= 1
end
sum + leap_days(y)
end
|
[
"def",
"days_in_lunar_date",
"(",
"y",
")",
"sum",
"=",
"348",
"i",
"=",
"0x8000",
"while",
"i",
">",
"0x8",
"if",
"(",
"(",
"@@lunar_info",
"[",
"y",
"-",
"1900",
"]",
"&",
"i",
")",
"!=",
"0",
")",
"sum",
"+=",
"1",
"end",
"i",
">>=",
"1",
"end",
"sum",
"+",
"leap_days",
"(",
"y",
")",
"end"
] |
Return the days in lunar of y year.
|
[
"Return",
"the",
"days",
"in",
"lunar",
"of",
"y",
"year",
"."
] |
f4e4a4f19fc1a7098fabe31f41b58b0e6c86e779
|
https://github.com/lanvige/chinese_lunar/blob/f4e4a4f19fc1a7098fabe31f41b58b0e6c86e779/lib/chinese_lunar/lunar.rb#L190-L201
|
8,107
|
mig-hub/sequel-crushyform
|
lib/sequel_crushyform.rb
|
::Sequel::Plugins::Crushyform.ClassMethods.to_dropdown
|
def to_dropdown(selection=nil, nil_name='** UNDEFINED **')
dropdown_cache.inject("<option value=''>#{nil_name}</option>\n") do |out, row|
selected = 'selected' if row[0]==selection
"%s%s%s%s" % [out, row[1], selected, row[2]]
end
end
|
ruby
|
def to_dropdown(selection=nil, nil_name='** UNDEFINED **')
dropdown_cache.inject("<option value=''>#{nil_name}</option>\n") do |out, row|
selected = 'selected' if row[0]==selection
"%s%s%s%s" % [out, row[1], selected, row[2]]
end
end
|
[
"def",
"to_dropdown",
"(",
"selection",
"=",
"nil",
",",
"nil_name",
"=",
"'** UNDEFINED **'",
")",
"dropdown_cache",
".",
"inject",
"(",
"\"<option value=''>#{nil_name}</option>\\n\"",
")",
"do",
"|",
"out",
",",
"row",
"|",
"selected",
"=",
"'selected'",
"if",
"row",
"[",
"0",
"]",
"==",
"selection",
"\"%s%s%s%s\"",
"%",
"[",
"out",
",",
"row",
"[",
"1",
"]",
",",
"selected",
",",
"row",
"[",
"2",
"]",
"]",
"end",
"end"
] |
Cache dropdown options for children classes to use
Meant to be reseted each time an entry is created, updated or destroyed
So it is only rebuild once required after the list has changed
Maintaining an array and not rebuilding it all might be faster
But it will not happen much so that it is fairly acceptable
|
[
"Cache",
"dropdown",
"options",
"for",
"children",
"classes",
"to",
"use",
"Meant",
"to",
"be",
"reseted",
"each",
"time",
"an",
"entry",
"is",
"created",
"updated",
"or",
"destroyed",
"So",
"it",
"is",
"only",
"rebuild",
"once",
"required",
"after",
"the",
"list",
"has",
"changed",
"Maintaining",
"an",
"array",
"and",
"not",
"rebuilding",
"it",
"all",
"might",
"be",
"faster",
"But",
"it",
"will",
"not",
"happen",
"much",
"so",
"that",
"it",
"is",
"fairly",
"acceptable"
] |
c717df86dea0206487d9b3ee340fbd529fc7b91f
|
https://github.com/mig-hub/sequel-crushyform/blob/c717df86dea0206487d9b3ee340fbd529fc7b91f/lib/sequel_crushyform.rb#L93-L98
|
8,108
|
mig-hub/sequel-crushyform
|
lib/sequel_crushyform.rb
|
::Sequel::Plugins::Crushyform.InstanceMethods.crushyfield
|
def crushyfield(col, o={})
return '' if (o[:type]==:none || model.crushyform_schema[col][:type]==:none)
field_name = o[:name] || model.crushyform_schema[col][:name] || col.to_s.sub(/_id$/, '').tr('_', ' ').capitalize
error_list = errors.on(col).map{|e|" - #{e}"} if !errors.on(col).nil?
"<p class='crushyfield %s'><label for='%s'>%s</label><span class='crushyfield-error-list'>%s</span><br />\n%s</p>\n" % [error_list&&'crushyfield-error', crushyid_for(col), field_name, error_list, crushyinput(col, o)]
end
|
ruby
|
def crushyfield(col, o={})
return '' if (o[:type]==:none || model.crushyform_schema[col][:type]==:none)
field_name = o[:name] || model.crushyform_schema[col][:name] || col.to_s.sub(/_id$/, '').tr('_', ' ').capitalize
error_list = errors.on(col).map{|e|" - #{e}"} if !errors.on(col).nil?
"<p class='crushyfield %s'><label for='%s'>%s</label><span class='crushyfield-error-list'>%s</span><br />\n%s</p>\n" % [error_list&&'crushyfield-error', crushyid_for(col), field_name, error_list, crushyinput(col, o)]
end
|
[
"def",
"crushyfield",
"(",
"col",
",",
"o",
"=",
"{",
"}",
")",
"return",
"''",
"if",
"(",
"o",
"[",
":type",
"]",
"==",
":none",
"||",
"model",
".",
"crushyform_schema",
"[",
"col",
"]",
"[",
":type",
"]",
"==",
":none",
")",
"field_name",
"=",
"o",
"[",
":name",
"]",
"||",
"model",
".",
"crushyform_schema",
"[",
"col",
"]",
"[",
":name",
"]",
"||",
"col",
".",
"to_s",
".",
"sub",
"(",
"/",
"/",
",",
"''",
")",
".",
"tr",
"(",
"'_'",
",",
"' '",
")",
".",
"capitalize",
"error_list",
"=",
"errors",
".",
"on",
"(",
"col",
")",
".",
"map",
"{",
"|",
"e",
"|",
"\" - #{e}\"",
"}",
"if",
"!",
"errors",
".",
"on",
"(",
"col",
")",
".",
"nil?",
"\"<p class='crushyfield %s'><label for='%s'>%s</label><span class='crushyfield-error-list'>%s</span><br />\\n%s</p>\\n\"",
"%",
"[",
"error_list",
"&&",
"'crushyfield-error'",
",",
"crushyid_for",
"(",
"col",
")",
",",
"field_name",
",",
"error_list",
",",
"crushyinput",
"(",
"col",
",",
"o",
")",
"]",
"end"
] |
crushyfield is crushyinput but with label+error
|
[
"crushyfield",
"is",
"crushyinput",
"but",
"with",
"label",
"+",
"error"
] |
c717df86dea0206487d9b3ee340fbd529fc7b91f
|
https://github.com/mig-hub/sequel-crushyform/blob/c717df86dea0206487d9b3ee340fbd529fc7b91f/lib/sequel_crushyform.rb#L124-L129
|
8,109
|
mig-hub/sequel-crushyform
|
lib/sequel_crushyform.rb
|
::Sequel::Plugins::Crushyform.InstanceMethods.to_thumb
|
def to_thumb(c)
current = self.__send__(c)
if model.respond_to?(:stash_reflection) && model.stash_reflection.key?(c)
!current.nil? && current[:type][/^image\//] ? "<img src='#{file_url(c, 'stash_thumb.gif')}?#{::Time.now.to_i.to_s}' /><br />\n" : ''
else
"<img src='#{current}?#{::Time.now.to_i.to_s}' width='100' onerror=\"this.style.display='none'\" />\n"
end
end
|
ruby
|
def to_thumb(c)
current = self.__send__(c)
if model.respond_to?(:stash_reflection) && model.stash_reflection.key?(c)
!current.nil? && current[:type][/^image\//] ? "<img src='#{file_url(c, 'stash_thumb.gif')}?#{::Time.now.to_i.to_s}' /><br />\n" : ''
else
"<img src='#{current}?#{::Time.now.to_i.to_s}' width='100' onerror=\"this.style.display='none'\" />\n"
end
end
|
[
"def",
"to_thumb",
"(",
"c",
")",
"current",
"=",
"self",
".",
"__send__",
"(",
"c",
")",
"if",
"model",
".",
"respond_to?",
"(",
":stash_reflection",
")",
"&&",
"model",
".",
"stash_reflection",
".",
"key?",
"(",
"c",
")",
"!",
"current",
".",
"nil?",
"&&",
"current",
"[",
":type",
"]",
"[",
"/",
"\\/",
"/",
"]",
"?",
"\"<img src='#{file_url(c, 'stash_thumb.gif')}?#{::Time.now.to_i.to_s}' /><br />\\n\"",
":",
"''",
"else",
"\"<img src='#{current}?#{::Time.now.to_i.to_s}' width='100' onerror=\\\"this.style.display='none'\\\" />\\n\"",
"end",
"end"
] |
Provide a thumbnail for the column
|
[
"Provide",
"a",
"thumbnail",
"for",
"the",
"column"
] |
c717df86dea0206487d9b3ee340fbd529fc7b91f
|
https://github.com/mig-hub/sequel-crushyform/blob/c717df86dea0206487d9b3ee340fbd529fc7b91f/lib/sequel_crushyform.rb#L151-L158
|
8,110
|
tbuehlmann/ponder
|
lib/ponder/thaum.rb
|
Ponder.Thaum.parse
|
def parse(message)
message.chomp!
if message =~ /^PING \S+$/
if @config.hide_ping_pongs
send_data message.sub(/PING/, 'PONG')
else
@loggers.info "<< #{message}"
raw message.sub(/PING/, 'PONG')
end
else
@loggers.info "<< #{message}"
event_data = IRC::Events::Parser.parse(message, @isupport['CHANTYPES'])
parse_event_data(event_data) unless event_data.empty?
end
end
|
ruby
|
def parse(message)
message.chomp!
if message =~ /^PING \S+$/
if @config.hide_ping_pongs
send_data message.sub(/PING/, 'PONG')
else
@loggers.info "<< #{message}"
raw message.sub(/PING/, 'PONG')
end
else
@loggers.info "<< #{message}"
event_data = IRC::Events::Parser.parse(message, @isupport['CHANTYPES'])
parse_event_data(event_data) unless event_data.empty?
end
end
|
[
"def",
"parse",
"(",
"message",
")",
"message",
".",
"chomp!",
"if",
"message",
"=~",
"/",
"\\S",
"/",
"if",
"@config",
".",
"hide_ping_pongs",
"send_data",
"message",
".",
"sub",
"(",
"/",
"/",
",",
"'PONG'",
")",
"else",
"@loggers",
".",
"info",
"\"<< #{message}\"",
"raw",
"message",
".",
"sub",
"(",
"/",
"/",
",",
"'PONG'",
")",
"end",
"else",
"@loggers",
".",
"info",
"\"<< #{message}\"",
"event_data",
"=",
"IRC",
"::",
"Events",
"::",
"Parser",
".",
"parse",
"(",
"message",
",",
"@isupport",
"[",
"'CHANTYPES'",
"]",
")",
"parse_event_data",
"(",
"event_data",
")",
"unless",
"event_data",
".",
"empty?",
"end",
"end"
] |
parsing incoming traffic
|
[
"parsing",
"incoming",
"traffic"
] |
930912e1b78b41afa1359121aca46197e9edff9c
|
https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/thaum.rb#L79-L94
|
8,111
|
tbuehlmann/ponder
|
lib/ponder/thaum.rb
|
Ponder.Thaum.setup_default_callbacks
|
def setup_default_callbacks
on :query, /^\001PING \d+\001$/ do |event_data|
time = event_data[:message].scan(/\d+/)[0]
notice event_data[:nick], "\001PING #{time}\001"
end
on :query, /^\001VERSION\001$/ do |event_data|
notice event_data[:nick], "\001VERSION Ponder #{Ponder::VERSION} (https://github.com/tbuehlmann/ponder)\001"
end
on :query, /^\001TIME\001$/ do |event_data|
notice event_data[:nick], "\001TIME #{Time.now.strftime('%a %b %d %H:%M:%S %Y')}\001"
end
on 005 do |event_data|
@isupport.parse event_data[:params]
end
end
|
ruby
|
def setup_default_callbacks
on :query, /^\001PING \d+\001$/ do |event_data|
time = event_data[:message].scan(/\d+/)[0]
notice event_data[:nick], "\001PING #{time}\001"
end
on :query, /^\001VERSION\001$/ do |event_data|
notice event_data[:nick], "\001VERSION Ponder #{Ponder::VERSION} (https://github.com/tbuehlmann/ponder)\001"
end
on :query, /^\001TIME\001$/ do |event_data|
notice event_data[:nick], "\001TIME #{Time.now.strftime('%a %b %d %H:%M:%S %Y')}\001"
end
on 005 do |event_data|
@isupport.parse event_data[:params]
end
end
|
[
"def",
"setup_default_callbacks",
"on",
":query",
",",
"/",
"\\001",
"\\d",
"\\001",
"/",
"do",
"|",
"event_data",
"|",
"time",
"=",
"event_data",
"[",
":message",
"]",
".",
"scan",
"(",
"/",
"\\d",
"/",
")",
"[",
"0",
"]",
"notice",
"event_data",
"[",
":nick",
"]",
",",
"\"\\001PING #{time}\\001\"",
"end",
"on",
":query",
",",
"/",
"\\001",
"\\001",
"/",
"do",
"|",
"event_data",
"|",
"notice",
"event_data",
"[",
":nick",
"]",
",",
"\"\\001VERSION Ponder #{Ponder::VERSION} (https://github.com/tbuehlmann/ponder)\\001\"",
"end",
"on",
":query",
",",
"/",
"\\001",
"\\001",
"/",
"do",
"|",
"event_data",
"|",
"notice",
"event_data",
"[",
":nick",
"]",
",",
"\"\\001TIME #{Time.now.strftime('%a %b %d %H:%M:%S %Y')}\\001\"",
"end",
"on",
"005",
"do",
"|",
"event_data",
"|",
"@isupport",
".",
"parse",
"event_data",
"[",
":params",
"]",
"end",
"end"
] |
Default callbacks for PING, VERSION, TIME and ISUPPORT processing.
|
[
"Default",
"callbacks",
"for",
"PING",
"VERSION",
"TIME",
"and",
"ISUPPORT",
"processing",
"."
] |
930912e1b78b41afa1359121aca46197e9edff9c
|
https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/thaum.rb#L135-L152
|
8,112
|
Deradon/Rails-LookUpTable
|
lib/look_up_table/cache.rb
|
LookUpTable.ClassMethods.lut_write_to_cache
|
def lut_write_to_cache(lut_key)
if lut_options(lut_key)[:sql_mode]
count = lut_write_to_cache_sql_mode(lut_key)
else
count = lut_write_to_cache_no_sql_mode(lut_key)
end
# HACK: Writing a \0 to terminate batch_items
lut_write_cache_item(lut_key, count, nil)
end
|
ruby
|
def lut_write_to_cache(lut_key)
if lut_options(lut_key)[:sql_mode]
count = lut_write_to_cache_sql_mode(lut_key)
else
count = lut_write_to_cache_no_sql_mode(lut_key)
end
# HACK: Writing a \0 to terminate batch_items
lut_write_cache_item(lut_key, count, nil)
end
|
[
"def",
"lut_write_to_cache",
"(",
"lut_key",
")",
"if",
"lut_options",
"(",
"lut_key",
")",
"[",
":sql_mode",
"]",
"count",
"=",
"lut_write_to_cache_sql_mode",
"(",
"lut_key",
")",
"else",
"count",
"=",
"lut_write_to_cache_no_sql_mode",
"(",
"lut_key",
")",
"end",
"# HACK: Writing a \\0 to terminate batch_items",
"lut_write_cache_item",
"(",
"lut_key",
",",
"count",
",",
"nil",
")",
"end"
] |
Write a LookUpTable into Cache
|
[
"Write",
"a",
"LookUpTable",
"into",
"Cache"
] |
da873f48b039ef01ed3d3820d3a59d8886281be1
|
https://github.com/Deradon/Rails-LookUpTable/blob/da873f48b039ef01ed3d3820d3a59d8886281be1/lib/look_up_table/cache.rb#L41-L50
|
8,113
|
charmkit/charmkit
|
lib/charmkit/helpers/template.rb
|
Charmkit.Helpers.template
|
def template(src, dst, **context)
rendered = TemplateRenderer.render(File.read(src), context)
File.write(dst, rendered)
end
|
ruby
|
def template(src, dst, **context)
rendered = TemplateRenderer.render(File.read(src), context)
File.write(dst, rendered)
end
|
[
"def",
"template",
"(",
"src",
",",
"dst",
",",
"**",
"context",
")",
"rendered",
"=",
"TemplateRenderer",
".",
"render",
"(",
"File",
".",
"read",
"(",
"src",
")",
",",
"context",
")",
"File",
".",
"write",
"(",
"dst",
",",
"rendered",
")",
"end"
] |
Reads from a erb file and renders the content with context
@param src String - file path of template
@param dst String - file path location to save
@param context Hash - parametized variables to pass to template
@return Boolean
@example
template('examples/my-demo-charm/templates/vhost.conf',
'/tmp/nginx-data.conf',
public_address: 'localhost',
app_path: '/srv/app')
|
[
"Reads",
"from",
"a",
"erb",
"file",
"and",
"renders",
"the",
"content",
"with",
"context"
] |
cdb51bbbe0a14c681edc00fdeb318307b80fd613
|
https://github.com/charmkit/charmkit/blob/cdb51bbbe0a14c681edc00fdeb318307b80fd613/lib/charmkit/helpers/template.rb#L30-L33
|
8,114
|
charmkit/charmkit
|
lib/charmkit/helpers/template.rb
|
Charmkit.Helpers.inline_template
|
def inline_template(name, dst, **context)
templates = {}
begin
app, data = File.read(caller.first.split(":").first).split("__END__", 2)
rescue Errno::ENOENT
app, data = nil
end
data.strip!
if data
template = nil
data.each_line do |line|
if line =~ /^@@\s*(.*\S)\s*$/
template = String.new
templates[$1.to_s] = template
elsif
template << line
end
end
begin
rendered = TemplateRenderer.render(templates[name], context)
rescue
puts "Unable to load inline template #{name}"
exit 1
end
File.write(dst, rendered)
end
end
|
ruby
|
def inline_template(name, dst, **context)
templates = {}
begin
app, data = File.read(caller.first.split(":").first).split("__END__", 2)
rescue Errno::ENOENT
app, data = nil
end
data.strip!
if data
template = nil
data.each_line do |line|
if line =~ /^@@\s*(.*\S)\s*$/
template = String.new
templates[$1.to_s] = template
elsif
template << line
end
end
begin
rendered = TemplateRenderer.render(templates[name], context)
rescue
puts "Unable to load inline template #{name}"
exit 1
end
File.write(dst, rendered)
end
end
|
[
"def",
"inline_template",
"(",
"name",
",",
"dst",
",",
"**",
"context",
")",
"templates",
"=",
"{",
"}",
"begin",
"app",
",",
"data",
"=",
"File",
".",
"read",
"(",
"caller",
".",
"first",
".",
"split",
"(",
"\":\"",
")",
".",
"first",
")",
".",
"split",
"(",
"\"__END__\"",
",",
"2",
")",
"rescue",
"Errno",
"::",
"ENOENT",
"app",
",",
"data",
"=",
"nil",
"end",
"data",
".",
"strip!",
"if",
"data",
"template",
"=",
"nil",
"data",
".",
"each_line",
"do",
"|",
"line",
"|",
"if",
"line",
"=~",
"/",
"\\s",
"\\S",
"\\s",
"/",
"template",
"=",
"String",
".",
"new",
"templates",
"[",
"$1",
".",
"to_s",
"]",
"=",
"template",
"elsif",
"template",
"<<",
"line",
"end",
"end",
"begin",
"rendered",
"=",
"TemplateRenderer",
".",
"render",
"(",
"templates",
"[",
"name",
"]",
",",
"context",
")",
"rescue",
"puts",
"\"Unable to load inline template #{name}\"",
"exit",
"1",
"end",
"File",
".",
"write",
"(",
"dst",
",",
"rendered",
")",
"end",
"end"
] |
Reads from a embedded template in the rake task itself.
@param src String - The data found after __END__
@param dst String - Save location
@param context Hash - variables to pass into template
@return Boolean
@example
inline_template('vhost.conf',
'/etc/nginx/sites-enabled/default')
server_name: "example.com")
__END__
@@ vhost.conf
server { name <%= server_name %> }
|
[
"Reads",
"from",
"a",
"embedded",
"template",
"in",
"the",
"rake",
"task",
"itself",
"."
] |
cdb51bbbe0a14c681edc00fdeb318307b80fd613
|
https://github.com/charmkit/charmkit/blob/cdb51bbbe0a14c681edc00fdeb318307b80fd613/lib/charmkit/helpers/template.rb#L50-L78
|
8,115
|
conversation/raca
|
lib/raca/container.rb
|
Raca.Container.delete
|
def delete(key)
log "deleting #{key} from #{container_path}"
object_path = File.join(container_path, Raca::Util.url_encode(key))
response = storage_client.delete(object_path)
(200..299).cover?(response.code.to_i)
end
|
ruby
|
def delete(key)
log "deleting #{key} from #{container_path}"
object_path = File.join(container_path, Raca::Util.url_encode(key))
response = storage_client.delete(object_path)
(200..299).cover?(response.code.to_i)
end
|
[
"def",
"delete",
"(",
"key",
")",
"log",
"\"deleting #{key} from #{container_path}\"",
"object_path",
"=",
"File",
".",
"join",
"(",
"container_path",
",",
"Raca",
"::",
"Util",
".",
"url_encode",
"(",
"key",
")",
")",
"response",
"=",
"storage_client",
".",
"delete",
"(",
"object_path",
")",
"(",
"200",
"..",
"299",
")",
".",
"cover?",
"(",
"response",
".",
"code",
".",
"to_i",
")",
"end"
] |
Delete +key+ from the container. If the container is on the CDN, the object will
still be served from the CDN until the TTL expires.
|
[
"Delete",
"+",
"key",
"+",
"from",
"the",
"container",
".",
"If",
"the",
"container",
"is",
"on",
"the",
"CDN",
"the",
"object",
"will",
"still",
"be",
"served",
"from",
"the",
"CDN",
"until",
"the",
"TTL",
"expires",
"."
] |
fa69dfde22359cc0e06f655055be4eadcc7019c0
|
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L50-L55
|
8,116
|
conversation/raca
|
lib/raca/container.rb
|
Raca.Container.object_metadata
|
def object_metadata(key)
object_path = File.join(container_path, Raca::Util.url_encode(key))
log "Requesting metadata from #{object_path}"
response = storage_client.head(object_path)
{
:content_type => response["Content-Type"],
:bytes => response["Content-Length"].to_i
}
end
|
ruby
|
def object_metadata(key)
object_path = File.join(container_path, Raca::Util.url_encode(key))
log "Requesting metadata from #{object_path}"
response = storage_client.head(object_path)
{
:content_type => response["Content-Type"],
:bytes => response["Content-Length"].to_i
}
end
|
[
"def",
"object_metadata",
"(",
"key",
")",
"object_path",
"=",
"File",
".",
"join",
"(",
"container_path",
",",
"Raca",
"::",
"Util",
".",
"url_encode",
"(",
"key",
")",
")",
"log",
"\"Requesting metadata from #{object_path}\"",
"response",
"=",
"storage_client",
".",
"head",
"(",
"object_path",
")",
"{",
":content_type",
"=>",
"response",
"[",
"\"Content-Type\"",
"]",
",",
":bytes",
"=>",
"response",
"[",
"\"Content-Length\"",
"]",
".",
"to_i",
"}",
"end"
] |
Returns some metadata about a single object in this container.
|
[
"Returns",
"some",
"metadata",
"about",
"a",
"single",
"object",
"in",
"this",
"container",
"."
] |
fa69dfde22359cc0e06f655055be4eadcc7019c0
|
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L75-L84
|
8,117
|
conversation/raca
|
lib/raca/container.rb
|
Raca.Container.download
|
def download(key, filepath)
log "downloading #{key} from #{container_path}"
object_path = File.join(container_path, Raca::Util.url_encode(key))
outer_response = storage_client.get(object_path) do |response|
File.open(filepath, 'wb') do |io|
response.read_body do |chunk|
io.write(chunk)
end
end
end
outer_response["Content-Length"].to_i
end
|
ruby
|
def download(key, filepath)
log "downloading #{key} from #{container_path}"
object_path = File.join(container_path, Raca::Util.url_encode(key))
outer_response = storage_client.get(object_path) do |response|
File.open(filepath, 'wb') do |io|
response.read_body do |chunk|
io.write(chunk)
end
end
end
outer_response["Content-Length"].to_i
end
|
[
"def",
"download",
"(",
"key",
",",
"filepath",
")",
"log",
"\"downloading #{key} from #{container_path}\"",
"object_path",
"=",
"File",
".",
"join",
"(",
"container_path",
",",
"Raca",
"::",
"Util",
".",
"url_encode",
"(",
"key",
")",
")",
"outer_response",
"=",
"storage_client",
".",
"get",
"(",
"object_path",
")",
"do",
"|",
"response",
"|",
"File",
".",
"open",
"(",
"filepath",
",",
"'wb'",
")",
"do",
"|",
"io",
"|",
"response",
".",
"read_body",
"do",
"|",
"chunk",
"|",
"io",
".",
"write",
"(",
"chunk",
")",
"end",
"end",
"end",
"outer_response",
"[",
"\"Content-Length\"",
"]",
".",
"to_i",
"end"
] |
Download the object at key into a local file at filepath.
Returns the number of downloaded bytes.
|
[
"Download",
"the",
"object",
"at",
"key",
"into",
"a",
"local",
"file",
"at",
"filepath",
"."
] |
fa69dfde22359cc0e06f655055be4eadcc7019c0
|
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L90-L101
|
8,118
|
conversation/raca
|
lib/raca/container.rb
|
Raca.Container.list
|
def list(options = {})
max = options.fetch(:max, 100_000_000)
marker = options.fetch(:marker, nil)
prefix = options.fetch(:prefix, nil)
details = options.fetch(:details, nil)
limit = [max, MAX_ITEMS_PER_LIST].min
log "retrieving up to #{max} items from #{container_path}"
request_path = list_request_path(marker, prefix, details, limit)
result = storage_client.get(request_path).body || ""
if details
result = JSON.parse(result)
else
result = result.split("\n")
end
result.tap {|items|
if max <= limit
log "Got #{items.length} items; we don't need any more."
elsif items.length < limit
log "Got #{items.length} items; there can't be any more."
else
log "Got #{items.length} items; requesting #{limit} more."
details ? marker = items.last["name"] : marker = items.last
items.concat list(max: max-items.length, marker: marker, prefix: prefix, details: details)
end
}
end
|
ruby
|
def list(options = {})
max = options.fetch(:max, 100_000_000)
marker = options.fetch(:marker, nil)
prefix = options.fetch(:prefix, nil)
details = options.fetch(:details, nil)
limit = [max, MAX_ITEMS_PER_LIST].min
log "retrieving up to #{max} items from #{container_path}"
request_path = list_request_path(marker, prefix, details, limit)
result = storage_client.get(request_path).body || ""
if details
result = JSON.parse(result)
else
result = result.split("\n")
end
result.tap {|items|
if max <= limit
log "Got #{items.length} items; we don't need any more."
elsif items.length < limit
log "Got #{items.length} items; there can't be any more."
else
log "Got #{items.length} items; requesting #{limit} more."
details ? marker = items.last["name"] : marker = items.last
items.concat list(max: max-items.length, marker: marker, prefix: prefix, details: details)
end
}
end
|
[
"def",
"list",
"(",
"options",
"=",
"{",
"}",
")",
"max",
"=",
"options",
".",
"fetch",
"(",
":max",
",",
"100_000_000",
")",
"marker",
"=",
"options",
".",
"fetch",
"(",
":marker",
",",
"nil",
")",
"prefix",
"=",
"options",
".",
"fetch",
"(",
":prefix",
",",
"nil",
")",
"details",
"=",
"options",
".",
"fetch",
"(",
":details",
",",
"nil",
")",
"limit",
"=",
"[",
"max",
",",
"MAX_ITEMS_PER_LIST",
"]",
".",
"min",
"log",
"\"retrieving up to #{max} items from #{container_path}\"",
"request_path",
"=",
"list_request_path",
"(",
"marker",
",",
"prefix",
",",
"details",
",",
"limit",
")",
"result",
"=",
"storage_client",
".",
"get",
"(",
"request_path",
")",
".",
"body",
"||",
"\"\"",
"if",
"details",
"result",
"=",
"JSON",
".",
"parse",
"(",
"result",
")",
"else",
"result",
"=",
"result",
".",
"split",
"(",
"\"\\n\"",
")",
"end",
"result",
".",
"tap",
"{",
"|",
"items",
"|",
"if",
"max",
"<=",
"limit",
"log",
"\"Got #{items.length} items; we don't need any more.\"",
"elsif",
"items",
".",
"length",
"<",
"limit",
"log",
"\"Got #{items.length} items; there can't be any more.\"",
"else",
"log",
"\"Got #{items.length} items; requesting #{limit} more.\"",
"details",
"?",
"marker",
"=",
"items",
".",
"last",
"[",
"\"name\"",
"]",
":",
"marker",
"=",
"items",
".",
"last",
"items",
".",
"concat",
"list",
"(",
"max",
":",
"max",
"-",
"items",
".",
"length",
",",
"marker",
":",
"marker",
",",
"prefix",
":",
"prefix",
",",
"details",
":",
"details",
")",
"end",
"}",
"end"
] |
Return an array of files in the container.
Supported options
max - the maximum number of items to return
marker - return items alphabetically after this key. Useful for pagination
prefix - only return items that start with this string
details - return extra details for each file - size, md5, etc
|
[
"Return",
"an",
"array",
"of",
"files",
"in",
"the",
"container",
"."
] |
fa69dfde22359cc0e06f655055be4eadcc7019c0
|
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L112-L137
|
8,119
|
conversation/raca
|
lib/raca/container.rb
|
Raca.Container.metadata
|
def metadata
log "retrieving container metadata from #{container_path}"
response = storage_client.head(container_path)
custom = {}
response.each_capitalized_name { |name|
custom[name] = response[name] if name[/\AX-Container-Meta-/]
}
{
:objects => response["X-Container-Object-Count"].to_i,
:bytes => response["X-Container-Bytes-Used"].to_i,
:custom => custom,
}
end
|
ruby
|
def metadata
log "retrieving container metadata from #{container_path}"
response = storage_client.head(container_path)
custom = {}
response.each_capitalized_name { |name|
custom[name] = response[name] if name[/\AX-Container-Meta-/]
}
{
:objects => response["X-Container-Object-Count"].to_i,
:bytes => response["X-Container-Bytes-Used"].to_i,
:custom => custom,
}
end
|
[
"def",
"metadata",
"log",
"\"retrieving container metadata from #{container_path}\"",
"response",
"=",
"storage_client",
".",
"head",
"(",
"container_path",
")",
"custom",
"=",
"{",
"}",
"response",
".",
"each_capitalized_name",
"{",
"|",
"name",
"|",
"custom",
"[",
"name",
"]",
"=",
"response",
"[",
"name",
"]",
"if",
"name",
"[",
"/",
"\\A",
"/",
"]",
"}",
"{",
":objects",
"=>",
"response",
"[",
"\"X-Container-Object-Count\"",
"]",
".",
"to_i",
",",
":bytes",
"=>",
"response",
"[",
"\"X-Container-Bytes-Used\"",
"]",
".",
"to_i",
",",
":custom",
"=>",
"custom",
",",
"}",
"end"
] |
Return some basic stats on the current container.
|
[
"Return",
"some",
"basic",
"stats",
"on",
"the",
"current",
"container",
"."
] |
fa69dfde22359cc0e06f655055be4eadcc7019c0
|
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L151-L163
|
8,120
|
conversation/raca
|
lib/raca/container.rb
|
Raca.Container.set_metadata
|
def set_metadata(headers)
log "setting headers for container #{container_path}"
response = storage_client.post(container_path, '', headers)
(200..299).cover?(response.code.to_i)
end
|
ruby
|
def set_metadata(headers)
log "setting headers for container #{container_path}"
response = storage_client.post(container_path, '', headers)
(200..299).cover?(response.code.to_i)
end
|
[
"def",
"set_metadata",
"(",
"headers",
")",
"log",
"\"setting headers for container #{container_path}\"",
"response",
"=",
"storage_client",
".",
"post",
"(",
"container_path",
",",
"''",
",",
"headers",
")",
"(",
"200",
"..",
"299",
")",
".",
"cover?",
"(",
"response",
".",
"code",
".",
"to_i",
")",
"end"
] |
Set metadata headers on the container
headers = { "X-Container-Meta-Access-Control-Allow-Origin" => "*" }
container.set_metadata(headers)
Note: Rackspace requires some headers to begin with 'X-Container-Meta-' or other prefixes, e.g. when setting
'Access-Control-Allow-Origin', it needs to be set as 'X-Container-Meta-Access-Control-Allow-Origin'.
See: http://docs.rackspace.com/files/api/v1/cf-devguide/content/CORS_Container_Header-d1e1300.html
http://docs.rackspace.com/files/api/v1/cf-devguide/content/
POST_updateacontainermeta_v1__account___container__containerServicesOperations_d1e000.html
|
[
"Set",
"metadata",
"headers",
"on",
"the",
"container"
] |
fa69dfde22359cc0e06f655055be4eadcc7019c0
|
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L176-L180
|
8,121
|
conversation/raca
|
lib/raca/container.rb
|
Raca.Container.cdn_metadata
|
def cdn_metadata
log "retrieving container CDN metadata from #{container_path}"
response = cdn_client.head(container_path)
{
:cdn_enabled => response["X-CDN-Enabled"] == "True",
:host => response["X-CDN-URI"],
:ssl_host => response["X-CDN-SSL-URI"],
:streaming_host => response["X-CDN-STREAMING-URI"],
:ttl => response["X-TTL"].to_i,
:log_retention => response["X-Log-Retention"] == "True"
}
end
|
ruby
|
def cdn_metadata
log "retrieving container CDN metadata from #{container_path}"
response = cdn_client.head(container_path)
{
:cdn_enabled => response["X-CDN-Enabled"] == "True",
:host => response["X-CDN-URI"],
:ssl_host => response["X-CDN-SSL-URI"],
:streaming_host => response["X-CDN-STREAMING-URI"],
:ttl => response["X-TTL"].to_i,
:log_retention => response["X-Log-Retention"] == "True"
}
end
|
[
"def",
"cdn_metadata",
"log",
"\"retrieving container CDN metadata from #{container_path}\"",
"response",
"=",
"cdn_client",
".",
"head",
"(",
"container_path",
")",
"{",
":cdn_enabled",
"=>",
"response",
"[",
"\"X-CDN-Enabled\"",
"]",
"==",
"\"True\"",
",",
":host",
"=>",
"response",
"[",
"\"X-CDN-URI\"",
"]",
",",
":ssl_host",
"=>",
"response",
"[",
"\"X-CDN-SSL-URI\"",
"]",
",",
":streaming_host",
"=>",
"response",
"[",
"\"X-CDN-STREAMING-URI\"",
"]",
",",
":ttl",
"=>",
"response",
"[",
"\"X-TTL\"",
"]",
".",
"to_i",
",",
":log_retention",
"=>",
"response",
"[",
"\"X-Log-Retention\"",
"]",
"==",
"\"True\"",
"}",
"end"
] |
Return the key details for CDN access to this container. Can be called
on non CDN enabled containers, but the details won't make much sense.
|
[
"Return",
"the",
"key",
"details",
"for",
"CDN",
"access",
"to",
"this",
"container",
".",
"Can",
"be",
"called",
"on",
"non",
"CDN",
"enabled",
"containers",
"but",
"the",
"details",
"won",
"t",
"make",
"much",
"sense",
"."
] |
fa69dfde22359cc0e06f655055be4eadcc7019c0
|
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L185-L196
|
8,122
|
conversation/raca
|
lib/raca/container.rb
|
Raca.Container.cdn_enable
|
def cdn_enable(ttl = 259200)
log "enabling CDN access to #{container_path} with a cache expiry of #{ttl / 60} minutes"
response = cdn_client.put(container_path, "X-TTL" => ttl.to_i.to_s)
(200..299).cover?(response.code.to_i)
end
|
ruby
|
def cdn_enable(ttl = 259200)
log "enabling CDN access to #{container_path} with a cache expiry of #{ttl / 60} minutes"
response = cdn_client.put(container_path, "X-TTL" => ttl.to_i.to_s)
(200..299).cover?(response.code.to_i)
end
|
[
"def",
"cdn_enable",
"(",
"ttl",
"=",
"259200",
")",
"log",
"\"enabling CDN access to #{container_path} with a cache expiry of #{ttl / 60} minutes\"",
"response",
"=",
"cdn_client",
".",
"put",
"(",
"container_path",
",",
"\"X-TTL\"",
"=>",
"ttl",
".",
"to_i",
".",
"to_s",
")",
"(",
"200",
"..",
"299",
")",
".",
"cover?",
"(",
"response",
".",
"code",
".",
"to_i",
")",
"end"
] |
use this with caution, it will make EVERY object in the container publicly available
via the CDN. CDN enabling can be done via the web UI but only with a TTL of 72 hours.
Using the API it's possible to set a TTL of 50 years.
TTL is defined in seconds, default is 72 hours.
|
[
"use",
"this",
"with",
"caution",
"it",
"will",
"make",
"EVERY",
"object",
"in",
"the",
"container",
"publicly",
"available",
"via",
"the",
"CDN",
".",
"CDN",
"enabling",
"can",
"be",
"done",
"via",
"the",
"web",
"UI",
"but",
"only",
"with",
"a",
"TTL",
"of",
"72",
"hours",
".",
"Using",
"the",
"API",
"it",
"s",
"possible",
"to",
"set",
"a",
"TTL",
"of",
"50",
"years",
"."
] |
fa69dfde22359cc0e06f655055be4eadcc7019c0
|
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L204-L209
|
8,123
|
conversation/raca
|
lib/raca/container.rb
|
Raca.Container.temp_url
|
def temp_url(object_key, temp_url_key, expires_at = Time.now.to_i + 60)
private_url("GET", object_key, temp_url_key, expires_at)
end
|
ruby
|
def temp_url(object_key, temp_url_key, expires_at = Time.now.to_i + 60)
private_url("GET", object_key, temp_url_key, expires_at)
end
|
[
"def",
"temp_url",
"(",
"object_key",
",",
"temp_url_key",
",",
"expires_at",
"=",
"Time",
".",
"now",
".",
"to_i",
"+",
"60",
")",
"private_url",
"(",
"\"GET\"",
",",
"object_key",
",",
"temp_url_key",
",",
"expires_at",
")",
"end"
] |
Generate an expiring URL for downloading a file that is otherwise private.
Useful for providing temporary access to files.
|
[
"Generate",
"an",
"expiring",
"URL",
"for",
"downloading",
"a",
"file",
"that",
"is",
"otherwise",
"private",
".",
"Useful",
"for",
"providing",
"temporary",
"access",
"to",
"files",
"."
] |
fa69dfde22359cc0e06f655055be4eadcc7019c0
|
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L214-L216
|
8,124
|
conversation/raca
|
lib/raca/container.rb
|
Raca.Container.temp_upload_url
|
def temp_upload_url(object_key, temp_url_key, expires_at = Time.now.to_i + 60)
private_url("PUT", object_key, temp_url_key, expires_at)
end
|
ruby
|
def temp_upload_url(object_key, temp_url_key, expires_at = Time.now.to_i + 60)
private_url("PUT", object_key, temp_url_key, expires_at)
end
|
[
"def",
"temp_upload_url",
"(",
"object_key",
",",
"temp_url_key",
",",
"expires_at",
"=",
"Time",
".",
"now",
".",
"to_i",
"+",
"60",
")",
"private_url",
"(",
"\"PUT\"",
",",
"object_key",
",",
"temp_url_key",
",",
"expires_at",
")",
"end"
] |
Generate a temporary URL for uploading a file to a private container. Anyone
can perform a PUT request to the URL returned from this method and an object
will be created in the container.
|
[
"Generate",
"a",
"temporary",
"URL",
"for",
"uploading",
"a",
"file",
"to",
"a",
"private",
"container",
".",
"Anyone",
"can",
"perform",
"a",
"PUT",
"request",
"to",
"the",
"URL",
"returned",
"from",
"this",
"method",
"and",
"an",
"object",
"will",
"be",
"created",
"in",
"the",
"container",
"."
] |
fa69dfde22359cc0e06f655055be4eadcc7019c0
|
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L228-L230
|
8,125
|
conversation/raca
|
lib/raca/container.rb
|
Raca.Container.list_request_path
|
def list_request_path(marker, prefix, details, limit)
query_string = "limit=#{limit}"
query_string += "&marker=#{Raca::Util.url_encode(marker)}" if marker
query_string += "&prefix=#{Raca::Util.url_encode(prefix)}" if prefix
query_string += "&format=json" if details
container_path + "?#{query_string}"
end
|
ruby
|
def list_request_path(marker, prefix, details, limit)
query_string = "limit=#{limit}"
query_string += "&marker=#{Raca::Util.url_encode(marker)}" if marker
query_string += "&prefix=#{Raca::Util.url_encode(prefix)}" if prefix
query_string += "&format=json" if details
container_path + "?#{query_string}"
end
|
[
"def",
"list_request_path",
"(",
"marker",
",",
"prefix",
",",
"details",
",",
"limit",
")",
"query_string",
"=",
"\"limit=#{limit}\"",
"query_string",
"+=",
"\"&marker=#{Raca::Util.url_encode(marker)}\"",
"if",
"marker",
"query_string",
"+=",
"\"&prefix=#{Raca::Util.url_encode(prefix)}\"",
"if",
"prefix",
"query_string",
"+=",
"\"&format=json\"",
"if",
"details",
"container_path",
"+",
"\"?#{query_string}\"",
"end"
] |
build the request path for listing the contents of a container
|
[
"build",
"the",
"request",
"path",
"for",
"listing",
"the",
"contents",
"of",
"a",
"container"
] |
fa69dfde22359cc0e06f655055be4eadcc7019c0
|
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/container.rb#L255-L261
|
8,126
|
sugaryourcoffee/timeleap
|
lib/syctimeleap/time_leap.rb
|
SycTimeleap.TimeLeap.method_missing
|
def method_missing(name, *args)
add_regex = %r{
^([ib])(?:n|ack)?
(?:\.|_|-| )?
(\d+)
(?:\.|_|-| )?
([dwmy])
(?:ays?|eeks?|onths?|ears?)?$
}x
weekday_regex = %r{
^(tod|tom|y)(?:a?y?|o?r?r?o?w?|e?s?t?e?r?d?a?y?)?$
}xi
next_weekday_regex = %r{
^(n|p)(?:e?x?t|r?e?v?i?o?u?s?)?
(?:\.|_| |-)?
(mo|tu|we|th|fr|sa|su)
(?:n?|e?s?|d?n?e?s?|u?r?s?|i?|t?u?r?|n?)(?:d?a?y?)$
}xi
next_weekday_in_regex = %r{
^(mo|tu|we|th|fr|sa|su)
(?:n?|e?s?|d?n?e?s?|u?r?s?|i?|t?u?r?|n?)(?:d?a?y?)(?:_?)
(i|b)
(?:n?|a?c?k?)(?:_?)
(\d+)(?:_?)([dwmy])(?:a?y?s?|e?e?k?s?|o?n?t?h?s?|e?a?r?s?)$
}xi
return add($1, $2, $3) if name =~ add_regex
return weekday($1) if name =~ weekday_regex
return next_weekday($1, $2) if name =~ next_weekday_regex
return next_weekday_in($1, $2, $3, $4) if name =~ next_weekday_in_regex
super
end
|
ruby
|
def method_missing(name, *args)
add_regex = %r{
^([ib])(?:n|ack)?
(?:\.|_|-| )?
(\d+)
(?:\.|_|-| )?
([dwmy])
(?:ays?|eeks?|onths?|ears?)?$
}x
weekday_regex = %r{
^(tod|tom|y)(?:a?y?|o?r?r?o?w?|e?s?t?e?r?d?a?y?)?$
}xi
next_weekday_regex = %r{
^(n|p)(?:e?x?t|r?e?v?i?o?u?s?)?
(?:\.|_| |-)?
(mo|tu|we|th|fr|sa|su)
(?:n?|e?s?|d?n?e?s?|u?r?s?|i?|t?u?r?|n?)(?:d?a?y?)$
}xi
next_weekday_in_regex = %r{
^(mo|tu|we|th|fr|sa|su)
(?:n?|e?s?|d?n?e?s?|u?r?s?|i?|t?u?r?|n?)(?:d?a?y?)(?:_?)
(i|b)
(?:n?|a?c?k?)(?:_?)
(\d+)(?:_?)([dwmy])(?:a?y?s?|e?e?k?s?|o?n?t?h?s?|e?a?r?s?)$
}xi
return add($1, $2, $3) if name =~ add_regex
return weekday($1) if name =~ weekday_regex
return next_weekday($1, $2) if name =~ next_weekday_regex
return next_weekday_in($1, $2, $3, $4) if name =~ next_weekday_in_regex
super
end
|
[
"def",
"method_missing",
"(",
"name",
",",
"*",
"args",
")",
"add_regex",
"=",
"%r{",
"\\.",
"\\d",
"\\.",
"}x",
"weekday_regex",
"=",
"%r{",
"}xi",
"next_weekday_regex",
"=",
"%r{",
"\\.",
"}xi",
"next_weekday_in_regex",
"=",
"%r{",
"\\d",
"}xi",
"return",
"add",
"(",
"$1",
",",
"$2",
",",
"$3",
")",
"if",
"name",
"=~",
"add_regex",
"return",
"weekday",
"(",
"$1",
")",
"if",
"name",
"=~",
"weekday_regex",
"return",
"next_weekday",
"(",
"$1",
",",
"$2",
")",
"if",
"name",
"=~",
"next_weekday_regex",
"return",
"next_weekday_in",
"(",
"$1",
",",
"$2",
",",
"$3",
",",
"$4",
")",
"if",
"name",
"=~",
"next_weekday_in_regex",
"super",
"end"
] |
Creates a new Temp and initializes it with the current date if no date
is provided
Provides the date calculation methods dynamically
|
[
"Creates",
"a",
"new",
"Temp",
"and",
"initializes",
"it",
"with",
"the",
"current",
"date",
"if",
"no",
"date",
"is",
"provided",
"Provides",
"the",
"date",
"calculation",
"methods",
"dynamically"
] |
f24e819c11f6bc7c423ad77dc71c5b76130e8c10
|
https://github.com/sugaryourcoffee/timeleap/blob/f24e819c11f6bc7c423ad77dc71c5b76130e8c10/lib/syctimeleap/time_leap.rb#L28-L62
|
8,127
|
jtkendall/ruser
|
lib/ruser/person.rb
|
RUser.Person.convert
|
def convert(data)
data.each do |k, v|
k = KEYS[k] if KEYS.include?(k)
v = v.to_s if k.eql? 'zip'
if NIDT.include?(k)
instance_variable_set('@nidt', k)
k = 'nidn'
v = v.to_s
end
var_set(k, v)
end
end
|
ruby
|
def convert(data)
data.each do |k, v|
k = KEYS[k] if KEYS.include?(k)
v = v.to_s if k.eql? 'zip'
if NIDT.include?(k)
instance_variable_set('@nidt', k)
k = 'nidn'
v = v.to_s
end
var_set(k, v)
end
end
|
[
"def",
"convert",
"(",
"data",
")",
"data",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"k",
"=",
"KEYS",
"[",
"k",
"]",
"if",
"KEYS",
".",
"include?",
"(",
"k",
")",
"v",
"=",
"v",
".",
"to_s",
"if",
"k",
".",
"eql?",
"'zip'",
"if",
"NIDT",
".",
"include?",
"(",
"k",
")",
"instance_variable_set",
"(",
"'@nidt'",
",",
"k",
")",
"k",
"=",
"'nidn'",
"v",
"=",
"v",
".",
"to_s",
"end",
"var_set",
"(",
"k",
",",
"v",
")",
"end",
"end"
] |
Creates a new person object
@param [Hash] data the data used to create the user
@return [Person]
Converts a hash to instance variables
@param [Hash] data the data used to create the instance variables
|
[
"Creates",
"a",
"new",
"person",
"object"
] |
2d038c65da8f4710a1e1b7fddabaab7a2f771172
|
https://github.com/jtkendall/ruser/blob/2d038c65da8f4710a1e1b7fddabaab7a2f771172/lib/ruser/person.rb#L107-L120
|
8,128
|
jtkendall/ruser
|
lib/ruser/person.rb
|
RUser.Person.var_set
|
def var_set(k, v)
varget = proc { instance_variable_get("@#{k}") }
varset = proc { |y| instance_variable_set("@#{k}", y) }
v.is_a?(Hash) ? convert(v) : instance_variable_set("@#{k}", v)
self.class.send(:define_method, k, varget)
self.class.send(:define_method, "#{k}=", varset)
end
|
ruby
|
def var_set(k, v)
varget = proc { instance_variable_get("@#{k}") }
varset = proc { |y| instance_variable_set("@#{k}", y) }
v.is_a?(Hash) ? convert(v) : instance_variable_set("@#{k}", v)
self.class.send(:define_method, k, varget)
self.class.send(:define_method, "#{k}=", varset)
end
|
[
"def",
"var_set",
"(",
"k",
",",
"v",
")",
"varget",
"=",
"proc",
"{",
"instance_variable_get",
"(",
"\"@#{k}\"",
")",
"}",
"varset",
"=",
"proc",
"{",
"|",
"y",
"|",
"instance_variable_set",
"(",
"\"@#{k}\"",
",",
"y",
")",
"}",
"v",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"convert",
"(",
"v",
")",
":",
"instance_variable_set",
"(",
"\"@#{k}\"",
",",
"v",
")",
"self",
".",
"class",
".",
"send",
"(",
":define_method",
",",
"k",
",",
"varget",
")",
"self",
".",
"class",
".",
"send",
"(",
":define_method",
",",
"\"#{k}=\"",
",",
"varset",
")",
"end"
] |
Sets all instance variables
@param [String] k the key used to create the instance variables
@param [String] v the value used to create the instance variables
|
[
"Sets",
"all",
"instance",
"variables"
] |
2d038c65da8f4710a1e1b7fddabaab7a2f771172
|
https://github.com/jtkendall/ruser/blob/2d038c65da8f4710a1e1b7fddabaab7a2f771172/lib/ruser/person.rb#L126-L132
|
8,129
|
gregspurrier/has_enumeration
|
lib/has_enumeration/aggregate_conditions_override.rb
|
HasEnumeration.AggregateConditionsOverride.expand_hash_conditions_for_aggregates
|
def expand_hash_conditions_for_aggregates(attrs)
expanded_attrs = attrs.dup
attr_enumeration_mapping_classes.each do |attr, klass|
if expanded_attrs[attr].is_a?(Symbol)
expanded_attrs[attr] = klass.from_sym(expanded_attrs[attr])
end
end
super(expanded_attrs)
end
|
ruby
|
def expand_hash_conditions_for_aggregates(attrs)
expanded_attrs = attrs.dup
attr_enumeration_mapping_classes.each do |attr, klass|
if expanded_attrs[attr].is_a?(Symbol)
expanded_attrs[attr] = klass.from_sym(expanded_attrs[attr])
end
end
super(expanded_attrs)
end
|
[
"def",
"expand_hash_conditions_for_aggregates",
"(",
"attrs",
")",
"expanded_attrs",
"=",
"attrs",
".",
"dup",
"attr_enumeration_mapping_classes",
".",
"each",
"do",
"|",
"attr",
",",
"klass",
"|",
"if",
"expanded_attrs",
"[",
"attr",
"]",
".",
"is_a?",
"(",
"Symbol",
")",
"expanded_attrs",
"[",
"attr",
"]",
"=",
"klass",
".",
"from_sym",
"(",
"expanded_attrs",
"[",
"attr",
"]",
")",
"end",
"end",
"super",
"(",
"expanded_attrs",
")",
"end"
] |
Override the aggregate hash conditions behavior to coerce has_enumeration
attributes that show up in finder options as symbols into instances of
the aggregate class before hash expansion.
|
[
"Override",
"the",
"aggregate",
"hash",
"conditions",
"behavior",
"to",
"coerce",
"has_enumeration",
"attributes",
"that",
"show",
"up",
"in",
"finder",
"options",
"as",
"symbols",
"into",
"instances",
"of",
"the",
"aggregate",
"class",
"before",
"hash",
"expansion",
"."
] |
40487c5b4958364ca6acaab3f05561ae0dca073e
|
https://github.com/gregspurrier/has_enumeration/blob/40487c5b4958364ca6acaab3f05561ae0dca073e/lib/has_enumeration/aggregate_conditions_override.rb#L6-L14
|
8,130
|
Stex/petra
|
lib/petra/exceptions.rb
|
Petra.ValueComparisonError.ignore!
|
def ignore!(update_value: false)
Petra.current_transaction.current_section.log_read_integrity_override(object,
attribute: attribute,
external_value: external_value,
update_value: update_value)
end
|
ruby
|
def ignore!(update_value: false)
Petra.current_transaction.current_section.log_read_integrity_override(object,
attribute: attribute,
external_value: external_value,
update_value: update_value)
end
|
[
"def",
"ignore!",
"(",
"update_value",
":",
"false",
")",
"Petra",
".",
"current_transaction",
".",
"current_section",
".",
"log_read_integrity_override",
"(",
"object",
",",
"attribute",
":",
"attribute",
",",
"external_value",
":",
"external_value",
",",
"update_value",
":",
"update_value",
")",
"end"
] |
The new external attribute value
Tells the current transaction to ignore further errors of this kind
until the attribute value is changed again externally.
@param [Boolean] update_value
If set to +true+, the read set entry for this attribute is updated with the
new external value. This means that the new value will be visible inside of
the transaction until it changes again.
Otherwise, the exception is completely ignored and will have no impact
on the values displayed inside the transaction.
|
[
"The",
"new",
"external",
"attribute",
"value"
] |
00e16e54c387289fd9049d6032dc0de79339ea16
|
https://github.com/Stex/petra/blob/00e16e54c387289fd9049d6032dc0de79339ea16/lib/petra/exceptions.rb#L100-L105
|
8,131
|
Stex/petra
|
lib/petra/exceptions.rb
|
Petra.WriteClashError.undo_changes!
|
def undo_changes!
Petra.current_transaction.current_section.log_attribute_change_veto(object,
attribute: attribute,
external_value: external_value)
end
|
ruby
|
def undo_changes!
Petra.current_transaction.current_section.log_attribute_change_veto(object,
attribute: attribute,
external_value: external_value)
end
|
[
"def",
"undo_changes!",
"Petra",
".",
"current_transaction",
".",
"current_section",
".",
"log_attribute_change_veto",
"(",
"object",
",",
"attribute",
":",
"attribute",
",",
"external_value",
":",
"external_value",
")",
"end"
] |
Tells the transaction to ignore all changes previously done to the current
attribute in the transaction.
|
[
"Tells",
"the",
"transaction",
"to",
"ignore",
"all",
"changes",
"previously",
"done",
"to",
"the",
"current",
"attribute",
"in",
"the",
"transaction",
"."
] |
00e16e54c387289fd9049d6032dc0de79339ea16
|
https://github.com/Stex/petra/blob/00e16e54c387289fd9049d6032dc0de79339ea16/lib/petra/exceptions.rb#L127-L131
|
8,132
|
26fe/sem4r
|
lib/sem4r_cli/commands/cmd_report.rb
|
Sem4rCli.CommandReport.download
|
def download(args)
if args.length != 1
puts "missing report id for 'download' subcommand"
return false
end
report_id = args[0].to_i
report = @common_args.account.reports.find { |r| r.id == report_id }
if report.nil?
puts "report '#{report_id}' not found"
return false
end
if report.status != 'Completed'
puts "cannot download report with status '#{report.status}'"
return false
end
path_name = "test_report.xml"
puts "Download report #{report.id} in #{path_name}"
report.download(path_name)
true
end
|
ruby
|
def download(args)
if args.length != 1
puts "missing report id for 'download' subcommand"
return false
end
report_id = args[0].to_i
report = @common_args.account.reports.find { |r| r.id == report_id }
if report.nil?
puts "report '#{report_id}' not found"
return false
end
if report.status != 'Completed'
puts "cannot download report with status '#{report.status}'"
return false
end
path_name = "test_report.xml"
puts "Download report #{report.id} in #{path_name}"
report.download(path_name)
true
end
|
[
"def",
"download",
"(",
"args",
")",
"if",
"args",
".",
"length",
"!=",
"1",
"puts",
"\"missing report id for 'download' subcommand\"",
"return",
"false",
"end",
"report_id",
"=",
"args",
"[",
"0",
"]",
".",
"to_i",
"report",
"=",
"@common_args",
".",
"account",
".",
"reports",
".",
"find",
"{",
"|",
"r",
"|",
"r",
".",
"id",
"==",
"report_id",
"}",
"if",
"report",
".",
"nil?",
"puts",
"\"report '#{report_id}' not found\"",
"return",
"false",
"end",
"if",
"report",
".",
"status",
"!=",
"'Completed'",
"puts",
"\"cannot download report with status '#{report.status}'\"",
"return",
"false",
"end",
"path_name",
"=",
"\"test_report.xml\"",
"puts",
"\"Download report #{report.id} in #{path_name}\"",
"report",
".",
"download",
"(",
"path_name",
")",
"true",
"end"
] |
download a v13 report
|
[
"download",
"a",
"v13",
"report"
] |
2326404f98b9c2833549fcfda078d39c9954a0fa
|
https://github.com/26fe/sem4r/blob/2326404f98b9c2833549fcfda078d39c9954a0fa/lib/sem4r_cli/commands/cmd_report.rb#L96-L118
|
8,133
|
26fe/sem4r
|
lib/sem4r_cli/commands/cmd_report.rb
|
Sem4rCli.CommandReport.schedule
|
def schedule(argv)
report = @account.report do
name 'boh'
type 'Url'
aggregation 'Daily'
cross_client true
zero_impression true
start_day '2010-01-01'
end_day '2010-01-30'
column "CustomerName"
column "ExternalCustomerId"
column "CampaignStatus"
column "Campaign"
column "CampaignId"
column "AdGroup"
column "AdGroupId"
column "AdGroupStatus"
column "QualityScore"
column "FirstPageCpc"
column "Keyword"
column "KeywordId"
column "KeywordTypeDisplay"
column "DestinationURL"
column "Impressions"
column "Clicks"
column "CTR"
column "CPC"
column "MaximumCPC"
column "Cost"
column "AveragePosition"
end
unless report.validate
puts "report not valid"
exit
end
puts "scheduled job"
job = report.schedule
job.wait(10) { |report, status| puts "status #{status}" }
report.download("test_report.xml")
true
end
|
ruby
|
def schedule(argv)
report = @account.report do
name 'boh'
type 'Url'
aggregation 'Daily'
cross_client true
zero_impression true
start_day '2010-01-01'
end_day '2010-01-30'
column "CustomerName"
column "ExternalCustomerId"
column "CampaignStatus"
column "Campaign"
column "CampaignId"
column "AdGroup"
column "AdGroupId"
column "AdGroupStatus"
column "QualityScore"
column "FirstPageCpc"
column "Keyword"
column "KeywordId"
column "KeywordTypeDisplay"
column "DestinationURL"
column "Impressions"
column "Clicks"
column "CTR"
column "CPC"
column "MaximumCPC"
column "Cost"
column "AveragePosition"
end
unless report.validate
puts "report not valid"
exit
end
puts "scheduled job"
job = report.schedule
job.wait(10) { |report, status| puts "status #{status}" }
report.download("test_report.xml")
true
end
|
[
"def",
"schedule",
"(",
"argv",
")",
"report",
"=",
"@account",
".",
"report",
"do",
"name",
"'boh'",
"type",
"'Url'",
"aggregation",
"'Daily'",
"cross_client",
"true",
"zero_impression",
"true",
"start_day",
"'2010-01-01'",
"end_day",
"'2010-01-30'",
"column",
"\"CustomerName\"",
"column",
"\"ExternalCustomerId\"",
"column",
"\"CampaignStatus\"",
"column",
"\"Campaign\"",
"column",
"\"CampaignId\"",
"column",
"\"AdGroup\"",
"column",
"\"AdGroupId\"",
"column",
"\"AdGroupStatus\"",
"column",
"\"QualityScore\"",
"column",
"\"FirstPageCpc\"",
"column",
"\"Keyword\"",
"column",
"\"KeywordId\"",
"column",
"\"KeywordTypeDisplay\"",
"column",
"\"DestinationURL\"",
"column",
"\"Impressions\"",
"column",
"\"Clicks\"",
"column",
"\"CTR\"",
"column",
"\"CPC\"",
"column",
"\"MaximumCPC\"",
"column",
"\"Cost\"",
"column",
"\"AveragePosition\"",
"end",
"unless",
"report",
".",
"validate",
"puts",
"\"report not valid\"",
"exit",
"end",
"puts",
"\"scheduled job\"",
"job",
"=",
"report",
".",
"schedule",
"job",
".",
"wait",
"(",
"10",
")",
"{",
"|",
"report",
",",
"status",
"|",
"puts",
"\"status #{status}\"",
"}",
"report",
".",
"download",
"(",
"\"test_report.xml\"",
")",
"true",
"end"
] |
schedule and download a v13 report
|
[
"schedule",
"and",
"download",
"a",
"v13",
"report"
] |
2326404f98b9c2833549fcfda078d39c9954a0fa
|
https://github.com/26fe/sem4r/blob/2326404f98b9c2833549fcfda078d39c9954a0fa/lib/sem4r_cli/commands/cmd_report.rb#L123-L167
|
8,134
|
jmcaffee/tartancloth
|
spec/lib/matchers.rb
|
TartanCloth::Matchers.TransformMatcher.make_patch
|
def make_patch( expected, actual )
diffs = Diff::LCS.sdiff( expected.split("\n"), actual.split("\n"),
Diff::LCS::ContextDiffCallbacks )
maxcol = diffs.flatten.
collect {|d| [d.old_element.to_s.length, d.new_element.to_s.length ] }.
flatten.max || 0
maxcol += 4
patch = " %#{maxcol}s | %s\n" % [ "Expected", "Actual" ]
patch << diffs.collect do |changeset|
changeset.collect do |change|
"%s [%03d, %03d]: %#{maxcol}s | %-#{maxcol}s" % [
change.action,
change.old_position,
change.new_position,
change.old_element.inspect,
change.new_element.inspect,
]
end.join("\n")
end.join("\n---\n")
end
|
ruby
|
def make_patch( expected, actual )
diffs = Diff::LCS.sdiff( expected.split("\n"), actual.split("\n"),
Diff::LCS::ContextDiffCallbacks )
maxcol = diffs.flatten.
collect {|d| [d.old_element.to_s.length, d.new_element.to_s.length ] }.
flatten.max || 0
maxcol += 4
patch = " %#{maxcol}s | %s\n" % [ "Expected", "Actual" ]
patch << diffs.collect do |changeset|
changeset.collect do |change|
"%s [%03d, %03d]: %#{maxcol}s | %-#{maxcol}s" % [
change.action,
change.old_position,
change.new_position,
change.old_element.inspect,
change.new_element.inspect,
]
end.join("\n")
end.join("\n---\n")
end
|
[
"def",
"make_patch",
"(",
"expected",
",",
"actual",
")",
"diffs",
"=",
"Diff",
"::",
"LCS",
".",
"sdiff",
"(",
"expected",
".",
"split",
"(",
"\"\\n\"",
")",
",",
"actual",
".",
"split",
"(",
"\"\\n\"",
")",
",",
"Diff",
"::",
"LCS",
"::",
"ContextDiffCallbacks",
")",
"maxcol",
"=",
"diffs",
".",
"flatten",
".",
"collect",
"{",
"|",
"d",
"|",
"[",
"d",
".",
"old_element",
".",
"to_s",
".",
"length",
",",
"d",
".",
"new_element",
".",
"to_s",
".",
"length",
"]",
"}",
".",
"flatten",
".",
"max",
"||",
"0",
"maxcol",
"+=",
"4",
"patch",
"=",
"\" %#{maxcol}s | %s\\n\"",
"%",
"[",
"\"Expected\"",
",",
"\"Actual\"",
"]",
"patch",
"<<",
"diffs",
".",
"collect",
"do",
"|",
"changeset",
"|",
"changeset",
".",
"collect",
"do",
"|",
"change",
"|",
"\"%s [%03d, %03d]: %#{maxcol}s | %-#{maxcol}s\"",
"%",
"[",
"change",
".",
"action",
",",
"change",
".",
"old_position",
",",
"change",
".",
"new_position",
",",
"change",
".",
"old_element",
".",
"inspect",
",",
"change",
".",
"new_element",
".",
"inspect",
",",
"]",
"end",
".",
"join",
"(",
"\"\\n\"",
")",
"end",
".",
"join",
"(",
"\"\\n---\\n\"",
")",
"end"
] |
Compute a patch between the given +expected+ output and the +actual+ output
and return it as a string.
|
[
"Compute",
"a",
"patch",
"between",
"the",
"given",
"+",
"expected",
"+",
"output",
"and",
"the",
"+",
"actual",
"+",
"output",
"and",
"return",
"it",
"as",
"a",
"string",
"."
] |
ac4576613549c2389fa20b52046d9f5c89a6689a
|
https://github.com/jmcaffee/tartancloth/blob/ac4576613549c2389fa20b52046d9f5c89a6689a/spec/lib/matchers.rb#L48-L69
|
8,135
|
dpickett/polypaperclip
|
lib/polypaperclip.rb
|
Polypaperclip.ClassMethods.initialize_polypaperclip
|
def initialize_polypaperclip
if polypaperclip_definitions.nil?
after_save :save_attached_files
before_destroy :destroy_attached_files
has_many_attachments_association
write_inheritable_attribute(:polypaperclip_definitions, {})
#sequence is important here - we have to override some paperclip stuff
include Paperclip::InstanceMethods
include InstanceMethods
end
end
|
ruby
|
def initialize_polypaperclip
if polypaperclip_definitions.nil?
after_save :save_attached_files
before_destroy :destroy_attached_files
has_many_attachments_association
write_inheritable_attribute(:polypaperclip_definitions, {})
#sequence is important here - we have to override some paperclip stuff
include Paperclip::InstanceMethods
include InstanceMethods
end
end
|
[
"def",
"initialize_polypaperclip",
"if",
"polypaperclip_definitions",
".",
"nil?",
"after_save",
":save_attached_files",
"before_destroy",
":destroy_attached_files",
"has_many_attachments_association",
"write_inheritable_attribute",
"(",
":polypaperclip_definitions",
",",
"{",
"}",
")",
"#sequence is important here - we have to override some paperclip stuff",
"include",
"Paperclip",
"::",
"InstanceMethods",
"include",
"InstanceMethods",
"end",
"end"
] |
initialize a polypaperclip model if a configuration hasn't already been loaded
|
[
"initialize",
"a",
"polypaperclip",
"model",
"if",
"a",
"configuration",
"hasn",
"t",
"already",
"been",
"loaded"
] |
456c7004417c8fc2385be9c7feedce3b256a3382
|
https://github.com/dpickett/polypaperclip/blob/456c7004417c8fc2385be9c7feedce3b256a3382/lib/polypaperclip.rb#L47-L60
|
8,136
|
marcinwyszynski/statefully
|
lib/statefully/state.rb
|
Statefully.State.method_missing
|
def method_missing(name, *args, &block)
sym_name = name.to_sym
return fetch(sym_name) if key?(sym_name)
str_name = name.to_s
modifier = str_name[-1]
return super unless %w[? !].include?(modifier)
base = str_name[0...-1].to_sym
known = key?(base)
return known if modifier == '?'
return fetch(base) if known
raise Errors::StateMissing, base
end
|
ruby
|
def method_missing(name, *args, &block)
sym_name = name.to_sym
return fetch(sym_name) if key?(sym_name)
str_name = name.to_s
modifier = str_name[-1]
return super unless %w[? !].include?(modifier)
base = str_name[0...-1].to_sym
known = key?(base)
return known if modifier == '?'
return fetch(base) if known
raise Errors::StateMissing, base
end
|
[
"def",
"method_missing",
"(",
"name",
",",
"*",
"args",
",",
"&",
"block",
")",
"sym_name",
"=",
"name",
".",
"to_sym",
"return",
"fetch",
"(",
"sym_name",
")",
"if",
"key?",
"(",
"sym_name",
")",
"str_name",
"=",
"name",
".",
"to_s",
"modifier",
"=",
"str_name",
"[",
"-",
"1",
"]",
"return",
"super",
"unless",
"%w[",
"?",
"!",
"]",
".",
"include?",
"(",
"modifier",
")",
"base",
"=",
"str_name",
"[",
"0",
"...",
"-",
"1",
"]",
".",
"to_sym",
"known",
"=",
"key?",
"(",
"base",
")",
"return",
"known",
"if",
"modifier",
"==",
"'?'",
"return",
"fetch",
"(",
"base",
")",
"if",
"known",
"raise",
"Errors",
"::",
"StateMissing",
",",
"base",
"end"
] |
Dynamically pass unknown messages to the underlying state storage
State fields become accessible through readers, like in an
{http://ruby-doc.org/stdlib-2.0.0/libdoc/ostruct/rdoc/OpenStruct.html OpenStruct}.
A single state field can be questioned for existence by having its name
followed by a question mark - eg. bacon?.
A single state field can be force-accessed by having its name followed by
an exclamation mark - eg. bacon!.
This method reeks of :reek:TooManyStatements.
@param name [Symbol|String]
@param args [Array<Object>]
@param block [Proc]
@return [Object]
@raise [NoMethodError]
@raise [Errors::StateMissing]
@api private
@example
state = Statefully::State.create(bacon: 'tasty')
state.bacon
=> "tasty"
state.bacon?
=> true
state.bacon!
=> "tasty"
state.cabbage
NoMethodError: undefined method `cabbage' for #<Statefully::State::Success bacon="tasty">
[STACK TRACE]
state.cabbage?
=> false
state.cabbage!
Statefully::Errors::StateMissing: field 'cabbage' missing from state
[STACK TRACE]
|
[
"Dynamically",
"pass",
"unknown",
"messages",
"to",
"the",
"underlying",
"state",
"storage"
] |
affca50625a26229e1af7ee30f2fe12bf9cddda9
|
https://github.com/marcinwyszynski/statefully/blob/affca50625a26229e1af7ee30f2fe12bf9cddda9/lib/statefully/state.rb#L273-L284
|
8,137
|
marcinwyszynski/statefully
|
lib/statefully/state.rb
|
Statefully.State.respond_to_missing?
|
def respond_to_missing?(name, _include_private = false)
str_name = name.to_s
key?(name.to_sym) || %w[? !].any?(&str_name.method(:end_with?)) || super
end
|
ruby
|
def respond_to_missing?(name, _include_private = false)
str_name = name.to_s
key?(name.to_sym) || %w[? !].any?(&str_name.method(:end_with?)) || super
end
|
[
"def",
"respond_to_missing?",
"(",
"name",
",",
"_include_private",
"=",
"false",
")",
"str_name",
"=",
"name",
".",
"to_s",
"key?",
"(",
"name",
".",
"to_sym",
")",
"||",
"%w[",
"?",
"!",
"]",
".",
"any?",
"(",
"str_name",
".",
"method",
"(",
":end_with?",
")",
")",
"||",
"super",
"end"
] |
Companion to `method_missing`
This method reeks of :reek:BooleanParameter.
@param name [Symbol|String]
@param _include_private [Boolean]
@return [Boolean]
@api private
|
[
"Companion",
"to",
"method_missing"
] |
affca50625a26229e1af7ee30f2fe12bf9cddda9
|
https://github.com/marcinwyszynski/statefully/blob/affca50625a26229e1af7ee30f2fe12bf9cddda9/lib/statefully/state.rb#L295-L298
|
8,138
|
anvil-src/anvil-core
|
lib/anvil/versioner.rb
|
Anvil.Versioner.bump!
|
def bump!(term)
fail NotSupportedTerm.new(term) unless TERMS.include?(term.to_sym)
new_version = clone
new_value = increment send(term)
new_version.send("#{term}=", new_value)
new_version.reset_terms_for(term)
end
|
ruby
|
def bump!(term)
fail NotSupportedTerm.new(term) unless TERMS.include?(term.to_sym)
new_version = clone
new_value = increment send(term)
new_version.send("#{term}=", new_value)
new_version.reset_terms_for(term)
end
|
[
"def",
"bump!",
"(",
"term",
")",
"fail",
"NotSupportedTerm",
".",
"new",
"(",
"term",
")",
"unless",
"TERMS",
".",
"include?",
"(",
"term",
".",
"to_sym",
")",
"new_version",
"=",
"clone",
"new_value",
"=",
"increment",
"send",
"(",
"term",
")",
"new_version",
".",
"send",
"(",
"\"#{term}=\"",
",",
"new_value",
")",
"new_version",
".",
"reset_terms_for",
"(",
"term",
")",
"end"
] |
Bumps a version by incrementing one of its terms and reseting the others
according to semver specification.
@example
Versioner.new('1.2.3-alpha.1+build.2').bump(:major)
# => '2.0.0'
Versioner.new('1.2.3-alpha.1+build.2').bump(:minor)
# => '1.3.0'
Versioner.new('1.2.3-alpha.1+build.2').bump(:patch)
# => '1.2.4'
Versioner.new('1.2.3-alpha.1+build.2').bump(:pre)
# => '1.2.3-alpha.2'
Versioner.new('1.2.3-alpha.1+build.2').bump(:build)
# => '1.2.3-alpha.2+build.3'
@param term [Symbol] the term to increment
@raise [Anvil::Versioner::NotSuportedTerm] When the given term is invalid
|
[
"Bumps",
"a",
"version",
"by",
"incrementing",
"one",
"of",
"its",
"terms",
"and",
"reseting",
"the",
"others",
"according",
"to",
"semver",
"specification",
"."
] |
8322ebd6a2f002e4177b86e707d9c8d5c2a7233d
|
https://github.com/anvil-src/anvil-core/blob/8322ebd6a2f002e4177b86e707d9c8d5c2a7233d/lib/anvil/versioner.rb#L41-L49
|
8,139
|
anvil-src/anvil-core
|
lib/anvil/versioner.rb
|
Anvil.Versioner.reset_terms_for
|
def reset_terms_for(term)
self.minor = 0 if term == :major
self.patch = 0 if term == :major || term == :minor
self.pre = nil if [:major, :minor, :patch].include? term
self.build = nil if [:major, :minor, :patch, :pre].include? term
self
end
|
ruby
|
def reset_terms_for(term)
self.minor = 0 if term == :major
self.patch = 0 if term == :major || term == :minor
self.pre = nil if [:major, :minor, :patch].include? term
self.build = nil if [:major, :minor, :patch, :pre].include? term
self
end
|
[
"def",
"reset_terms_for",
"(",
"term",
")",
"self",
".",
"minor",
"=",
"0",
"if",
"term",
"==",
":major",
"self",
".",
"patch",
"=",
"0",
"if",
"term",
"==",
":major",
"||",
"term",
"==",
":minor",
"self",
".",
"pre",
"=",
"nil",
"if",
"[",
":major",
",",
":minor",
",",
":patch",
"]",
".",
"include?",
"term",
"self",
".",
"build",
"=",
"nil",
"if",
"[",
":major",
",",
":minor",
",",
":patch",
",",
":pre",
"]",
".",
"include?",
"term",
"self",
"end"
] |
Resets all the terms which need to be reset after a bump
@param term [Symbol] The term which has been bumped
@return [Anvil::Versioner] A new version with the proper number
@todo we still need to reset pre-release and builds properly
|
[
"Resets",
"all",
"the",
"terms",
"which",
"need",
"to",
"be",
"reset",
"after",
"a",
"bump"
] |
8322ebd6a2f002e4177b86e707d9c8d5c2a7233d
|
https://github.com/anvil-src/anvil-core/blob/8322ebd6a2f002e4177b86e707d9c8d5c2a7233d/lib/anvil/versioner.rb#L69-L76
|
8,140
|
soccerbrain/telstra-sms
|
lib/telstra/sms.rb
|
Telstra.SMS.send_sms
|
def send_sms(to: sms_to, body: sms_body)
[to, body]
generate_token
options = { body: {
body: body,
to: to
}.to_json,
headers: { "Content-Type" => "application/json", "Authorization" => "Bearer #{@token}" }}
response = HTTParty.post("https://api.telstra.com/v1/sms/messages", options)
return JSON.parse(response.body)
end
|
ruby
|
def send_sms(to: sms_to, body: sms_body)
[to, body]
generate_token
options = { body: {
body: body,
to: to
}.to_json,
headers: { "Content-Type" => "application/json", "Authorization" => "Bearer #{@token}" }}
response = HTTParty.post("https://api.telstra.com/v1/sms/messages", options)
return JSON.parse(response.body)
end
|
[
"def",
"send_sms",
"(",
"to",
":",
"sms_to",
",",
"body",
":",
"sms_body",
")",
"[",
"to",
",",
"body",
"]",
"generate_token",
"options",
"=",
"{",
"body",
":",
"{",
"body",
":",
"body",
",",
"to",
":",
"to",
"}",
".",
"to_json",
",",
"headers",
":",
"{",
"\"Content-Type\"",
"=>",
"\"application/json\"",
",",
"\"Authorization\"",
"=>",
"\"Bearer #{@token}\"",
"}",
"}",
"response",
"=",
"HTTParty",
".",
"post",
"(",
"\"https://api.telstra.com/v1/sms/messages\"",
",",
"options",
")",
"return",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
"end"
] |
Receipient number should be in the format of 04xxxxxxxx where x is a digit.
Authorization header value should be in the format of "Bearer xxx" where xxx
is the access token returned from a token request.
|
[
"Receipient",
"number",
"should",
"be",
"in",
"the",
"format",
"of",
"04xxxxxxxx",
"where",
"x",
"is",
"a",
"digit",
".",
"Authorization",
"header",
"value",
"should",
"be",
"in",
"the",
"format",
"of",
"Bearer",
"xxx",
"where",
"xxx",
"is",
"the",
"access",
"token",
"returned",
"from",
"a",
"token",
"request",
"."
] |
32ce42a589b7b69405e5d81224deceae00334803
|
https://github.com/soccerbrain/telstra-sms/blob/32ce42a589b7b69405e5d81224deceae00334803/lib/telstra/sms.rb#L25-L35
|
8,141
|
nickcharlton/atlas-ruby
|
lib/atlas/box_provider.rb
|
Atlas.BoxProvider.save
|
def save
body = { provider: to_hash }
begin
response = Atlas.client.put(url_builder.box_provider_url, body: body)
rescue Atlas::Errors::NotFoundError
response = Atlas.client.post("#{url_builder.box_version_url}/providers",
body: body)
end
update_with_response(response)
end
|
ruby
|
def save
body = { provider: to_hash }
begin
response = Atlas.client.put(url_builder.box_provider_url, body: body)
rescue Atlas::Errors::NotFoundError
response = Atlas.client.post("#{url_builder.box_version_url}/providers",
body: body)
end
update_with_response(response)
end
|
[
"def",
"save",
"body",
"=",
"{",
"provider",
":",
"to_hash",
"}",
"begin",
"response",
"=",
"Atlas",
".",
"client",
".",
"put",
"(",
"url_builder",
".",
"box_provider_url",
",",
"body",
":",
"body",
")",
"rescue",
"Atlas",
"::",
"Errors",
"::",
"NotFoundError",
"response",
"=",
"Atlas",
".",
"client",
".",
"post",
"(",
"\"#{url_builder.box_version_url}/providers\"",
",",
"body",
":",
"body",
")",
"end",
"update_with_response",
"(",
"response",
")",
"end"
] |
Initialize a provider from a tag and object hash.
@param [String] tag the tag which represents the origin on the provider.
@param [Hash] hash the attributes for the box
@param hash [String] :name The name of the provider.
@param hash [String] :url An HTTP URL to the box file. Omit if uploading
with Atlas.
Save the provider.
@return [Hash] Atlas response object.
|
[
"Initialize",
"a",
"provider",
"from",
"a",
"tag",
"and",
"object",
"hash",
"."
] |
2170c04496682e0d8e7c959bd9f267f62fa84c1d
|
https://github.com/nickcharlton/atlas-ruby/blob/2170c04496682e0d8e7c959bd9f267f62fa84c1d/lib/atlas/box_provider.rb#L56-L67
|
8,142
|
nickcharlton/atlas-ruby
|
lib/atlas/box_provider.rb
|
Atlas.BoxProvider.upload
|
def upload(file)
# get the path for upload
response = Atlas.client.get("#{url_builder.box_provider_url}/upload")
# upload the file
upload_url = response['upload_path']
Excon.put(upload_url, body: file)
end
|
ruby
|
def upload(file)
# get the path for upload
response = Atlas.client.get("#{url_builder.box_provider_url}/upload")
# upload the file
upload_url = response['upload_path']
Excon.put(upload_url, body: file)
end
|
[
"def",
"upload",
"(",
"file",
")",
"# get the path for upload",
"response",
"=",
"Atlas",
".",
"client",
".",
"get",
"(",
"\"#{url_builder.box_provider_url}/upload\"",
")",
"# upload the file",
"upload_url",
"=",
"response",
"[",
"'upload_path'",
"]",
"Excon",
".",
"put",
"(",
"upload_url",
",",
"body",
":",
"file",
")",
"end"
] |
Upload a .box file for this provider.
@param [File] file a File object for the file.
|
[
"Upload",
"a",
".",
"box",
"file",
"for",
"this",
"provider",
"."
] |
2170c04496682e0d8e7c959bd9f267f62fa84c1d
|
https://github.com/nickcharlton/atlas-ruby/blob/2170c04496682e0d8e7c959bd9f267f62fa84c1d/lib/atlas/box_provider.rb#L72-L79
|
8,143
|
danielbush/RubyCron
|
lib/CronR/CronJob.rb
|
CronR.CronJob.runnable?
|
def runnable? time
result = [:minute,:hour,:day,:dow,:month].map{|ct|
if self[ct] == true then
true
else
case ct
when :month,:day,:hour
val = time.send(ct)
when :dow
val = time.wday
when :minute
val = time.min
end
case self[ct]
when Numeric # Should be Fixnum
self[ct] == val
else # Assume array-like thing...
self[ct].include?(val)
end
end
}
# Everything should be true to make us eligible for running:
[result.inject(true){|s,v| s && v},result]
end
|
ruby
|
def runnable? time
result = [:minute,:hour,:day,:dow,:month].map{|ct|
if self[ct] == true then
true
else
case ct
when :month,:day,:hour
val = time.send(ct)
when :dow
val = time.wday
when :minute
val = time.min
end
case self[ct]
when Numeric # Should be Fixnum
self[ct] == val
else # Assume array-like thing...
self[ct].include?(val)
end
end
}
# Everything should be true to make us eligible for running:
[result.inject(true){|s,v| s && v},result]
end
|
[
"def",
"runnable?",
"time",
"result",
"=",
"[",
":minute",
",",
":hour",
",",
":day",
",",
":dow",
",",
":month",
"]",
".",
"map",
"{",
"|",
"ct",
"|",
"if",
"self",
"[",
"ct",
"]",
"==",
"true",
"then",
"true",
"else",
"case",
"ct",
"when",
":month",
",",
":day",
",",
":hour",
"val",
"=",
"time",
".",
"send",
"(",
"ct",
")",
"when",
":dow",
"val",
"=",
"time",
".",
"wday",
"when",
":minute",
"val",
"=",
"time",
".",
"min",
"end",
"case",
"self",
"[",
"ct",
"]",
"when",
"Numeric",
"# Should be Fixnum",
"self",
"[",
"ct",
"]",
"==",
"val",
"else",
"# Assume array-like thing...",
"self",
"[",
"ct",
"]",
".",
"include?",
"(",
"val",
")",
"end",
"end",
"}",
"# Everything should be true to make us eligible for running:",
"[",
"result",
".",
"inject",
"(",
"true",
")",
"{",
"|",
"s",
",",
"v",
"|",
"s",
"&&",
"v",
"}",
",",
"result",
"]",
"end"
] |
Return true if job is runnable at the given time.
Note we expect an instance of Time.
ActiveSupport can be used to give us time zones in Time.
Example
ok,details = runnable?(Time.now)
|
[
"Return",
"true",
"if",
"job",
"is",
"runnable",
"at",
"the",
"given",
"time",
"."
] |
24a2f997b81663ded1ac1d01017e8d807d5caffd
|
https://github.com/danielbush/RubyCron/blob/24a2f997b81663ded1ac1d01017e8d807d5caffd/lib/CronR/CronJob.rb#L112-L136
|
8,144
|
dnd/permit
|
lib/permit/permit_rules.rb
|
Permit.PermitRules.allow
|
def allow(roles, options = {})
actions = options.delete(:to)
rule = PermitRule.new(roles, options)
index_rule_by_actions @action_allow_rules, actions, rule
return rule
end
|
ruby
|
def allow(roles, options = {})
actions = options.delete(:to)
rule = PermitRule.new(roles, options)
index_rule_by_actions @action_allow_rules, actions, rule
return rule
end
|
[
"def",
"allow",
"(",
"roles",
",",
"options",
"=",
"{",
"}",
")",
"actions",
"=",
"options",
".",
"delete",
"(",
":to",
")",
"rule",
"=",
"PermitRule",
".",
"new",
"(",
"roles",
",",
"options",
")",
"index_rule_by_actions",
"@action_allow_rules",
",",
"actions",
",",
"rule",
"return",
"rule",
"end"
] |
Adds an allow rule for the given actions to the collection.
@example Allow a person that is a member of a team to show
allow :person, :who => :is_member, :of => :team, :to => :show
@example Allow a person that is a member of any of the teams to index.
allow :person, :who => :is_member, :of => [:team1, :team2], :to => :index
@example Allow a person with either of the named roles for a resource to perform any "write" operations.
allow [:project_admin, :project_manager], :of => :project, :to => :write
@example Allow a person with the viewer role of either of the projects to show.
allow :viewer, :of => [:project1, :project2], :to => :show
@param [Symbol, <Symbol>] roles the role(s) that the rule will apply to.
@param [Hash] options the options used to build the rule.
@option options [Symbol] :who the method to call on the target resource.
@option options [Symbol] :that alias for :who
@option options [Symbol, nil, :any, <Symbol, nil>] :of the name of the instance variable holding the target
resource. If set to +:any+ then the match will apply to a person that has
a matching role authorization for any resource. If not given, or set to
+nil+, then the match will apply to a person that has a matching role
authorization for a nil resource. +:any/nil+ functionality only applies
when using named roles. (see Permit::NamedRoles).
@option options [Symbol, nil, :any, <Symbol, nil>] :on alias for +:of+
@option options [Symbol, String, Proc] :if code to evaluate at the end of the
match if it is still valid. If it returns false, the rule will not
match. If a proc if given, it will be passed the current subject and
binding. A method will be called without any arguments.
@option options [Symbol, String, Proc] :unless code to evaluate at the end
of the match if it is still valid. If it returns true, the rule will not
match. If a proc if given, it will be passed the current subject and
binding. A method will be called without any arguments.
@option options [Symbol, <Symbol>] :to the action(s) to allow access to if this
rule matches. +:all+ may be given to indicate that access is given to all
actions if the rule matches. Actions will be expanded using the aliases
defined in {Permit::Config.action_aliases}. The expansion operation is
not recursive.
@return [PermitRule] the rule that was created for the parameters.
@raise [PermitConfigurationError] if +:to+ is not valid, or if the rule
cannot be created.
|
[
"Adds",
"an",
"allow",
"rule",
"for",
"the",
"given",
"actions",
"to",
"the",
"collection",
"."
] |
4bf41d5cc1fe1cbd100405bda773921e605f7a7a
|
https://github.com/dnd/permit/blob/4bf41d5cc1fe1cbd100405bda773921e605f7a7a/lib/permit/permit_rules.rb#L82-L87
|
8,145
|
dlangevin/tinia
|
lib/tinia.rb
|
Tinia.ActiveRecord.indexed_with_cloud_search
|
def indexed_with_cloud_search(&block)
mods = [
Tinia::Connection,
Tinia::Index,
Tinia::Search
]
mods.each do |mod|
unless self.included_modules.include?(mod)
self.send(:include, mod)
end
end
# config block
yield(self) if block_given?
# ensure config is all set
unless self.cloud_search_domain.present?
raise Tinia::MissingSearchDomain.new(self)
end
end
|
ruby
|
def indexed_with_cloud_search(&block)
mods = [
Tinia::Connection,
Tinia::Index,
Tinia::Search
]
mods.each do |mod|
unless self.included_modules.include?(mod)
self.send(:include, mod)
end
end
# config block
yield(self) if block_given?
# ensure config is all set
unless self.cloud_search_domain.present?
raise Tinia::MissingSearchDomain.new(self)
end
end
|
[
"def",
"indexed_with_cloud_search",
"(",
"&",
"block",
")",
"mods",
"=",
"[",
"Tinia",
"::",
"Connection",
",",
"Tinia",
"::",
"Index",
",",
"Tinia",
"::",
"Search",
"]",
"mods",
".",
"each",
"do",
"|",
"mod",
"|",
"unless",
"self",
".",
"included_modules",
".",
"include?",
"(",
"mod",
")",
"self",
".",
"send",
"(",
":include",
",",
"mod",
")",
"end",
"end",
"# config block",
"yield",
"(",
"self",
")",
"if",
"block_given?",
"# ensure config is all set",
"unless",
"self",
".",
"cloud_search_domain",
".",
"present?",
"raise",
"Tinia",
"::",
"MissingSearchDomain",
".",
"new",
"(",
"self",
")",
"end",
"end"
] |
activation method for an AR class
|
[
"activation",
"method",
"for",
"an",
"AR",
"class"
] |
ad5f2aba55765dbd3f67dc79630d5686b2ce6894
|
https://github.com/dlangevin/tinia/blob/ad5f2aba55765dbd3f67dc79630d5686b2ce6894/lib/tinia.rb#L22-L40
|
8,146
|
smsified/smsified-ruby
|
lib/smsified/subscriptions.rb
|
Smsified.Subscriptions.create_inbound_subscription
|
def create_inbound_subscription(destination_address, options)
query = options.merge({ :destination_address => destination_address })
Response.new self.class.post("/smsmessaging/inbound/subscriptions",
:basic_auth => @auth,
:body => camelcase_keys(query),
:headers => SMSIFIED_HTTP_HEADERS
)
end
|
ruby
|
def create_inbound_subscription(destination_address, options)
query = options.merge({ :destination_address => destination_address })
Response.new self.class.post("/smsmessaging/inbound/subscriptions",
:basic_auth => @auth,
:body => camelcase_keys(query),
:headers => SMSIFIED_HTTP_HEADERS
)
end
|
[
"def",
"create_inbound_subscription",
"(",
"destination_address",
",",
"options",
")",
"query",
"=",
"options",
".",
"merge",
"(",
"{",
":destination_address",
"=>",
"destination_address",
"}",
")",
"Response",
".",
"new",
"self",
".",
"class",
".",
"post",
"(",
"\"/smsmessaging/inbound/subscriptions\"",
",",
":basic_auth",
"=>",
"@auth",
",",
":body",
"=>",
"camelcase_keys",
"(",
"query",
")",
",",
":headers",
"=>",
"SMSIFIED_HTTP_HEADERS",
")",
"end"
] |
Intantiate a new class to work with subscriptions
@param [required, Hash] params to create the user
@option params [required, String] :username username to authenticate with
@option params [required, String] :password to authenticate with
@option params [optional, String] :base_uri of an alternative location of SMSified
@option params [optional, String] :destination_address to use with subscriptions
@option params [optional, String] :sender_address to use with subscriptions
@option params [optional, Boolean] :debug to turn on the HTTparty debugging to stdout
@example
subscription = Subscription.new :username => 'user', :password => '123'
Creates an inbound subscription
@param [required, String] destination_address to subscribe to
@param [required, Hash] params to send an sms
@option params [optional, String] :notify_url to send callbacks to
@option params [optional, String] :client_correlator to update
@option params [optional, String] :callback_data to update
@return [Object] A Response Object with http and data instance methods
@param [required, String] notify_url to send callbacks to
@return [Object] A Response Object with http and data instance methods
@example
subscriptions.create_inbound_subscription('tel:+14155551212', :notify_url => 'http://foobar.com')
|
[
"Intantiate",
"a",
"new",
"class",
"to",
"work",
"with",
"subscriptions"
] |
1c7a0f445ffe7fe0fb035a1faf44ac55687a4488
|
https://github.com/smsified/smsified-ruby/blob/1c7a0f445ffe7fe0fb035a1faf44ac55687a4488/lib/smsified/subscriptions.rb#L46-L55
|
8,147
|
pkubicki/yamled_acl
|
lib/yamled_acl/controller_extension.rb
|
YamledAcl.ControllerExtension.authorize_action
|
def authorize_action
YamledAcl.init(current_user_group_name, params[:controller])
allowed_to?(params[:action]) or raise(YamledAcl::AccessDenied)
end
|
ruby
|
def authorize_action
YamledAcl.init(current_user_group_name, params[:controller])
allowed_to?(params[:action]) or raise(YamledAcl::AccessDenied)
end
|
[
"def",
"authorize_action",
"YamledAcl",
".",
"init",
"(",
"current_user_group_name",
",",
"params",
"[",
":controller",
"]",
")",
"allowed_to?",
"(",
"params",
"[",
":action",
"]",
")",
"or",
"raise",
"(",
"YamledAcl",
"::",
"AccessDenied",
")",
"end"
] |
This method should be be called by +before_filter+.
before_filter :authorize_action
|
[
"This",
"method",
"should",
"be",
"be",
"called",
"by",
"+",
"before_filter",
"+",
"."
] |
cd4a02e3b70977112830c5c1f2487e06d43b5a34
|
https://github.com/pkubicki/yamled_acl/blob/cd4a02e3b70977112830c5c1f2487e06d43b5a34/lib/yamled_acl/controller_extension.rb#L56-L59
|
8,148
|
gluons/mysticonfig
|
lib/mysticonfig.rb
|
Mysticonfig.Loader.load
|
def load
config_file = find_file @filenames
config = Utils.load_auto config_file
config.empty? ? @default_config : @default_config.merge(config)
end
|
ruby
|
def load
config_file = find_file @filenames
config = Utils.load_auto config_file
config.empty? ? @default_config : @default_config.merge(config)
end
|
[
"def",
"load",
"config_file",
"=",
"find_file",
"@filenames",
"config",
"=",
"Utils",
".",
"load_auto",
"config_file",
"config",
".",
"empty?",
"?",
"@default_config",
":",
"@default_config",
".",
"merge",
"(",
"config",
")",
"end"
] |
Find and load config file.
|
[
"Find",
"and",
"load",
"config",
"file",
"."
] |
4bc6354a3f1f77e76f1f1211e9f26acc044ff539
|
https://github.com/gluons/mysticonfig/blob/4bc6354a3f1f77e76f1f1211e9f26acc044ff539/lib/mysticonfig.rb#L16-L21
|
8,149
|
gluons/mysticonfig
|
lib/mysticonfig.rb
|
Mysticonfig.Loader.load_json
|
def load_json
json_config_file = Utils.lookup_file @filenames[:json]
config = Utils.load_json json_config_file
config.empty? ? @default_config : @default_config.merge(config)
end
|
ruby
|
def load_json
json_config_file = Utils.lookup_file @filenames[:json]
config = Utils.load_json json_config_file
config.empty? ? @default_config : @default_config.merge(config)
end
|
[
"def",
"load_json",
"json_config_file",
"=",
"Utils",
".",
"lookup_file",
"@filenames",
"[",
":json",
"]",
"config",
"=",
"Utils",
".",
"load_json",
"json_config_file",
"config",
".",
"empty?",
"?",
"@default_config",
":",
"@default_config",
".",
"merge",
"(",
"config",
")",
"end"
] |
Find and load JSON config file.
|
[
"Find",
"and",
"load",
"JSON",
"config",
"file",
"."
] |
4bc6354a3f1f77e76f1f1211e9f26acc044ff539
|
https://github.com/gluons/mysticonfig/blob/4bc6354a3f1f77e76f1f1211e9f26acc044ff539/lib/mysticonfig.rb#L25-L30
|
8,150
|
gluons/mysticonfig
|
lib/mysticonfig.rb
|
Mysticonfig.Loader.load_yaml
|
def load_yaml
yaml_config_files = @filenames[:yaml]
yaml_config_file = nil
yaml_config_files.each do |file|
yaml_config_file = Utils.lookup_file file
unless yaml_config_file.nil?
config = Utils.load_yaml(yaml_config_file)
return config.empty? ? @default_config : @default_config.merge(config)
end
end
@default_config # Return default config when can't load config file
end
|
ruby
|
def load_yaml
yaml_config_files = @filenames[:yaml]
yaml_config_file = nil
yaml_config_files.each do |file|
yaml_config_file = Utils.lookup_file file
unless yaml_config_file.nil?
config = Utils.load_yaml(yaml_config_file)
return config.empty? ? @default_config : @default_config.merge(config)
end
end
@default_config # Return default config when can't load config file
end
|
[
"def",
"load_yaml",
"yaml_config_files",
"=",
"@filenames",
"[",
":yaml",
"]",
"yaml_config_file",
"=",
"nil",
"yaml_config_files",
".",
"each",
"do",
"|",
"file",
"|",
"yaml_config_file",
"=",
"Utils",
".",
"lookup_file",
"file",
"unless",
"yaml_config_file",
".",
"nil?",
"config",
"=",
"Utils",
".",
"load_yaml",
"(",
"yaml_config_file",
")",
"return",
"config",
".",
"empty?",
"?",
"@default_config",
":",
"@default_config",
".",
"merge",
"(",
"config",
")",
"end",
"end",
"@default_config",
"# Return default config when can't load config file",
"end"
] |
Find and load YAML config file.
|
[
"Find",
"and",
"load",
"YAML",
"config",
"file",
"."
] |
4bc6354a3f1f77e76f1f1211e9f26acc044ff539
|
https://github.com/gluons/mysticonfig/blob/4bc6354a3f1f77e76f1f1211e9f26acc044ff539/lib/mysticonfig.rb#L34-L47
|
8,151
|
georgyangelov/vcs-toolkit
|
lib/vcs_toolkit/diff.rb
|
VCSToolkit.Diff.new_content
|
def new_content(conflict_start='<<<', conflict_switch='>>>', conflict_end='===')
flat_map do |change|
if change.conflict?
version_one = change.diff_one.new_content(conflict_start, conflict_switch, conflict_end)
version_two = change.diff_two.new_content(conflict_start, conflict_switch, conflict_end)
[conflict_start] + version_one + [conflict_switch] + version_two + [conflict_end]
elsif change.deleting?
[]
else
[change.new_element]
end
end
end
|
ruby
|
def new_content(conflict_start='<<<', conflict_switch='>>>', conflict_end='===')
flat_map do |change|
if change.conflict?
version_one = change.diff_one.new_content(conflict_start, conflict_switch, conflict_end)
version_two = change.diff_two.new_content(conflict_start, conflict_switch, conflict_end)
[conflict_start] + version_one + [conflict_switch] + version_two + [conflict_end]
elsif change.deleting?
[]
else
[change.new_element]
end
end
end
|
[
"def",
"new_content",
"(",
"conflict_start",
"=",
"'<<<'",
",",
"conflict_switch",
"=",
"'>>>'",
",",
"conflict_end",
"=",
"'==='",
")",
"flat_map",
"do",
"|",
"change",
"|",
"if",
"change",
".",
"conflict?",
"version_one",
"=",
"change",
".",
"diff_one",
".",
"new_content",
"(",
"conflict_start",
",",
"conflict_switch",
",",
"conflict_end",
")",
"version_two",
"=",
"change",
".",
"diff_two",
".",
"new_content",
"(",
"conflict_start",
",",
"conflict_switch",
",",
"conflict_end",
")",
"[",
"conflict_start",
"]",
"+",
"version_one",
"+",
"[",
"conflict_switch",
"]",
"+",
"version_two",
"+",
"[",
"conflict_end",
"]",
"elsif",
"change",
".",
"deleting?",
"[",
"]",
"else",
"[",
"change",
".",
"new_element",
"]",
"end",
"end",
"end"
] |
Reconstruct the new sequence from the diff
|
[
"Reconstruct",
"the",
"new",
"sequence",
"from",
"the",
"diff"
] |
9d73735da090a5e0f612aee04f423306fa512f38
|
https://github.com/georgyangelov/vcs-toolkit/blob/9d73735da090a5e0f612aee04f423306fa512f38/lib/vcs_toolkit/diff.rb#L42-L55
|
8,152
|
finn-francis/ruby-edit
|
lib/ruby_edit/source_file.rb
|
RubyEdit.SourceFile.populate
|
def populate(content, **options)
generator.create_file(RubyEdit::SOURCE_FILE_LOCATION,
content,
force: true,
verbose: false,
**options)
end
|
ruby
|
def populate(content, **options)
generator.create_file(RubyEdit::SOURCE_FILE_LOCATION,
content,
force: true,
verbose: false,
**options)
end
|
[
"def",
"populate",
"(",
"content",
",",
"**",
"options",
")",
"generator",
".",
"create_file",
"(",
"RubyEdit",
"::",
"SOURCE_FILE_LOCATION",
",",
"content",
",",
"force",
":",
"true",
",",
"verbose",
":",
"false",
",",
"**",
"options",
")",
"end"
] |
Populates the sourcefile with the given content
@param content [String] - Usually the output of a bash command
@param **options [key value pairs] -
See https://github.com/piotrmurach/tty-file for TTY::File docs
|
[
"Populates",
"the",
"sourcefile",
"with",
"the",
"given",
"content"
] |
90022f4de01b420f5321f12c490566d0a1e19a29
|
https://github.com/finn-francis/ruby-edit/blob/90022f4de01b420f5321f12c490566d0a1e19a29/lib/ruby_edit/source_file.rb#L16-L22
|
8,153
|
cjfuller/rimageanalysistools
|
lib/rimageanalysistools/skeletonizer.rb
|
RImageAnalysisTools.Skeletonizer.compute_n
|
def compute_n(ic)
temp_ic = ImageCoordinate.cloneCoord(ic)
n = -1 # compensate for 0,0 case
x_off = [-1,0,1]
y_off = [-1,0,1]
x_off.each do |x|
y_off.each do |y|
temp_ic[:x] = ic[:x] + x
temp_ic[:y] = ic[:y] + y
if @im.inBounds(temp_ic) and @im[temp_ic] == @im[ic] then
n += 1
end
end
end
temp_ic.recycle
n
end
|
ruby
|
def compute_n(ic)
temp_ic = ImageCoordinate.cloneCoord(ic)
n = -1 # compensate for 0,0 case
x_off = [-1,0,1]
y_off = [-1,0,1]
x_off.each do |x|
y_off.each do |y|
temp_ic[:x] = ic[:x] + x
temp_ic[:y] = ic[:y] + y
if @im.inBounds(temp_ic) and @im[temp_ic] == @im[ic] then
n += 1
end
end
end
temp_ic.recycle
n
end
|
[
"def",
"compute_n",
"(",
"ic",
")",
"temp_ic",
"=",
"ImageCoordinate",
".",
"cloneCoord",
"(",
"ic",
")",
"n",
"=",
"-",
"1",
"# compensate for 0,0 case",
"x_off",
"=",
"[",
"-",
"1",
",",
"0",
",",
"1",
"]",
"y_off",
"=",
"[",
"-",
"1",
",",
"0",
",",
"1",
"]",
"x_off",
".",
"each",
"do",
"|",
"x",
"|",
"y_off",
".",
"each",
"do",
"|",
"y",
"|",
"temp_ic",
"[",
":x",
"]",
"=",
"ic",
"[",
":x",
"]",
"+",
"x",
"temp_ic",
"[",
":y",
"]",
"=",
"ic",
"[",
":y",
"]",
"+",
"y",
"if",
"@im",
".",
"inBounds",
"(",
"temp_ic",
")",
"and",
"@im",
"[",
"temp_ic",
"]",
"==",
"@im",
"[",
"ic",
"]",
"then",
"n",
"+=",
"1",
"end",
"end",
"end",
"temp_ic",
".",
"recycle",
"n",
"end"
] |
implementation of skeletonization algorithm presented in Gonzalez & Woods, p 651-652
|
[
"implementation",
"of",
"skeletonization",
"algorithm",
"presented",
"in",
"Gonzalez",
"&",
"Woods",
"p",
"651",
"-",
"652"
] |
991aa7a61a8ad7bd902a31d99a19ce135e3cc485
|
https://github.com/cjfuller/rimageanalysistools/blob/991aa7a61a8ad7bd902a31d99a19ce135e3cc485/lib/rimageanalysistools/skeletonizer.rb#L44-L71
|
8,154
|
mrlhumphreys/board_game_grid
|
lib/board_game_grid/square_set.rb
|
BoardGameGrid.SquareSet.where
|
def where(hash)
res = hash.inject(squares) do |memo, (attribute, value)|
memo.select { |square| square.attribute_match?(attribute, value) }
end
self.class.new(squares: res)
end
|
ruby
|
def where(hash)
res = hash.inject(squares) do |memo, (attribute, value)|
memo.select { |square| square.attribute_match?(attribute, value) }
end
self.class.new(squares: res)
end
|
[
"def",
"where",
"(",
"hash",
")",
"res",
"=",
"hash",
".",
"inject",
"(",
"squares",
")",
"do",
"|",
"memo",
",",
"(",
"attribute",
",",
"value",
")",
"|",
"memo",
".",
"select",
"{",
"|",
"square",
"|",
"square",
".",
"attribute_match?",
"(",
"attribute",
",",
"value",
")",
"}",
"end",
"self",
".",
"class",
".",
"new",
"(",
"squares",
":",
"res",
")",
"end"
] |
Filter the squares with a hash of attribute and matching values.
@param [Hash] hash
attributes to query for.
@return [SquareSet]
==== Example:
# Find all squares where piece is nil
square_set.where(piece: nil)
|
[
"Filter",
"the",
"squares",
"with",
"a",
"hash",
"of",
"attribute",
"and",
"matching",
"values",
"."
] |
df07a84c7f7db076d055c6063f1e418f0c8ed288
|
https://github.com/mrlhumphreys/board_game_grid/blob/df07a84c7f7db076d055c6063f1e418f0c8ed288/lib/board_game_grid/square_set.rb#L128-L133
|
8,155
|
mrlhumphreys/board_game_grid
|
lib/board_game_grid/square_set.rb
|
BoardGameGrid.SquareSet.find_by_x_and_y
|
def find_by_x_and_y(x, y)
select { |square| square.x == x && square.y == y }.first
end
|
ruby
|
def find_by_x_and_y(x, y)
select { |square| square.x == x && square.y == y }.first
end
|
[
"def",
"find_by_x_and_y",
"(",
"x",
",",
"y",
")",
"select",
"{",
"|",
"square",
"|",
"square",
".",
"x",
"==",
"x",
"&&",
"square",
".",
"y",
"==",
"y",
"}",
".",
"first",
"end"
] |
Find the square with the matching x and y co-ordinates
@param [Fixnum] x
the x co-ordinate.
@param [Fixnum] y
the y co-ordinate.
@return [Square]
==== Example:
# Find the square at 4,2
square_set.find_by_x_and_y(4, 2)
|
[
"Find",
"the",
"square",
"with",
"the",
"matching",
"x",
"and",
"y",
"co",
"-",
"ordinates"
] |
df07a84c7f7db076d055c6063f1e418f0c8ed288
|
https://github.com/mrlhumphreys/board_game_grid/blob/df07a84c7f7db076d055c6063f1e418f0c8ed288/lib/board_game_grid/square_set.rb#L160-L162
|
8,156
|
mrlhumphreys/board_game_grid
|
lib/board_game_grid/square_set.rb
|
BoardGameGrid.SquareSet.in_range
|
def in_range(origin, distance)
select { |square| Vector.new(origin, square).magnitude <= distance }
end
|
ruby
|
def in_range(origin, distance)
select { |square| Vector.new(origin, square).magnitude <= distance }
end
|
[
"def",
"in_range",
"(",
"origin",
",",
"distance",
")",
"select",
"{",
"|",
"square",
"|",
"Vector",
".",
"new",
"(",
"origin",
",",
"square",
")",
".",
"magnitude",
"<=",
"distance",
"}",
"end"
] |
Find all squares within distance of square
@param [Square] square
the originating square
@param [Fixnum] distance
the specified distance from the square
@return [SquareSet]
==== Example:
# Get all squares within 2 squares of square_a
square_set.in_range(square_a, 2)
|
[
"Find",
"all",
"squares",
"within",
"distance",
"of",
"square"
] |
df07a84c7f7db076d055c6063f1e418f0c8ed288
|
https://github.com/mrlhumphreys/board_game_grid/blob/df07a84c7f7db076d055c6063f1e418f0c8ed288/lib/board_game_grid/square_set.rb#L176-L178
|
8,157
|
mrlhumphreys/board_game_grid
|
lib/board_game_grid/square_set.rb
|
BoardGameGrid.SquareSet.at_range
|
def at_range(origin, distance)
select { |square| Vector.new(origin, square).magnitude == distance }
end
|
ruby
|
def at_range(origin, distance)
select { |square| Vector.new(origin, square).magnitude == distance }
end
|
[
"def",
"at_range",
"(",
"origin",
",",
"distance",
")",
"select",
"{",
"|",
"square",
"|",
"Vector",
".",
"new",
"(",
"origin",
",",
"square",
")",
".",
"magnitude",
"==",
"distance",
"}",
"end"
] |
Find all squares at distance of square
@param [Square] square
the originating square
@param [Fixnum] distance
the specified distance from the square
@return [SquareSet]
==== Example:
# Get all squares at 2 squares from square_a
square_set.at_range(square_a, 2)
|
[
"Find",
"all",
"squares",
"at",
"distance",
"of",
"square"
] |
df07a84c7f7db076d055c6063f1e418f0c8ed288
|
https://github.com/mrlhumphreys/board_game_grid/blob/df07a84c7f7db076d055c6063f1e418f0c8ed288/lib/board_game_grid/square_set.rb#L192-L194
|
8,158
|
mrlhumphreys/board_game_grid
|
lib/board_game_grid/square_set.rb
|
BoardGameGrid.SquareSet.unblocked
|
def unblocked(origin, square_set)
select { |destination| square_set.between(origin, destination).all?(&:unoccupied?) }
end
|
ruby
|
def unblocked(origin, square_set)
select { |destination| square_set.between(origin, destination).all?(&:unoccupied?) }
end
|
[
"def",
"unblocked",
"(",
"origin",
",",
"square_set",
")",
"select",
"{",
"|",
"destination",
"|",
"square_set",
".",
"between",
"(",
"origin",
",",
"destination",
")",
".",
"all?",
"(",
":unoccupied?",
")",
"}",
"end"
] |
Returns destination from the origin that have a clear path
@param [Square] origin
the originating square.
@param [SquareSet] square_set
the board position.
@return [SquareSet]
|
[
"Returns",
"destination",
"from",
"the",
"origin",
"that",
"have",
"a",
"clear",
"path"
] |
df07a84c7f7db076d055c6063f1e418f0c8ed288
|
https://github.com/mrlhumphreys/board_game_grid/blob/df07a84c7f7db076d055c6063f1e418f0c8ed288/lib/board_game_grid/square_set.rb#L264-L266
|
8,159
|
mrlhumphreys/board_game_grid
|
lib/board_game_grid/square_set.rb
|
BoardGameGrid.SquareSet.between
|
def between(origin, destination)
vector = Vector.new(origin, destination)
if vector.diagonal? || vector.orthogonal?
point_counter = origin.point
direction = vector.direction
_squares = []
while point_counter != destination.point
point_counter = point_counter + direction
square = find_by_x_and_y(point_counter.x, point_counter.y)
if square && square.point != destination.point
_squares.push(square)
end
end
else
_squares = []
end
self.class.new(squares: _squares)
end
|
ruby
|
def between(origin, destination)
vector = Vector.new(origin, destination)
if vector.diagonal? || vector.orthogonal?
point_counter = origin.point
direction = vector.direction
_squares = []
while point_counter != destination.point
point_counter = point_counter + direction
square = find_by_x_and_y(point_counter.x, point_counter.y)
if square && square.point != destination.point
_squares.push(square)
end
end
else
_squares = []
end
self.class.new(squares: _squares)
end
|
[
"def",
"between",
"(",
"origin",
",",
"destination",
")",
"vector",
"=",
"Vector",
".",
"new",
"(",
"origin",
",",
"destination",
")",
"if",
"vector",
".",
"diagonal?",
"||",
"vector",
".",
"orthogonal?",
"point_counter",
"=",
"origin",
".",
"point",
"direction",
"=",
"vector",
".",
"direction",
"_squares",
"=",
"[",
"]",
"while",
"point_counter",
"!=",
"destination",
".",
"point",
"point_counter",
"=",
"point_counter",
"+",
"direction",
"square",
"=",
"find_by_x_and_y",
"(",
"point_counter",
".",
"x",
",",
"point_counter",
".",
"y",
")",
"if",
"square",
"&&",
"square",
".",
"point",
"!=",
"destination",
".",
"point",
"_squares",
".",
"push",
"(",
"square",
")",
"end",
"end",
"else",
"_squares",
"=",
"[",
"]",
"end",
"self",
".",
"class",
".",
"new",
"(",
"squares",
":",
"_squares",
")",
"end"
] |
Returns squares between a and b.
Only squares that are in the same diagonal will return squares.
@param [Square] a
a square.
@param [Square] b
another square.
@return [SquareSet]
==== Example:
# Get all squares between square_a and square_b
square_set.between(square_a, square_b)
|
[
"Returns",
"squares",
"between",
"a",
"and",
"b",
".",
"Only",
"squares",
"that",
"are",
"in",
"the",
"same",
"diagonal",
"will",
"return",
"squares",
"."
] |
df07a84c7f7db076d055c6063f1e418f0c8ed288
|
https://github.com/mrlhumphreys/board_game_grid/blob/df07a84c7f7db076d055c6063f1e418f0c8ed288/lib/board_game_grid/square_set.rb#L282-L302
|
8,160
|
bradfeehan/derelict
|
lib/derelict/parser/version.rb
|
Derelict.Parser::Version.version
|
def version
logger.debug "Parsing version from output using #{description}"
matches = output.match PARSE_VERSION_FROM_OUTPUT
raise InvalidFormat.new output if matches.nil?
matches.captures[0]
end
|
ruby
|
def version
logger.debug "Parsing version from output using #{description}"
matches = output.match PARSE_VERSION_FROM_OUTPUT
raise InvalidFormat.new output if matches.nil?
matches.captures[0]
end
|
[
"def",
"version",
"logger",
".",
"debug",
"\"Parsing version from output using #{description}\"",
"matches",
"=",
"output",
".",
"match",
"PARSE_VERSION_FROM_OUTPUT",
"raise",
"InvalidFormat",
".",
"new",
"output",
"if",
"matches",
".",
"nil?",
"matches",
".",
"captures",
"[",
"0",
"]",
"end"
] |
Determines the version of Vagrant based on the output
|
[
"Determines",
"the",
"version",
"of",
"Vagrant",
"based",
"on",
"the",
"output"
] |
c9d70f04562280a34083dd060b0e4099e6f32d8d
|
https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/parser/version.rb#L13-L18
|
8,161
|
eunomie/valr
|
lib/valr/repo.rb
|
Valr.Repo.full_changelog
|
def full_changelog(first_parent: false, range: nil, branch: nil, from_ancestor_with: nil)
changelog_list = changelog first_parent: first_parent, range: range, branch: branch, from_ancestor_with: from_ancestor_with
if !range.nil?
header = full_changelog_header_range range
elsif !branch.nil?
header = full_changelog_header_branch branch, from_ancestor_with
else
header = full_changelog_header_no_range
end
[header, changelog_list].join "\n"
end
|
ruby
|
def full_changelog(first_parent: false, range: nil, branch: nil, from_ancestor_with: nil)
changelog_list = changelog first_parent: first_parent, range: range, branch: branch, from_ancestor_with: from_ancestor_with
if !range.nil?
header = full_changelog_header_range range
elsif !branch.nil?
header = full_changelog_header_branch branch, from_ancestor_with
else
header = full_changelog_header_no_range
end
[header, changelog_list].join "\n"
end
|
[
"def",
"full_changelog",
"(",
"first_parent",
":",
"false",
",",
"range",
":",
"nil",
",",
"branch",
":",
"nil",
",",
"from_ancestor_with",
":",
"nil",
")",
"changelog_list",
"=",
"changelog",
"first_parent",
":",
"first_parent",
",",
"range",
":",
"range",
",",
"branch",
":",
"branch",
",",
"from_ancestor_with",
":",
"from_ancestor_with",
"if",
"!",
"range",
".",
"nil?",
"header",
"=",
"full_changelog_header_range",
"range",
"elsif",
"!",
"branch",
".",
"nil?",
"header",
"=",
"full_changelog_header_branch",
"branch",
",",
"from_ancestor_with",
"else",
"header",
"=",
"full_changelog_header_no_range",
"end",
"[",
"header",
",",
"changelog_list",
"]",
".",
"join",
"\"\\n\"",
"end"
] |
Get the full changelog including metadata.
@param [Boolean] first_parent Optional, if true limits to first parent commits
@param [String] range Optional, define a specific range of commits
@param [String] branch Optional, show commits in a branch
@param [String] from_ancestor_with Optional, from common ancestor with this branch
@return [String] changelog
|
[
"Get",
"the",
"full",
"changelog",
"including",
"metadata",
"."
] |
f6a79ab33dbed0be21b1609405a667139524a251
|
https://github.com/eunomie/valr/blob/f6a79ab33dbed0be21b1609405a667139524a251/lib/valr/repo.rb#L38-L48
|
8,162
|
eunomie/valr
|
lib/valr/repo.rb
|
Valr.Repo.log_messages
|
def log_messages(first_parent = false, range = nil, branch = nil, from_ancestor_with = nil)
walker = Rugged::Walker.new @repo
if !range.nil?
begin
walker.push_range range
rescue Rugged::ReferenceError
raise Valr::NotValidRangeError.new range
end
elsif !branch.nil?
b = @repo.references["refs/heads/#{branch}"]
raise Valr::NotValidBranchError.new branch if b.nil?
if !from_ancestor_with.nil?
a = @repo.references["refs/heads/#{from_ancestor_with}"]
raise Valr::NotValidBranchError.new from_ancestor_with if a.nil?
base = @repo.merge_base b.target_id, a.target_id
walker.push_range "#{base}..#{b.target_id}"
else
walker.push b.target_id
end
else
walker.push @repo.head.target_id
end
walker.simplify_first_parent if first_parent
message_list = walker.inject([]) { |messages, c| messages << c.message }
walker.reset
message_list
end
|
ruby
|
def log_messages(first_parent = false, range = nil, branch = nil, from_ancestor_with = nil)
walker = Rugged::Walker.new @repo
if !range.nil?
begin
walker.push_range range
rescue Rugged::ReferenceError
raise Valr::NotValidRangeError.new range
end
elsif !branch.nil?
b = @repo.references["refs/heads/#{branch}"]
raise Valr::NotValidBranchError.new branch if b.nil?
if !from_ancestor_with.nil?
a = @repo.references["refs/heads/#{from_ancestor_with}"]
raise Valr::NotValidBranchError.new from_ancestor_with if a.nil?
base = @repo.merge_base b.target_id, a.target_id
walker.push_range "#{base}..#{b.target_id}"
else
walker.push b.target_id
end
else
walker.push @repo.head.target_id
end
walker.simplify_first_parent if first_parent
message_list = walker.inject([]) { |messages, c| messages << c.message }
walker.reset
message_list
end
|
[
"def",
"log_messages",
"(",
"first_parent",
"=",
"false",
",",
"range",
"=",
"nil",
",",
"branch",
"=",
"nil",
",",
"from_ancestor_with",
"=",
"nil",
")",
"walker",
"=",
"Rugged",
"::",
"Walker",
".",
"new",
"@repo",
"if",
"!",
"range",
".",
"nil?",
"begin",
"walker",
".",
"push_range",
"range",
"rescue",
"Rugged",
"::",
"ReferenceError",
"raise",
"Valr",
"::",
"NotValidRangeError",
".",
"new",
"range",
"end",
"elsif",
"!",
"branch",
".",
"nil?",
"b",
"=",
"@repo",
".",
"references",
"[",
"\"refs/heads/#{branch}\"",
"]",
"raise",
"Valr",
"::",
"NotValidBranchError",
".",
"new",
"branch",
"if",
"b",
".",
"nil?",
"if",
"!",
"from_ancestor_with",
".",
"nil?",
"a",
"=",
"@repo",
".",
"references",
"[",
"\"refs/heads/#{from_ancestor_with}\"",
"]",
"raise",
"Valr",
"::",
"NotValidBranchError",
".",
"new",
"from_ancestor_with",
"if",
"a",
".",
"nil?",
"base",
"=",
"@repo",
".",
"merge_base",
"b",
".",
"target_id",
",",
"a",
".",
"target_id",
"walker",
".",
"push_range",
"\"#{base}..#{b.target_id}\"",
"else",
"walker",
".",
"push",
"b",
".",
"target_id",
"end",
"else",
"walker",
".",
"push",
"@repo",
".",
"head",
".",
"target_id",
"end",
"walker",
".",
"simplify_first_parent",
"if",
"first_parent",
"message_list",
"=",
"walker",
".",
"inject",
"(",
"[",
"]",
")",
"{",
"|",
"messages",
",",
"c",
"|",
"messages",
"<<",
"c",
".",
"message",
"}",
"walker",
".",
"reset",
"message_list",
"end"
] |
Get log messages for a repository
@param [Boolean] first_parent Optional, if true limit to first parent commits
@param [String] range Optional, define a specific range of commits
@param [String] branch Optional, show commits in a branch
@param [String] from_ancestor_with Optional, from common ancestor with this branch
@return [Array<String>] log messages
|
[
"Get",
"log",
"messages",
"for",
"a",
"repository"
] |
f6a79ab33dbed0be21b1609405a667139524a251
|
https://github.com/eunomie/valr/blob/f6a79ab33dbed0be21b1609405a667139524a251/lib/valr/repo.rb#L76-L102
|
8,163
|
eunomie/valr
|
lib/valr/repo.rb
|
Valr.Repo.full_changelog_header_range
|
def full_changelog_header_range(range)
from, to = range.split '..'
from_commit, to_commit = [from, to].map { |ref| rev_parse ref }
Koios::Doc.write {
[pre(["from: #{from} <#{from_commit.oid}>",
"to: #{to} <#{to_commit.oid}>"])]
}
end
|
ruby
|
def full_changelog_header_range(range)
from, to = range.split '..'
from_commit, to_commit = [from, to].map { |ref| rev_parse ref }
Koios::Doc.write {
[pre(["from: #{from} <#{from_commit.oid}>",
"to: #{to} <#{to_commit.oid}>"])]
}
end
|
[
"def",
"full_changelog_header_range",
"(",
"range",
")",
"from",
",",
"to",
"=",
"range",
".",
"split",
"'..'",
"from_commit",
",",
"to_commit",
"=",
"[",
"from",
",",
"to",
"]",
".",
"map",
"{",
"|",
"ref",
"|",
"rev_parse",
"ref",
"}",
"Koios",
"::",
"Doc",
".",
"write",
"{",
"[",
"pre",
"(",
"[",
"\"from: #{from} <#{from_commit.oid}>\"",
",",
"\"to: #{to} <#{to_commit.oid}>\"",
"]",
")",
"]",
"}",
"end"
] |
Get the header when a range is defined
@param [String] range Define a specific range of commits
@return [String] header with a range
|
[
"Get",
"the",
"header",
"when",
"a",
"range",
"is",
"defined"
] |
f6a79ab33dbed0be21b1609405a667139524a251
|
https://github.com/eunomie/valr/blob/f6a79ab33dbed0be21b1609405a667139524a251/lib/valr/repo.rb#L114-L121
|
8,164
|
eunomie/valr
|
lib/valr/repo.rb
|
Valr.Repo.full_changelog_header_branch
|
def full_changelog_header_branch(branch, ancestor)
h = ["branch: #{branch} <#{@repo.references["refs/heads/#{branch}"].target_id}>"]
h << "from ancestor with: #{ancestor} <#{@repo.references["refs/heads/#{ancestor}"].target_id}>" unless ancestor.nil?
Koios::Doc.write {[pre(h)]}
end
|
ruby
|
def full_changelog_header_branch(branch, ancestor)
h = ["branch: #{branch} <#{@repo.references["refs/heads/#{branch}"].target_id}>"]
h << "from ancestor with: #{ancestor} <#{@repo.references["refs/heads/#{ancestor}"].target_id}>" unless ancestor.nil?
Koios::Doc.write {[pre(h)]}
end
|
[
"def",
"full_changelog_header_branch",
"(",
"branch",
",",
"ancestor",
")",
"h",
"=",
"[",
"\"branch: #{branch} <#{@repo.references[\"refs/heads/#{branch}\"].target_id}>\"",
"]",
"h",
"<<",
"\"from ancestor with: #{ancestor} <#{@repo.references[\"refs/heads/#{ancestor}\"].target_id}>\"",
"unless",
"ancestor",
".",
"nil?",
"Koios",
"::",
"Doc",
".",
"write",
"{",
"[",
"pre",
"(",
"h",
")",
"]",
"}",
"end"
] |
Get the header when a branch is defined
@param [String] branch Show commits for a branch
@param [String] ancestor Ancestor or nil
@return [String] header with a branch
|
[
"Get",
"the",
"header",
"when",
"a",
"branch",
"is",
"defined"
] |
f6a79ab33dbed0be21b1609405a667139524a251
|
https://github.com/eunomie/valr/blob/f6a79ab33dbed0be21b1609405a667139524a251/lib/valr/repo.rb#L127-L131
|
8,165
|
OiNutter/grayskull
|
lib/grayskull/validator.rb
|
Grayskull.Validator.match_node
|
def match_node(node,expected,label)
#check type
if !check_type(node,expected['type'],label,expected['ok_empty'])
@errors.push('Error: node ' + label + ' is not of an accepted type. Should be one of ' + expected['accepts'].join(', '))
return false
end
if (node.kind_of?(Hash) || node.kind_of?(Array))
if node.empty? && !expected['ok_empty']
@errors.push('Error: node ' + label + ' cannot be empty')
return false
elsif !node.empty? && expected.has_key?('accepts')
valid_content = false
if node.kind_of?(Hash)
matched = []
unmatched = []
node.each_pair{
|key,value|
expected['accepts'].each{
|accepts|
result = check_type(value,accepts,key)
if result
matched.push(key)
if !unmatched.find_index(key).nil?
unmatched.slice(unmatched.find_index(key))
end
break
else
unmatched.push(key)
end
}
}
if(matched.count==node.count)
valid_content = true
else
unmatched.each{
|node|
@errors.push('Error: node ' + node + ' is not of an accepted type. Should be one of ' + expected['accepts'].join(', '))
}
end
elsif node.kind_of?(Array)
matched = []
unmatched = []
node.each_index{
|n|
expected['accepts'].each{
|accepts|
key = label + '[' + n.to_s + ']'
result = check_type(node[n],accepts,key)
if result
matched.push(key)
if !unmatched.find_index(key).nil?
unmatched.slice(unmatched.find_index(key))
end
break
else
unmatched.push(key)
end
}
}
if(matched.count==node.count)
valid_content = true
else
unmatched.each{
|node|
@errors.push('Error: node ' + node + ' is not of an accepted type. Should be one of ' + expected['accepts'].join(', '))
}
end
end
if !valid_content
@errors.push('Error: node ' + label + ' contains an unaccepted type.')
return false
end
end
end
return true
end
|
ruby
|
def match_node(node,expected,label)
#check type
if !check_type(node,expected['type'],label,expected['ok_empty'])
@errors.push('Error: node ' + label + ' is not of an accepted type. Should be one of ' + expected['accepts'].join(', '))
return false
end
if (node.kind_of?(Hash) || node.kind_of?(Array))
if node.empty? && !expected['ok_empty']
@errors.push('Error: node ' + label + ' cannot be empty')
return false
elsif !node.empty? && expected.has_key?('accepts')
valid_content = false
if node.kind_of?(Hash)
matched = []
unmatched = []
node.each_pair{
|key,value|
expected['accepts'].each{
|accepts|
result = check_type(value,accepts,key)
if result
matched.push(key)
if !unmatched.find_index(key).nil?
unmatched.slice(unmatched.find_index(key))
end
break
else
unmatched.push(key)
end
}
}
if(matched.count==node.count)
valid_content = true
else
unmatched.each{
|node|
@errors.push('Error: node ' + node + ' is not of an accepted type. Should be one of ' + expected['accepts'].join(', '))
}
end
elsif node.kind_of?(Array)
matched = []
unmatched = []
node.each_index{
|n|
expected['accepts'].each{
|accepts|
key = label + '[' + n.to_s + ']'
result = check_type(node[n],accepts,key)
if result
matched.push(key)
if !unmatched.find_index(key).nil?
unmatched.slice(unmatched.find_index(key))
end
break
else
unmatched.push(key)
end
}
}
if(matched.count==node.count)
valid_content = true
else
unmatched.each{
|node|
@errors.push('Error: node ' + node + ' is not of an accepted type. Should be one of ' + expected['accepts'].join(', '))
}
end
end
if !valid_content
@errors.push('Error: node ' + label + ' contains an unaccepted type.')
return false
end
end
end
return true
end
|
[
"def",
"match_node",
"(",
"node",
",",
"expected",
",",
"label",
")",
"#check type ",
"if",
"!",
"check_type",
"(",
"node",
",",
"expected",
"[",
"'type'",
"]",
",",
"label",
",",
"expected",
"[",
"'ok_empty'",
"]",
")",
"@errors",
".",
"push",
"(",
"'Error: node '",
"+",
"label",
"+",
"' is not of an accepted type. Should be one of '",
"+",
"expected",
"[",
"'accepts'",
"]",
".",
"join",
"(",
"', '",
")",
")",
"return",
"false",
"end",
"if",
"(",
"node",
".",
"kind_of?",
"(",
"Hash",
")",
"||",
"node",
".",
"kind_of?",
"(",
"Array",
")",
")",
"if",
"node",
".",
"empty?",
"&&",
"!",
"expected",
"[",
"'ok_empty'",
"]",
"@errors",
".",
"push",
"(",
"'Error: node '",
"+",
"label",
"+",
"' cannot be empty'",
")",
"return",
"false",
"elsif",
"!",
"node",
".",
"empty?",
"&&",
"expected",
".",
"has_key?",
"(",
"'accepts'",
")",
"valid_content",
"=",
"false",
"if",
"node",
".",
"kind_of?",
"(",
"Hash",
")",
"matched",
"=",
"[",
"]",
"unmatched",
"=",
"[",
"]",
"node",
".",
"each_pair",
"{",
"|",
"key",
",",
"value",
"|",
"expected",
"[",
"'accepts'",
"]",
".",
"each",
"{",
"|",
"accepts",
"|",
"result",
"=",
"check_type",
"(",
"value",
",",
"accepts",
",",
"key",
")",
"if",
"result",
"matched",
".",
"push",
"(",
"key",
")",
"if",
"!",
"unmatched",
".",
"find_index",
"(",
"key",
")",
".",
"nil?",
"unmatched",
".",
"slice",
"(",
"unmatched",
".",
"find_index",
"(",
"key",
")",
")",
"end",
"break",
"else",
"unmatched",
".",
"push",
"(",
"key",
")",
"end",
"}",
"}",
"if",
"(",
"matched",
".",
"count",
"==",
"node",
".",
"count",
")",
"valid_content",
"=",
"true",
"else",
"unmatched",
".",
"each",
"{",
"|",
"node",
"|",
"@errors",
".",
"push",
"(",
"'Error: node '",
"+",
"node",
"+",
"' is not of an accepted type. Should be one of '",
"+",
"expected",
"[",
"'accepts'",
"]",
".",
"join",
"(",
"', '",
")",
")",
"}",
"end",
"elsif",
"node",
".",
"kind_of?",
"(",
"Array",
")",
"matched",
"=",
"[",
"]",
"unmatched",
"=",
"[",
"]",
"node",
".",
"each_index",
"{",
"|",
"n",
"|",
"expected",
"[",
"'accepts'",
"]",
".",
"each",
"{",
"|",
"accepts",
"|",
"key",
"=",
"label",
"+",
"'['",
"+",
"n",
".",
"to_s",
"+",
"']'",
"result",
"=",
"check_type",
"(",
"node",
"[",
"n",
"]",
",",
"accepts",
",",
"key",
")",
"if",
"result",
"matched",
".",
"push",
"(",
"key",
")",
"if",
"!",
"unmatched",
".",
"find_index",
"(",
"key",
")",
".",
"nil?",
"unmatched",
".",
"slice",
"(",
"unmatched",
".",
"find_index",
"(",
"key",
")",
")",
"end",
"break",
"else",
"unmatched",
".",
"push",
"(",
"key",
")",
"end",
"}",
"}",
"if",
"(",
"matched",
".",
"count",
"==",
"node",
".",
"count",
")",
"valid_content",
"=",
"true",
"else",
"unmatched",
".",
"each",
"{",
"|",
"node",
"|",
"@errors",
".",
"push",
"(",
"'Error: node '",
"+",
"node",
"+",
"' is not of an accepted type. Should be one of '",
"+",
"expected",
"[",
"'accepts'",
"]",
".",
"join",
"(",
"', '",
")",
")",
"}",
"end",
"end",
"if",
"!",
"valid_content",
"@errors",
".",
"push",
"(",
"'Error: node '",
"+",
"label",
"+",
"' contains an unaccepted type.'",
")",
"return",
"false",
"end",
"end",
"end",
"return",
"true",
"end"
] |
Checks file node matches the schema.
Checks type of node against expected type and
checks any children are of the accepted types.
|
[
"Checks",
"file",
"node",
"matches",
"the",
"schema",
"."
] |
c0bcdebcd1ef8220c61953e75c941edf0ae5df16
|
https://github.com/OiNutter/grayskull/blob/c0bcdebcd1ef8220c61953e75c941edf0ae5df16/lib/grayskull/validator.rb#L65-L164
|
8,166
|
OiNutter/grayskull
|
lib/grayskull/validator.rb
|
Grayskull.Validator.check_type
|
def check_type(node,expected_type,label,accept_nil = false)
valid_type = true;
if(@types.has_key?(expected_type))
valid_type = match_node(node,@types[expected_type],label)
elsif node.class.to_s != expected_type && !(node.kind_of?(NilClass) && (expected_type=='empty' || accept_nil))
valid_type = false
end
return valid_type
end
|
ruby
|
def check_type(node,expected_type,label,accept_nil = false)
valid_type = true;
if(@types.has_key?(expected_type))
valid_type = match_node(node,@types[expected_type],label)
elsif node.class.to_s != expected_type && !(node.kind_of?(NilClass) && (expected_type=='empty' || accept_nil))
valid_type = false
end
return valid_type
end
|
[
"def",
"check_type",
"(",
"node",
",",
"expected_type",
",",
"label",
",",
"accept_nil",
"=",
"false",
")",
"valid_type",
"=",
"true",
";",
"if",
"(",
"@types",
".",
"has_key?",
"(",
"expected_type",
")",
")",
"valid_type",
"=",
"match_node",
"(",
"node",
",",
"@types",
"[",
"expected_type",
"]",
",",
"label",
")",
"elsif",
"node",
".",
"class",
".",
"to_s",
"!=",
"expected_type",
"&&",
"!",
"(",
"node",
".",
"kind_of?",
"(",
"NilClass",
")",
"&&",
"(",
"expected_type",
"==",
"'empty'",
"||",
"accept_nil",
")",
")",
"valid_type",
"=",
"false",
"end",
"return",
"valid_type",
"end"
] |
Checks that the node is of the correct type
If the expected node is a custom node type as defined in the schema
It will run `match_node` to check that the node schema matches the
custom type.
|
[
"Checks",
"that",
"the",
"node",
"is",
"of",
"the",
"correct",
"type"
] |
c0bcdebcd1ef8220c61953e75c941edf0ae5df16
|
https://github.com/OiNutter/grayskull/blob/c0bcdebcd1ef8220c61953e75c941edf0ae5df16/lib/grayskull/validator.rb#L171-L182
|
8,167
|
barnabyalter/microservice_precompiler
|
lib/microservice_precompiler/builder.rb
|
MicroservicePrecompiler.Builder.cleanup
|
def cleanup(sprocket_assets = [:javascripts, :stylesheets])
# Remove previous dist path
FileUtils.rm_r build_path if File.exists?(build_path)
# Clean compass project
Compass::Exec::SubCommandUI.new(["clean", project_root]).run!
# Don't initialize Compass assets, the config will take care of it
sprocket_assets.each do |asset|
FileUtils.mkdir_p File.join(build_path, asset.to_s)
end
if mustaches_config_file_exists?
mustaches_yaml.each_key do |dir|
FileUtils.mkdir_p File.join(build_path, dir.to_s)
end
end
end
|
ruby
|
def cleanup(sprocket_assets = [:javascripts, :stylesheets])
# Remove previous dist path
FileUtils.rm_r build_path if File.exists?(build_path)
# Clean compass project
Compass::Exec::SubCommandUI.new(["clean", project_root]).run!
# Don't initialize Compass assets, the config will take care of it
sprocket_assets.each do |asset|
FileUtils.mkdir_p File.join(build_path, asset.to_s)
end
if mustaches_config_file_exists?
mustaches_yaml.each_key do |dir|
FileUtils.mkdir_p File.join(build_path, dir.to_s)
end
end
end
|
[
"def",
"cleanup",
"(",
"sprocket_assets",
"=",
"[",
":javascripts",
",",
":stylesheets",
"]",
")",
"# Remove previous dist path",
"FileUtils",
".",
"rm_r",
"build_path",
"if",
"File",
".",
"exists?",
"(",
"build_path",
")",
"# Clean compass project",
"Compass",
"::",
"Exec",
"::",
"SubCommandUI",
".",
"new",
"(",
"[",
"\"clean\"",
",",
"project_root",
"]",
")",
".",
"run!",
"# Don't initialize Compass assets, the config will take care of it",
"sprocket_assets",
".",
"each",
"do",
"|",
"asset",
"|",
"FileUtils",
".",
"mkdir_p",
"File",
".",
"join",
"(",
"build_path",
",",
"asset",
".",
"to_s",
")",
"end",
"if",
"mustaches_config_file_exists?",
"mustaches_yaml",
".",
"each_key",
"do",
"|",
"dir",
"|",
"FileUtils",
".",
"mkdir_p",
"File",
".",
"join",
"(",
"build_path",
",",
"dir",
".",
"to_s",
")",
"end",
"end",
"end"
] |
Public function for running cleanup of previous build
|
[
"Public",
"function",
"for",
"running",
"cleanup",
"of",
"previous",
"build"
] |
c485955eaf27ab70970426b4aeecd20740ac482c
|
https://github.com/barnabyalter/microservice_precompiler/blob/c485955eaf27ab70970426b4aeecd20740ac482c/lib/microservice_precompiler/builder.rb#L32-L46
|
8,168
|
barnabyalter/microservice_precompiler
|
lib/microservice_precompiler/builder.rb
|
MicroservicePrecompiler.Builder.sprockets_build
|
def sprockets_build(sprocket_assets = [:javascripts, :stylesheets])
sprocket_assets.each do |asset_type|
load_path = File.join(@project_root, asset_type.to_s)
next unless File.exists?(load_path)
sprockets_env.append_path load_path
Dir.new(load_path).each do |filename|
file = File.join(load_path, filename)
if File.file?(file)
asset = sprockets_env[filename]
attributes = sprockets_env.find_asset(asset.pathname)
# logical_path is the filename
build_file = File.join(build_path, asset_type.to_s, attributes.logical_path)
File.open(build_file, 'w') do |f|
extension = attributes.logical_path.split(".").last
f.write(minify(asset, extension))
end
end
end
end
end
|
ruby
|
def sprockets_build(sprocket_assets = [:javascripts, :stylesheets])
sprocket_assets.each do |asset_type|
load_path = File.join(@project_root, asset_type.to_s)
next unless File.exists?(load_path)
sprockets_env.append_path load_path
Dir.new(load_path).each do |filename|
file = File.join(load_path, filename)
if File.file?(file)
asset = sprockets_env[filename]
attributes = sprockets_env.find_asset(asset.pathname)
# logical_path is the filename
build_file = File.join(build_path, asset_type.to_s, attributes.logical_path)
File.open(build_file, 'w') do |f|
extension = attributes.logical_path.split(".").last
f.write(minify(asset, extension))
end
end
end
end
end
|
[
"def",
"sprockets_build",
"(",
"sprocket_assets",
"=",
"[",
":javascripts",
",",
":stylesheets",
"]",
")",
"sprocket_assets",
".",
"each",
"do",
"|",
"asset_type",
"|",
"load_path",
"=",
"File",
".",
"join",
"(",
"@project_root",
",",
"asset_type",
".",
"to_s",
")",
"next",
"unless",
"File",
".",
"exists?",
"(",
"load_path",
")",
"sprockets_env",
".",
"append_path",
"load_path",
"Dir",
".",
"new",
"(",
"load_path",
")",
".",
"each",
"do",
"|",
"filename",
"|",
"file",
"=",
"File",
".",
"join",
"(",
"load_path",
",",
"filename",
")",
"if",
"File",
".",
"file?",
"(",
"file",
")",
"asset",
"=",
"sprockets_env",
"[",
"filename",
"]",
"attributes",
"=",
"sprockets_env",
".",
"find_asset",
"(",
"asset",
".",
"pathname",
")",
"# logical_path is the filename",
"build_file",
"=",
"File",
".",
"join",
"(",
"build_path",
",",
"asset_type",
".",
"to_s",
",",
"attributes",
".",
"logical_path",
")",
"File",
".",
"open",
"(",
"build_file",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"extension",
"=",
"attributes",
".",
"logical_path",
".",
"split",
"(",
"\".\"",
")",
".",
"last",
"f",
".",
"write",
"(",
"minify",
"(",
"asset",
",",
"extension",
")",
")",
"end",
"end",
"end",
"end",
"end"
] |
Public function for building sprockets assets and minifying
|
[
"Public",
"function",
"for",
"building",
"sprockets",
"assets",
"and",
"minifying"
] |
c485955eaf27ab70970426b4aeecd20740ac482c
|
https://github.com/barnabyalter/microservice_precompiler/blob/c485955eaf27ab70970426b4aeecd20740ac482c/lib/microservice_precompiler/builder.rb#L55-L74
|
8,169
|
barnabyalter/microservice_precompiler
|
lib/microservice_precompiler/builder.rb
|
MicroservicePrecompiler.Builder.mustache_template_build
|
def mustache_template_build(dir, template_file, logic_file)
# Get the class name from an underscore-named file
logic_class_name = underscore_to_camelcase(logic_file)
# Output file should match the syntax of the mustaches config
output_file = logic_file
# Now we can name the logic_file to underscored version
logic_file = camelcase_to_underscore(logic_file)
# Require logic file, used to generate content from template
require File.join(project_root, camelcase_to_underscore(dir), logic_file)
# Create relevant directory path
FileUtils.mkdir_p File.join(build_path, dir.to_s)
# Instantiate class from required file
mustache = Kernel.const_get(logic_class_name).new
# Set the template file
mustache.template_file = File.join(project_root, camelcase_to_underscore(dir), template_file) + ".html.mustache"
# Get the name of the file we will write to after it's template is processed
build_file = File.join(build_path, dir, "#{output_file}.html")
File.open(build_file, 'w') do |f|
f.write(mustache.render)
end
end
|
ruby
|
def mustache_template_build(dir, template_file, logic_file)
# Get the class name from an underscore-named file
logic_class_name = underscore_to_camelcase(logic_file)
# Output file should match the syntax of the mustaches config
output_file = logic_file
# Now we can name the logic_file to underscored version
logic_file = camelcase_to_underscore(logic_file)
# Require logic file, used to generate content from template
require File.join(project_root, camelcase_to_underscore(dir), logic_file)
# Create relevant directory path
FileUtils.mkdir_p File.join(build_path, dir.to_s)
# Instantiate class from required file
mustache = Kernel.const_get(logic_class_name).new
# Set the template file
mustache.template_file = File.join(project_root, camelcase_to_underscore(dir), template_file) + ".html.mustache"
# Get the name of the file we will write to after it's template is processed
build_file = File.join(build_path, dir, "#{output_file}.html")
File.open(build_file, 'w') do |f|
f.write(mustache.render)
end
end
|
[
"def",
"mustache_template_build",
"(",
"dir",
",",
"template_file",
",",
"logic_file",
")",
"# Get the class name from an underscore-named file",
"logic_class_name",
"=",
"underscore_to_camelcase",
"(",
"logic_file",
")",
"# Output file should match the syntax of the mustaches config",
"output_file",
"=",
"logic_file",
"# Now we can name the logic_file to underscored version",
"logic_file",
"=",
"camelcase_to_underscore",
"(",
"logic_file",
")",
"# Require logic file, used to generate content from template",
"require",
"File",
".",
"join",
"(",
"project_root",
",",
"camelcase_to_underscore",
"(",
"dir",
")",
",",
"logic_file",
")",
"# Create relevant directory path",
"FileUtils",
".",
"mkdir_p",
"File",
".",
"join",
"(",
"build_path",
",",
"dir",
".",
"to_s",
")",
"# Instantiate class from required file",
"mustache",
"=",
"Kernel",
".",
"const_get",
"(",
"logic_class_name",
")",
".",
"new",
"# Set the template file",
"mustache",
".",
"template_file",
"=",
"File",
".",
"join",
"(",
"project_root",
",",
"camelcase_to_underscore",
"(",
"dir",
")",
",",
"template_file",
")",
"+",
"\".html.mustache\"",
"# Get the name of the file we will write to after it's template is processed",
"build_file",
"=",
"File",
".",
"join",
"(",
"build_path",
",",
"dir",
",",
"\"#{output_file}.html\"",
")",
"File",
".",
"open",
"(",
"build_file",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"mustache",
".",
"render",
")",
"end",
"end"
] |
Render html from a mustache template
|
[
"Render",
"html",
"from",
"a",
"mustache",
"template"
] |
c485955eaf27ab70970426b4aeecd20740ac482c
|
https://github.com/barnabyalter/microservice_precompiler/blob/c485955eaf27ab70970426b4aeecd20740ac482c/lib/microservice_precompiler/builder.rb#L128-L148
|
8,170
|
barnabyalter/microservice_precompiler
|
lib/microservice_precompiler/builder.rb
|
MicroservicePrecompiler.Builder.underscore_to_camelcase
|
def underscore_to_camelcase(underscore_string)
underscore_string = underscore_string.gsub(/(_)/,' ').split(' ').each { |word| word.capitalize! }.join("") unless underscore_string.match(/_/).nil?
underscore_string = underscore_string if underscore_string.match(/_/).nil?
return underscore_string
end
|
ruby
|
def underscore_to_camelcase(underscore_string)
underscore_string = underscore_string.gsub(/(_)/,' ').split(' ').each { |word| word.capitalize! }.join("") unless underscore_string.match(/_/).nil?
underscore_string = underscore_string if underscore_string.match(/_/).nil?
return underscore_string
end
|
[
"def",
"underscore_to_camelcase",
"(",
"underscore_string",
")",
"underscore_string",
"=",
"underscore_string",
".",
"gsub",
"(",
"/",
"/",
",",
"' '",
")",
".",
"split",
"(",
"' '",
")",
".",
"each",
"{",
"|",
"word",
"|",
"word",
".",
"capitalize!",
"}",
".",
"join",
"(",
"\"\"",
")",
"unless",
"underscore_string",
".",
"match",
"(",
"/",
"/",
")",
".",
"nil?",
"underscore_string",
"=",
"underscore_string",
"if",
"underscore_string",
".",
"match",
"(",
"/",
"/",
")",
".",
"nil?",
"return",
"underscore_string",
"end"
] |
Conver underscore to camelcase
|
[
"Conver",
"underscore",
"to",
"camelcase"
] |
c485955eaf27ab70970426b4aeecd20740ac482c
|
https://github.com/barnabyalter/microservice_precompiler/blob/c485955eaf27ab70970426b4aeecd20740ac482c/lib/microservice_precompiler/builder.rb#L156-L160
|
8,171
|
barnabyalter/microservice_precompiler
|
lib/microservice_precompiler/builder.rb
|
MicroservicePrecompiler.Builder.sprockets_env
|
def sprockets_env
@sprockets_env ||= Sprockets::Environment.new(project_root) { |env| env.logger = Logger.new(STDOUT) }
end
|
ruby
|
def sprockets_env
@sprockets_env ||= Sprockets::Environment.new(project_root) { |env| env.logger = Logger.new(STDOUT) }
end
|
[
"def",
"sprockets_env",
"@sprockets_env",
"||=",
"Sprockets",
"::",
"Environment",
".",
"new",
"(",
"project_root",
")",
"{",
"|",
"env",
"|",
"env",
".",
"logger",
"=",
"Logger",
".",
"new",
"(",
"STDOUT",
")",
"}",
"end"
] |
Initialize sprockets environment
|
[
"Initialize",
"sprockets",
"environment"
] |
c485955eaf27ab70970426b4aeecd20740ac482c
|
https://github.com/barnabyalter/microservice_precompiler/blob/c485955eaf27ab70970426b4aeecd20740ac482c/lib/microservice_precompiler/builder.rb#L163-L165
|
8,172
|
barnabyalter/microservice_precompiler
|
lib/microservice_precompiler/builder.rb
|
MicroservicePrecompiler.Builder.minify
|
def minify(asset, format)
asset = asset.to_s
# Minify JS
return Uglifier.compile(asset) if format.eql?("js")
# Minify CSS
return YUI::CssCompressor.new.compress(asset) if format.eql?("css")
# Return string representation if not minimizing
return asset
end
|
ruby
|
def minify(asset, format)
asset = asset.to_s
# Minify JS
return Uglifier.compile(asset) if format.eql?("js")
# Minify CSS
return YUI::CssCompressor.new.compress(asset) if format.eql?("css")
# Return string representation if not minimizing
return asset
end
|
[
"def",
"minify",
"(",
"asset",
",",
"format",
")",
"asset",
"=",
"asset",
".",
"to_s",
"# Minify JS",
"return",
"Uglifier",
".",
"compile",
"(",
"asset",
")",
"if",
"format",
".",
"eql?",
"(",
"\"js\"",
")",
"# Minify CSS",
"return",
"YUI",
"::",
"CssCompressor",
".",
"new",
".",
"compress",
"(",
"asset",
")",
"if",
"format",
".",
"eql?",
"(",
"\"css\"",
")",
"# Return string representation if not minimizing",
"return",
"asset",
"end"
] |
Minify assets in format
|
[
"Minify",
"assets",
"in",
"format"
] |
c485955eaf27ab70970426b4aeecd20740ac482c
|
https://github.com/barnabyalter/microservice_precompiler/blob/c485955eaf27ab70970426b4aeecd20740ac482c/lib/microservice_precompiler/builder.rb#L168-L176
|
8,173
|
jeremyd/virtualmonkey
|
lib/virtualmonkey/deployment_runner.rb
|
VirtualMonkey.DeploymentRunner.launch_all
|
def launch_all
@servers.each { |s|
begin
object_behavior(s, :start)
rescue Exception => e
raise e unless e.message =~ /AlreadyLaunchedError/
end
}
end
|
ruby
|
def launch_all
@servers.each { |s|
begin
object_behavior(s, :start)
rescue Exception => e
raise e unless e.message =~ /AlreadyLaunchedError/
end
}
end
|
[
"def",
"launch_all",
"@servers",
".",
"each",
"{",
"|",
"s",
"|",
"begin",
"object_behavior",
"(",
"s",
",",
":start",
")",
"rescue",
"Exception",
"=>",
"e",
"raise",
"e",
"unless",
"e",
".",
"message",
"=~",
"/",
"/",
"end",
"}",
"end"
] |
Launch all servers in the deployment.
|
[
"Launch",
"all",
"servers",
"in",
"the",
"deployment",
"."
] |
b2c7255f20ac5ec881eb90afbb5e712160db0dcb
|
https://github.com/jeremyd/virtualmonkey/blob/b2c7255f20ac5ec881eb90afbb5e712160db0dcb/lib/virtualmonkey/deployment_runner.rb#L57-L65
|
8,174
|
jeremyd/virtualmonkey
|
lib/virtualmonkey/deployment_runner.rb
|
VirtualMonkey.DeploymentRunner.check_monitoring
|
def check_monitoring
@servers.each do |server|
server.settings
response = nil
count = 0
until response || count > 20 do
begin
response = server.monitoring
rescue
response = nil
count += 1
sleep 10
end
end
raise "Fatal: Failed to verify that monitoring is operational" unless response
#TODO: pass in some list of plugin info to check multiple values. For now just
# hardcoding the cpu check
sleep 60 # This is to allow monitoring data to accumulate
monitor=server.get_sketchy_data({'start'=>-60,'end'=>-20,'plugin_name'=>"cpu-0",'plugin_type'=>"cpu-idle"})
idle_values = monitor['data']['value']
raise "No cpu idle data" unless idle_values.length > 0
raise "No idle time" unless idle_values[0] > 0
puts "Monitoring is OK for #{server.nickname}"
end
end
|
ruby
|
def check_monitoring
@servers.each do |server|
server.settings
response = nil
count = 0
until response || count > 20 do
begin
response = server.monitoring
rescue
response = nil
count += 1
sleep 10
end
end
raise "Fatal: Failed to verify that monitoring is operational" unless response
#TODO: pass in some list of plugin info to check multiple values. For now just
# hardcoding the cpu check
sleep 60 # This is to allow monitoring data to accumulate
monitor=server.get_sketchy_data({'start'=>-60,'end'=>-20,'plugin_name'=>"cpu-0",'plugin_type'=>"cpu-idle"})
idle_values = monitor['data']['value']
raise "No cpu idle data" unless idle_values.length > 0
raise "No idle time" unless idle_values[0] > 0
puts "Monitoring is OK for #{server.nickname}"
end
end
|
[
"def",
"check_monitoring",
"@servers",
".",
"each",
"do",
"|",
"server",
"|",
"server",
".",
"settings",
"response",
"=",
"nil",
"count",
"=",
"0",
"until",
"response",
"||",
"count",
">",
"20",
"do",
"begin",
"response",
"=",
"server",
".",
"monitoring",
"rescue",
"response",
"=",
"nil",
"count",
"+=",
"1",
"sleep",
"10",
"end",
"end",
"raise",
"\"Fatal: Failed to verify that monitoring is operational\"",
"unless",
"response",
"#TODO: pass in some list of plugin info to check multiple values. For now just",
"# hardcoding the cpu check",
"sleep",
"60",
"# This is to allow monitoring data to accumulate",
"monitor",
"=",
"server",
".",
"get_sketchy_data",
"(",
"{",
"'start'",
"=>",
"-",
"60",
",",
"'end'",
"=>",
"-",
"20",
",",
"'plugin_name'",
"=>",
"\"cpu-0\"",
",",
"'plugin_type'",
"=>",
"\"cpu-idle\"",
"}",
")",
"idle_values",
"=",
"monitor",
"[",
"'data'",
"]",
"[",
"'value'",
"]",
"raise",
"\"No cpu idle data\"",
"unless",
"idle_values",
".",
"length",
">",
"0",
"raise",
"\"No idle time\"",
"unless",
"idle_values",
"[",
"0",
"]",
">",
"0",
"puts",
"\"Monitoring is OK for #{server.nickname}\"",
"end",
"end"
] |
Checks that monitoring is enabled on all servers in the deployment. Will raise an error if monitoring is not enabled.
|
[
"Checks",
"that",
"monitoring",
"is",
"enabled",
"on",
"all",
"servers",
"in",
"the",
"deployment",
".",
"Will",
"raise",
"an",
"error",
"if",
"monitoring",
"is",
"not",
"enabled",
"."
] |
b2c7255f20ac5ec881eb90afbb5e712160db0dcb
|
https://github.com/jeremyd/virtualmonkey/blob/b2c7255f20ac5ec881eb90afbb5e712160db0dcb/lib/virtualmonkey/deployment_runner.rb#L248-L272
|
8,175
|
malditogeek/redisrecord
|
lib/redisrecord.rb
|
RedisRecord.Model.add_attributes
|
def add_attributes(hash)
hash.each_pair do |k,v|
k = k.to_sym
#raise DuplicateAttribute.new("#{k}") unless (k == :id or !self.respond_to?(k))
if k == :id or !self.respond_to?(k)
@cached_attrs[k] = v
meta = class << self; self; end
meta.send(:define_method, k) { @cached_attrs[k] }
meta.send(:define_method, "#{k}=") do |new_value|
@cached_attrs[k] = new_value.is_a?(RedisRecord::Model) ? new_value.id : new_value
@stored_attrs.delete(k)
end
end
end
hash
end
|
ruby
|
def add_attributes(hash)
hash.each_pair do |k,v|
k = k.to_sym
#raise DuplicateAttribute.new("#{k}") unless (k == :id or !self.respond_to?(k))
if k == :id or !self.respond_to?(k)
@cached_attrs[k] = v
meta = class << self; self; end
meta.send(:define_method, k) { @cached_attrs[k] }
meta.send(:define_method, "#{k}=") do |new_value|
@cached_attrs[k] = new_value.is_a?(RedisRecord::Model) ? new_value.id : new_value
@stored_attrs.delete(k)
end
end
end
hash
end
|
[
"def",
"add_attributes",
"(",
"hash",
")",
"hash",
".",
"each_pair",
"do",
"|",
"k",
",",
"v",
"|",
"k",
"=",
"k",
".",
"to_sym",
"#raise DuplicateAttribute.new(\"#{k}\") unless (k == :id or !self.respond_to?(k))",
"if",
"k",
"==",
":id",
"or",
"!",
"self",
".",
"respond_to?",
"(",
"k",
")",
"@cached_attrs",
"[",
"k",
"]",
"=",
"v",
"meta",
"=",
"class",
"<<",
"self",
";",
"self",
";",
"end",
"meta",
".",
"send",
"(",
":define_method",
",",
"k",
")",
"{",
"@cached_attrs",
"[",
"k",
"]",
"}",
"meta",
".",
"send",
"(",
":define_method",
",",
"\"#{k}=\"",
")",
"do",
"|",
"new_value",
"|",
"@cached_attrs",
"[",
"k",
"]",
"=",
"new_value",
".",
"is_a?",
"(",
"RedisRecord",
"::",
"Model",
")",
"?",
"new_value",
".",
"id",
":",
"new_value",
"@stored_attrs",
".",
"delete",
"(",
"k",
")",
"end",
"end",
"end",
"hash",
"end"
] |
Add attributes to the instance cache and define the accessor methods
|
[
"Add",
"attributes",
"to",
"the",
"instance",
"cache",
"and",
"define",
"the",
"accessor",
"methods"
] |
ae2d9904c622559904b9b6b02f00f9e9635525d1
|
https://github.com/malditogeek/redisrecord/blob/ae2d9904c622559904b9b6b02f00f9e9635525d1/lib/redisrecord.rb#L343-L358
|
8,176
|
malditogeek/redisrecord
|
lib/redisrecord.rb
|
RedisRecord.Model.add_foreign_keys_as_attributes
|
def add_foreign_keys_as_attributes
@@reflections[self.class.name.to_sym][:belongs_to].each do |klass|
add_attribute klass.to_s.foreign_key.to_sym
end
end
|
ruby
|
def add_foreign_keys_as_attributes
@@reflections[self.class.name.to_sym][:belongs_to].each do |klass|
add_attribute klass.to_s.foreign_key.to_sym
end
end
|
[
"def",
"add_foreign_keys_as_attributes",
"@@reflections",
"[",
"self",
".",
"class",
".",
"name",
".",
"to_sym",
"]",
"[",
":belongs_to",
"]",
".",
"each",
"do",
"|",
"klass",
"|",
"add_attribute",
"klass",
".",
"to_s",
".",
"foreign_key",
".",
"to_sym",
"end",
"end"
] |
Add the foreign key for the belongs_to relationships
|
[
"Add",
"the",
"foreign",
"key",
"for",
"the",
"belongs_to",
"relationships"
] |
ae2d9904c622559904b9b6b02f00f9e9635525d1
|
https://github.com/malditogeek/redisrecord/blob/ae2d9904c622559904b9b6b02f00f9e9635525d1/lib/redisrecord.rb#L366-L370
|
8,177
|
jutonz/dctl_rb
|
lib/dctl/main.rb
|
Dctl.Main.image_tag
|
def image_tag(image, version: current_version_for_image(image))
org = settings.org
project = settings.project
tag = "#{org}/#{project}-#{env}-#{image}"
if !version.nil?
version = version.to_i
tag +=
if version.negative?
current_version = current_version_for_image(image)
":#{current_version.to_i + version}"
else
":#{version}"
end
end
tag
end
|
ruby
|
def image_tag(image, version: current_version_for_image(image))
org = settings.org
project = settings.project
tag = "#{org}/#{project}-#{env}-#{image}"
if !version.nil?
version = version.to_i
tag +=
if version.negative?
current_version = current_version_for_image(image)
":#{current_version.to_i + version}"
else
":#{version}"
end
end
tag
end
|
[
"def",
"image_tag",
"(",
"image",
",",
"version",
":",
"current_version_for_image",
"(",
"image",
")",
")",
"org",
"=",
"settings",
".",
"org",
"project",
"=",
"settings",
".",
"project",
"tag",
"=",
"\"#{org}/#{project}-#{env}-#{image}\"",
"if",
"!",
"version",
".",
"nil?",
"version",
"=",
"version",
".",
"to_i",
"tag",
"+=",
"if",
"version",
".",
"negative?",
"current_version",
"=",
"current_version_for_image",
"(",
"image",
")",
"\":#{current_version.to_i + version}\"",
"else",
"\":#{version}\"",
"end",
"end",
"tag",
"end"
] |
Generate the full tag for the given image, concatenating the org,
project, env, image name, and version.
Pass `version: nil` to exclude the version portion.
@example
image_tag("app") # => jutonz/dctl-dev-app:1
|
[
"Generate",
"the",
"full",
"tag",
"for",
"the",
"given",
"image",
"concatenating",
"the",
"org",
"project",
"env",
"image",
"name",
"and",
"version",
"."
] |
55bae93a0ae642841231abe862a578344b732c5f
|
https://github.com/jutonz/dctl_rb/blob/55bae93a0ae642841231abe862a578344b732c5f/lib/dctl/main.rb#L18-L35
|
8,178
|
jutonz/dctl_rb
|
lib/dctl/main.rb
|
Dctl.Main.config_path
|
def config_path
path = File.expand_path ".dctl.yml", Dir.pwd
unless File.exist? path
error = "Could not find config file at #{path}"
puts Rainbow(error).red
exit 1
end
path
end
|
ruby
|
def config_path
path = File.expand_path ".dctl.yml", Dir.pwd
unless File.exist? path
error = "Could not find config file at #{path}"
puts Rainbow(error).red
exit 1
end
path
end
|
[
"def",
"config_path",
"path",
"=",
"File",
".",
"expand_path",
"\".dctl.yml\"",
",",
"Dir",
".",
"pwd",
"unless",
"File",
".",
"exist?",
"path",
"error",
"=",
"\"Could not find config file at #{path}\"",
"puts",
"Rainbow",
"(",
"error",
")",
".",
"red",
"exit",
"1",
"end",
"path",
"end"
] |
Returns the path to the .dctl.yml file for the current project
|
[
"Returns",
"the",
"path",
"to",
"the",
".",
"dctl",
".",
"yml",
"file",
"for",
"the",
"current",
"project"
] |
55bae93a0ae642841231abe862a578344b732c5f
|
https://github.com/jutonz/dctl_rb/blob/55bae93a0ae642841231abe862a578344b732c5f/lib/dctl/main.rb#L90-L100
|
8,179
|
jutonz/dctl_rb
|
lib/dctl/main.rb
|
Dctl.Main.define_custom_commands
|
def define_custom_commands(klass)
Array(settings.custom_commands).each do |command, args|
klass.send(:desc, command, "[Custom Command] #{command}")
# Concat with string so we can use exec rather than executing multiple
# subshells. Exec allows us to reuse the shell in which dctl is being
# executed, so we get to do things like reuse sudo authorizations
# rather than always having to prmopt.
concatenated = Array(args).join(" && ").strip
klass.send(:define_method, command, -> do
stream_output(concatenated, exec: true)
end)
end
end
|
ruby
|
def define_custom_commands(klass)
Array(settings.custom_commands).each do |command, args|
klass.send(:desc, command, "[Custom Command] #{command}")
# Concat with string so we can use exec rather than executing multiple
# subshells. Exec allows us to reuse the shell in which dctl is being
# executed, so we get to do things like reuse sudo authorizations
# rather than always having to prmopt.
concatenated = Array(args).join(" && ").strip
klass.send(:define_method, command, -> do
stream_output(concatenated, exec: true)
end)
end
end
|
[
"def",
"define_custom_commands",
"(",
"klass",
")",
"Array",
"(",
"settings",
".",
"custom_commands",
")",
".",
"each",
"do",
"|",
"command",
",",
"args",
"|",
"klass",
".",
"send",
"(",
":desc",
",",
"command",
",",
"\"[Custom Command] #{command}\"",
")",
"# Concat with string so we can use exec rather than executing multiple",
"# subshells. Exec allows us to reuse the shell in which dctl is being",
"# executed, so we get to do things like reuse sudo authorizations",
"# rather than always having to prmopt.",
"concatenated",
"=",
"Array",
"(",
"args",
")",
".",
"join",
"(",
"\" && \"",
")",
".",
"strip",
"klass",
".",
"send",
"(",
":define_method",
",",
"command",
",",
"->",
"do",
"stream_output",
"(",
"concatenated",
",",
"exec",
":",
"true",
")",
"end",
")",
"end",
"end"
] |
If there are user defined commands in .dctl.yml, dynamically add them to
the passed thor CLI so they may be executed.
|
[
"If",
"there",
"are",
"user",
"defined",
"commands",
"in",
".",
"dctl",
".",
"yml",
"dynamically",
"add",
"them",
"to",
"the",
"passed",
"thor",
"CLI",
"so",
"they",
"may",
"be",
"executed",
"."
] |
55bae93a0ae642841231abe862a578344b732c5f
|
https://github.com/jutonz/dctl_rb/blob/55bae93a0ae642841231abe862a578344b732c5f/lib/dctl/main.rb#L164-L177
|
8,180
|
jutonz/dctl_rb
|
lib/dctl/main.rb
|
Dctl.Main.check_settings!
|
def check_settings!
required_keys = %w(
org
project
)
required_keys.each do |key|
unless Settings.send key
error = "Config is missing required key '#{key}'. Please add it " \
"to #{config_path} and try again."
error += "\n\nFor more info, see https://github.com/jutonz/dctl_rb#required-keys"
puts Rainbow(error).red
exit 1
end
end
end
|
ruby
|
def check_settings!
required_keys = %w(
org
project
)
required_keys.each do |key|
unless Settings.send key
error = "Config is missing required key '#{key}'. Please add it " \
"to #{config_path} and try again."
error += "\n\nFor more info, see https://github.com/jutonz/dctl_rb#required-keys"
puts Rainbow(error).red
exit 1
end
end
end
|
[
"def",
"check_settings!",
"required_keys",
"=",
"%w(",
"org",
"project",
")",
"required_keys",
".",
"each",
"do",
"|",
"key",
"|",
"unless",
"Settings",
".",
"send",
"key",
"error",
"=",
"\"Config is missing required key '#{key}'. Please add it \"",
"\"to #{config_path} and try again.\"",
"error",
"+=",
"\"\\n\\nFor more info, see https://github.com/jutonz/dctl_rb#required-keys\"",
"puts",
"Rainbow",
"(",
"error",
")",
".",
"red",
"exit",
"1",
"end",
"end",
"end"
] |
Ensure the current project's .dctl.yml contains all the requisite keys.
|
[
"Ensure",
"the",
"current",
"project",
"s",
".",
"dctl",
".",
"yml",
"contains",
"all",
"the",
"requisite",
"keys",
"."
] |
55bae93a0ae642841231abe862a578344b732c5f
|
https://github.com/jutonz/dctl_rb/blob/55bae93a0ae642841231abe862a578344b732c5f/lib/dctl/main.rb#L181-L196
|
8,181
|
sinefunc/sinatra-helpers
|
lib/sinatra/helpers.rb
|
Sinatra.Helpers.select_options
|
def select_options(pairs, current = nil, prompt = nil)
pairs.unshift([prompt, '']) if prompt
pairs.map { |label, value|
tag(:option, label, :value => value, :selected => (current == value))
}.join("\n")
end
|
ruby
|
def select_options(pairs, current = nil, prompt = nil)
pairs.unshift([prompt, '']) if prompt
pairs.map { |label, value|
tag(:option, label, :value => value, :selected => (current == value))
}.join("\n")
end
|
[
"def",
"select_options",
"(",
"pairs",
",",
"current",
"=",
"nil",
",",
"prompt",
"=",
"nil",
")",
"pairs",
".",
"unshift",
"(",
"[",
"prompt",
",",
"''",
"]",
")",
"if",
"prompt",
"pairs",
".",
"map",
"{",
"|",
"label",
",",
"value",
"|",
"tag",
"(",
":option",
",",
"label",
",",
":value",
"=>",
"value",
",",
":selected",
"=>",
"(",
"current",
"==",
"value",
")",
")",
"}",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] |
Accepts a list of pairs and produces option tags.
@example
select_options([['One', 1], ['Two', 2]])
select_options([['One', 1], ['Two', 2]], 1)
select_options([['One', 1], ['Two', 2]], 1, '- Choose -')
# using it with the provided date helpers...
select_options year_choices, 2010 # select 2010 as default
select_options month_choices, 5 # select May as default
select_options day_choices, 25 # select the 25th as default
@param [Array] pairs a collection of label, value tuples.
@param [Object] current the current value of this select.
@param [#to_s] prompt a default prompt to place at the beginning
of the list.
|
[
"Accepts",
"a",
"list",
"of",
"pairs",
"and",
"produces",
"option",
"tags",
"."
] |
d13b3caf83fdc0ba73a8d1a3fab80f562fbbcdb4
|
https://github.com/sinefunc/sinatra-helpers/blob/d13b3caf83fdc0ba73a8d1a3fab80f562fbbcdb4/lib/sinatra/helpers.rb#L122-L128
|
8,182
|
sinefunc/sinatra-helpers
|
lib/sinatra/helpers.rb
|
Sinatra.Helpers.errors_on
|
def errors_on(object, options = { :class => 'errors' }, &block)
return if object.errors.empty?
lines = if object.errors.respond_to?(:full_messages)
object.errors.full_messages
else
HamlErrorPresenter.new(object.errors).present(self, &block)
end
haml_tag(:div, options) do
haml_tag(:ul) do
lines.each do |error|
haml_tag(:li, error)
end
end
end
end
|
ruby
|
def errors_on(object, options = { :class => 'errors' }, &block)
return if object.errors.empty?
lines = if object.errors.respond_to?(:full_messages)
object.errors.full_messages
else
HamlErrorPresenter.new(object.errors).present(self, &block)
end
haml_tag(:div, options) do
haml_tag(:ul) do
lines.each do |error|
haml_tag(:li, error)
end
end
end
end
|
[
"def",
"errors_on",
"(",
"object",
",",
"options",
"=",
"{",
":class",
"=>",
"'errors'",
"}",
",",
"&",
"block",
")",
"return",
"if",
"object",
".",
"errors",
".",
"empty?",
"lines",
"=",
"if",
"object",
".",
"errors",
".",
"respond_to?",
"(",
":full_messages",
")",
"object",
".",
"errors",
".",
"full_messages",
"else",
"HamlErrorPresenter",
".",
"new",
"(",
"object",
".",
"errors",
")",
".",
"present",
"(",
"self",
",",
"block",
")",
"end",
"haml_tag",
"(",
":div",
",",
"options",
")",
"do",
"haml_tag",
"(",
":ul",
")",
"do",
"lines",
".",
"each",
"do",
"|",
"error",
"|",
"haml_tag",
"(",
":li",
",",
"error",
")",
"end",
"end",
"end",
"end"
] |
Presents errors on your form. Takes the explicit approach and assumes
that for every form you have, the copy for the errors are important,
instead of producing canned responses.
Allows you to do the following in your haml view:
@example
- errors_on @user do |e|
- e.on [:email, :not_present], "We need your email address."
- e.on [:password, :not_present], "You must specify a password."
# produces the following:
# <div class="errors">
# <ul>
# <li>We need your email address</li>
# <li>You must specify a password.</li>
# </ul>
# </div>
@param [#errors] object An object responding to #errors. This validation
also checks for the presence of a #full_messages method
in the errors object for compatibility with ActiveRecord
style objects.
@param [Hash] options a hash of HTML attributes to place on the
containing div.
@option options [#to_s] :class (defaults to errors) The css class to put
in the div.
@yield [Sinatra::Helpers::HamlErrorPresenter] an object responding to #on.
@see Sinatra::Helpers::HamlErrorPresenter#on
|
[
"Presents",
"errors",
"on",
"your",
"form",
".",
"Takes",
"the",
"explicit",
"approach",
"and",
"assumes",
"that",
"for",
"every",
"form",
"you",
"have",
"the",
"copy",
"for",
"the",
"errors",
"are",
"important",
"instead",
"of",
"producing",
"canned",
"responses",
"."
] |
d13b3caf83fdc0ba73a8d1a3fab80f562fbbcdb4
|
https://github.com/sinefunc/sinatra-helpers/blob/d13b3caf83fdc0ba73a8d1a3fab80f562fbbcdb4/lib/sinatra/helpers.rb#L161-L177
|
8,183
|
sinefunc/sinatra-helpers
|
lib/sinatra/helpers.rb
|
Sinatra.Helpers.percentage
|
def percentage(number, precision = 2)
return if number.to_s.empty?
ret = "%02.#{ precision }f%" % number
ret.gsub(/\.0*%$/, '%')
end
|
ruby
|
def percentage(number, precision = 2)
return if number.to_s.empty?
ret = "%02.#{ precision }f%" % number
ret.gsub(/\.0*%$/, '%')
end
|
[
"def",
"percentage",
"(",
"number",
",",
"precision",
"=",
"2",
")",
"return",
"if",
"number",
".",
"to_s",
".",
"empty?",
"ret",
"=",
"\"%02.#{ precision }f%\"",
"%",
"number",
"ret",
".",
"gsub",
"(",
"/",
"\\.",
"/",
",",
"'%'",
")",
"end"
] |
Show the percentage representation of a numeric value.
@example
percentage(100) == "100.00%"
percentage(100, 0) == "100%"
@param [Numeric] number A numeric value
@param [Fixnum] precision (defaults to 2) Number of decimals to show.
@return [String] the number displayed as a percentage
@return [nil] given a nil value or an empty string.
|
[
"Show",
"the",
"percentage",
"representation",
"of",
"a",
"numeric",
"value",
"."
] |
d13b3caf83fdc0ba73a8d1a3fab80f562fbbcdb4
|
https://github.com/sinefunc/sinatra-helpers/blob/d13b3caf83fdc0ba73a8d1a3fab80f562fbbcdb4/lib/sinatra/helpers.rb#L234-L239
|
8,184
|
minch/buoy_data
|
lib/buoy_data/noaa_buoy_observation.rb
|
BuoyData.NoaaBuoyObservation.google_chart_url
|
def google_chart_url
max = 120
response = get_all
return unless response
historical_data = []
response.each_with_index do |row, index|
break if index >= max
next if row.match(/^#/)
row = row.split(/ ?/)
historical_data << row[5]
end
return if historical_data.blank?
historical_data = historical_data.join(',')
[ self.class.google_chart_base(@buoy_id), '&chd=t:', historical_data ].join
end
|
ruby
|
def google_chart_url
max = 120
response = get_all
return unless response
historical_data = []
response.each_with_index do |row, index|
break if index >= max
next if row.match(/^#/)
row = row.split(/ ?/)
historical_data << row[5]
end
return if historical_data.blank?
historical_data = historical_data.join(',')
[ self.class.google_chart_base(@buoy_id), '&chd=t:', historical_data ].join
end
|
[
"def",
"google_chart_url",
"max",
"=",
"120",
"response",
"=",
"get_all",
"return",
"unless",
"response",
"historical_data",
"=",
"[",
"]",
"response",
".",
"each_with_index",
"do",
"|",
"row",
",",
"index",
"|",
"break",
"if",
"index",
">=",
"max",
"next",
"if",
"row",
".",
"match",
"(",
"/",
"/",
")",
"row",
"=",
"row",
".",
"split",
"(",
"/",
"/",
")",
"historical_data",
"<<",
"row",
"[",
"5",
"]",
"end",
"return",
"if",
"historical_data",
".",
"blank?",
"historical_data",
"=",
"historical_data",
".",
"join",
"(",
"','",
")",
"[",
"self",
".",
"class",
".",
"google_chart_base",
"(",
"@buoy_id",
")",
",",
"'&chd=t:'",
",",
"historical_data",
"]",
".",
"join",
"end"
] |
Get a graph of the historical data for the given buoy.
Inspired by:
https://github.com/thepug/nbdc_graph/blob/master/generate_graphs.py
|
[
"Get",
"a",
"graph",
"of",
"the",
"historical",
"data",
"for",
"the",
"given",
"buoy",
"."
] |
6f1e36828ed6df1cb2610d09cc046118291dbe55
|
https://github.com/minch/buoy_data/blob/6f1e36828ed6df1cb2610d09cc046118291dbe55/lib/buoy_data/noaa_buoy_observation.rb#L49-L66
|
8,185
|
octoai/gem-octocore-cassandra
|
lib/octocore-cassandra/models/contactus.rb
|
Octo.ContactUs.send_email
|
def send_email
# Send thankyou mail
subject = 'Thanks for contacting us - Octo.ai'
opts = {
text: 'Hey we will get in touch with you shortly. Thanks :)',
name: self.firstname + ' ' + self.lastname
}
Octo::Email.send(self.email, subject, opts)
# Send mail to aron and param
Octo.get_config(:email_to).each { |x|
opts1 = {
text: self.email + ' \n\r ' + self.typeofrequest + '\n\r' + self.message,
name: x.fetch('name')
}
Octo::Email.send(x.fetch('email'), subject, opts1)
}
end
|
ruby
|
def send_email
# Send thankyou mail
subject = 'Thanks for contacting us - Octo.ai'
opts = {
text: 'Hey we will get in touch with you shortly. Thanks :)',
name: self.firstname + ' ' + self.lastname
}
Octo::Email.send(self.email, subject, opts)
# Send mail to aron and param
Octo.get_config(:email_to).each { |x|
opts1 = {
text: self.email + ' \n\r ' + self.typeofrequest + '\n\r' + self.message,
name: x.fetch('name')
}
Octo::Email.send(x.fetch('email'), subject, opts1)
}
end
|
[
"def",
"send_email",
"# Send thankyou mail",
"subject",
"=",
"'Thanks for contacting us - Octo.ai'",
"opts",
"=",
"{",
"text",
":",
"'Hey we will get in touch with you shortly. Thanks :)'",
",",
"name",
":",
"self",
".",
"firstname",
"+",
"' '",
"+",
"self",
".",
"lastname",
"}",
"Octo",
"::",
"Email",
".",
"send",
"(",
"self",
".",
"email",
",",
"subject",
",",
"opts",
")",
"# Send mail to aron and param",
"Octo",
".",
"get_config",
"(",
":email_to",
")",
".",
"each",
"{",
"|",
"x",
"|",
"opts1",
"=",
"{",
"text",
":",
"self",
".",
"email",
"+",
"' \\n\\r '",
"+",
"self",
".",
"typeofrequest",
"+",
"'\\n\\r'",
"+",
"self",
".",
"message",
",",
"name",
":",
"x",
".",
"fetch",
"(",
"'name'",
")",
"}",
"Octo",
"::",
"Email",
".",
"send",
"(",
"x",
".",
"fetch",
"(",
"'email'",
")",
",",
"subject",
",",
"opts1",
")",
"}",
"end"
] |
Send Email after model save
|
[
"Send",
"Email",
"after",
"model",
"save"
] |
c0977dce5ba0eb174ff810f161aba151069935df
|
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/models/contactus.rb#L19-L39
|
8,186
|
conversation/raca
|
lib/raca/servers.rb
|
Raca.Servers.create
|
def create(server_name, flavor_name, image_name, files = {})
request = {
"server" => {
"name" => server_name,
"imageRef" => image_name_to_id(image_name),
"flavorRef" => flavor_name_to_id(flavor_name),
}
}
files.each do |path, blob|
request['server']['personality'] ||= []
request['server']['personality'] << {
'path' => path,
'contents' => Base64.encode64(blob)
}
end
response = servers_client.post(servers_path, JSON.dump(request), json_headers)
data = JSON.parse(response.body)['server']
Raca::Server.new(@account, @region, data['id'])
end
|
ruby
|
def create(server_name, flavor_name, image_name, files = {})
request = {
"server" => {
"name" => server_name,
"imageRef" => image_name_to_id(image_name),
"flavorRef" => flavor_name_to_id(flavor_name),
}
}
files.each do |path, blob|
request['server']['personality'] ||= []
request['server']['personality'] << {
'path' => path,
'contents' => Base64.encode64(blob)
}
end
response = servers_client.post(servers_path, JSON.dump(request), json_headers)
data = JSON.parse(response.body)['server']
Raca::Server.new(@account, @region, data['id'])
end
|
[
"def",
"create",
"(",
"server_name",
",",
"flavor_name",
",",
"image_name",
",",
"files",
"=",
"{",
"}",
")",
"request",
"=",
"{",
"\"server\"",
"=>",
"{",
"\"name\"",
"=>",
"server_name",
",",
"\"imageRef\"",
"=>",
"image_name_to_id",
"(",
"image_name",
")",
",",
"\"flavorRef\"",
"=>",
"flavor_name_to_id",
"(",
"flavor_name",
")",
",",
"}",
"}",
"files",
".",
"each",
"do",
"|",
"path",
",",
"blob",
"|",
"request",
"[",
"'server'",
"]",
"[",
"'personality'",
"]",
"||=",
"[",
"]",
"request",
"[",
"'server'",
"]",
"[",
"'personality'",
"]",
"<<",
"{",
"'path'",
"=>",
"path",
",",
"'contents'",
"=>",
"Base64",
".",
"encode64",
"(",
"blob",
")",
"}",
"end",
"response",
"=",
"servers_client",
".",
"post",
"(",
"servers_path",
",",
"JSON",
".",
"dump",
"(",
"request",
")",
",",
"json_headers",
")",
"data",
"=",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
"[",
"'server'",
"]",
"Raca",
"::",
"Server",
".",
"new",
"(",
"@account",
",",
"@region",
",",
"data",
"[",
"'id'",
"]",
")",
"end"
] |
create a new server on Rackspace.
server_name is a free text name you want to assign the server.
flavor_name is a string that describes the amount of RAM. If you enter
an invalid option a list of valid options will be raised.
image_name is a string that describes the OS image to use. If you enter
an invalid option a list of valid options will be raised. I suggest
starting with 'Ubuntu 10.04 LTS'
files is an optional Hash of path to blobs. Use it to place a file on the
disk of the new server.
Use it like this:
server.create("my-server", 512, "Ubuntu 10.04 LTS", "/root/.ssh/authorised_keys" => File.read("/foo"))
|
[
"create",
"a",
"new",
"server",
"on",
"Rackspace",
"."
] |
fa69dfde22359cc0e06f655055be4eadcc7019c0
|
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/servers.rb#L43-L62
|
8,187
|
jeremyruppel/codependency
|
lib/codependency/graph.rb
|
Codependency.Graph.require
|
def require( file )
return if key?( file )
self[ file ] = deps( file )
self[ file ].each do |dependency|
self.require dependency
end
end
|
ruby
|
def require( file )
return if key?( file )
self[ file ] = deps( file )
self[ file ].each do |dependency|
self.require dependency
end
end
|
[
"def",
"require",
"(",
"file",
")",
"return",
"if",
"key?",
"(",
"file",
")",
"self",
"[",
"file",
"]",
"=",
"deps",
"(",
"file",
")",
"self",
"[",
"file",
"]",
".",
"each",
"do",
"|",
"dependency",
"|",
"self",
".",
"require",
"dependency",
"end",
"end"
] |
Add the given file to this graph. Creates a new entry in the
graph, the key of which is the relative path to this file and
the value is the array of relative paths to its dependencies.
Any dependent files will also be recursively added to this
graph.
|
[
"Add",
"the",
"given",
"file",
"to",
"this",
"graph",
".",
"Creates",
"a",
"new",
"entry",
"in",
"the",
"graph",
"the",
"key",
"of",
"which",
"is",
"the",
"relative",
"path",
"to",
"this",
"file",
"and",
"the",
"value",
"is",
"the",
"array",
"of",
"relative",
"paths",
"to",
"its",
"dependencies",
".",
"Any",
"dependent",
"files",
"will",
"also",
"be",
"recursively",
"added",
"to",
"this",
"graph",
"."
] |
635eddcc0149211e71f89bcaddaa6603aacf942f
|
https://github.com/jeremyruppel/codependency/blob/635eddcc0149211e71f89bcaddaa6603aacf942f/lib/codependency/graph.rb#L12-L19
|
8,188
|
jeremyruppel/codependency
|
lib/codependency/graph.rb
|
Codependency.Graph.scan
|
def scan( glob )
Dir[ glob ].flat_map { |f| deps( f ) }.uniq.each do |dependency|
self.require dependency
end
end
|
ruby
|
def scan( glob )
Dir[ glob ].flat_map { |f| deps( f ) }.uniq.each do |dependency|
self.require dependency
end
end
|
[
"def",
"scan",
"(",
"glob",
")",
"Dir",
"[",
"glob",
"]",
".",
"flat_map",
"{",
"|",
"f",
"|",
"deps",
"(",
"f",
")",
"}",
".",
"uniq",
".",
"each",
"do",
"|",
"dependency",
"|",
"self",
".",
"require",
"dependency",
"end",
"end"
] |
Parses all of the files in the given glob and adds their
dependencies to the graph. A file in this glob is not added
to the graph unless another file in the glob depends on it.
|
[
"Parses",
"all",
"of",
"the",
"files",
"in",
"the",
"given",
"glob",
"and",
"adds",
"their",
"dependencies",
"to",
"the",
"graph",
".",
"A",
"file",
"in",
"this",
"glob",
"is",
"not",
"added",
"to",
"the",
"graph",
"unless",
"another",
"file",
"in",
"the",
"glob",
"depends",
"on",
"it",
"."
] |
635eddcc0149211e71f89bcaddaa6603aacf942f
|
https://github.com/jeremyruppel/codependency/blob/635eddcc0149211e71f89bcaddaa6603aacf942f/lib/codependency/graph.rb#L26-L30
|
8,189
|
jeremyruppel/codependency
|
lib/codependency/graph.rb
|
Codependency.Graph.deps
|
def deps( file )
parser.parse( file ).map { |f| path_to path[ f ] }
end
|
ruby
|
def deps( file )
parser.parse( file ).map { |f| path_to path[ f ] }
end
|
[
"def",
"deps",
"(",
"file",
")",
"parser",
".",
"parse",
"(",
"file",
")",
".",
"map",
"{",
"|",
"f",
"|",
"path_to",
"path",
"[",
"f",
"]",
"}",
"end"
] |
Parses the file and returns the relative paths to its dependencies.
|
[
"Parses",
"the",
"file",
"and",
"returns",
"the",
"relative",
"paths",
"to",
"its",
"dependencies",
"."
] |
635eddcc0149211e71f89bcaddaa6603aacf942f
|
https://github.com/jeremyruppel/codependency/blob/635eddcc0149211e71f89bcaddaa6603aacf942f/lib/codependency/graph.rb#L85-L87
|
8,190
|
Deradon/Ruby-Rescuetime
|
lib/rescuetime/loop.rb
|
Rescuetime.Loop.run
|
def run
running!
@current_app = Application.create(:debug => debug?)
while true
sleep 1 # TODO: move to config
focus_changed if @current_app.finished? || backup?
end
end
|
ruby
|
def run
running!
@current_app = Application.create(:debug => debug?)
while true
sleep 1 # TODO: move to config
focus_changed if @current_app.finished? || backup?
end
end
|
[
"def",
"run",
"running!",
"@current_app",
"=",
"Application",
".",
"create",
"(",
":debug",
"=>",
"debug?",
")",
"while",
"true",
"sleep",
"1",
"# TODO: move to config",
"focus_changed",
"if",
"@current_app",
".",
"finished?",
"||",
"backup?",
"end",
"end"
] |
Run the loop
|
[
"Run",
"the",
"loop"
] |
0a81fb2e889bd225e0a0714d23c61fb9b1e36ffd
|
https://github.com/Deradon/Ruby-Rescuetime/blob/0a81fb2e889bd225e0a0714d23c61fb9b1e36ffd/lib/rescuetime/loop.rb#L77-L85
|
8,191
|
mochnatiy/flexible_accessibility
|
lib/flexible_accessibility/controller_methods.rb
|
FlexibleAccessibility.ControllerMethods.has_access?
|
def has_access?(permission, user)
raise UnknownUserException if user.nil?
AccessProvider.action_permitted_for_user?(permission, user)
end
|
ruby
|
def has_access?(permission, user)
raise UnknownUserException if user.nil?
AccessProvider.action_permitted_for_user?(permission, user)
end
|
[
"def",
"has_access?",
"(",
"permission",
",",
"user",
")",
"raise",
"UnknownUserException",
"if",
"user",
".",
"nil?",
"AccessProvider",
".",
"action_permitted_for_user?",
"(",
"permission",
",",
"user",
")",
"end"
] |
Check the url for each link in view to show it
|
[
"Check",
"the",
"url",
"for",
"each",
"link",
"in",
"view",
"to",
"show",
"it"
] |
ffd7f76e0765aa28909625b3bfa282264b8a5195
|
https://github.com/mochnatiy/flexible_accessibility/blob/ffd7f76e0765aa28909625b3bfa282264b8a5195/lib/flexible_accessibility/controller_methods.rb#L79-L83
|
8,192
|
GeoffWilliams/puppetbox
|
lib/puppetbox/puppetbox.rb
|
PuppetBox.PuppetBox.run_puppet
|
def run_puppet(driver_instance, puppet_tests, logger:nil, reset_after_run:true)
# use supplied logger in preference to the default puppetbox logger instance
logger = logger || @logger
logger.debug("#{driver_instance.node_name} running #{puppet_tests.size} tests")
if driver_instance.open
logger.debug("#{driver_instance.node_name} started")
if driver_instance.self_test
logger.debug("#{driver_instance.node_name} self_test OK, running puppet")
puppet_tests.each { |test_name, puppet_code|
if @result_set.class_size(driver_instance.node_name) > 0 and reset_after_run
# purge and reboot the vm - this will save approximately 1 second
# per class on the self-test which we now know will succeed
driver_instance.reset
end
setup_test(driver_instance, test_name)
logger.info("running test #{driver_instance.node_name} - #{test_name}")
# write out the local test file
relative_puppet_file = commit_testcase(
puppet_tests, driver_instance.node_name, test_name
)
driver_instance.sync_testcase(driver_instance.node_name, test_name)
puppet_file_remote = File.join(PUPPET_TESTCASE_DIR, relative_puppet_file)
driver_instance.run_puppet_x2(puppet_file_remote)
@logger.debug("Saved result #{driver_instance.node_name} #{test_name} #{driver_instance.result.passed?}")
@result_set.save(driver_instance.node_name, test_name, driver_instance.result)
Report::log_test_result_or_errors(
@logger,
driver_instance.node_name,
test_name,
driver_instance.result,
)
}
logger.debug("#{driver_instance.node_name} test completed, closing instance")
else
raise "#{driver_instance.node_name} self test failed, unable to continue"
end
else
raise "#{driver_instance.node_name} failed to start, unable to continue"
end
driver_instance.close
end
|
ruby
|
def run_puppet(driver_instance, puppet_tests, logger:nil, reset_after_run:true)
# use supplied logger in preference to the default puppetbox logger instance
logger = logger || @logger
logger.debug("#{driver_instance.node_name} running #{puppet_tests.size} tests")
if driver_instance.open
logger.debug("#{driver_instance.node_name} started")
if driver_instance.self_test
logger.debug("#{driver_instance.node_name} self_test OK, running puppet")
puppet_tests.each { |test_name, puppet_code|
if @result_set.class_size(driver_instance.node_name) > 0 and reset_after_run
# purge and reboot the vm - this will save approximately 1 second
# per class on the self-test which we now know will succeed
driver_instance.reset
end
setup_test(driver_instance, test_name)
logger.info("running test #{driver_instance.node_name} - #{test_name}")
# write out the local test file
relative_puppet_file = commit_testcase(
puppet_tests, driver_instance.node_name, test_name
)
driver_instance.sync_testcase(driver_instance.node_name, test_name)
puppet_file_remote = File.join(PUPPET_TESTCASE_DIR, relative_puppet_file)
driver_instance.run_puppet_x2(puppet_file_remote)
@logger.debug("Saved result #{driver_instance.node_name} #{test_name} #{driver_instance.result.passed?}")
@result_set.save(driver_instance.node_name, test_name, driver_instance.result)
Report::log_test_result_or_errors(
@logger,
driver_instance.node_name,
test_name,
driver_instance.result,
)
}
logger.debug("#{driver_instance.node_name} test completed, closing instance")
else
raise "#{driver_instance.node_name} self test failed, unable to continue"
end
else
raise "#{driver_instance.node_name} failed to start, unable to continue"
end
driver_instance.close
end
|
[
"def",
"run_puppet",
"(",
"driver_instance",
",",
"puppet_tests",
",",
"logger",
":",
"nil",
",",
"reset_after_run",
":",
"true",
")",
"# use supplied logger in preference to the default puppetbox logger instance",
"logger",
"=",
"logger",
"||",
"@logger",
"logger",
".",
"debug",
"(",
"\"#{driver_instance.node_name} running #{puppet_tests.size} tests\"",
")",
"if",
"driver_instance",
".",
"open",
"logger",
".",
"debug",
"(",
"\"#{driver_instance.node_name} started\"",
")",
"if",
"driver_instance",
".",
"self_test",
"logger",
".",
"debug",
"(",
"\"#{driver_instance.node_name} self_test OK, running puppet\"",
")",
"puppet_tests",
".",
"each",
"{",
"|",
"test_name",
",",
"puppet_code",
"|",
"if",
"@result_set",
".",
"class_size",
"(",
"driver_instance",
".",
"node_name",
")",
">",
"0",
"and",
"reset_after_run",
"# purge and reboot the vm - this will save approximately 1 second",
"# per class on the self-test which we now know will succeed",
"driver_instance",
".",
"reset",
"end",
"setup_test",
"(",
"driver_instance",
",",
"test_name",
")",
"logger",
".",
"info",
"(",
"\"running test #{driver_instance.node_name} - #{test_name}\"",
")",
"# write out the local test file",
"relative_puppet_file",
"=",
"commit_testcase",
"(",
"puppet_tests",
",",
"driver_instance",
".",
"node_name",
",",
"test_name",
")",
"driver_instance",
".",
"sync_testcase",
"(",
"driver_instance",
".",
"node_name",
",",
"test_name",
")",
"puppet_file_remote",
"=",
"File",
".",
"join",
"(",
"PUPPET_TESTCASE_DIR",
",",
"relative_puppet_file",
")",
"driver_instance",
".",
"run_puppet_x2",
"(",
"puppet_file_remote",
")",
"@logger",
".",
"debug",
"(",
"\"Saved result #{driver_instance.node_name} #{test_name} #{driver_instance.result.passed?}\"",
")",
"@result_set",
".",
"save",
"(",
"driver_instance",
".",
"node_name",
",",
"test_name",
",",
"driver_instance",
".",
"result",
")",
"Report",
"::",
"log_test_result_or_errors",
"(",
"@logger",
",",
"driver_instance",
".",
"node_name",
",",
"test_name",
",",
"driver_instance",
".",
"result",
",",
")",
"}",
"logger",
".",
"debug",
"(",
"\"#{driver_instance.node_name} test completed, closing instance\"",
")",
"else",
"raise",
"\"#{driver_instance.node_name} self test failed, unable to continue\"",
"end",
"else",
"raise",
"\"#{driver_instance.node_name} failed to start, unable to continue\"",
"end",
"driver_instance",
".",
"close",
"end"
] |
Run puppet using `driver_instance` to execute `puppet_codes`
@param puppet_test Hash of test names <-> puppet code, eg {"apache"=>"include apache","nginx"=>"include nginx"}}
|
[
"Run",
"puppet",
"using",
"driver_instance",
"to",
"execute",
"puppet_codes"
] |
8ace050aa46e8908c1b266b9307f01929e222e53
|
https://github.com/GeoffWilliams/puppetbox/blob/8ace050aa46e8908c1b266b9307f01929e222e53/lib/puppetbox/puppetbox.rb#L180-L225
|
8,193
|
elementar/shapewear
|
lib/shapewear/request.rb
|
Shapewear::Request.RequestHandler.extract_parameters
|
def extract_parameters(op_options, node)
logger.debug "Operation node: #{node.inspect}"
r = []
op_options[:parameters].each do |p|
logger.debug " Looking for: tns:#{p.first.camelize_if_symbol(:lower)}"
v = node.xpath("tns:#{p.first.camelize_if_symbol(:lower)}", namespaces).first
if v.nil?
# does nothing
elsif p.last == Fixnum
v = v.text.to_i
elsif p.last == DateTime
v = DateTime.parse(v.text) # TODO: add tests
else
v = v.text
end
logger.debug " Found: #{v.inspect}"
r << v
end
r
end
|
ruby
|
def extract_parameters(op_options, node)
logger.debug "Operation node: #{node.inspect}"
r = []
op_options[:parameters].each do |p|
logger.debug " Looking for: tns:#{p.first.camelize_if_symbol(:lower)}"
v = node.xpath("tns:#{p.first.camelize_if_symbol(:lower)}", namespaces).first
if v.nil?
# does nothing
elsif p.last == Fixnum
v = v.text.to_i
elsif p.last == DateTime
v = DateTime.parse(v.text) # TODO: add tests
else
v = v.text
end
logger.debug " Found: #{v.inspect}"
r << v
end
r
end
|
[
"def",
"extract_parameters",
"(",
"op_options",
",",
"node",
")",
"logger",
".",
"debug",
"\"Operation node: #{node.inspect}\"",
"r",
"=",
"[",
"]",
"op_options",
"[",
":parameters",
"]",
".",
"each",
"do",
"|",
"p",
"|",
"logger",
".",
"debug",
"\" Looking for: tns:#{p.first.camelize_if_symbol(:lower)}\"",
"v",
"=",
"node",
".",
"xpath",
"(",
"\"tns:#{p.first.camelize_if_symbol(:lower)}\"",
",",
"namespaces",
")",
".",
"first",
"if",
"v",
".",
"nil?",
"# does nothing",
"elsif",
"p",
".",
"last",
"==",
"Fixnum",
"v",
"=",
"v",
".",
"text",
".",
"to_i",
"elsif",
"p",
".",
"last",
"==",
"DateTime",
"v",
"=",
"DateTime",
".",
"parse",
"(",
"v",
".",
"text",
")",
"# TODO: add tests",
"else",
"v",
"=",
"v",
".",
"text",
"end",
"logger",
".",
"debug",
"\" Found: #{v.inspect}\"",
"r",
"<<",
"v",
"end",
"r",
"end"
] |
Extracts all parameters from the operation node, and return as an array.
@param op_options [Hash] The operation options.
@param node [Nokogiri::XML] The operation node.
@return [Array] The parsed parameters.
|
[
"Extracts",
"all",
"parameters",
"from",
"the",
"operation",
"node",
"and",
"return",
"as",
"an",
"array",
"."
] |
18cef0227930dbe26a2c821e8e636fda5d2bc6e2
|
https://github.com/elementar/shapewear/blob/18cef0227930dbe26a2c821e8e636fda5d2bc6e2/lib/shapewear/request.rb#L75-L94
|
8,194
|
elementar/shapewear
|
lib/shapewear/request.rb
|
Shapewear::Request.RequestHandler.serialize_soap_result
|
def serialize_soap_result(op_options, r)
xb = Builder::XmlMarkup.new
xb.instruct!
xb.Envelope :xmlns => soap_env_ns, 'xmlns:xsi' => namespaces['xsi'] do |xenv|
xenv.Body do |xbody|
xbody.tag! "#{op_options[:public_name]}Response", :xmlns => namespaces['tns'] do |xresp|
if r.nil?
xresp.tag! "#{op_options[:public_name]}Result", 'xsi:nil' => 'true'
else
ret = op_options[:returns] rescue nil
case ret
when NilClass, Class
xresp.tag! "#{op_options[:public_name]}Result", r
when Hash
xresp.tag! "#{op_options[:public_name]}Result" do |xres|
ret.each do |k, v|
extract_and_serialize_value(xres, r, k, v)
end
end
else
raise "Unsupported return type: #{ret.inspect}"
end
end
end
end
end
end
|
ruby
|
def serialize_soap_result(op_options, r)
xb = Builder::XmlMarkup.new
xb.instruct!
xb.Envelope :xmlns => soap_env_ns, 'xmlns:xsi' => namespaces['xsi'] do |xenv|
xenv.Body do |xbody|
xbody.tag! "#{op_options[:public_name]}Response", :xmlns => namespaces['tns'] do |xresp|
if r.nil?
xresp.tag! "#{op_options[:public_name]}Result", 'xsi:nil' => 'true'
else
ret = op_options[:returns] rescue nil
case ret
when NilClass, Class
xresp.tag! "#{op_options[:public_name]}Result", r
when Hash
xresp.tag! "#{op_options[:public_name]}Result" do |xres|
ret.each do |k, v|
extract_and_serialize_value(xres, r, k, v)
end
end
else
raise "Unsupported return type: #{ret.inspect}"
end
end
end
end
end
end
|
[
"def",
"serialize_soap_result",
"(",
"op_options",
",",
"r",
")",
"xb",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"xb",
".",
"instruct!",
"xb",
".",
"Envelope",
":xmlns",
"=>",
"soap_env_ns",
",",
"'xmlns:xsi'",
"=>",
"namespaces",
"[",
"'xsi'",
"]",
"do",
"|",
"xenv",
"|",
"xenv",
".",
"Body",
"do",
"|",
"xbody",
"|",
"xbody",
".",
"tag!",
"\"#{op_options[:public_name]}Response\"",
",",
":xmlns",
"=>",
"namespaces",
"[",
"'tns'",
"]",
"do",
"|",
"xresp",
"|",
"if",
"r",
".",
"nil?",
"xresp",
".",
"tag!",
"\"#{op_options[:public_name]}Result\"",
",",
"'xsi:nil'",
"=>",
"'true'",
"else",
"ret",
"=",
"op_options",
"[",
":returns",
"]",
"rescue",
"nil",
"case",
"ret",
"when",
"NilClass",
",",
"Class",
"xresp",
".",
"tag!",
"\"#{op_options[:public_name]}Result\"",
",",
"r",
"when",
"Hash",
"xresp",
".",
"tag!",
"\"#{op_options[:public_name]}Result\"",
"do",
"|",
"xres",
"|",
"ret",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"extract_and_serialize_value",
"(",
"xres",
",",
"r",
",",
"k",
",",
"v",
")",
"end",
"end",
"else",
"raise",
"\"Unsupported return type: #{ret.inspect}\"",
"end",
"end",
"end",
"end",
"end",
"end"
] |
Serializes the result of an operation as a SOAP Envelope.
@param op_options [Hash] The operation options.
@param r [Hash,Object] The operation result.
noinspection RubyArgCount
|
[
"Serializes",
"the",
"result",
"of",
"an",
"operation",
"as",
"a",
"SOAP",
"Envelope",
"."
] |
18cef0227930dbe26a2c821e8e636fda5d2bc6e2
|
https://github.com/elementar/shapewear/blob/18cef0227930dbe26a2c821e8e636fda5d2bc6e2/lib/shapewear/request.rb#L101-L128
|
8,195
|
elementar/shapewear
|
lib/shapewear/request.rb
|
Shapewear::Request.RequestHandler.extract_and_serialize_value
|
def extract_and_serialize_value(builder, obj, field, type)
v = if obj.is_a?(Hash)
obj[field] or obj[field.to_sym] or obj[field.to_s.underscore] or obj[field.to_s.underscore.to_sym]
elsif obj.respond_to?(field)
obj.send(field)
elsif obj.respond_to?(field.underscore)
obj.send(field.underscore)
else
raise "Could not extract #{field.inspect} from object: #{obj.inspect}"
end
if v.nil?
builder.tag! field.camelize_if_symbol, 'xsi:nil' => 'true'
else
builder.tag! field.camelize_if_symbol, v
end
end
|
ruby
|
def extract_and_serialize_value(builder, obj, field, type)
v = if obj.is_a?(Hash)
obj[field] or obj[field.to_sym] or obj[field.to_s.underscore] or obj[field.to_s.underscore.to_sym]
elsif obj.respond_to?(field)
obj.send(field)
elsif obj.respond_to?(field.underscore)
obj.send(field.underscore)
else
raise "Could not extract #{field.inspect} from object: #{obj.inspect}"
end
if v.nil?
builder.tag! field.camelize_if_symbol, 'xsi:nil' => 'true'
else
builder.tag! field.camelize_if_symbol, v
end
end
|
[
"def",
"extract_and_serialize_value",
"(",
"builder",
",",
"obj",
",",
"field",
",",
"type",
")",
"v",
"=",
"if",
"obj",
".",
"is_a?",
"(",
"Hash",
")",
"obj",
"[",
"field",
"]",
"or",
"obj",
"[",
"field",
".",
"to_sym",
"]",
"or",
"obj",
"[",
"field",
".",
"to_s",
".",
"underscore",
"]",
"or",
"obj",
"[",
"field",
".",
"to_s",
".",
"underscore",
".",
"to_sym",
"]",
"elsif",
"obj",
".",
"respond_to?",
"(",
"field",
")",
"obj",
".",
"send",
"(",
"field",
")",
"elsif",
"obj",
".",
"respond_to?",
"(",
"field",
".",
"underscore",
")",
"obj",
".",
"send",
"(",
"field",
".",
"underscore",
")",
"else",
"raise",
"\"Could not extract #{field.inspect} from object: #{obj.inspect}\"",
"end",
"if",
"v",
".",
"nil?",
"builder",
".",
"tag!",
"field",
".",
"camelize_if_symbol",
",",
"'xsi:nil'",
"=>",
"'true'",
"else",
"builder",
".",
"tag!",
"field",
".",
"camelize_if_symbol",
",",
"v",
"end",
"end"
] |
Extracts a field from an object, casts it to the appropriate type, and serializes as XML.
@param builder [Builder::XmlMarkup] The XML builder.
@param obj [Hash,Object] The resulting object.
@param field [Symbol,String] The field to extract.
@param type [Class] The type to convert.
|
[
"Extracts",
"a",
"field",
"from",
"an",
"object",
"casts",
"it",
"to",
"the",
"appropriate",
"type",
"and",
"serializes",
"as",
"XML",
"."
] |
18cef0227930dbe26a2c821e8e636fda5d2bc6e2
|
https://github.com/elementar/shapewear/blob/18cef0227930dbe26a2c821e8e636fda5d2bc6e2/lib/shapewear/request.rb#L136-L152
|
8,196
|
elementar/shapewear
|
lib/shapewear/request.rb
|
Shapewear::Request.RequestHandler.serialize_soap_fault
|
def serialize_soap_fault(ex)
logger.debug "Serializing SOAP Fault: #{ex.inspect}"
xb = Builder::XmlMarkup.new
xb.instruct!
xb.tag! 'e:Envelope', 'xmlns:e' => soap_env_ns do |xenv|
xenv.tag! 'e:Body' do |xbody|
xbody.tag! 'e:Fault' do |xf|
case soap_version
when :soap11
xf.faultcode "e:Server.#{ex.class.name}"
xf.faultstring ex.message
when :soap12
xf.tag! 'e:Code' do |xcode|
xcode.tag! 'e:Value', 'e:Receiver'
xcode.tag! 'e:Subcode' do |xsubcode|
xsubcode.tag! 'e:Value', ex.class.name
end
end
xf.tag! 'e:Reason', ex.message
else
raise "Unsupported SOAP version: #{soap_version}"
end
end
end
end
end
|
ruby
|
def serialize_soap_fault(ex)
logger.debug "Serializing SOAP Fault: #{ex.inspect}"
xb = Builder::XmlMarkup.new
xb.instruct!
xb.tag! 'e:Envelope', 'xmlns:e' => soap_env_ns do |xenv|
xenv.tag! 'e:Body' do |xbody|
xbody.tag! 'e:Fault' do |xf|
case soap_version
when :soap11
xf.faultcode "e:Server.#{ex.class.name}"
xf.faultstring ex.message
when :soap12
xf.tag! 'e:Code' do |xcode|
xcode.tag! 'e:Value', 'e:Receiver'
xcode.tag! 'e:Subcode' do |xsubcode|
xsubcode.tag! 'e:Value', ex.class.name
end
end
xf.tag! 'e:Reason', ex.message
else
raise "Unsupported SOAP version: #{soap_version}"
end
end
end
end
end
|
[
"def",
"serialize_soap_fault",
"(",
"ex",
")",
"logger",
".",
"debug",
"\"Serializing SOAP Fault: #{ex.inspect}\"",
"xb",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"xb",
".",
"instruct!",
"xb",
".",
"tag!",
"'e:Envelope'",
",",
"'xmlns:e'",
"=>",
"soap_env_ns",
"do",
"|",
"xenv",
"|",
"xenv",
".",
"tag!",
"'e:Body'",
"do",
"|",
"xbody",
"|",
"xbody",
".",
"tag!",
"'e:Fault'",
"do",
"|",
"xf",
"|",
"case",
"soap_version",
"when",
":soap11",
"xf",
".",
"faultcode",
"\"e:Server.#{ex.class.name}\"",
"xf",
".",
"faultstring",
"ex",
".",
"message",
"when",
":soap12",
"xf",
".",
"tag!",
"'e:Code'",
"do",
"|",
"xcode",
"|",
"xcode",
".",
"tag!",
"'e:Value'",
",",
"'e:Receiver'",
"xcode",
".",
"tag!",
"'e:Subcode'",
"do",
"|",
"xsubcode",
"|",
"xsubcode",
".",
"tag!",
"'e:Value'",
",",
"ex",
".",
"class",
".",
"name",
"end",
"end",
"xf",
".",
"tag!",
"'e:Reason'",
",",
"ex",
".",
"message",
"else",
"raise",
"\"Unsupported SOAP version: #{soap_version}\"",
"end",
"end",
"end",
"end",
"end"
] |
Serializes an exception as a SOAP Envelope containing a SOAP Fault.
@param ex [Exception] The Exception to serialize.
@return [String] The SOAP Envelope containing the Fault.
noinspection RubyArgCount
|
[
"Serializes",
"an",
"exception",
"as",
"a",
"SOAP",
"Envelope",
"containing",
"a",
"SOAP",
"Fault",
"."
] |
18cef0227930dbe26a2c821e8e636fda5d2bc6e2
|
https://github.com/elementar/shapewear/blob/18cef0227930dbe26a2c821e8e636fda5d2bc6e2/lib/shapewear/request.rb#L159-L186
|
8,197
|
nerboda/easy_breadcrumbs
|
lib/easy_breadcrumbs/sinatra_config.rb
|
Sinatra.EasyBreadcrumbs.view_variables
|
def view_variables
instance_variables
.select { |var| additional_var?(var) }
.map { |var| fetch_ivar_value(var) }
end
|
ruby
|
def view_variables
instance_variables
.select { |var| additional_var?(var) }
.map { |var| fetch_ivar_value(var) }
end
|
[
"def",
"view_variables",
"instance_variables",
".",
"select",
"{",
"|",
"var",
"|",
"additional_var?",
"(",
"var",
")",
"}",
".",
"map",
"{",
"|",
"var",
"|",
"fetch_ivar_value",
"(",
"var",
")",
"}",
"end"
] |
All user defined instance variables for current request.
|
[
"All",
"user",
"defined",
"instance",
"variables",
"for",
"current",
"request",
"."
] |
53af89b4ba1329a4963ff6bc253f4714ac9030f8
|
https://github.com/nerboda/easy_breadcrumbs/blob/53af89b4ba1329a4963ff6bc253f4714ac9030f8/lib/easy_breadcrumbs/sinatra_config.rb#L31-L35
|
8,198
|
starpeak/gricer
|
app/controllers/gricer/capture_controller.rb
|
Gricer.CaptureController.index
|
def index
gricer_request = ::Gricer.config.request_model.first_by_id(params[:id])
gricer_session = ::Gricer.config.session_model.first_by_id(session[:gricer_session])
if gricer_session
gricer_session.javascript = true
gricer_session.java = params[:j]
gricer_session.flash_version = params[:f] unless params[:f] == 'false'
gricer_session.silverlight_version = params[:sl] unless params[:sl] == 'false'
gricer_session.screen_width = params[:sx]
gricer_session.screen_height = params[:sy]
gricer_session.screen_size = "#{params[:sx]}x#{params[:sy]}" unless params[:sx].blank? or params[:sy].blank?
gricer_session.screen_depth = params[:sd]
gricer_session.save
if gricer_request and gricer_request.session == gricer_session
gricer_request.javascript = true
gricer_request.window_width = params[:wx]
gricer_request.window_height = params[:wy]
if gricer_request.save
render text: 'ok'
else
render text: 'session only', status: 500
end
return
else
render text: 'session only'
return
end
end
render text: 'failed', status: 500
end
|
ruby
|
def index
gricer_request = ::Gricer.config.request_model.first_by_id(params[:id])
gricer_session = ::Gricer.config.session_model.first_by_id(session[:gricer_session])
if gricer_session
gricer_session.javascript = true
gricer_session.java = params[:j]
gricer_session.flash_version = params[:f] unless params[:f] == 'false'
gricer_session.silverlight_version = params[:sl] unless params[:sl] == 'false'
gricer_session.screen_width = params[:sx]
gricer_session.screen_height = params[:sy]
gricer_session.screen_size = "#{params[:sx]}x#{params[:sy]}" unless params[:sx].blank? or params[:sy].blank?
gricer_session.screen_depth = params[:sd]
gricer_session.save
if gricer_request and gricer_request.session == gricer_session
gricer_request.javascript = true
gricer_request.window_width = params[:wx]
gricer_request.window_height = params[:wy]
if gricer_request.save
render text: 'ok'
else
render text: 'session only', status: 500
end
return
else
render text: 'session only'
return
end
end
render text: 'failed', status: 500
end
|
[
"def",
"index",
"gricer_request",
"=",
"::",
"Gricer",
".",
"config",
".",
"request_model",
".",
"first_by_id",
"(",
"params",
"[",
":id",
"]",
")",
"gricer_session",
"=",
"::",
"Gricer",
".",
"config",
".",
"session_model",
".",
"first_by_id",
"(",
"session",
"[",
":gricer_session",
"]",
")",
"if",
"gricer_session",
"gricer_session",
".",
"javascript",
"=",
"true",
"gricer_session",
".",
"java",
"=",
"params",
"[",
":j",
"]",
"gricer_session",
".",
"flash_version",
"=",
"params",
"[",
":f",
"]",
"unless",
"params",
"[",
":f",
"]",
"==",
"'false'",
"gricer_session",
".",
"silverlight_version",
"=",
"params",
"[",
":sl",
"]",
"unless",
"params",
"[",
":sl",
"]",
"==",
"'false'",
"gricer_session",
".",
"screen_width",
"=",
"params",
"[",
":sx",
"]",
"gricer_session",
".",
"screen_height",
"=",
"params",
"[",
":sy",
"]",
"gricer_session",
".",
"screen_size",
"=",
"\"#{params[:sx]}x#{params[:sy]}\"",
"unless",
"params",
"[",
":sx",
"]",
".",
"blank?",
"or",
"params",
"[",
":sy",
"]",
".",
"blank?",
"gricer_session",
".",
"screen_depth",
"=",
"params",
"[",
":sd",
"]",
"gricer_session",
".",
"save",
"if",
"gricer_request",
"and",
"gricer_request",
".",
"session",
"==",
"gricer_session",
"gricer_request",
".",
"javascript",
"=",
"true",
"gricer_request",
".",
"window_width",
"=",
"params",
"[",
":wx",
"]",
"gricer_request",
".",
"window_height",
"=",
"params",
"[",
":wy",
"]",
"if",
"gricer_request",
".",
"save",
"render",
"text",
":",
"'ok'",
"else",
"render",
"text",
":",
"'session only'",
",",
"status",
":",
"500",
"end",
"return",
"else",
"render",
"text",
":",
"'session only'",
"return",
"end",
"end",
"render",
"text",
":",
"'failed'",
",",
"status",
":",
"500",
"end"
] |
This action stores the data submitted by the Javascript.
|
[
"This",
"action",
"stores",
"the",
"data",
"submitted",
"by",
"the",
"Javascript",
"."
] |
46bb77bd4fc7074ce294d0310ad459fef068f507
|
https://github.com/starpeak/gricer/blob/46bb77bd4fc7074ce294d0310ad459fef068f507/app/controllers/gricer/capture_controller.rb#L7-L40
|
8,199
|
byu/optser
|
lib/optser/opt_set.rb
|
Optser.OptSet.get
|
def get(key, default=nil, &block)
value = options[key]
value = default if value.nil?
value = block.call if value.nil? && block
return value
end
|
ruby
|
def get(key, default=nil, &block)
value = options[key]
value = default if value.nil?
value = block.call if value.nil? && block
return value
end
|
[
"def",
"get",
"(",
"key",
",",
"default",
"=",
"nil",
",",
"&",
"block",
")",
"value",
"=",
"options",
"[",
"key",
"]",
"value",
"=",
"default",
"if",
"value",
".",
"nil?",
"value",
"=",
"block",
".",
"call",
"if",
"value",
".",
"nil?",
"&&",
"block",
"return",
"value",
"end"
] |
Lookup an option from our options set.
Examples:
# Optional parameter whose default value is nil.
do_extra = opt_set.get :do_extra
# Optional params that defaults to [1,2,3]
start_array = opt_set.get :start_array, [1,2,3]
Returns default value when:
* Key is non-existent in Options Hash.
* OR when the value of the key in the Options Hash is nil.
Returns nil when:
* Default is nil and the Options Hash lookup returns a nil.
Options Hash returns a nil because of either a
non-existent key or a nil value in said hash for said key.
|
[
"Lookup",
"an",
"option",
"from",
"our",
"options",
"set",
"."
] |
c88c19f15ca31874ad46fb6f15b20485635a5ffb
|
https://github.com/byu/optser/blob/c88c19f15ca31874ad46fb6f15b20485635a5ffb/lib/optser/opt_set.rb#L32-L37
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.