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
6,100
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.histogram
def histogram( *ret_shape ) options = ret_shape.last.is_a?( Hash ) ? ret_shape.pop : {} options = { :weight => UINT.new( 1 ), :safe => true }.merge options unless options[:weight].matched? options[:weight] = Node.match(options[:weight]).maxint.new options[:weight] end if ( shape.first != 1 or dimension == 1 ) and ret_shape.size == 1 [ self ].histogram *( ret_shape + [ options ] ) else ( 0 ... shape.first ).collect { |i| unroll[i] }. histogram *( ret_shape + [ options ] ) end end
ruby
def histogram( *ret_shape ) options = ret_shape.last.is_a?( Hash ) ? ret_shape.pop : {} options = { :weight => UINT.new( 1 ), :safe => true }.merge options unless options[:weight].matched? options[:weight] = Node.match(options[:weight]).maxint.new options[:weight] end if ( shape.first != 1 or dimension == 1 ) and ret_shape.size == 1 [ self ].histogram *( ret_shape + [ options ] ) else ( 0 ... shape.first ).collect { |i| unroll[i] }. histogram *( ret_shape + [ options ] ) end end
[ "def", "histogram", "(", "*", "ret_shape", ")", "options", "=", "ret_shape", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "ret_shape", ".", "pop", ":", "{", "}", "options", "=", "{", ":weight", "=>", "UINT", ".", "new", "(", "1", ")", ",", ":safe", "=>", "true", "}", ".", "merge", "options", "unless", "options", "[", ":weight", "]", ".", "matched?", "options", "[", ":weight", "]", "=", "Node", ".", "match", "(", "options", "[", ":weight", "]", ")", ".", "maxint", ".", "new", "options", "[", ":weight", "]", "end", "if", "(", "shape", ".", "first", "!=", "1", "or", "dimension", "==", "1", ")", "and", "ret_shape", ".", "size", "==", "1", "[", "self", "]", ".", "histogram", "(", "ret_shape", "+", "[", "options", "]", ")", "else", "(", "0", "...", "shape", ".", "first", ")", ".", "collect", "{", "|", "i", "|", "unroll", "[", "i", "]", "}", ".", "histogram", "(", "ret_shape", "+", "[", "options", "]", ")", "end", "end" ]
Compute histogram of this array @overload histogram( *ret_shape, options = {} ) @param [Array<Integer>] ret_shape Dimensions of resulting histogram. @option options [Node] :weight (UINT(1)) Weights for computing the histogram. @option options [Boolean] :safe (true) Do a boundary check before creating the histogram. @return [Node] The histogram.
[ "Compute", "histogram", "of", "this", "array" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L705-L717
6,101
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.lut
def lut( table, options = {} ) if ( shape.first != 1 or dimension == 1 ) and table.dimension == 1 [ self ].lut table, options else ( 0 ... shape.first ).collect { |i| unroll[i] }.lut table, options end end
ruby
def lut( table, options = {} ) if ( shape.first != 1 or dimension == 1 ) and table.dimension == 1 [ self ].lut table, options else ( 0 ... shape.first ).collect { |i| unroll[i] }.lut table, options end end
[ "def", "lut", "(", "table", ",", "options", "=", "{", "}", ")", "if", "(", "shape", ".", "first", "!=", "1", "or", "dimension", "==", "1", ")", "and", "table", ".", "dimension", "==", "1", "[", "self", "]", ".", "lut", "table", ",", "options", "else", "(", "0", "...", "shape", ".", "first", ")", ".", "collect", "{", "|", "i", "|", "unroll", "[", "i", "]", "}", ".", "lut", "table", ",", "options", "end", "end" ]
Perform element-wise lookup @param [Node] table The lookup table (LUT). @option options [Boolean] :safe (true) Do a boundary check before creating the element-wise lookup. @return [Node] The result of the lookup operation.
[ "Perform", "element", "-", "wise", "lookup" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L726-L732
6,102
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.warp
def warp( *field ) options = field.last.is_a?( Hash ) ? field.pop : {} options = { :safe => true, :default => typecode.default }.merge options if options[ :safe ] if field.size > dimension raise "Number of arrays for warp (#{field.size}) is greater than the " + "number of dimensions of source (#{dimension})" end Hornetseye::lazy do ( 0 ... field.size ). collect { |i| ( field[i] >= 0 ).and( field[i] < shape[i] ) }. inject :and end.conditional Lut.new( *( field + [ self ] ) ), options[ :default ] else field.lut self, :safe => false end end
ruby
def warp( *field ) options = field.last.is_a?( Hash ) ? field.pop : {} options = { :safe => true, :default => typecode.default }.merge options if options[ :safe ] if field.size > dimension raise "Number of arrays for warp (#{field.size}) is greater than the " + "number of dimensions of source (#{dimension})" end Hornetseye::lazy do ( 0 ... field.size ). collect { |i| ( field[i] >= 0 ).and( field[i] < shape[i] ) }. inject :and end.conditional Lut.new( *( field + [ self ] ) ), options[ :default ] else field.lut self, :safe => false end end
[ "def", "warp", "(", "*", "field", ")", "options", "=", "field", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "field", ".", "pop", ":", "{", "}", "options", "=", "{", ":safe", "=>", "true", ",", ":default", "=>", "typecode", ".", "default", "}", ".", "merge", "options", "if", "options", "[", ":safe", "]", "if", "field", ".", "size", ">", "dimension", "raise", "\"Number of arrays for warp (#{field.size}) is greater than the \"", "+", "\"number of dimensions of source (#{dimension})\"", "end", "Hornetseye", "::", "lazy", "do", "(", "0", "...", "field", ".", "size", ")", ".", "collect", "{", "|", "i", "|", "(", "field", "[", "i", "]", ">=", "0", ")", ".", "and", "(", "field", "[", "i", "]", "<", "shape", "[", "i", "]", ")", "}", ".", "inject", ":and", "end", ".", "conditional", "Lut", ".", "new", "(", "(", "field", "+", "[", "self", "]", ")", ")", ",", "options", "[", ":default", "]", "else", "field", ".", "lut", "self", ",", ":safe", "=>", "false", "end", "end" ]
Warp an array @overload warp( *field, options = {} ) @param [Array<Integer>] ret_shape Dimensions of resulting histogram. @option options [Object] :default (typecode.default) Default value for out of range warp vectors. @option options [Boolean] :safe (true) Apply clip to warp vectors. @return [Node] The result of the lookup operation.
[ "Warp", "an", "array" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L743-L759
6,103
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.integral
def integral left = allocate block = Integral.new left, self if block.compilable? GCCFunction.run block else block.demand end left end
ruby
def integral left = allocate block = Integral.new left, self if block.compilable? GCCFunction.run block else block.demand end left end
[ "def", "integral", "left", "=", "allocate", "block", "=", "Integral", ".", "new", "left", ",", "self", "if", "block", ".", "compilable?", "GCCFunction", ".", "run", "block", "else", "block", ".", "demand", "end", "left", "end" ]
Compute integral image @return [Node] The integral image of this array.
[ "Compute", "integral", "image" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L764-L773
6,104
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.components
def components( options = {} ) if shape.any? { |x| x <= 1 } raise "Every dimension must be greater than 1 (shape was #{shape})" end options = { :target => UINT, :default => typecode.default }.merge options target = options[ :target ] default = options[ :default ] default = typecode.new default unless default.matched? left = Hornetseye::MultiArray(target, dimension).new *shape labels = Sequence.new target, size; labels[0] = 0 rank = Sequence.uint size; rank[0] = 0 n = Hornetseye::Pointer( INT ).new; n.store INT.new( 0 ) block = Components.new left, self, default, target.new(0), labels, rank, n if block.compilable? Hornetseye::GCCFunction.run block else block.demand end labels = labels[0 .. n.demand.get] left.lut labels.lut(labels.histogram(labels.size, :weight => target.new(1)). minor(1).integral - 1) end
ruby
def components( options = {} ) if shape.any? { |x| x <= 1 } raise "Every dimension must be greater than 1 (shape was #{shape})" end options = { :target => UINT, :default => typecode.default }.merge options target = options[ :target ] default = options[ :default ] default = typecode.new default unless default.matched? left = Hornetseye::MultiArray(target, dimension).new *shape labels = Sequence.new target, size; labels[0] = 0 rank = Sequence.uint size; rank[0] = 0 n = Hornetseye::Pointer( INT ).new; n.store INT.new( 0 ) block = Components.new left, self, default, target.new(0), labels, rank, n if block.compilable? Hornetseye::GCCFunction.run block else block.demand end labels = labels[0 .. n.demand.get] left.lut labels.lut(labels.histogram(labels.size, :weight => target.new(1)). minor(1).integral - 1) end
[ "def", "components", "(", "options", "=", "{", "}", ")", "if", "shape", ".", "any?", "{", "|", "x", "|", "x", "<=", "1", "}", "raise", "\"Every dimension must be greater than 1 (shape was #{shape})\"", "end", "options", "=", "{", ":target", "=>", "UINT", ",", ":default", "=>", "typecode", ".", "default", "}", ".", "merge", "options", "target", "=", "options", "[", ":target", "]", "default", "=", "options", "[", ":default", "]", "default", "=", "typecode", ".", "new", "default", "unless", "default", ".", "matched?", "left", "=", "Hornetseye", "::", "MultiArray", "(", "target", ",", "dimension", ")", ".", "new", "shape", "labels", "=", "Sequence", ".", "new", "target", ",", "size", ";", "labels", "[", "0", "]", "=", "0", "rank", "=", "Sequence", ".", "uint", "size", ";", "rank", "[", "0", "]", "=", "0", "n", "=", "Hornetseye", "::", "Pointer", "(", "INT", ")", ".", "new", ";", "n", ".", "store", "INT", ".", "new", "(", "0", ")", "block", "=", "Components", ".", "new", "left", ",", "self", ",", "default", ",", "target", ".", "new", "(", "0", ")", ",", "labels", ",", "rank", ",", "n", "if", "block", ".", "compilable?", "Hornetseye", "::", "GCCFunction", ".", "run", "block", "else", "block", ".", "demand", "end", "labels", "=", "labels", "[", "0", "..", "n", ".", "demand", ".", "get", "]", "left", ".", "lut", "labels", ".", "lut", "(", "labels", ".", "histogram", "(", "labels", ".", "size", ",", ":weight", "=>", "target", ".", "new", "(", "1", ")", ")", ".", "minor", "(", "1", ")", ".", "integral", "-", "1", ")", "end" ]
Perform connected component labeling @option options [Object] :default (typecode.default) Value of background elements. @option options [Class] :target (UINT) Typecode of labels. @return [Node] Array with labels of connected components.
[ "Perform", "connected", "component", "labeling" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L781-L803
6,105
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.mask
def mask( m ) check_shape m left = MultiArray.new typecode, *( shape.first( dimension - m.dimension ) + [ m.size ] ) index = Hornetseye::Pointer( INT ).new index.store INT.new( 0 ) block = Mask.new left, self, m, index if block.compilable? GCCFunction.run block else block.demand end left[0 ... index[]].roll end
ruby
def mask( m ) check_shape m left = MultiArray.new typecode, *( shape.first( dimension - m.dimension ) + [ m.size ] ) index = Hornetseye::Pointer( INT ).new index.store INT.new( 0 ) block = Mask.new left, self, m, index if block.compilable? GCCFunction.run block else block.demand end left[0 ... index[]].roll end
[ "def", "mask", "(", "m", ")", "check_shape", "m", "left", "=", "MultiArray", ".", "new", "typecode", ",", "(", "shape", ".", "first", "(", "dimension", "-", "m", ".", "dimension", ")", "+", "[", "m", ".", "size", "]", ")", "index", "=", "Hornetseye", "::", "Pointer", "(", "INT", ")", ".", "new", "index", ".", "store", "INT", ".", "new", "(", "0", ")", "block", "=", "Mask", ".", "new", "left", ",", "self", ",", "m", ",", "index", "if", "block", ".", "compilable?", "GCCFunction", ".", "run", "block", "else", "block", ".", "demand", "end", "left", "[", "0", "...", "index", "[", "]", "]", ".", "roll", "end" ]
Select values from array using a mask @param [Node] m Mask to apply to this array. @return [Node] The masked array.
[ "Select", "values", "from", "array", "using", "a", "mask" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L810-L823
6,106
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.unmask
def unmask( m, options = {} ) options = { :safe => true, :default => typecode.default }.merge options default = options[:default] default = typecode.new default unless default.matched? m.check_shape default if options[ :safe ] if m.to_ubyte.sum > shape.last raise "#{m.to_ubyte.sum} value(s) of the mask are true but the last " + "dimension of the array for unmasking only has #{shape.last} value(s)" end end left = Hornetseye::MultiArray(typecode, dimension - 1 + m.dimension). coercion(default.typecode).new *(shape[1 .. -1] + m.shape) index = Hornetseye::Pointer(INT).new index.store INT.new(0) block = Unmask.new left, self, m, index, default if block.compilable? GCCFunction.run block else block.demand end left end
ruby
def unmask( m, options = {} ) options = { :safe => true, :default => typecode.default }.merge options default = options[:default] default = typecode.new default unless default.matched? m.check_shape default if options[ :safe ] if m.to_ubyte.sum > shape.last raise "#{m.to_ubyte.sum} value(s) of the mask are true but the last " + "dimension of the array for unmasking only has #{shape.last} value(s)" end end left = Hornetseye::MultiArray(typecode, dimension - 1 + m.dimension). coercion(default.typecode).new *(shape[1 .. -1] + m.shape) index = Hornetseye::Pointer(INT).new index.store INT.new(0) block = Unmask.new left, self, m, index, default if block.compilable? GCCFunction.run block else block.demand end left end
[ "def", "unmask", "(", "m", ",", "options", "=", "{", "}", ")", "options", "=", "{", ":safe", "=>", "true", ",", ":default", "=>", "typecode", ".", "default", "}", ".", "merge", "options", "default", "=", "options", "[", ":default", "]", "default", "=", "typecode", ".", "new", "default", "unless", "default", ".", "matched?", "m", ".", "check_shape", "default", "if", "options", "[", ":safe", "]", "if", "m", ".", "to_ubyte", ".", "sum", ">", "shape", ".", "last", "raise", "\"#{m.to_ubyte.sum} value(s) of the mask are true but the last \"", "+", "\"dimension of the array for unmasking only has #{shape.last} value(s)\"", "end", "end", "left", "=", "Hornetseye", "::", "MultiArray", "(", "typecode", ",", "dimension", "-", "1", "+", "m", ".", "dimension", ")", ".", "coercion", "(", "default", ".", "typecode", ")", ".", "new", "(", "shape", "[", "1", "..", "-", "1", "]", "+", "m", ".", "shape", ")", "index", "=", "Hornetseye", "::", "Pointer", "(", "INT", ")", ".", "new", "index", ".", "store", "INT", ".", "new", "(", "0", ")", "block", "=", "Unmask", ".", "new", "left", ",", "self", ",", "m", ",", "index", ",", "default", "if", "block", ".", "compilable?", "GCCFunction", ".", "run", "block", "else", "block", ".", "demand", "end", "left", "end" ]
Distribute values in a new array using a mask @param [Node] m Mask for inverse masking operation. @option options [Object] :default (typecode.default) Default value for elements where mask is +false+. @option options [Boolean] :safe (true) Ensure that the size of this size is sufficient. @return [Node] The result of the inverse masking operation.
[ "Distribute", "values", "in", "a", "new", "array", "using", "a", "mask" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L834-L856
6,107
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.flip
def flip( *dimensions ) field = ( 0 ... dimension ).collect do |i| if dimensions.member? i Hornetseye::lazy( *shape ) { |*args| shape[i] - 1 - args[i] } else Hornetseye::lazy( *shape ) { |*args| args[i] } end end warp *( field + [ :safe => false ] ) end
ruby
def flip( *dimensions ) field = ( 0 ... dimension ).collect do |i| if dimensions.member? i Hornetseye::lazy( *shape ) { |*args| shape[i] - 1 - args[i] } else Hornetseye::lazy( *shape ) { |*args| args[i] } end end warp *( field + [ :safe => false ] ) end
[ "def", "flip", "(", "*", "dimensions", ")", "field", "=", "(", "0", "...", "dimension", ")", ".", "collect", "do", "|", "i", "|", "if", "dimensions", ".", "member?", "i", "Hornetseye", "::", "lazy", "(", "shape", ")", "{", "|", "*", "args", "|", "shape", "[", "i", "]", "-", "1", "-", "args", "[", "i", "]", "}", "else", "Hornetseye", "::", "lazy", "(", "shape", ")", "{", "|", "*", "args", "|", "args", "[", "i", "]", "}", "end", "end", "warp", "(", "field", "+", "[", ":safe", "=>", "false", "]", ")", "end" ]
Mirror the array @param [Array<Integer>] dimensions The dimensions which should be flipped. @return [Node] The result of flipping the dimensions.
[ "Mirror", "the", "array" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L863-L872
6,108
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.shift
def shift( *offset ) if offset.size != dimension raise "#{offset.size} offset(s) were given but array has " + "#{dimension} dimension(s)" end retval = Hornetseye::MultiArray(typecode, dimension).new *shape target, source, open, close = [], [], [], [] ( shape.size - 1 ).step( 0, -1 ) do |i| callcc do |pass| delta = offset[i] % shape[i] source[i] = 0 ... shape[i] - delta target[i] = delta ... shape[i] callcc do |c| open[i] = c pass.call end source[i] = shape[i] - delta ... shape[i] target[i] = 0 ... delta callcc do |c| open[i] = c pass.call end close[i].call end end retval[ *target ] = self[ *source ] unless target.any? { |t| t.size == 0 } for i in 0 ... shape.size callcc do |c| close[i] = c open[i].call end end retval end
ruby
def shift( *offset ) if offset.size != dimension raise "#{offset.size} offset(s) were given but array has " + "#{dimension} dimension(s)" end retval = Hornetseye::MultiArray(typecode, dimension).new *shape target, source, open, close = [], [], [], [] ( shape.size - 1 ).step( 0, -1 ) do |i| callcc do |pass| delta = offset[i] % shape[i] source[i] = 0 ... shape[i] - delta target[i] = delta ... shape[i] callcc do |c| open[i] = c pass.call end source[i] = shape[i] - delta ... shape[i] target[i] = 0 ... delta callcc do |c| open[i] = c pass.call end close[i].call end end retval[ *target ] = self[ *source ] unless target.any? { |t| t.size == 0 } for i in 0 ... shape.size callcc do |c| close[i] = c open[i].call end end retval end
[ "def", "shift", "(", "*", "offset", ")", "if", "offset", ".", "size", "!=", "dimension", "raise", "\"#{offset.size} offset(s) were given but array has \"", "+", "\"#{dimension} dimension(s)\"", "end", "retval", "=", "Hornetseye", "::", "MultiArray", "(", "typecode", ",", "dimension", ")", ".", "new", "shape", "target", ",", "source", ",", "open", ",", "close", "=", "[", "]", ",", "[", "]", ",", "[", "]", ",", "[", "]", "(", "shape", ".", "size", "-", "1", ")", ".", "step", "(", "0", ",", "-", "1", ")", "do", "|", "i", "|", "callcc", "do", "|", "pass", "|", "delta", "=", "offset", "[", "i", "]", "%", "shape", "[", "i", "]", "source", "[", "i", "]", "=", "0", "...", "shape", "[", "i", "]", "-", "delta", "target", "[", "i", "]", "=", "delta", "...", "shape", "[", "i", "]", "callcc", "do", "|", "c", "|", "open", "[", "i", "]", "=", "c", "pass", ".", "call", "end", "source", "[", "i", "]", "=", "shape", "[", "i", "]", "-", "delta", "...", "shape", "[", "i", "]", "target", "[", "i", "]", "=", "0", "...", "delta", "callcc", "do", "|", "c", "|", "open", "[", "i", "]", "=", "c", "pass", ".", "call", "end", "close", "[", "i", "]", ".", "call", "end", "end", "retval", "[", "target", "]", "=", "self", "[", "source", "]", "unless", "target", ".", "any?", "{", "|", "t", "|", "t", ".", "size", "==", "0", "}", "for", "i", "in", "0", "...", "shape", ".", "size", "callcc", "do", "|", "c", "|", "close", "[", "i", "]", "=", "c", "open", "[", "i", "]", ".", "call", "end", "end", "retval", "end" ]
Create array with shifted elements @param [Array<Integer>] offset Array with amount of shift for each dimension. @return [Node] The result of the shifting operation.
[ "Create", "array", "with", "shifted", "elements" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L879-L912
6,109
wedesoft/multiarray
lib/multiarray/operations.rb
Hornetseye.Node.downsample
def downsample( *rate ) options = rate.last.is_a?( Hash ) ? rate.pop : {} options = { :offset => rate.collect { |r| r - 1 } }.merge options offset = options[ :offset ] if rate.size != dimension raise "#{rate.size} sampling rate(s) given but array has " + "#{dimension} dimension(s)" end if offset.size != dimension raise "#{offset.size} sampling offset(s) given but array has " + "#{dimension} dimension(s)" end ret_shape = ( 0 ... dimension ).collect do |i| ( shape[i] + rate[i] - 1 - offset[i] ).div rate[i] end field = ( 0 ... dimension ).collect do |i| Hornetseye::lazy( *ret_shape ) { |*args| args[i] * rate[i] + offset[i] } end warp *( field + [ :safe => false ] ) end
ruby
def downsample( *rate ) options = rate.last.is_a?( Hash ) ? rate.pop : {} options = { :offset => rate.collect { |r| r - 1 } }.merge options offset = options[ :offset ] if rate.size != dimension raise "#{rate.size} sampling rate(s) given but array has " + "#{dimension} dimension(s)" end if offset.size != dimension raise "#{offset.size} sampling offset(s) given but array has " + "#{dimension} dimension(s)" end ret_shape = ( 0 ... dimension ).collect do |i| ( shape[i] + rate[i] - 1 - offset[i] ).div rate[i] end field = ( 0 ... dimension ).collect do |i| Hornetseye::lazy( *ret_shape ) { |*args| args[i] * rate[i] + offset[i] } end warp *( field + [ :safe => false ] ) end
[ "def", "downsample", "(", "*", "rate", ")", "options", "=", "rate", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "rate", ".", "pop", ":", "{", "}", "options", "=", "{", ":offset", "=>", "rate", ".", "collect", "{", "|", "r", "|", "r", "-", "1", "}", "}", ".", "merge", "options", "offset", "=", "options", "[", ":offset", "]", "if", "rate", ".", "size", "!=", "dimension", "raise", "\"#{rate.size} sampling rate(s) given but array has \"", "+", "\"#{dimension} dimension(s)\"", "end", "if", "offset", ".", "size", "!=", "dimension", "raise", "\"#{offset.size} sampling offset(s) given but array has \"", "+", "\"#{dimension} dimension(s)\"", "end", "ret_shape", "=", "(", "0", "...", "dimension", ")", ".", "collect", "do", "|", "i", "|", "(", "shape", "[", "i", "]", "+", "rate", "[", "i", "]", "-", "1", "-", "offset", "[", "i", "]", ")", ".", "div", "rate", "[", "i", "]", "end", "field", "=", "(", "0", "...", "dimension", ")", ".", "collect", "do", "|", "i", "|", "Hornetseye", "::", "lazy", "(", "ret_shape", ")", "{", "|", "*", "args", "|", "args", "[", "i", "]", "*", "rate", "[", "i", "]", "+", "offset", "[", "i", "]", "}", "end", "warp", "(", "field", "+", "[", ":safe", "=>", "false", "]", ")", "end" ]
Downsampling of arrays @overload downsample( *rate, options = {} ) @param [Array<Integer>] rate The sampling rates for each dimension. @option options [Array<Integer>] :offset Sampling offsets for each dimension. @return [Node] The downsampled data.
[ "Downsampling", "of", "arrays" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/operations.rb#L921-L940
6,110
GemHQ/coin-op
lib/coin-op/bit/multi_wallet.rb
CoinOp::Bit.MultiWallet.signatures
def signatures(transaction, names: [:primary]) transaction.inputs.map do |input| path = input.output.metadata[:wallet_path] node = self.path(path) sig_hash = transaction.sig_hash(input, node.script) node.signatures(sig_hash, names: names) end end
ruby
def signatures(transaction, names: [:primary]) transaction.inputs.map do |input| path = input.output.metadata[:wallet_path] node = self.path(path) sig_hash = transaction.sig_hash(input, node.script) node.signatures(sig_hash, names: names) end end
[ "def", "signatures", "(", "transaction", ",", "names", ":", "[", ":primary", "]", ")", "transaction", ".", "inputs", ".", "map", "do", "|", "input", "|", "path", "=", "input", ".", "output", ".", "metadata", "[", ":wallet_path", "]", "node", "=", "self", ".", "path", "(", "path", ")", "sig_hash", "=", "transaction", ".", "sig_hash", "(", "input", ",", "node", ".", "script", ")", "node", ".", "signatures", "(", "sig_hash", ",", "names", ":", "names", ")", "end", "end" ]
Takes a Transaction ready to be signed. Returns an Array of signature dictionaries.
[ "Takes", "a", "Transaction", "ready", "to", "be", "signed", "." ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/multi_wallet.rb#L157-L164
6,111
GemHQ/coin-op
lib/coin-op/bit/multi_wallet.rb
CoinOp::Bit.MultiWallet.authorize
def authorize(transaction, *signers) transaction.set_script_sigs *signers do |input, *sig_dicts| node = self.path(input.output.metadata[:wallet_path]) signatures = combine_signatures(*sig_dicts) node.script_sig(signatures) end transaction end
ruby
def authorize(transaction, *signers) transaction.set_script_sigs *signers do |input, *sig_dicts| node = self.path(input.output.metadata[:wallet_path]) signatures = combine_signatures(*sig_dicts) node.script_sig(signatures) end transaction end
[ "def", "authorize", "(", "transaction", ",", "*", "signers", ")", "transaction", ".", "set_script_sigs", "signers", "do", "|", "input", ",", "*", "sig_dicts", "|", "node", "=", "self", ".", "path", "(", "input", ".", "output", ".", "metadata", "[", ":wallet_path", "]", ")", "signatures", "=", "combine_signatures", "(", "sig_dicts", ")", "node", ".", "script_sig", "(", "signatures", ")", "end", "transaction", "end" ]
Takes a Transaction and any number of Arrays of signature dictionaries. Each sig_dict in an Array corresponds to the Input with the same index. Uses the combined signatures from all the signers to generate and set the script_sig for each Input. Returns the transaction.
[ "Takes", "a", "Transaction", "and", "any", "number", "of", "Arrays", "of", "signature", "dictionaries", ".", "Each", "sig_dict", "in", "an", "Array", "corresponds", "to", "the", "Input", "with", "the", "same", "index", "." ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/multi_wallet.rb#L181-L188
6,112
GemHQ/coin-op
lib/coin-op/bit/multi_wallet.rb
CoinOp::Bit.MultiWallet.combine_signatures
def combine_signatures(*sig_dicts) combined = {} sig_dicts.each do |sig_dict| sig_dict.each do |tree, signature| decoded_sig = decode_base58(signature) low_s_der_sig = Bitcoin::Script.is_low_der_signature?(decoded_sig) ? decoded_sig : Bitcoin::OpenSSL_EC.signature_to_low_s(decoded_sig) combined[tree] = Bitcoin::OpenSSL_EC.repack_der_signature(low_s_der_sig) end end # Order of signatures is important for validation, so we always # sort public keys and signatures by the name of the tree # they belong to. combined.sort_by { |tree, value| tree }.map { |tree, sig| sig } end
ruby
def combine_signatures(*sig_dicts) combined = {} sig_dicts.each do |sig_dict| sig_dict.each do |tree, signature| decoded_sig = decode_base58(signature) low_s_der_sig = Bitcoin::Script.is_low_der_signature?(decoded_sig) ? decoded_sig : Bitcoin::OpenSSL_EC.signature_to_low_s(decoded_sig) combined[tree] = Bitcoin::OpenSSL_EC.repack_der_signature(low_s_der_sig) end end # Order of signatures is important for validation, so we always # sort public keys and signatures by the name of the tree # they belong to. combined.sort_by { |tree, value| tree }.map { |tree, sig| sig } end
[ "def", "combine_signatures", "(", "*", "sig_dicts", ")", "combined", "=", "{", "}", "sig_dicts", ".", "each", "do", "|", "sig_dict", "|", "sig_dict", ".", "each", "do", "|", "tree", ",", "signature", "|", "decoded_sig", "=", "decode_base58", "(", "signature", ")", "low_s_der_sig", "=", "Bitcoin", "::", "Script", ".", "is_low_der_signature?", "(", "decoded_sig", ")", "?", "decoded_sig", ":", "Bitcoin", "::", "OpenSSL_EC", ".", "signature_to_low_s", "(", "decoded_sig", ")", "combined", "[", "tree", "]", "=", "Bitcoin", "::", "OpenSSL_EC", ".", "repack_der_signature", "(", "low_s_der_sig", ")", "end", "end", "# Order of signatures is important for validation, so we always", "# sort public keys and signatures by the name of the tree", "# they belong to.", "combined", ".", "sort_by", "{", "|", "tree", ",", "value", "|", "tree", "}", ".", "map", "{", "|", "tree", ",", "sig", "|", "sig", "}", "end" ]
Takes any number of "signature dictionaries", which are Hashes where the keys are tree names, and the values are base58-encoded signatures for a single input. Returns an Array of the signatures in binary, sorted by their tree names.
[ "Takes", "any", "number", "of", "signature", "dictionaries", "which", "are", "Hashes", "where", "the", "keys", "are", "tree", "names", "and", "the", "values", "are", "base58", "-", "encoded", "signatures", "for", "a", "single", "input", "." ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/multi_wallet.rb#L195-L210
6,113
RobertDober/Forwarder19
lib/forwarder/arguments.rb
Forwarder.Arguments.evaluable?
def evaluable? !lambda? && !aop? && ( !args || args.all?{|a| Evaller.evaluable? a } ) && ( !custom_target? || Evaller.evaluable?( custom_target? ) ) end
ruby
def evaluable? !lambda? && !aop? && ( !args || args.all?{|a| Evaller.evaluable? a } ) && ( !custom_target? || Evaller.evaluable?( custom_target? ) ) end
[ "def", "evaluable?", "!", "lambda?", "&&", "!", "aop?", "&&", "(", "!", "args", "||", "args", ".", "all?", "{", "|", "a", "|", "Evaller", ".", "evaluable?", "a", "}", ")", "&&", "(", "!", "custom_target?", "||", "Evaller", ".", "evaluable?", "(", "custom_target?", ")", ")", "end" ]
def delegatable? !aop? && !custom_target? && !all? && !chain? && !args && !lambda? end
[ "def", "delegatable?", "!aop?", "&&", "!custom_target?", "&&", "!all?", "&&", "!chain?", "&&", "!args", "&&", "!lambda?", "end" ]
b8d0a0b568f14b157fea078ed5b4102c55701c99
https://github.com/RobertDober/Forwarder19/blob/b8d0a0b568f14b157fea078ed5b4102c55701c99/lib/forwarder/arguments.rb#L51-L56
6,114
rolandasb/gogcom
lib/gogcom/sale.rb
Gogcom.Sale.fetch
def fetch() url = "http://www.gog.com/" page = Net::HTTP.get(URI(url)) @data = JSON.parse(page[/(?<=var gogData = )(.*)(?=;)/,1]) end
ruby
def fetch() url = "http://www.gog.com/" page = Net::HTTP.get(URI(url)) @data = JSON.parse(page[/(?<=var gogData = )(.*)(?=;)/,1]) end
[ "def", "fetch", "(", ")", "url", "=", "\"http://www.gog.com/\"", "page", "=", "Net", "::", "HTTP", ".", "get", "(", "URI", "(", "url", ")", ")", "@data", "=", "JSON", ".", "parse", "(", "page", "[", "/", "/", ",", "1", "]", ")", "end" ]
Fetches raw data from source. @return [Object]
[ "Fetches", "raw", "data", "from", "source", "." ]
015de453bb214c9ccb51665ecadce1367e6d987d
https://github.com/rolandasb/gogcom/blob/015de453bb214c9ccb51665ecadce1367e6d987d/lib/gogcom/sale.rb#L19-L23
6,115
rolandasb/gogcom
lib/gogcom/sale.rb
Gogcom.Sale.parse
def parse(data) items = [] data["on_sale"].each do |item| sale_item = SaleItem.new(get_title(item), get_current_price(item), get_original_price(item), get_discount_percentage(item), get_discount_amount(item)) if @type.nil? items.push(sale_item) else if (@type == "games" && is_game?(item)) items.push(sale_item) end if (@type == "movies" && is_movie?(item)) items.push(sale_item) end end end unless @limit.nil? items.take(@limit) else items end end
ruby
def parse(data) items = [] data["on_sale"].each do |item| sale_item = SaleItem.new(get_title(item), get_current_price(item), get_original_price(item), get_discount_percentage(item), get_discount_amount(item)) if @type.nil? items.push(sale_item) else if (@type == "games" && is_game?(item)) items.push(sale_item) end if (@type == "movies" && is_movie?(item)) items.push(sale_item) end end end unless @limit.nil? items.take(@limit) else items end end
[ "def", "parse", "(", "data", ")", "items", "=", "[", "]", "data", "[", "\"on_sale\"", "]", ".", "each", "do", "|", "item", "|", "sale_item", "=", "SaleItem", ".", "new", "(", "get_title", "(", "item", ")", ",", "get_current_price", "(", "item", ")", ",", "get_original_price", "(", "item", ")", ",", "get_discount_percentage", "(", "item", ")", ",", "get_discount_amount", "(", "item", ")", ")", "if", "@type", ".", "nil?", "items", ".", "push", "(", "sale_item", ")", "else", "if", "(", "@type", "==", "\"games\"", "&&", "is_game?", "(", "item", ")", ")", "items", ".", "push", "(", "sale_item", ")", "end", "if", "(", "@type", "==", "\"movies\"", "&&", "is_movie?", "(", "item", ")", ")", "items", ".", "push", "(", "sale_item", ")", "end", "end", "end", "unless", "@limit", ".", "nil?", "items", ".", "take", "(", "@limit", ")", "else", "items", "end", "end" ]
Parses raw data and returns sale items. @return [Array]
[ "Parses", "raw", "data", "and", "returns", "sale", "items", "." ]
015de453bb214c9ccb51665ecadce1367e6d987d
https://github.com/rolandasb/gogcom/blob/015de453bb214c9ccb51665ecadce1367e6d987d/lib/gogcom/sale.rb#L28-L54
6,116
schrodingersbox/split_cat
app/models/split_cat/experiment.rb
SplitCat.Experiment.choose_hypothesis
def choose_hypothesis total = 0 roll = Kernel.rand( total_weight ) + 1 hypothesis = nil hypotheses.each do |h| if roll <= ( total += h.weight ) hypothesis ||= h end end hypothesis ||= hypotheses.first return hypothesis end
ruby
def choose_hypothesis total = 0 roll = Kernel.rand( total_weight ) + 1 hypothesis = nil hypotheses.each do |h| if roll <= ( total += h.weight ) hypothesis ||= h end end hypothesis ||= hypotheses.first return hypothesis end
[ "def", "choose_hypothesis", "total", "=", "0", "roll", "=", "Kernel", ".", "rand", "(", "total_weight", ")", "+", "1", "hypothesis", "=", "nil", "hypotheses", ".", "each", "do", "|", "h", "|", "if", "roll", "<=", "(", "total", "+=", "h", ".", "weight", ")", "hypothesis", "||=", "h", "end", "end", "hypothesis", "||=", "hypotheses", ".", "first", "return", "hypothesis", "end" ]
Returns a random hypothesis with weighted probability
[ "Returns", "a", "random", "hypothesis", "with", "weighted", "probability" ]
afe9c55e8d9be992ca601c0742b7512035e037a4
https://github.com/schrodingersbox/split_cat/blob/afe9c55e8d9be992ca601c0742b7512035e037a4/app/models/split_cat/experiment.rb#L81-L92
6,117
schrodingersbox/split_cat
app/models/split_cat/experiment.rb
SplitCat.Experiment.same_structure?
def same_structure?( experiment ) return nil if name.to_sym != experiment.name.to_sym return nil if goal_hash.keys != experiment.goal_hash.keys return nil if hypothesis_hash.keys != experiment.hypothesis_hash.keys return experiment end
ruby
def same_structure?( experiment ) return nil if name.to_sym != experiment.name.to_sym return nil if goal_hash.keys != experiment.goal_hash.keys return nil if hypothesis_hash.keys != experiment.hypothesis_hash.keys return experiment end
[ "def", "same_structure?", "(", "experiment", ")", "return", "nil", "if", "name", ".", "to_sym", "!=", "experiment", ".", "name", ".", "to_sym", "return", "nil", "if", "goal_hash", ".", "keys", "!=", "experiment", ".", "goal_hash", ".", "keys", "return", "nil", "if", "hypothesis_hash", ".", "keys", "!=", "experiment", ".", "hypothesis_hash", ".", "keys", "return", "experiment", "end" ]
Returns true if the experiment has the same name, goals, and hypotheses as this one
[ "Returns", "true", "if", "the", "experiment", "has", "the", "same", "name", "goals", "and", "hypotheses", "as", "this", "one" ]
afe9c55e8d9be992ca601c0742b7512035e037a4
https://github.com/schrodingersbox/split_cat/blob/afe9c55e8d9be992ca601c0742b7512035e037a4/app/models/split_cat/experiment.rb#L117-L122
6,118
detroit/detroit-dnote
lib/detroit-dnote.rb
Detroit.DNote.current?
def current? output_mapping.each do |file, format| return false if outofdate?(file, *dnote_session.files) end "DNotes are current (#{output})" end
ruby
def current? output_mapping.each do |file, format| return false if outofdate?(file, *dnote_session.files) end "DNotes are current (#{output})" end
[ "def", "current?", "output_mapping", ".", "each", "do", "|", "file", ",", "format", "|", "return", "false", "if", "outofdate?", "(", "file", ",", "dnote_session", ".", "files", ")", "end", "\"DNotes are current (#{output})\"", "end" ]
Check the output file and see if they are older than the input files. @return [Boolean] whether output is up-to-date
[ "Check", "the", "output", "file", "and", "see", "if", "they", "are", "older", "than", "the", "input", "files", "." ]
2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef
https://github.com/detroit/detroit-dnote/blob/2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef/lib/detroit-dnote.rb#L84-L89
6,119
detroit/detroit-dnote
lib/detroit-dnote.rb
Detroit.DNote.document
def document session = dnote_session output_mapping.each do |file, format| #next unless verify_format(format) dir = File.dirname(file) mkdir_p(dir) unless File.directory?(dir) session.output = file session.format = format session.run report "Updated #{file.sub(Dir.pwd+'/','')}" end end
ruby
def document session = dnote_session output_mapping.each do |file, format| #next unless verify_format(format) dir = File.dirname(file) mkdir_p(dir) unless File.directory?(dir) session.output = file session.format = format session.run report "Updated #{file.sub(Dir.pwd+'/','')}" end end
[ "def", "document", "session", "=", "dnote_session", "output_mapping", ".", "each", "do", "|", "file", ",", "format", "|", "#next unless verify_format(format)", "dir", "=", "File", ".", "dirname", "(", "file", ")", "mkdir_p", "(", "dir", ")", "unless", "File", ".", "directory?", "(", "dir", ")", "session", ".", "output", "=", "file", "session", ".", "format", "=", "format", "session", ".", "run", "report", "\"Updated #{file.sub(Dir.pwd+'/','')}\"", "end", "end" ]
Generate notes documents. @return [void]
[ "Generate", "notes", "documents", "." ]
2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef
https://github.com/detroit/detroit-dnote/blob/2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef/lib/detroit-dnote.rb#L94-L109
6,120
detroit/detroit-dnote
lib/detroit-dnote.rb
Detroit.DNote.reset
def reset output.each do |file, format| if File.exist?(file) utime(0,0,file) report "Marked #{file} as out-of-date." end end end
ruby
def reset output.each do |file, format| if File.exist?(file) utime(0,0,file) report "Marked #{file} as out-of-date." end end end
[ "def", "reset", "output", ".", "each", "do", "|", "file", ",", "format", "|", "if", "File", ".", "exist?", "(", "file", ")", "utime", "(", "0", ",", "0", ",", "file", ")", "report", "\"Marked #{file} as out-of-date.\"", "end", "end", "end" ]
Reset output files, marking them as out-of-date. @return [void]
[ "Reset", "output", "files", "marking", "them", "as", "out", "-", "of", "-", "date", "." ]
2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef
https://github.com/detroit/detroit-dnote/blob/2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef/lib/detroit-dnote.rb#L114-L121
6,121
detroit/detroit-dnote
lib/detroit-dnote.rb
Detroit.DNote.purge
def purge output.each do |file, format| if File.exist?(file) rm(file) report "Removed #{file}" end end end
ruby
def purge output.each do |file, format| if File.exist?(file) rm(file) report "Removed #{file}" end end end
[ "def", "purge", "output", ".", "each", "do", "|", "file", ",", "format", "|", "if", "File", ".", "exist?", "(", "file", ")", "rm", "(", "file", ")", "report", "\"Removed #{file}\"", "end", "end", "end" ]
Remove output files. @return [void]
[ "Remove", "output", "files", "." ]
2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef
https://github.com/detroit/detroit-dnote/blob/2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef/lib/detroit-dnote.rb#L126-L133
6,122
detroit/detroit-dnote
lib/detroit-dnote.rb
Detroit.DNote.output_mapping
def output_mapping @output_mapping ||= ( hash = {} case output when Array output.each do |path| hash[path] = format(path) end when String hash[output] = format(output) when Hash hash = output end hash ) end
ruby
def output_mapping @output_mapping ||= ( hash = {} case output when Array output.each do |path| hash[path] = format(path) end when String hash[output] = format(output) when Hash hash = output end hash ) end
[ "def", "output_mapping", "@output_mapping", "||=", "(", "hash", "=", "{", "}", "case", "output", "when", "Array", "output", ".", "each", "do", "|", "path", "|", "hash", "[", "path", "]", "=", "format", "(", "path", ")", "end", "when", "String", "hash", "[", "output", "]", "=", "format", "(", "output", ")", "when", "Hash", "hash", "=", "output", "end", "hash", ")", "end" ]
Convert output into a hash of `file => format`. @todo Should we use #apply_naming_policy ? @return [Hash]
[ "Convert", "output", "into", "a", "hash", "of", "file", "=", ">", "format", "." ]
2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef
https://github.com/detroit/detroit-dnote/blob/2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef/lib/detroit-dnote.rb#L150-L165
6,123
detroit/detroit-dnote
lib/detroit-dnote.rb
Detroit.DNote.format
def format(file) type = File.extname(file).sub('.','') type = DEFAULT_FORMAT if type.empty? type end
ruby
def format(file) type = File.extname(file).sub('.','') type = DEFAULT_FORMAT if type.empty? type end
[ "def", "format", "(", "file", ")", "type", "=", "File", ".", "extname", "(", "file", ")", ".", "sub", "(", "'.'", ",", "''", ")", "type", "=", "DEFAULT_FORMAT", "if", "type", ".", "empty?", "type", "end" ]
The format of the file based on the extension. If the file has no extension then the value of `DEFAULT_FORMAT` is returned. @return [String]
[ "The", "format", "of", "the", "file", "based", "on", "the", "extension", ".", "If", "the", "file", "has", "no", "extension", "then", "the", "value", "of", "DEFAULT_FORMAT", "is", "returned", "." ]
2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef
https://github.com/detroit/detroit-dnote/blob/2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef/lib/detroit-dnote.rb#L172-L176
6,124
detroit/detroit-dnote
lib/detroit-dnote.rb
Detroit.DNote.dnote_session
def dnote_session ::DNote::Session.new do |s| s.paths = files s.exclude = exclude s.ignore = ignore s.labels = labels s.title = title s.context = lines s.dryrun = trial? end end
ruby
def dnote_session ::DNote::Session.new do |s| s.paths = files s.exclude = exclude s.ignore = ignore s.labels = labels s.title = title s.context = lines s.dryrun = trial? end end
[ "def", "dnote_session", "::", "DNote", "::", "Session", ".", "new", "do", "|", "s", "|", "s", ".", "paths", "=", "files", "s", ".", "exclude", "=", "exclude", "s", ".", "ignore", "=", "ignore", "s", ".", "labels", "=", "labels", "s", ".", "title", "=", "title", "s", ".", "context", "=", "lines", "s", ".", "dryrun", "=", "trial?", "end", "end" ]
DNote Session instance. @return [DNote::Session]
[ "DNote", "Session", "instance", "." ]
2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef
https://github.com/detroit/detroit-dnote/blob/2f4dfd2deb31227b34d4bb7f9e8ce6937d6210ef/lib/detroit-dnote.rb#L181-L191
6,125
aaronpk/jawbone-up-ruby
lib/jawbone-up/session.rb
JawboneUP.Session.get
def get(path, query=nil, headers={}) response = execute :get, path, query, headers hash = JSON.parse response.body end
ruby
def get(path, query=nil, headers={}) response = execute :get, path, query, headers hash = JSON.parse response.body end
[ "def", "get", "(", "path", ",", "query", "=", "nil", ",", "headers", "=", "{", "}", ")", "response", "=", "execute", ":get", ",", "path", ",", "query", ",", "headers", "hash", "=", "JSON", ".", "parse", "response", ".", "body", "end" ]
Raw HTTP methods
[ "Raw", "HTTP", "methods" ]
6fec67a72d7f3df5aa040fa4d5341d0c434f72ca
https://github.com/aaronpk/jawbone-up-ruby/blob/6fec67a72d7f3df5aa040fa4d5341d0c434f72ca/lib/jawbone-up/session.rb#L90-L93
6,126
seoaqua/baidumap
lib/baidumap/request.rb
Baidumap.Request.request
def request http_segments = @segments.clone @params.each do |key,value| http_segments[key] = value end uri = URI::HTTP.build( :host => HOST, :path => @action_path, :query => URI.encode_www_form(http_segments) ).to_s result = JSON.parse(HTTParty.get(uri).parsed_response) Baidumap::Response.new(result,self) end
ruby
def request http_segments = @segments.clone @params.each do |key,value| http_segments[key] = value end uri = URI::HTTP.build( :host => HOST, :path => @action_path, :query => URI.encode_www_form(http_segments) ).to_s result = JSON.parse(HTTParty.get(uri).parsed_response) Baidumap::Response.new(result,self) end
[ "def", "request", "http_segments", "=", "@segments", ".", "clone", "@params", ".", "each", "do", "|", "key", ",", "value", "|", "http_segments", "[", "key", "]", "=", "value", "end", "uri", "=", "URI", "::", "HTTP", ".", "build", "(", ":host", "=>", "HOST", ",", ":path", "=>", "@action_path", ",", ":query", "=>", "URI", ".", "encode_www_form", "(", "http_segments", ")", ")", ".", "to_s", "result", "=", "JSON", ".", "parse", "(", "HTTParty", ".", "get", "(", "uri", ")", ".", "parsed_response", ")", "Baidumap", "::", "Response", ".", "new", "(", "result", ",", "self", ")", "end" ]
send http request
[ "send", "http", "request" ]
da6c0fd4ff61eb5b89ff8acea8389b2894a2661a
https://github.com/seoaqua/baidumap/blob/da6c0fd4ff61eb5b89ff8acea8389b2894a2661a/lib/baidumap/request.rb#L36-L48
6,127
midi-visualizer/vissen-parameterized
lib/vissen/parameterized.rb
Vissen.Parameterized.bind
def bind(param, target) raise ScopeError unless scope.include? target @_params.fetch(param).bind target end
ruby
def bind(param, target) raise ScopeError unless scope.include? target @_params.fetch(param).bind target end
[ "def", "bind", "(", "param", ",", "target", ")", "raise", "ScopeError", "unless", "scope", ".", "include?", "target", "@_params", ".", "fetch", "(", "param", ")", ".", "bind", "target", "end" ]
Binds a parameter to a target value. @see Parameter#bind @raise [KeyError] if the parameter is not found. @raise [ScopeError] if the parameter is out of scope. @param param [Symbol] the parameter to bind. @param target [#value] the value object to bind to. @return [Parameter] the parameter that was bound.
[ "Binds", "a", "parameter", "to", "a", "target", "value", "." ]
20cfb1cbaf6c7af5f5907b41c5439c39eed06420
https://github.com/midi-visualizer/vissen-parameterized/blob/20cfb1cbaf6c7af5f5907b41c5439c39eed06420/lib/vissen/parameterized.rb#L133-L136
6,128
midi-visualizer/vissen-parameterized
lib/vissen/parameterized.rb
Vissen.Parameterized.inspect
def inspect format INSPECT_FORMAT, name: self.class.name, object_id: object_id, params: params_with_types, type: Value.canonicalize(@_value.class) end
ruby
def inspect format INSPECT_FORMAT, name: self.class.name, object_id: object_id, params: params_with_types, type: Value.canonicalize(@_value.class) end
[ "def", "inspect", "format", "INSPECT_FORMAT", ",", "name", ":", "self", ".", "class", ".", "name", ",", "object_id", ":", "object_id", ",", "params", ":", "params_with_types", ",", "type", ":", "Value", ".", "canonicalize", "(", "@_value", ".", "class", ")", "end" ]
Produces a readable string representation of the parameterized object. @return [String] a string representation.
[ "Produces", "a", "readable", "string", "representation", "of", "the", "parameterized", "object", "." ]
20cfb1cbaf6c7af5f5907b41c5439c39eed06420
https://github.com/midi-visualizer/vissen-parameterized/blob/20cfb1cbaf6c7af5f5907b41c5439c39eed06420/lib/vissen/parameterized.rb#L166-L171
6,129
midi-visualizer/vissen-parameterized
lib/vissen/parameterized.rb
Vissen.Parameterized.each_parameterized
def each_parameterized return to_enum(__callee__) unless block_given? @_params.each do |_, param| next if param.constant? target = param.target yield target if target.is_a? Parameterized end end
ruby
def each_parameterized return to_enum(__callee__) unless block_given? @_params.each do |_, param| next if param.constant? target = param.target yield target if target.is_a? Parameterized end end
[ "def", "each_parameterized", "return", "to_enum", "(", "__callee__", ")", "unless", "block_given?", "@_params", ".", "each", "do", "|", "_", ",", "param", "|", "next", "if", "param", ".", "constant?", "target", "=", "param", ".", "target", "yield", "target", "if", "target", ".", "is_a?", "Parameterized", "end", "end" ]
Iterates over the parameterized objects currently bound to the parameters. @return [Enumerable] if no block is given.
[ "Iterates", "over", "the", "parameterized", "objects", "currently", "bound", "to", "the", "parameters", "." ]
20cfb1cbaf6c7af5f5907b41c5439c39eed06420
https://github.com/midi-visualizer/vissen-parameterized/blob/20cfb1cbaf6c7af5f5907b41c5439c39eed06420/lib/vissen/parameterized.rb#L176-L183
6,130
triglav-dataflow/triglav-client-ruby
lib/triglav_client/api/auth_api.rb
TriglavClient.AuthApi.create_token
def create_token(credential, opts = {}) data, _status_code, _headers = create_token_with_http_info(credential, opts) return data end
ruby
def create_token(credential, opts = {}) data, _status_code, _headers = create_token_with_http_info(credential, opts) return data end
[ "def", "create_token", "(", "credential", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "create_token_with_http_info", "(", "credential", ",", "opts", ")", "return", "data", "end" ]
Creates a new token @param credential @param [Hash] opts the optional parameters @return [TokenResponse]
[ "Creates", "a", "new", "token" ]
b2f3781d65ee032ba96eb703fbd789c713a5e0bd
https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/auth_api.rb#L39-L42
6,131
barkerest/barkest_core
app/models/barkest_core/auth_config.rb
BarkestCore.AuthConfig.to_h
def to_h { enable_db_auth: enable_db_auth?, enable_ldap_auth: enable_ldap_auth?, ldap_host: ldap_host.to_s, ldap_port: ldap_port.to_s.to_i, ldap_ssl: ldap_ssl?, ldap_base_dn: ldap_base_dn.to_s, ldap_browse_user: ldap_browse_user.to_s, ldap_browse_password: ldap_browse_password.to_s, ldap_auto_activate: ldap_auto_activate?, ldap_system_admin_groups: ldap_system_admin_groups.to_s, } end
ruby
def to_h { enable_db_auth: enable_db_auth?, enable_ldap_auth: enable_ldap_auth?, ldap_host: ldap_host.to_s, ldap_port: ldap_port.to_s.to_i, ldap_ssl: ldap_ssl?, ldap_base_dn: ldap_base_dn.to_s, ldap_browse_user: ldap_browse_user.to_s, ldap_browse_password: ldap_browse_password.to_s, ldap_auto_activate: ldap_auto_activate?, ldap_system_admin_groups: ldap_system_admin_groups.to_s, } end
[ "def", "to_h", "{", "enable_db_auth", ":", "enable_db_auth?", ",", "enable_ldap_auth", ":", "enable_ldap_auth?", ",", "ldap_host", ":", "ldap_host", ".", "to_s", ",", "ldap_port", ":", "ldap_port", ".", "to_s", ".", "to_i", ",", "ldap_ssl", ":", "ldap_ssl?", ",", "ldap_base_dn", ":", "ldap_base_dn", ".", "to_s", ",", "ldap_browse_user", ":", "ldap_browse_user", ".", "to_s", ",", "ldap_browse_password", ":", "ldap_browse_password", ".", "to_s", ",", "ldap_auto_activate", ":", "ldap_auto_activate?", ",", "ldap_system_admin_groups", ":", "ldap_system_admin_groups", ".", "to_s", ",", "}", "end" ]
Converts the configuration to a hash.
[ "Converts", "the", "configuration", "to", "a", "hash", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/auth_config.rb#L67-L80
6,132
nrser/nrser.rb
lib/nrser/message.rb
NRSER.Message.send_to
def send_to receiver, publicly: true if publicly receiver.public_send symbol, *args, &block else receiver.send symbol, *args, &block end end
ruby
def send_to receiver, publicly: true if publicly receiver.public_send symbol, *args, &block else receiver.send symbol, *args, &block end end
[ "def", "send_to", "receiver", ",", "publicly", ":", "true", "if", "publicly", "receiver", ".", "public_send", "symbol", ",", "args", ",", "block", "else", "receiver", ".", "send", "symbol", ",", "args", ",", "block", "end", "end" ]
Send this instance to a receiver object. @example msg.send_to obj @param [Object] receiver Object that the message will be sent to. @param [Boolean] publicly When `true`, the message will be sent via {Object#public_send}. This is the default behavior. When `false`, the message will be sent via {Object#send}, allowing it to invoke private and protected methods on the receiver. @return [Object] Result of the method call.
[ "Send", "this", "instance", "to", "a", "receiver", "object", "." ]
7db9a729ec65894dfac13fd50851beae8b809738
https://github.com/nrser/nrser.rb/blob/7db9a729ec65894dfac13fd50851beae8b809738/lib/nrser/message.rb#L159-L165
6,133
coralnexus/nucleon
lib/core/core.rb
Nucleon.Core.logger=
def logger=logger Util::Logger.loggers.delete(self.logger.resource) if self.logger if logger.is_a?(Util::Logger) @logger = logger else @logger = Util::Logger.new(logger) end end
ruby
def logger=logger Util::Logger.loggers.delete(self.logger.resource) if self.logger if logger.is_a?(Util::Logger) @logger = logger else @logger = Util::Logger.new(logger) end end
[ "def", "logger", "=", "logger", "Util", "::", "Logger", ".", "loggers", ".", "delete", "(", "self", ".", "logger", ".", "resource", ")", "if", "self", ".", "logger", "if", "logger", ".", "is_a?", "(", "Util", "::", "Logger", ")", "@logger", "=", "logger", "else", "@logger", "=", "Util", "::", "Logger", ".", "new", "(", "logger", ")", "end", "end" ]
Set current object logger instance * *Parameters* - [String, Nucleon::Util::Logger] *logger* Logger instance or resource name for new logger * *Returns* - [Void] This method does not return a value * *Errors* See also: - Nucleon::Util::Logger::loggers - Nucleon::Util::Logger::new
[ "Set", "current", "object", "logger", "instance" ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/core.rb#L153-L161
6,134
coralnexus/nucleon
lib/core/core.rb
Nucleon.Core.ui=
def ui=ui if ui.is_a?(Util::Console) @ui = ui else @ui = Util::Console.new(ui) end end
ruby
def ui=ui if ui.is_a?(Util::Console) @ui = ui else @ui = Util::Console.new(ui) end end
[ "def", "ui", "=", "ui", "if", "ui", ".", "is_a?", "(", "Util", "::", "Console", ")", "@ui", "=", "ui", "else", "@ui", "=", "Util", "::", "Console", ".", "new", "(", "ui", ")", "end", "end" ]
Set current object console instance * *Parameters* - [String, Nucleon::Util::Console] *ui* Console instance or resource name for new console * *Returns* - [Void] This method does not return a value * *Errors* See also: - Nucleon::Util::Console::new
[ "Set", "current", "object", "console", "instance" ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/core.rb#L192-L198
6,135
coralnexus/nucleon
lib/core/core.rb
Nucleon.Core.ui_group
def ui_group(resource, color = :cyan) # :yields: ui ui_resource = ui.resource ui.resource = Util::Console.colorize(resource, color) yield(ui) ensure ui.resource = ui_resource end
ruby
def ui_group(resource, color = :cyan) # :yields: ui ui_resource = ui.resource ui.resource = Util::Console.colorize(resource, color) yield(ui) ensure ui.resource = ui_resource end
[ "def", "ui_group", "(", "resource", ",", "color", "=", ":cyan", ")", "# :yields: ui", "ui_resource", "=", "ui", ".", "resource", "ui", ".", "resource", "=", "Util", "::", "Console", ".", "colorize", "(", "resource", ",", "color", ")", "yield", "(", "ui", ")", "ensure", "ui", ".", "resource", "=", "ui_resource", "end" ]
Contextualize console operations in a code block with a given resource name. * *Parameters* - [String, Symbol] *resource* Console resource identifier (prefix) - [Symbol] *color* Color to use; *:black*, *:red*, *:green*, *:yellow*, *:blue*, *:purple*, *:cyan*, *:grey* * *Returns* - [Void] This method does not return a value * *Errors* * *Yields* - [Nucleon::Util::Console] *ui* Current object console instance See also: - Nucleon::Util::Console::colorize
[ "Contextualize", "console", "operations", "in", "a", "code", "block", "with", "a", "given", "resource", "name", "." ]
3a3c489251139c184e0884feaa55269cf64cad44
https://github.com/coralnexus/nucleon/blob/3a3c489251139c184e0884feaa55269cf64cad44/lib/core/core.rb#L252-L259
6,136
DigitPaint/html_mockup
lib/html_mockup/release.rb
HtmlMockup.Release.log
def log(part, msg, verbose = false, &block) if !verbose || verbose && self.project.options[:verbose] self.project.shell.say "\033[37m#{part.class.to_s}\033[0m" + " : " + msg.to_s, nil, true end if block_given? begin self.project.shell.padding = self.project.shell.padding + 1 yield ensure self.project.shell.padding = self.project.shell.padding - 1 end end end
ruby
def log(part, msg, verbose = false, &block) if !verbose || verbose && self.project.options[:verbose] self.project.shell.say "\033[37m#{part.class.to_s}\033[0m" + " : " + msg.to_s, nil, true end if block_given? begin self.project.shell.padding = self.project.shell.padding + 1 yield ensure self.project.shell.padding = self.project.shell.padding - 1 end end end
[ "def", "log", "(", "part", ",", "msg", ",", "verbose", "=", "false", ",", "&", "block", ")", "if", "!", "verbose", "||", "verbose", "&&", "self", ".", "project", ".", "options", "[", ":verbose", "]", "self", ".", "project", ".", "shell", ".", "say", "\"\\033[37m#{part.class.to_s}\\033[0m\"", "+", "\" : \"", "+", "msg", ".", "to_s", ",", "nil", ",", "true", "end", "if", "block_given?", "begin", "self", ".", "project", ".", "shell", ".", "padding", "=", "self", ".", "project", ".", "shell", ".", "padding", "+", "1", "yield", "ensure", "self", ".", "project", ".", "shell", ".", "padding", "=", "self", ".", "project", ".", "shell", ".", "padding", "-", "1", "end", "end", "end" ]
Write out a log message
[ "Write", "out", "a", "log", "message" ]
976edadc01216b82a8cea177f53fb32559eaf41e
https://github.com/DigitPaint/html_mockup/blob/976edadc01216b82a8cea177f53fb32559eaf41e/lib/html_mockup/release.rb#L223-L235
6,137
DigitPaint/html_mockup
lib/html_mockup/release.rb
HtmlMockup.Release.validate_stack!
def validate_stack! mockup_options = {} relativizer_options = {} run_relativizer = true if @extractor_options mockup_options = {:env => @extractor_options[:env]} relativizer_options = {:url_attributes => @extractor_options[:url_attributes]} run_relativizer = @extractor_options[:url_relativize] end unless @stack.find{|(processor, options)| processor.class == HtmlMockup::Release::Processors::Mockup } @stack.unshift([HtmlMockup::Release::Processors::UrlRelativizer.new, relativizer_options]) @stack.unshift([HtmlMockup::Release::Processors::Mockup.new, mockup_options]) end end
ruby
def validate_stack! mockup_options = {} relativizer_options = {} run_relativizer = true if @extractor_options mockup_options = {:env => @extractor_options[:env]} relativizer_options = {:url_attributes => @extractor_options[:url_attributes]} run_relativizer = @extractor_options[:url_relativize] end unless @stack.find{|(processor, options)| processor.class == HtmlMockup::Release::Processors::Mockup } @stack.unshift([HtmlMockup::Release::Processors::UrlRelativizer.new, relativizer_options]) @stack.unshift([HtmlMockup::Release::Processors::Mockup.new, mockup_options]) end end
[ "def", "validate_stack!", "mockup_options", "=", "{", "}", "relativizer_options", "=", "{", "}", "run_relativizer", "=", "true", "if", "@extractor_options", "mockup_options", "=", "{", ":env", "=>", "@extractor_options", "[", ":env", "]", "}", "relativizer_options", "=", "{", ":url_attributes", "=>", "@extractor_options", "[", ":url_attributes", "]", "}", "run_relativizer", "=", "@extractor_options", "[", ":url_relativize", "]", "end", "unless", "@stack", ".", "find", "{", "|", "(", "processor", ",", "options", ")", "|", "processor", ".", "class", "==", "HtmlMockup", "::", "Release", "::", "Processors", "::", "Mockup", "}", "@stack", ".", "unshift", "(", "[", "HtmlMockup", "::", "Release", "::", "Processors", "::", "UrlRelativizer", ".", "new", ",", "relativizer_options", "]", ")", "@stack", ".", "unshift", "(", "[", "HtmlMockup", "::", "Release", "::", "Processors", "::", "Mockup", ".", "new", ",", "mockup_options", "]", ")", "end", "end" ]
Checks if deprecated extractor options have been set Checks if the mockup will be runned
[ "Checks", "if", "deprecated", "extractor", "options", "have", "been", "set", "Checks", "if", "the", "mockup", "will", "be", "runned" ]
976edadc01216b82a8cea177f53fb32559eaf41e
https://github.com/DigitPaint/html_mockup/blob/976edadc01216b82a8cea177f53fb32559eaf41e/lib/html_mockup/release.rb#L280-L295
6,138
riddopic/garcun
lib/garcon/task/priority_queue.rb
Garcon.MutexPriorityQueue.delete
def delete(item) original_length = @length k = 1 while k <= @length if @queue[k] == item swap(k, @length) @length -= 1 sink(k) @queue.pop else k += 1 end end @length != original_length end
ruby
def delete(item) original_length = @length k = 1 while k <= @length if @queue[k] == item swap(k, @length) @length -= 1 sink(k) @queue.pop else k += 1 end end @length != original_length end
[ "def", "delete", "(", "item", ")", "original_length", "=", "@length", "k", "=", "1", "while", "k", "<=", "@length", "if", "@queue", "[", "k", "]", "==", "item", "swap", "(", "k", ",", "@length", ")", "@length", "-=", "1", "sink", "(", "k", ")", "@queue", ".", "pop", "else", "k", "+=", "1", "end", "end", "@length", "!=", "original_length", "end" ]
Deletes all items from `self` that are equal to `item`. @param [Object] item The item to be removed from the queue. @return [Object] True if the item is found else false.
[ "Deletes", "all", "items", "from", "self", "that", "are", "equal", "to", "item", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/priority_queue.rb#L63-L77
6,139
riddopic/garcun
lib/garcon/task/priority_queue.rb
Garcon.MutexPriorityQueue.sink
def sink(k) while (j = (2 * k)) <= @length do j += 1 if j < @length && ! ordered?(j, j+1) break if ordered?(k, j) swap(k, j) k = j end end
ruby
def sink(k) while (j = (2 * k)) <= @length do j += 1 if j < @length && ! ordered?(j, j+1) break if ordered?(k, j) swap(k, j) k = j end end
[ "def", "sink", "(", "k", ")", "while", "(", "j", "=", "(", "2", "*", "k", ")", ")", "<=", "@length", "do", "j", "+=", "1", "if", "j", "<", "@length", "&&", "!", "ordered?", "(", "j", ",", "j", "+", "1", ")", "break", "if", "ordered?", "(", "k", ",", "j", ")", "swap", "(", "k", ",", "j", ")", "k", "=", "j", "end", "end" ]
Percolate down to maintain heap invariant. @param [Integer] k The index at which to start the percolation. @!visibility private
[ "Percolate", "down", "to", "maintain", "heap", "invariant", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/priority_queue.rb#L210-L217
6,140
riddopic/garcun
lib/garcon/task/priority_queue.rb
Garcon.MutexPriorityQueue.swim
def swim(k) while k > 1 && ! ordered?(k/2, k) do swap(k, k/2) k = k/2 end end
ruby
def swim(k) while k > 1 && ! ordered?(k/2, k) do swap(k, k/2) k = k/2 end end
[ "def", "swim", "(", "k", ")", "while", "k", ">", "1", "&&", "!", "ordered?", "(", "k", "/", "2", ",", "k", ")", "do", "swap", "(", "k", ",", "k", "/", "2", ")", "k", "=", "k", "/", "2", "end", "end" ]
Percolate up to maintain heap invariant. @param [Integer] k The index at which to start the percolation. @!visibility private
[ "Percolate", "up", "to", "maintain", "heap", "invariant", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/priority_queue.rb#L225-L230
6,141
devnull-tools/yummi
lib/yummi/text_box.rb
Yummi.TextBox.add
def add (obj, params = {}) text = obj.to_s params = { :width => style.width, :align => style.align }.merge! params if params[:width] width = params[:width] words = text.gsub($/, ' ').split(' ') unless params[:raw] words ||= [text] buff = '' words.each do |word| # go to next line if the current word blows up the width limit if buff.size + word.size >= width and not buff.empty? _add_ buff, params buff = '' end buff << ' ' unless buff.empty? buff << word end unless buff.empty? _add_ buff, params end else text.each_line do |line| _add_ line, params end end end
ruby
def add (obj, params = {}) text = obj.to_s params = { :width => style.width, :align => style.align }.merge! params if params[:width] width = params[:width] words = text.gsub($/, ' ').split(' ') unless params[:raw] words ||= [text] buff = '' words.each do |word| # go to next line if the current word blows up the width limit if buff.size + word.size >= width and not buff.empty? _add_ buff, params buff = '' end buff << ' ' unless buff.empty? buff << word end unless buff.empty? _add_ buff, params end else text.each_line do |line| _add_ line, params end end end
[ "def", "add", "(", "obj", ",", "params", "=", "{", "}", ")", "text", "=", "obj", ".", "to_s", "params", "=", "{", ":width", "=>", "style", ".", "width", ",", ":align", "=>", "style", ".", "align", "}", ".", "merge!", "params", "if", "params", "[", ":width", "]", "width", "=", "params", "[", ":width", "]", "words", "=", "text", ".", "gsub", "(", "$/", ",", "' '", ")", ".", "split", "(", "' '", ")", "unless", "params", "[", ":raw", "]", "words", "||=", "[", "text", "]", "buff", "=", "''", "words", ".", "each", "do", "|", "word", "|", "# go to next line if the current word blows up the width limit", "if", "buff", ".", "size", "+", "word", ".", "size", ">=", "width", "and", "not", "buff", ".", "empty?", "_add_", "buff", ",", "params", "buff", "=", "''", "end", "buff", "<<", "' '", "unless", "buff", ".", "empty?", "buff", "<<", "word", "end", "unless", "buff", ".", "empty?", "_add_", "buff", ",", "params", "end", "else", "text", ".", "each_line", "do", "|", "line", "|", "_add_", "line", ",", "params", "end", "end", "end" ]
Adds a line text to this box === Args +obj+:: The obj to add (will be converted to string). +params+:: A hash of parameters. Currently supported are: color: the text color (see #Yummi#COLORS) width: the text maximum width. Set this to break the lines automatically. If the #width is set, this will override the box width for this lines. raw: if true, the entire text will be used as one word to align the text. align: the text alignment (see #Yummi#Aligner)
[ "Adds", "a", "line", "text", "to", "this", "box" ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/text_box.rb#L97-L125
6,142
devnull-tools/yummi
lib/yummi/text_box.rb
Yummi.TextBox.separator
def separator (params = {}) params = style.separator.merge params params[:width] ||= style.width raise Exception::new('Define a width for using separators') unless params[:width] line = fill(params[:pattern], params[:width]) #replace the width with the box width to align the separator params[:width] = style.width add line, params end
ruby
def separator (params = {}) params = style.separator.merge params params[:width] ||= style.width raise Exception::new('Define a width for using separators') unless params[:width] line = fill(params[:pattern], params[:width]) #replace the width with the box width to align the separator params[:width] = style.width add line, params end
[ "def", "separator", "(", "params", "=", "{", "}", ")", "params", "=", "style", ".", "separator", ".", "merge", "params", "params", "[", ":width", "]", "||=", "style", ".", "width", "raise", "Exception", "::", "new", "(", "'Define a width for using separators'", ")", "unless", "params", "[", ":width", "]", "line", "=", "fill", "(", "params", "[", ":pattern", "]", ",", "params", "[", ":width", "]", ")", "#replace the width with the box width to align the separator", "params", "[", ":width", "]", "=", "style", ".", "width", "add", "line", ",", "params", "end" ]
Adds a line separator. === Args +params+:: A hash of parameters. Currently supported are: pattern: the pattern to build the line color: the separator color (see #Yummi#COLORS) width: the separator width (#self#width will be used if unset) align: the separator alignment (see #Yummi#Aligner)
[ "Adds", "a", "line", "separator", "." ]
b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df
https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/text_box.rb#L147-L155
6,143
kukushkin/aerogel-core
lib/aerogel/core/render/block_helper.rb
Aerogel::Render.BlockHelper.render
def render content = output_capture(@block) do instance_exec( *@args, &@block ) end content_wrapped = output_capture() { wrap( content ) } output_concat content_wrapped end
ruby
def render content = output_capture(@block) do instance_exec( *@args, &@block ) end content_wrapped = output_capture() { wrap( content ) } output_concat content_wrapped end
[ "def", "render", "content", "=", "output_capture", "(", "@block", ")", "do", "instance_exec", "(", "@args", ",", "@block", ")", "end", "content_wrapped", "=", "output_capture", "(", ")", "{", "wrap", "(", "content", ")", "}", "output_concat", "content_wrapped", "end" ]
Renders output to the template or returns it as a string.
[ "Renders", "output", "to", "the", "template", "or", "returns", "it", "as", "a", "string", "." ]
e156af6b237c410c1ee75e5cdf1b10075e7fbb8b
https://github.com/kukushkin/aerogel-core/blob/e156af6b237c410c1ee75e5cdf1b10075e7fbb8b/lib/aerogel/core/render/block_helper.rb#L32-L38
6,144
barkerest/incline
lib/incline/extensions/application.rb
Incline::Extensions.Application.app_instance_name
def app_instance_name @app_instance_name ||= begin yaml = Rails.root.join('config','instance.yml') if File.exist?(yaml) yaml = (YAML.load(ERB.new(File.read(yaml)).result) || {}).symbolize_keys yaml[:name].blank? ? 'default' : yaml[:name] else 'default' end end end
ruby
def app_instance_name @app_instance_name ||= begin yaml = Rails.root.join('config','instance.yml') if File.exist?(yaml) yaml = (YAML.load(ERB.new(File.read(yaml)).result) || {}).symbolize_keys yaml[:name].blank? ? 'default' : yaml[:name] else 'default' end end end
[ "def", "app_instance_name", "@app_instance_name", "||=", "begin", "yaml", "=", "Rails", ".", "root", ".", "join", "(", "'config'", ",", "'instance.yml'", ")", "if", "File", ".", "exist?", "(", "yaml", ")", "yaml", "=", "(", "YAML", ".", "load", "(", "ERB", ".", "new", "(", "File", ".", "read", "(", "yaml", ")", ")", ".", "result", ")", "||", "{", "}", ")", ".", "symbolize_keys", "yaml", "[", ":name", "]", ".", "blank?", "?", "'default'", ":", "yaml", "[", ":name", "]", "else", "'default'", "end", "end", "end" ]
Gets the application instance name. This can be set by creating a +config/instance.yml+ configuration file and setting the 'name' property. The instance name is used to create unique cookies for each instance of an application. The default instance name is 'default'.
[ "Gets", "the", "application", "instance", "name", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/application.rb#L46-L57
6,145
barkerest/incline
lib/incline/extensions/application.rb
Incline::Extensions.Application.restart_pending?
def restart_pending? return false unless File.exist?(restart_file) request_time = File.mtime(restart_file) request_time > Incline.start_time end
ruby
def restart_pending? return false unless File.exist?(restart_file) request_time = File.mtime(restart_file) request_time > Incline.start_time end
[ "def", "restart_pending?", "return", "false", "unless", "File", ".", "exist?", "(", "restart_file", ")", "request_time", "=", "File", ".", "mtime", "(", "restart_file", ")", "request_time", ">", "Incline", ".", "start_time", "end" ]
Is a restart currently pending.
[ "Is", "a", "restart", "currently", "pending", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/application.rb#L103-L107
6,146
barkerest/incline
lib/incline/extensions/application.rb
Incline::Extensions.Application.request_restart!
def request_restart! Incline::Log::info 'Requesting an application restart.' FileUtils.touch restart_file File.mtime restart_file end
ruby
def request_restart! Incline::Log::info 'Requesting an application restart.' FileUtils.touch restart_file File.mtime restart_file end
[ "def", "request_restart!", "Incline", "::", "Log", "::", "info", "'Requesting an application restart.'", "FileUtils", ".", "touch", "restart_file", "File", ".", "mtime", "restart_file", "end" ]
Updates the restart file to indicate we want to restart the web app.
[ "Updates", "the", "restart", "file", "to", "indicate", "we", "want", "to", "restart", "the", "web", "app", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/extensions/application.rb#L111-L115
6,147
mbj/ducktrap
lib/ducktrap/formatter.rb
Ducktrap.Formatter.nest
def nest(label, nested) indented = indent indented.puts("#{label}:") nested.pretty_dump(indented.indent) self end
ruby
def nest(label, nested) indented = indent indented.puts("#{label}:") nested.pretty_dump(indented.indent) self end
[ "def", "nest", "(", "label", ",", "nested", ")", "indented", "=", "indent", "indented", ".", "puts", "(", "\"#{label}:\"", ")", "nested", ".", "pretty_dump", "(", "indented", ".", "indent", ")", "self", "end" ]
Write nest with label @param [String] label @param [#pretty_dump] nested @return [self] @api private
[ "Write", "nest", "with", "label" ]
482d874d3eb43b2dbb518b8537851d742d785903
https://github.com/mbj/ducktrap/blob/482d874d3eb43b2dbb518b8537851d742d785903/lib/ducktrap/formatter.rb#L58-L63
6,148
mbj/ducktrap
lib/ducktrap/formatter.rb
Ducktrap.Formatter.puts
def puts(string) util = output util.write(prefix) util.puts(string) self end
ruby
def puts(string) util = output util.write(prefix) util.puts(string) self end
[ "def", "puts", "(", "string", ")", "util", "=", "output", "util", ".", "write", "(", "prefix", ")", "util", ".", "puts", "(", "string", ")", "self", "end" ]
Write string with indentation @param [String] string @return [self] @api private
[ "Write", "string", "with", "indentation" ]
482d874d3eb43b2dbb518b8537851d742d785903
https://github.com/mbj/ducktrap/blob/482d874d3eb43b2dbb518b8537851d742d785903/lib/ducktrap/formatter.rb#L104-L109
6,149
bmedici/bmc-daemon-lib
lib/bmc-daemon-lib/logger.rb
BmcDaemonLib.Logger.build_context
def build_context context # Skip if no format defined return unless @format[:context].is_a? Hash # Call the instance's method to get hash context return unless context.is_a? Hash # Build each context part return @format[:context].collect do |key, format| sprintf(format, context[key]) end.join rescue KeyError, ArgumentError => ex return "[context: #{ex.message}]" end
ruby
def build_context context # Skip if no format defined return unless @format[:context].is_a? Hash # Call the instance's method to get hash context return unless context.is_a? Hash # Build each context part return @format[:context].collect do |key, format| sprintf(format, context[key]) end.join rescue KeyError, ArgumentError => ex return "[context: #{ex.message}]" end
[ "def", "build_context", "context", "# Skip if no format defined", "return", "unless", "@format", "[", ":context", "]", ".", "is_a?", "Hash", "# Call the instance's method to get hash context", "return", "unless", "context", ".", "is_a?", "Hash", "# Build each context part", "return", "@format", "[", ":context", "]", ".", "collect", "do", "|", "key", ",", "format", "|", "sprintf", "(", "format", ",", "context", "[", "key", "]", ")", "end", ".", "join", "rescue", "KeyError", ",", "ArgumentError", "=>", "ex", "return", "\"[context: #{ex.message}]\"", "end" ]
Builds prefix from @format[:context] and context
[ "Builds", "prefix", "from" ]
63682b875adecde960691d8a1dfbade06cf8d1ab
https://github.com/bmedici/bmc-daemon-lib/blob/63682b875adecde960691d8a1dfbade06cf8d1ab/lib/bmc-daemon-lib/logger.rb#L104-L118
6,150
tatey/simple_mock
lib/simple_mock/mock_delegator.rb
SimpleMock.MockDelegator.expect
def expect name, retval, args = [] method_definition = Module.new do define_method name do |*args, &block| __tracer.assert name, args retval end end extend method_definition __tracer.register name, args self end
ruby
def expect name, retval, args = [] method_definition = Module.new do define_method name do |*args, &block| __tracer.assert name, args retval end end extend method_definition __tracer.register name, args self end
[ "def", "expect", "name", ",", "retval", ",", "args", "=", "[", "]", "method_definition", "=", "Module", ".", "new", "do", "define_method", "name", "do", "|", "*", "args", ",", "&", "block", "|", "__tracer", ".", "assert", "name", ",", "args", "retval", "end", "end", "extend", "method_definition", "__tracer", ".", "register", "name", ",", "args", "self", "end" ]
Expect that method +name+ is called, optionally with +args+, and returns +retval+. mock.expect :meaning_of_life, 42 mock.meaning_of_life # => 42 mock.expect :do_something_with, true, [some_obj, true] mock.do_something_with some_obj, true # => true +args+ is compared to the expected args using case equality (ie, the '===' method), allowing for less specific expectations. mock.expect :uses_any_string, true, [String] mock.uses_any_string 'foo' # => true mock.verify # => true mock.expect :uses_one_string, true, ['foo'] mock.uses_one_string 'bar' # => true mock.verify # => raises MockExpectationError
[ "Expect", "that", "method", "+", "name", "+", "is", "called", "optionally", "with", "+", "args", "+", "and", "returns", "+", "retval", "+", "." ]
3081f714228903745d66f32cc6186946a9f2524e
https://github.com/tatey/simple_mock/blob/3081f714228903745d66f32cc6186946a9f2524e/lib/simple_mock/mock_delegator.rb#L33-L43
6,151
cknadler/rcomp
lib/rcomp/reporter.rb
RComp.Reporter.report
def report(test) case test.result when :success if @type == :test print_test_success(test) else print_generate_success(test) end @success += 1 when :skipped if @type == :test print_test_skipped(test) else print_generate_skipped(test) end @skipped += 1 # Generate can't fail directly when :failed print_test_failed(test) @failed += 1 when :timedout if @type == :test print_test_timeout(test) else print_generate_timeout(test) end @failed += 1 end end
ruby
def report(test) case test.result when :success if @type == :test print_test_success(test) else print_generate_success(test) end @success += 1 when :skipped if @type == :test print_test_skipped(test) else print_generate_skipped(test) end @skipped += 1 # Generate can't fail directly when :failed print_test_failed(test) @failed += 1 when :timedout if @type == :test print_test_timeout(test) else print_generate_timeout(test) end @failed += 1 end end
[ "def", "report", "(", "test", ")", "case", "test", ".", "result", "when", ":success", "if", "@type", "==", ":test", "print_test_success", "(", "test", ")", "else", "print_generate_success", "(", "test", ")", "end", "@success", "+=", "1", "when", ":skipped", "if", "@type", "==", ":test", "print_test_skipped", "(", "test", ")", "else", "print_generate_skipped", "(", "test", ")", "end", "@skipped", "+=", "1", "# Generate can't fail directly", "when", ":failed", "print_test_failed", "(", "test", ")", "@failed", "+=", "1", "when", ":timedout", "if", "@type", "==", ":test", "print_test_timeout", "(", "test", ")", "else", "print_generate_timeout", "(", "test", ")", "end", "@failed", "+=", "1", "end", "end" ]
Initialize a new Reporter type - The type (Symbol) of the suite Initialize counters for all result types Main interface for reporting Reports the result of a single test or generation test - A test object that has been run Returns nothing
[ "Initialize", "a", "new", "Reporter" ]
76fe71e1ef3b13923738ea6ab9cd502fe2f64f51
https://github.com/cknadler/rcomp/blob/76fe71e1ef3b13923738ea6ab9cd502fe2f64f51/lib/rcomp/reporter.rb#L31-L62
6,152
ritxi/sermepa_web_tpv
lib/sermepa_web_tpv/request.rb
SermepaWebTpv.Request.url_for
def url_for(option) host = SermepaWebTpv.response_host path = SermepaWebTpv.send(option) return if !host.present? || !path.present? URI.join(host, path).to_s end
ruby
def url_for(option) host = SermepaWebTpv.response_host path = SermepaWebTpv.send(option) return if !host.present? || !path.present? URI.join(host, path).to_s end
[ "def", "url_for", "(", "option", ")", "host", "=", "SermepaWebTpv", ".", "response_host", "path", "=", "SermepaWebTpv", ".", "send", "(", "option", ")", "return", "if", "!", "host", ".", "present?", "||", "!", "path", ".", "present?", "URI", ".", "join", "(", "host", ",", "path", ")", ".", "to_s", "end" ]
Available options redirect_success_path redirect_failure_path callback_response_path
[ "Available", "options", "redirect_success_path", "redirect_failure_path", "callback_response_path" ]
a923d1668ad1ce161896eb8e0fe32082ee969399
https://github.com/ritxi/sermepa_web_tpv/blob/a923d1668ad1ce161896eb8e0fe32082ee969399/lib/sermepa_web_tpv/request.rb#L61-L67
6,153
premist/motion-locman
lib/locman/manager.rb
Locman.Manager.background=
def background=(background) if !background.is_a?(TrueClass) && !background.is_a?(FalseClass) fail(ArgumentError, "Background should be boolean") end manager.allowsBackgroundLocationUpdates = background @background = background end
ruby
def background=(background) if !background.is_a?(TrueClass) && !background.is_a?(FalseClass) fail(ArgumentError, "Background should be boolean") end manager.allowsBackgroundLocationUpdates = background @background = background end
[ "def", "background", "=", "(", "background", ")", "if", "!", "background", ".", "is_a?", "(", "TrueClass", ")", "&&", "!", "background", ".", "is_a?", "(", "FalseClass", ")", "fail", "(", "ArgumentError", ",", "\"Background should be boolean\"", ")", "end", "manager", ".", "allowsBackgroundLocationUpdates", "=", "background", "@background", "=", "background", "end" ]
Sets whether location should be updated on the background or not.
[ "Sets", "whether", "location", "should", "be", "updated", "on", "the", "background", "or", "not", "." ]
edf8853b16c4bcbddb103b0aa0cec6517256574a
https://github.com/premist/motion-locman/blob/edf8853b16c4bcbddb103b0aa0cec6517256574a/lib/locman/manager.rb#L73-L80
6,154
wedesoft/multiarray
lib/multiarray/methods.rb
Hornetseye.Methods.define_unary_method
def define_unary_method( mod, op, conversion = :identity ) mod.module_eval do define_method "#{op}_with_hornetseye" do |a| if a.matched? if a.dimension == 0 and a.variables.empty? target = a.typecode.send conversion target.new mod.send( op, a.simplify.get ) else Hornetseye::ElementWise( proc { |x| mod.send op, x }, "#{mod}.#{op}", proc { |x| x.send conversion } ). new(a).force end else send "#{op}_without_hornetseye", a end end alias_method_chain op, :hornetseye module_function "#{op}_without_hornetseye" module_function op end end
ruby
def define_unary_method( mod, op, conversion = :identity ) mod.module_eval do define_method "#{op}_with_hornetseye" do |a| if a.matched? if a.dimension == 0 and a.variables.empty? target = a.typecode.send conversion target.new mod.send( op, a.simplify.get ) else Hornetseye::ElementWise( proc { |x| mod.send op, x }, "#{mod}.#{op}", proc { |x| x.send conversion } ). new(a).force end else send "#{op}_without_hornetseye", a end end alias_method_chain op, :hornetseye module_function "#{op}_without_hornetseye" module_function op end end
[ "def", "define_unary_method", "(", "mod", ",", "op", ",", "conversion", "=", ":identity", ")", "mod", ".", "module_eval", "do", "define_method", "\"#{op}_with_hornetseye\"", "do", "|", "a", "|", "if", "a", ".", "matched?", "if", "a", ".", "dimension", "==", "0", "and", "a", ".", "variables", ".", "empty?", "target", "=", "a", ".", "typecode", ".", "send", "conversion", "target", ".", "new", "mod", ".", "send", "(", "op", ",", "a", ".", "simplify", ".", "get", ")", "else", "Hornetseye", "::", "ElementWise", "(", "proc", "{", "|", "x", "|", "mod", ".", "send", "op", ",", "x", "}", ",", "\"#{mod}.#{op}\"", ",", "proc", "{", "|", "x", "|", "x", ".", "send", "conversion", "}", ")", ".", "new", "(", "a", ")", ".", "force", "end", "else", "send", "\"#{op}_without_hornetseye\"", ",", "a", "end", "end", "alias_method_chain", "op", ",", ":hornetseye", "module_function", "\"#{op}_without_hornetseye\"", "module_function", "op", "end", "end" ]
Extend unary method with capability to handle arrays @param [Module] mod The mathematics module. @param [Symbol,String] op The unary method to extend. @param [Symbol,String] conversion A method for doing the type conversion. @return [Proc] The new method. @private
[ "Extend", "unary", "method", "with", "capability", "to", "handle", "arrays" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/methods.rb#L58-L79
6,155
wedesoft/multiarray
lib/multiarray/methods.rb
Hornetseye.Methods.define_binary_method
def define_binary_method( mod, op, coercion = :coercion ) mod.module_eval do define_method "#{op}_with_hornetseye" do |a,b| if a.matched? or b.matched? a = Node.match(a, b).new a unless a.matched? b = Node.match(b, a).new b unless b.matched? if a.dimension == 0 and a.variables.empty? and b.dimension == 0 and b.variables.empty? target = a.typecode.send coercion, b.typecode target.new mod.send(op, a.simplify.get, b.simplify.get) else Hornetseye::ElementWise( proc { |x,y| mod.send op, x, y }, "#{mod}.#{op}", proc { |t,u| t.send coercion, u } ). new(a, b).force end else send "#{op}_without_hornetseye", a, b end end alias_method_chain op, :hornetseye module_function "#{op}_without_hornetseye" module_function op end end
ruby
def define_binary_method( mod, op, coercion = :coercion ) mod.module_eval do define_method "#{op}_with_hornetseye" do |a,b| if a.matched? or b.matched? a = Node.match(a, b).new a unless a.matched? b = Node.match(b, a).new b unless b.matched? if a.dimension == 0 and a.variables.empty? and b.dimension == 0 and b.variables.empty? target = a.typecode.send coercion, b.typecode target.new mod.send(op, a.simplify.get, b.simplify.get) else Hornetseye::ElementWise( proc { |x,y| mod.send op, x, y }, "#{mod}.#{op}", proc { |t,u| t.send coercion, u } ). new(a, b).force end else send "#{op}_without_hornetseye", a, b end end alias_method_chain op, :hornetseye module_function "#{op}_without_hornetseye" module_function op end end
[ "def", "define_binary_method", "(", "mod", ",", "op", ",", "coercion", "=", ":coercion", ")", "mod", ".", "module_eval", "do", "define_method", "\"#{op}_with_hornetseye\"", "do", "|", "a", ",", "b", "|", "if", "a", ".", "matched?", "or", "b", ".", "matched?", "a", "=", "Node", ".", "match", "(", "a", ",", "b", ")", ".", "new", "a", "unless", "a", ".", "matched?", "b", "=", "Node", ".", "match", "(", "b", ",", "a", ")", ".", "new", "b", "unless", "b", ".", "matched?", "if", "a", ".", "dimension", "==", "0", "and", "a", ".", "variables", ".", "empty?", "and", "b", ".", "dimension", "==", "0", "and", "b", ".", "variables", ".", "empty?", "target", "=", "a", ".", "typecode", ".", "send", "coercion", ",", "b", ".", "typecode", "target", ".", "new", "mod", ".", "send", "(", "op", ",", "a", ".", "simplify", ".", "get", ",", "b", ".", "simplify", ".", "get", ")", "else", "Hornetseye", "::", "ElementWise", "(", "proc", "{", "|", "x", ",", "y", "|", "mod", ".", "send", "op", ",", "x", ",", "y", "}", ",", "\"#{mod}.#{op}\"", ",", "proc", "{", "|", "t", ",", "u", "|", "t", ".", "send", "coercion", ",", "u", "}", ")", ".", "new", "(", "a", ",", "b", ")", ".", "force", "end", "else", "send", "\"#{op}_without_hornetseye\"", ",", "a", ",", "b", "end", "end", "alias_method_chain", "op", ",", ":hornetseye", "module_function", "\"#{op}_without_hornetseye\"", "module_function", "op", "end", "end" ]
Extend binary method with capability to handle arrays @param [Module] mod The mathematics module. @param [Symbol,String] op The binary method to extend. @param [Symbol,String] conversion A method for doing the type balancing. @return [Proc] The new method. @private
[ "Extend", "binary", "method", "with", "capability", "to", "handle", "arrays" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/methods.rb#L91-L115
6,156
jinx/core
lib/jinx/import/class_path_modifier.rb
Jinx.ClassPathModifier.expand_to_class_path
def expand_to_class_path(path) # the path separator sep = path[WINDOWS_PATH_SEP] ? WINDOWS_PATH_SEP : UNIX_PATH_SEP # the path directories dirs = path.split(sep).map { |dir| File.expand_path(dir) } expanded = expand_jars(dirs) expanded.each { |dir| add_to_classpath(dir) } end
ruby
def expand_to_class_path(path) # the path separator sep = path[WINDOWS_PATH_SEP] ? WINDOWS_PATH_SEP : UNIX_PATH_SEP # the path directories dirs = path.split(sep).map { |dir| File.expand_path(dir) } expanded = expand_jars(dirs) expanded.each { |dir| add_to_classpath(dir) } end
[ "def", "expand_to_class_path", "(", "path", ")", "# the path separator", "sep", "=", "path", "[", "WINDOWS_PATH_SEP", "]", "?", "WINDOWS_PATH_SEP", ":", "UNIX_PATH_SEP", "# the path directories", "dirs", "=", "path", ".", "split", "(", "sep", ")", ".", "map", "{", "|", "dir", "|", "File", ".", "expand_path", "(", "dir", ")", "}", "expanded", "=", "expand_jars", "(", "dirs", ")", "expanded", ".", "each", "{", "|", "dir", "|", "add_to_classpath", "(", "dir", ")", "}", "end" ]
Adds the directories in the given path and all Java jar files contained in the directories to the Java classpath. @quirk Java The jar files found by this method are added to the classpath in sort order. Java applications usually add jars in sort order. For examle, the Apache Ant directory-based classpath tasks are in sort order, although this is not stipulated in the documentation. Well-behaved Java libraries are not dependent on the sort order of included jar files. For poorly-behaved Java libraries, ensure that the classpath is in the expected order. If the classpath must be in a non-sorted order, then call {#add_to_classpath} on each jar file instead. @param [String] path the colon or semi-colon separated directories
[ "Adds", "the", "directories", "in", "the", "given", "path", "and", "all", "Java", "jar", "files", "contained", "in", "the", "directories", "to", "the", "Java", "classpath", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/import/class_path_modifier.rb#L17-L24
6,157
jinx/core
lib/jinx/import/class_path_modifier.rb
Jinx.ClassPathModifier.add_to_classpath
def add_to_classpath(file) unless File.exist?(file) then logger.warn("File to place on Java classpath does not exist: #{file}") return end if File.extname(file) == '.jar' then # require is preferred to classpath append for a jar file. require file else # A directory must end in a slash since JRuby uses an URLClassLoader. if File.directory?(file) then last = file[-1, 1] if last == "\\" then file = file[0...-1] + '/' elsif last != '/' then file = file + '/' end end # Append the file to the classpath. $CLASSPATH << file end end
ruby
def add_to_classpath(file) unless File.exist?(file) then logger.warn("File to place on Java classpath does not exist: #{file}") return end if File.extname(file) == '.jar' then # require is preferred to classpath append for a jar file. require file else # A directory must end in a slash since JRuby uses an URLClassLoader. if File.directory?(file) then last = file[-1, 1] if last == "\\" then file = file[0...-1] + '/' elsif last != '/' then file = file + '/' end end # Append the file to the classpath. $CLASSPATH << file end end
[ "def", "add_to_classpath", "(", "file", ")", "unless", "File", ".", "exist?", "(", "file", ")", "then", "logger", ".", "warn", "(", "\"File to place on Java classpath does not exist: #{file}\"", ")", "return", "end", "if", "File", ".", "extname", "(", "file", ")", "==", "'.jar'", "then", "# require is preferred to classpath append for a jar file.", "require", "file", "else", "# A directory must end in a slash since JRuby uses an URLClassLoader.", "if", "File", ".", "directory?", "(", "file", ")", "then", "last", "=", "file", "[", "-", "1", ",", "1", "]", "if", "last", "==", "\"\\\\\"", "then", "file", "=", "file", "[", "0", "...", "-", "1", "]", "+", "'/'", "elsif", "last", "!=", "'/'", "then", "file", "=", "file", "+", "'/'", "end", "end", "# Append the file to the classpath.", "$CLASSPATH", "<<", "file", "end", "end" ]
Adds the given jar file or directory to the classpath. @param [String] file the jar file or directory to add
[ "Adds", "the", "given", "jar", "file", "or", "directory", "to", "the", "classpath", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/import/class_path_modifier.rb#L29-L50
6,158
jinx/core
lib/jinx/import/class_path_modifier.rb
Jinx.ClassPathModifier.expand_jars
def expand_jars(directories) # If there are jar files, then the file list is the sorted jar files. # Otherwise, the file list is a singleton directory array. expanded = directories.map do |dir| jars = Dir[File.join(dir , "**", "*.jar")].sort jars.empty? ? [dir] : jars end expanded.flatten end
ruby
def expand_jars(directories) # If there are jar files, then the file list is the sorted jar files. # Otherwise, the file list is a singleton directory array. expanded = directories.map do |dir| jars = Dir[File.join(dir , "**", "*.jar")].sort jars.empty? ? [dir] : jars end expanded.flatten end
[ "def", "expand_jars", "(", "directories", ")", "# If there are jar files, then the file list is the sorted jar files.", "# Otherwise, the file list is a singleton directory array.", "expanded", "=", "directories", ".", "map", "do", "|", "dir", "|", "jars", "=", "Dir", "[", "File", ".", "join", "(", "dir", ",", "\"**\"", ",", "\"*.jar\"", ")", "]", ".", "sort", "jars", ".", "empty?", "?", "[", "dir", "]", ":", "jars", "end", "expanded", ".", "flatten", "end" ]
Expands the given directories to include the contained jar files. If a directory contains jar files, then the jar files are included in the resulting array. Otherwise, the directory itself is included in the resulting array. @param [<String>] directories the directories containing jars to add @return [<String>] each directory or its jars
[ "Expands", "the", "given", "directories", "to", "include", "the", "contained", "jar", "files", ".", "If", "a", "directory", "contains", "jar", "files", "then", "the", "jar", "files", "are", "included", "in", "the", "resulting", "array", ".", "Otherwise", "the", "directory", "itself", "is", "included", "in", "the", "resulting", "array", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/import/class_path_modifier.rb#L67-L75
6,159
robfors/ruby-sumac
lib/sumac/messenger.rb
Sumac.Messenger.validate_message_broker
def validate_message_broker message_broker = @connection.message_broker raise TypeError, "'message_broker' must respond to #close" unless message_broker.respond_to?(:close) raise TypeError, "'message_broker' must respond to #kill" unless message_broker.respond_to?(:kill) raise TypeError, "'message_broker' must respond to #object_request_broker=" unless message_broker.respond_to?(:object_request_broker=) raise TypeError, "'message_broker' must respond to #send" unless message_broker.respond_to?(:send) end
ruby
def validate_message_broker message_broker = @connection.message_broker raise TypeError, "'message_broker' must respond to #close" unless message_broker.respond_to?(:close) raise TypeError, "'message_broker' must respond to #kill" unless message_broker.respond_to?(:kill) raise TypeError, "'message_broker' must respond to #object_request_broker=" unless message_broker.respond_to?(:object_request_broker=) raise TypeError, "'message_broker' must respond to #send" unless message_broker.respond_to?(:send) end
[ "def", "validate_message_broker", "message_broker", "=", "@connection", ".", "message_broker", "raise", "TypeError", ",", "\"'message_broker' must respond to #close\"", "unless", "message_broker", ".", "respond_to?", "(", ":close", ")", "raise", "TypeError", ",", "\"'message_broker' must respond to #kill\"", "unless", "message_broker", ".", "respond_to?", "(", ":kill", ")", "raise", "TypeError", ",", "\"'message_broker' must respond to #object_request_broker=\"", "unless", "message_broker", ".", "respond_to?", "(", ":object_request_broker=", ")", "raise", "TypeError", ",", "\"'message_broker' must respond to #send\"", "unless", "message_broker", ".", "respond_to?", "(", ":send", ")", "end" ]
Validates that the message broker will respond to the necessary methods. @raise [TypeError] if any methods are missing @return [void]
[ "Validates", "that", "the", "message", "broker", "will", "respond", "to", "the", "necessary", "methods", "." ]
524fa68b7d1bb10a74baa69cd594ab2b8cae20a3
https://github.com/robfors/ruby-sumac/blob/524fa68b7d1bb10a74baa69cd594ab2b8cae20a3/lib/sumac/messenger.rb#L63-L69
6,160
bigxiang/bootstrap-component-helper
app/helpers/bootstrap/typography_helper.rb
Bootstrap.TypographyHelper.list
def list(options = {}, &block) builder = List.new(self, options) capture(builder, &block) if block_given? builder.to_s end
ruby
def list(options = {}, &block) builder = List.new(self, options) capture(builder, &block) if block_given? builder.to_s end
[ "def", "list", "(", "options", "=", "{", "}", ",", "&", "block", ")", "builder", "=", "List", ".", "new", "(", "self", ",", "options", ")", "capture", "(", "builder", ",", "block", ")", "if", "block_given?", "builder", ".", "to_s", "end" ]
Typography Headings not implemented Lead not implemented Small not implemented Bold not implemented Italics not implemented muted, text-warning, text-error, text-info, text-success not implemented Abbreviations not implemented Addresses not implemented Blockquotes not implemented Lists Public: Bootstrap Typography List, wraps List class to generate ul or ol tags with html options. options - options can be accepted by ul or ol. :type - unordered, ordered, unstyled. ( default: 'unordered' ) :li_options - common li options in ul ( default: {} ) other options can be accepted by ul or ol. block - yield with List object, used to add li tags into ul or ol. Also can add nested lists. Examples = list(type: 'ordered') do |i| - i.add('line 1') - i.add('line 2') - i.add(link_to('line 3', hello_world_path), class: "li-class") - i.add 'line 4' + list(type: 'unstyled') do |nested_li| - nested_li.add('line 4.1') - nested_li.add('line 4.2') # => <ol> <li>line 1</li> <li>line 2</li> <li class="li-class"> <a href="/hello_world">line 3</a> </li> <li> line 4 <ul class="unstyled"> <li>line 4.1</li> <li>line 4.2</li> </ul> </li> </ol> Returns html content of the list.
[ "Typography", "Headings", "not", "implemented", "Lead", "not", "implemented", "Small", "not", "implemented", "Bold", "not", "implemented", "Italics", "not", "implemented", "muted", "text", "-", "warning", "text", "-", "error", "text", "-", "info", "text", "-", "success", "not", "implemented", "Abbreviations", "not", "implemented", "Addresses", "not", "implemented", "Blockquotes", "not", "implemented", "Lists" ]
e88a243acf6157fdae489af575850862cf08fe0c
https://github.com/bigxiang/bootstrap-component-helper/blob/e88a243acf6157fdae489af575850862cf08fe0c/app/helpers/bootstrap/typography_helper.rb#L100-L104
6,161
renz45/table_me
lib/table_me/table_me_presenter.rb
TableMe.TableMePresenter.set_defaults_for
def set_defaults_for model options[:page] = 1 options[:per_page] ||= 10 options[:name] ||= model.to_s.downcase options[:order] ||= 'created_at ASC' self.name = options[:name] end
ruby
def set_defaults_for model options[:page] = 1 options[:per_page] ||= 10 options[:name] ||= model.to_s.downcase options[:order] ||= 'created_at ASC' self.name = options[:name] end
[ "def", "set_defaults_for", "model", "options", "[", ":page", "]", "=", "1", "options", "[", ":per_page", "]", "||=", "10", "options", "[", ":name", "]", "||=", "model", ".", "to_s", ".", "downcase", "options", "[", ":order", "]", "||=", "'created_at ASC'", "self", ".", "name", "=", "options", "[", ":name", "]", "end" ]
set defaults for options
[ "set", "defaults", "for", "options" ]
a04bd7c26497828b2f8f0178631253b6749025cf
https://github.com/renz45/table_me/blob/a04bd7c26497828b2f8f0178631253b6749025cf/lib/table_me/table_me_presenter.rb#L50-L56
6,162
renz45/table_me
lib/table_me/table_me_presenter.rb
TableMe.TableMePresenter.get_data_for
def get_data_for model model = apply_search_to(model) @data = model.limit(options[:per_page]).offset(start_item).order(options[:order]) options[:total_count] = model.count options[:page_total] = (options[:total_count] / options[:per_page].to_f).ceil end
ruby
def get_data_for model model = apply_search_to(model) @data = model.limit(options[:per_page]).offset(start_item).order(options[:order]) options[:total_count] = model.count options[:page_total] = (options[:total_count] / options[:per_page].to_f).ceil end
[ "def", "get_data_for", "model", "model", "=", "apply_search_to", "(", "model", ")", "@data", "=", "model", ".", "limit", "(", "options", "[", ":per_page", "]", ")", ".", "offset", "(", "start_item", ")", ".", "order", "(", "options", "[", ":order", "]", ")", "options", "[", ":total_count", "]", "=", "model", ".", "count", "options", "[", ":page_total", "]", "=", "(", "options", "[", ":total_count", "]", "/", "options", "[", ":per_page", "]", ".", "to_f", ")", ".", "ceil", "end" ]
make the model queries to pull back the data based on pagination and search results if given
[ "make", "the", "model", "queries", "to", "pull", "back", "the", "data", "based", "on", "pagination", "and", "search", "results", "if", "given" ]
a04bd7c26497828b2f8f0178631253b6749025cf
https://github.com/renz45/table_me/blob/a04bd7c26497828b2f8f0178631253b6749025cf/lib/table_me/table_me_presenter.rb#L59-L66
6,163
raygao/rforce-raygao
wsdl/wsdl.rb
RForce.WSDL.retrieve
def retrieve(fieldList, from, ids) soap.retrieve(Retrieve.new(fieldList, from, ids)).result end
ruby
def retrieve(fieldList, from, ids) soap.retrieve(Retrieve.new(fieldList, from, ids)).result end
[ "def", "retrieve", "(", "fieldList", ",", "from", ",", "ids", ")", "soap", ".", "retrieve", "(", "Retrieve", ".", "new", "(", "fieldList", ",", "from", ",", "ids", ")", ")", ".", "result", "end" ]
Retrieve a list of specific objects
[ "Retrieve", "a", "list", "of", "specific", "objects" ]
21bf35db2844f3e43b1cf8d290bfc0f413384fbf
https://github.com/raygao/rforce-raygao/blob/21bf35db2844f3e43b1cf8d290bfc0f413384fbf/wsdl/wsdl.rb#L86-L88
6,164
delano/familia
lib/familia/redisobject.rb
Familia.RedisObject.rediskey
def rediskey if parent? # We need to check if the parent has a specific suffix # for the case where we have specified one other than :object. suffix = parent.kind_of?(Familia) && parent.class.suffix != :object ? parent.class.suffix : name k = parent.rediskey(name, nil) else k = [name].flatten.compact.join(Familia.delim) end if @opts[:quantize] args = case @opts[:quantize] when Numeric [@opts[:quantize]] # :quantize => 1.minute when Array @opts[:quantize] # :quantize => [1.day, '%m%D'] else [] # :quantize => true end k = [k, qstamp(*args)].join(Familia.delim) end k end
ruby
def rediskey if parent? # We need to check if the parent has a specific suffix # for the case where we have specified one other than :object. suffix = parent.kind_of?(Familia) && parent.class.suffix != :object ? parent.class.suffix : name k = parent.rediskey(name, nil) else k = [name].flatten.compact.join(Familia.delim) end if @opts[:quantize] args = case @opts[:quantize] when Numeric [@opts[:quantize]] # :quantize => 1.minute when Array @opts[:quantize] # :quantize => [1.day, '%m%D'] else [] # :quantize => true end k = [k, qstamp(*args)].join(Familia.delim) end k end
[ "def", "rediskey", "if", "parent?", "# We need to check if the parent has a specific suffix", "# for the case where we have specified one other than :object.", "suffix", "=", "parent", ".", "kind_of?", "(", "Familia", ")", "&&", "parent", ".", "class", ".", "suffix", "!=", ":object", "?", "parent", ".", "class", ".", "suffix", ":", "name", "k", "=", "parent", ".", "rediskey", "(", "name", ",", "nil", ")", "else", "k", "=", "[", "name", "]", ".", "flatten", ".", "compact", ".", "join", "(", "Familia", ".", "delim", ")", "end", "if", "@opts", "[", ":quantize", "]", "args", "=", "case", "@opts", "[", ":quantize", "]", "when", "Numeric", "[", "@opts", "[", ":quantize", "]", "]", "# :quantize => 1.minute", "when", "Array", "@opts", "[", ":quantize", "]", "# :quantize => [1.day, '%m%D']", "else", "[", "]", "# :quantize => true", "end", "k", "=", "[", "k", ",", "qstamp", "(", "args", ")", "]", ".", "join", "(", "Familia", ".", "delim", ")", "end", "k", "end" ]
returns a redis key based on the parent object so it will include the proper index.
[ "returns", "a", "redis", "key", "based", "on", "the", "parent", "object", "so", "it", "will", "include", "the", "proper", "index", "." ]
4ecb29e796c86611c5d37e1924729fb562eeb529
https://github.com/delano/familia/blob/4ecb29e796c86611c5d37e1924729fb562eeb529/lib/familia/redisobject.rb#L160-L181
6,165
JoshMcKin/hot_tub
lib/hot_tub/pool.rb
HotTub.Pool.clean!
def clean! HotTub.logger.info "[HotTub] Cleaning pool #{@name}!" if HotTub.logger @mutex.synchronize do begin @_pool.each do |clnt| clean_client(clnt) end ensure @cond.signal end end nil end
ruby
def clean! HotTub.logger.info "[HotTub] Cleaning pool #{@name}!" if HotTub.logger @mutex.synchronize do begin @_pool.each do |clnt| clean_client(clnt) end ensure @cond.signal end end nil end
[ "def", "clean!", "HotTub", ".", "logger", ".", "info", "\"[HotTub] Cleaning pool #{@name}!\"", "if", "HotTub", ".", "logger", "@mutex", ".", "synchronize", "do", "begin", "@_pool", ".", "each", "do", "|", "clnt", "|", "clean_client", "(", "clnt", ")", "end", "ensure", "@cond", ".", "signal", "end", "end", "nil", "end" ]
Clean all clients currently checked into the pool. Its possible clients may be returned to the pool after cleaning
[ "Clean", "all", "clients", "currently", "checked", "into", "the", "pool", ".", "Its", "possible", "clients", "may", "be", "returned", "to", "the", "pool", "after", "cleaning" ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/pool.rb#L139-L151
6,166
JoshMcKin/hot_tub
lib/hot_tub/pool.rb
HotTub.Pool.drain!
def drain! HotTub.logger.info "[HotTub] Draining pool #{@name}!" if HotTub.logger @mutex.synchronize do begin while clnt = @_pool.pop close_client(clnt) end ensure @_out.clear @_pool.clear @pid = Process.pid @cond.broadcast end end nil end
ruby
def drain! HotTub.logger.info "[HotTub] Draining pool #{@name}!" if HotTub.logger @mutex.synchronize do begin while clnt = @_pool.pop close_client(clnt) end ensure @_out.clear @_pool.clear @pid = Process.pid @cond.broadcast end end nil end
[ "def", "drain!", "HotTub", ".", "logger", ".", "info", "\"[HotTub] Draining pool #{@name}!\"", "if", "HotTub", ".", "logger", "@mutex", ".", "synchronize", "do", "begin", "while", "clnt", "=", "@_pool", ".", "pop", "close_client", "(", "clnt", ")", "end", "ensure", "@_out", ".", "clear", "@_pool", ".", "clear", "@pid", "=", "Process", ".", "pid", "@cond", ".", "broadcast", "end", "end", "nil", "end" ]
Drain the pool of all clients currently checked into the pool. After draining, wake all sleeping threads to allow repopulating the pool or if shutdown allow threads to quickly finish their work Its possible clients may be returned to the pool after cleaning
[ "Drain", "the", "pool", "of", "all", "clients", "currently", "checked", "into", "the", "pool", ".", "After", "draining", "wake", "all", "sleeping", "threads", "to", "allow", "repopulating", "the", "pool", "or", "if", "shutdown", "allow", "threads", "to", "quickly", "finish", "their", "work", "Its", "possible", "clients", "may", "be", "returned", "to", "the", "pool", "after", "cleaning" ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/pool.rb#L157-L172
6,167
JoshMcKin/hot_tub
lib/hot_tub/pool.rb
HotTub.Pool.shutdown!
def shutdown! HotTub.logger.info "[HotTub] Shutting down pool #{@name}!" if HotTub.logger @shutdown = true kill_reaper if @reaper drain! @shutdown = false nil end
ruby
def shutdown! HotTub.logger.info "[HotTub] Shutting down pool #{@name}!" if HotTub.logger @shutdown = true kill_reaper if @reaper drain! @shutdown = false nil end
[ "def", "shutdown!", "HotTub", ".", "logger", ".", "info", "\"[HotTub] Shutting down pool #{@name}!\"", "if", "HotTub", ".", "logger", "@shutdown", "=", "true", "kill_reaper", "if", "@reaper", "drain!", "@shutdown", "=", "false", "nil", "end" ]
Kills the reaper and drains the pool.
[ "Kills", "the", "reaper", "and", "drains", "the", "pool", "." ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/pool.rb#L177-L184
6,168
JoshMcKin/hot_tub
lib/hot_tub/pool.rb
HotTub.Pool.reap!
def reap! HotTub.logger.info "[HotTub] Reaping pool #{@name}!" if HotTub.log_trace? while !@shutdown reaped = nil @mutex.synchronize do begin if _reap? if _dead_clients? reaped = @_out.select { |clnt, thrd| !thrd.alive? }.keys @_out.delete_if { |k,v| reaped.include? k } else reaped = [@_pool.shift] end else reaped = nil end ensure @cond.signal end end if reaped reaped.each do |clnt| close_client(clnt) end else break end end nil end
ruby
def reap! HotTub.logger.info "[HotTub] Reaping pool #{@name}!" if HotTub.log_trace? while !@shutdown reaped = nil @mutex.synchronize do begin if _reap? if _dead_clients? reaped = @_out.select { |clnt, thrd| !thrd.alive? }.keys @_out.delete_if { |k,v| reaped.include? k } else reaped = [@_pool.shift] end else reaped = nil end ensure @cond.signal end end if reaped reaped.each do |clnt| close_client(clnt) end else break end end nil end
[ "def", "reap!", "HotTub", ".", "logger", ".", "info", "\"[HotTub] Reaping pool #{@name}!\"", "if", "HotTub", ".", "log_trace?", "while", "!", "@shutdown", "reaped", "=", "nil", "@mutex", ".", "synchronize", "do", "begin", "if", "_reap?", "if", "_dead_clients?", "reaped", "=", "@_out", ".", "select", "{", "|", "clnt", ",", "thrd", "|", "!", "thrd", ".", "alive?", "}", ".", "keys", "@_out", ".", "delete_if", "{", "|", "k", ",", "v", "|", "reaped", ".", "include?", "k", "}", "else", "reaped", "=", "[", "@_pool", ".", "shift", "]", "end", "else", "reaped", "=", "nil", "end", "ensure", "@cond", ".", "signal", "end", "end", "if", "reaped", "reaped", ".", "each", "do", "|", "clnt", "|", "close_client", "(", "clnt", ")", "end", "else", "break", "end", "end", "nil", "end" ]
Remove and close extra clients Releases mutex each iteration because reaping is a low priority action
[ "Remove", "and", "close", "extra", "clients", "Releases", "mutex", "each", "iteration", "because", "reaping", "is", "a", "low", "priority", "action" ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/pool.rb#L189-L218
6,169
JoshMcKin/hot_tub
lib/hot_tub/pool.rb
HotTub.Pool.push
def push(clnt) if clnt orphaned = false @mutex.synchronize do begin if !@shutdown && @_out.delete(clnt) @_pool << clnt else orphaned = true end ensure @cond.signal end end close_orphan(clnt) if orphaned reap! if @blocking_reap end nil end
ruby
def push(clnt) if clnt orphaned = false @mutex.synchronize do begin if !@shutdown && @_out.delete(clnt) @_pool << clnt else orphaned = true end ensure @cond.signal end end close_orphan(clnt) if orphaned reap! if @blocking_reap end nil end
[ "def", "push", "(", "clnt", ")", "if", "clnt", "orphaned", "=", "false", "@mutex", ".", "synchronize", "do", "begin", "if", "!", "@shutdown", "&&", "@_out", ".", "delete", "(", "clnt", ")", "@_pool", "<<", "clnt", "else", "orphaned", "=", "true", "end", "ensure", "@cond", ".", "signal", "end", "end", "close_orphan", "(", "clnt", ")", "if", "orphaned", "reap!", "if", "@blocking_reap", "end", "nil", "end" ]
Safely add client back to pool, only if that client is registered
[ "Safely", "add", "client", "back", "to", "pool", "only", "if", "that", "client", "is", "registered" ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/pool.rb#L254-L272
6,170
JoshMcKin/hot_tub
lib/hot_tub/pool.rb
HotTub.Pool.pop
def pop alarm = (Time.now + @wait_timeout) clnt = nil dirty = false while !@shutdown raise_alarm if (Time.now > alarm) @mutex.synchronize do begin if clnt = @_pool.pop dirty = true else clnt = _fetch_new(&@client_block) end ensure if clnt _checkout(clnt) @cond.signal else @reaper.wakeup if @reaper && _dead_clients? @cond.wait(@mutex,@wait_timeout) end end end break if clnt end clean_client(clnt) if dirty && clnt clnt end
ruby
def pop alarm = (Time.now + @wait_timeout) clnt = nil dirty = false while !@shutdown raise_alarm if (Time.now > alarm) @mutex.synchronize do begin if clnt = @_pool.pop dirty = true else clnt = _fetch_new(&@client_block) end ensure if clnt _checkout(clnt) @cond.signal else @reaper.wakeup if @reaper && _dead_clients? @cond.wait(@mutex,@wait_timeout) end end end break if clnt end clean_client(clnt) if dirty && clnt clnt end
[ "def", "pop", "alarm", "=", "(", "Time", ".", "now", "+", "@wait_timeout", ")", "clnt", "=", "nil", "dirty", "=", "false", "while", "!", "@shutdown", "raise_alarm", "if", "(", "Time", ".", "now", ">", "alarm", ")", "@mutex", ".", "synchronize", "do", "begin", "if", "clnt", "=", "@_pool", ".", "pop", "dirty", "=", "true", "else", "clnt", "=", "_fetch_new", "(", "@client_block", ")", "end", "ensure", "if", "clnt", "_checkout", "(", "clnt", ")", "@cond", ".", "signal", "else", "@reaper", ".", "wakeup", "if", "@reaper", "&&", "_dead_clients?", "@cond", ".", "wait", "(", "@mutex", ",", "@wait_timeout", ")", "end", "end", "end", "break", "if", "clnt", "end", "clean_client", "(", "clnt", ")", "if", "dirty", "&&", "clnt", "clnt", "end" ]
Safely pull client from pool, adding if allowed If a client is not available, check for dead resources and schedule reap if nesseccary
[ "Safely", "pull", "client", "from", "pool", "adding", "if", "allowed", "If", "a", "client", "is", "not", "available", "check", "for", "dead", "resources", "and", "schedule", "reap", "if", "nesseccary" ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/pool.rb#L277-L304
6,171
JoshMcKin/hot_tub
lib/hot_tub/pool.rb
HotTub.Pool._fetch_new
def _fetch_new(&client_block) if (@never_block || (_total_current_size < @max_size)) if client_block.arity == 0 nc = yield else nc = yield @sessions_key end HotTub.logger.info "[HotTub] Adding client: #{nc.class.name} to #{@name}." if HotTub.log_trace? nc end end
ruby
def _fetch_new(&client_block) if (@never_block || (_total_current_size < @max_size)) if client_block.arity == 0 nc = yield else nc = yield @sessions_key end HotTub.logger.info "[HotTub] Adding client: #{nc.class.name} to #{@name}." if HotTub.log_trace? nc end end
[ "def", "_fetch_new", "(", "&", "client_block", ")", "if", "(", "@never_block", "||", "(", "_total_current_size", "<", "@max_size", ")", ")", "if", "client_block", ".", "arity", "==", "0", "nc", "=", "yield", "else", "nc", "=", "yield", "@sessions_key", "end", "HotTub", ".", "logger", ".", "info", "\"[HotTub] Adding client: #{nc.class.name} to #{@name}.\"", "if", "HotTub", ".", "log_trace?", "nc", "end", "end" ]
Returns a new client if its allowed. _add is volatile; and may cause threading issues if called outside @mutex.synchronize {}
[ "Returns", "a", "new", "client", "if", "its", "allowed", ".", "_add", "is", "volatile", ";", "and", "may", "cause", "threading", "issues", "if", "called", "outside" ]
44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d
https://github.com/JoshMcKin/hot_tub/blob/44f22b0dfbca40bfe7cc4f7e6393122c88d7da0d/lib/hot_tub/pool.rb#L322-L332
6,172
mrackwitz/CLIntegracon
lib/CLIntegracon/diff.rb
CLIntegracon.Diff.each
def each(options = {}, &block) options = { :source => compares_files? ? 'files' : 'strings', :context => 3 }.merge options Diffy::Diff.new(preprocessed_expected.to_s, preprocessed_produced.to_s, options).each &block end
ruby
def each(options = {}, &block) options = { :source => compares_files? ? 'files' : 'strings', :context => 3 }.merge options Diffy::Diff.new(preprocessed_expected.to_s, preprocessed_produced.to_s, options).each &block end
[ "def", "each", "(", "options", "=", "{", "}", ",", "&", "block", ")", "options", "=", "{", ":source", "=>", "compares_files?", "?", "'files'", ":", "'strings'", ",", ":context", "=>", "3", "}", ".", "merge", "options", "Diffy", "::", "Diff", ".", "new", "(", "preprocessed_expected", ".", "to_s", ",", "preprocessed_produced", ".", "to_s", ",", "options", ")", ".", "each", "block", "end" ]
Enumerate all lines which differ. @param [Hash] options see Diffy#initialize for help. @return [Diffy::Diff]
[ "Enumerate", "all", "lines", "which", "differ", "." ]
b675f23762d10e527487aa5576d6a77f9c623485
https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/diff.rb#L84-L90
6,173
nepalez/immutability
lib/immutability.rb
Immutability.ClassMethods.new
def new(*args, &block) instance = allocate.tap { |obj| obj.__send__(:initialize, *args, &block) } IceNine.deep_freeze(instance) end
ruby
def new(*args, &block) instance = allocate.tap { |obj| obj.__send__(:initialize, *args, &block) } IceNine.deep_freeze(instance) end
[ "def", "new", "(", "*", "args", ",", "&", "block", ")", "instance", "=", "allocate", ".", "tap", "{", "|", "obj", "|", "obj", ".", "__send__", "(", ":initialize", ",", "args", ",", "block", ")", "}", "IceNine", ".", "deep_freeze", "(", "instance", ")", "end" ]
Reloads instance's constructor to make it immutable @api private @param [Object, Array<Object>] args @param [Proc] block @return [Object]
[ "Reloads", "instance", "s", "constructor", "to", "make", "it", "immutable" ]
6f44a7e3dad9cbc51f40e5ec9b3810d1cc730a10
https://github.com/nepalez/immutability/blob/6f44a7e3dad9cbc51f40e5ec9b3810d1cc730a10/lib/immutability.rb#L86-L89
6,174
chrisjensen/hash_redactor
lib/hash_redactor/hash_redactor.rb
HashRedactor.HashRedactor.whitelist_redact_hash
def whitelist_redact_hash redact_hash digest_hash = {} redact_hash.each do |key,how| if (how.to_sym == :digest) digest_hash[digest_key(key)] = :keep end end digest_hash.merge redact_hash end
ruby
def whitelist_redact_hash redact_hash digest_hash = {} redact_hash.each do |key,how| if (how.to_sym == :digest) digest_hash[digest_key(key)] = :keep end end digest_hash.merge redact_hash end
[ "def", "whitelist_redact_hash", "redact_hash", "digest_hash", "=", "{", "}", "redact_hash", ".", "each", "do", "|", "key", ",", "how", "|", "if", "(", "how", ".", "to_sym", "==", ":digest", ")", "digest_hash", "[", "digest_key", "(", "key", ")", "]", "=", ":keep", "end", "end", "digest_hash", ".", "merge", "redact_hash", "end" ]
Calculate all keys that should be kept in whitelist mode In multiple iterations of redact -> decrypt - digest keys will remain and then get deleted in the second iteration, so we have to add the digest keys so they're not wiped out on later iteration
[ "Calculate", "all", "keys", "that", "should", "be", "kept", "in", "whitelist", "mode", "In", "multiple", "iterations", "of", "redact", "-", ">", "decrypt", "-", "digest", "keys", "will", "remain", "and", "then", "get", "deleted", "in", "the", "second", "iteration", "so", "we", "have", "to", "add", "the", "digest", "keys", "so", "they", "re", "not", "wiped", "out", "on", "later", "iteration" ]
dd35d5dc9a7fa529ad3a2168975cd8beecce549a
https://github.com/chrisjensen/hash_redactor/blob/dd35d5dc9a7fa529ad3a2168975cd8beecce549a/lib/hash_redactor/hash_redactor.rb#L184-L194
6,175
sa2taka/nameko
lib/nameko/nameko.rb
Nameko.Mecab.parse
def parse(str) node = MecabNode.new mecab_sparse_tonode(@mecab, str) result = [] while !node.null? do if node.surface.empty? node = node.next next end result << node node = node.next end result end
ruby
def parse(str) node = MecabNode.new mecab_sparse_tonode(@mecab, str) result = [] while !node.null? do if node.surface.empty? node = node.next next end result << node node = node.next end result end
[ "def", "parse", "(", "str", ")", "node", "=", "MecabNode", ".", "new", "mecab_sparse_tonode", "(", "@mecab", ",", "str", ")", "result", "=", "[", "]", "while", "!", "node", ".", "null?", "do", "if", "node", ".", "surface", ".", "empty?", "node", "=", "node", ".", "next", "next", "end", "result", "<<", "node", "node", "=", "node", ".", "next", "end", "result", "end" ]
Initialize the mecab tagger with the given option. How to specify options is as follows: @example mecab = Nameko::Mecab.new("-d /usr/local/lib/mecab/dic/mecab-ipadic-neologd") mecab = Nameko::Mecab.new(["-d /usr/local/lib/mecab/dic/mecab-ipadic-neologd"]) mecab = Nameko::Mecab.new(["-d", "/usr/local/lib/mecab/dic/mecab-ipadic-neologd"]) Parse the given string by MeCab. @param [String] str Parsed text @return [Array<MecabNode>] Result of Mecab parsing @example node = mecab.parse("私以外私じゃないの")[0] node.surface # => "私" node.feature #=> {:pos=>"名詞", :pos1=>"代名詞", :pos2=>"一般", :pos3=>"", :conjugation_form=>"", :conjugation=>"", :base=>"私", :yomi=>"ワタシ", :pronunciation=>"ワタシ"} node.posid #=> 59 node.id #=> 1
[ "Initialize", "the", "mecab", "tagger", "with", "the", "given", "option", "." ]
4d9353a367ebf22bd653f89dea54ccf18aad9aea
https://github.com/sa2taka/nameko/blob/4d9353a367ebf22bd653f89dea54ccf18aad9aea/lib/nameko/nameko.rb#L65-L79
6,176
DouweM/mongoid-siblings
lib/mongoid/siblings.rb
Mongoid.Siblings.siblings_and_self
def siblings_and_self(options = {}) scopes = options[:scope] || self.default_sibling_scope scope_values = options[:scope_values] || {} scopes = Array.wrap(scopes).compact criteria = base_document_class.all detail_scopes = [] # Find out what scope determines the root criteria. This can be # [klass].all or self.[relation]. # It is assumed that for `scopes: [:rel1, :rel2]`, sibling objects always # have the same `rel1` *and* `rel2`, and that two objects with the same # `rel1` will always have the same `rel2`. scopes.reverse_each do |scope| scope_value = scope_values.fetch(scope) { self.send(scope) } relation_metadata = self.reflect_on_association(scope) if relation_metadata && scope_value proxy = self.siblings_through_relation(scope, scope_value) if proxy criteria = proxy.criteria next end end detail_scopes << scope end # Apply detail criteria, to make sure siblings share every simple # attribute or nil-relation. detail_scopes.each do |scope| scope_value = scope_values.fetch(scope) { self.send(scope) } relation_metadata = self.reflect_on_association(scope) if relation_metadata criteria = criteria.where(relation_metadata.key => scope_value) if scope_value && relation_metadata.polymorphic? type = scope_value.class.name inverse_of = send(relation_metadata.inverse_of_field) criteria = criteria.where(relation_metadata.inverse_type => type) criteria = criteria.any_in(relation_metadata.inverse_of_field => [inverse_of, nil]) end else criteria = criteria.where(scope => scope_value) end end criteria end
ruby
def siblings_and_self(options = {}) scopes = options[:scope] || self.default_sibling_scope scope_values = options[:scope_values] || {} scopes = Array.wrap(scopes).compact criteria = base_document_class.all detail_scopes = [] # Find out what scope determines the root criteria. This can be # [klass].all or self.[relation]. # It is assumed that for `scopes: [:rel1, :rel2]`, sibling objects always # have the same `rel1` *and* `rel2`, and that two objects with the same # `rel1` will always have the same `rel2`. scopes.reverse_each do |scope| scope_value = scope_values.fetch(scope) { self.send(scope) } relation_metadata = self.reflect_on_association(scope) if relation_metadata && scope_value proxy = self.siblings_through_relation(scope, scope_value) if proxy criteria = proxy.criteria next end end detail_scopes << scope end # Apply detail criteria, to make sure siblings share every simple # attribute or nil-relation. detail_scopes.each do |scope| scope_value = scope_values.fetch(scope) { self.send(scope) } relation_metadata = self.reflect_on_association(scope) if relation_metadata criteria = criteria.where(relation_metadata.key => scope_value) if scope_value && relation_metadata.polymorphic? type = scope_value.class.name inverse_of = send(relation_metadata.inverse_of_field) criteria = criteria.where(relation_metadata.inverse_type => type) criteria = criteria.any_in(relation_metadata.inverse_of_field => [inverse_of, nil]) end else criteria = criteria.where(scope => scope_value) end end criteria end
[ "def", "siblings_and_self", "(", "options", "=", "{", "}", ")", "scopes", "=", "options", "[", ":scope", "]", "||", "self", ".", "default_sibling_scope", "scope_values", "=", "options", "[", ":scope_values", "]", "||", "{", "}", "scopes", "=", "Array", ".", "wrap", "(", "scopes", ")", ".", "compact", "criteria", "=", "base_document_class", ".", "all", "detail_scopes", "=", "[", "]", "# Find out what scope determines the root criteria. This can be ", "# [klass].all or self.[relation].", "# It is assumed that for `scopes: [:rel1, :rel2]`, sibling objects always", "# have the same `rel1` *and* `rel2`, and that two objects with the same", "# `rel1` will always have the same `rel2`.", "scopes", ".", "reverse_each", "do", "|", "scope", "|", "scope_value", "=", "scope_values", ".", "fetch", "(", "scope", ")", "{", "self", ".", "send", "(", "scope", ")", "}", "relation_metadata", "=", "self", ".", "reflect_on_association", "(", "scope", ")", "if", "relation_metadata", "&&", "scope_value", "proxy", "=", "self", ".", "siblings_through_relation", "(", "scope", ",", "scope_value", ")", "if", "proxy", "criteria", "=", "proxy", ".", "criteria", "next", "end", "end", "detail_scopes", "<<", "scope", "end", "# Apply detail criteria, to make sure siblings share every simple ", "# attribute or nil-relation. ", "detail_scopes", ".", "each", "do", "|", "scope", "|", "scope_value", "=", "scope_values", ".", "fetch", "(", "scope", ")", "{", "self", ".", "send", "(", "scope", ")", "}", "relation_metadata", "=", "self", ".", "reflect_on_association", "(", "scope", ")", "if", "relation_metadata", "criteria", "=", "criteria", ".", "where", "(", "relation_metadata", ".", "key", "=>", "scope_value", ")", "if", "scope_value", "&&", "relation_metadata", ".", "polymorphic?", "type", "=", "scope_value", ".", "class", ".", "name", "inverse_of", "=", "send", "(", "relation_metadata", ".", "inverse_of_field", ")", "criteria", "=", "criteria", ".", "where", "(", "relation_metadata", ".", "inverse_type", "=>", "type", ")", "criteria", "=", "criteria", ".", "any_in", "(", "relation_metadata", ".", "inverse_of_field", "=>", "[", "inverse_of", ",", "nil", "]", ")", "end", "else", "criteria", "=", "criteria", ".", "where", "(", "scope", "=>", "scope_value", ")", "end", "end", "criteria", "end" ]
Returns this document's siblings and itself. @example Retrieve document's siblings and itself within a certain scope. book.siblings_and_self(scope: :author) @example Retrieve what would be document's siblings if it had another scope value. book.siblings_and_self( scope: :author, scope_values: { author: other_author } ) @param [ Hash ] options The options. @option options [ Array<Symbol>, Symbol ] scope One or more relations or attributes that siblings of this object need to have in common. @option options [ Hash<Symbol, Object> ] scope_values Optional alternative values to use to determine siblingship. @return [ Mongoid::Criteria ] Criteria to retrieve the document's siblings.
[ "Returns", "this", "document", "s", "siblings", "and", "itself", "." ]
095c973628255eccf4a5341079d0dcac546df3a3
https://github.com/DouweM/mongoid-siblings/blob/095c973628255eccf4a5341079d0dcac546df3a3/lib/mongoid/siblings.rb#L43-L96
6,177
DouweM/mongoid-siblings
lib/mongoid/siblings.rb
Mongoid.Siblings.sibling_of?
def sibling_of?(other, options = {}) scopes = options[:scope] || self.default_sibling_scope scope_values = options[:scope_values] || {} other_scope_values = options[:other_scope_values] || {} scopes = Array.wrap(scopes).compact return false if base_document_class != base_document_class(other) scopes.each do |scope| scope_value = scope_values.fetch(scope) { self.send(scope) } other_scope_value = other_scope_values.fetch(scope) { other.send(scope) } return false if scope_value != other_scope_value end true end
ruby
def sibling_of?(other, options = {}) scopes = options[:scope] || self.default_sibling_scope scope_values = options[:scope_values] || {} other_scope_values = options[:other_scope_values] || {} scopes = Array.wrap(scopes).compact return false if base_document_class != base_document_class(other) scopes.each do |scope| scope_value = scope_values.fetch(scope) { self.send(scope) } other_scope_value = other_scope_values.fetch(scope) { other.send(scope) } return false if scope_value != other_scope_value end true end
[ "def", "sibling_of?", "(", "other", ",", "options", "=", "{", "}", ")", "scopes", "=", "options", "[", ":scope", "]", "||", "self", ".", "default_sibling_scope", "scope_values", "=", "options", "[", ":scope_values", "]", "||", "{", "}", "other_scope_values", "=", "options", "[", ":other_scope_values", "]", "||", "{", "}", "scopes", "=", "Array", ".", "wrap", "(", "scopes", ")", ".", "compact", "return", "false", "if", "base_document_class", "!=", "base_document_class", "(", "other", ")", "scopes", ".", "each", "do", "|", "scope", "|", "scope_value", "=", "scope_values", ".", "fetch", "(", "scope", ")", "{", "self", ".", "send", "(", "scope", ")", "}", "other_scope_value", "=", "other_scope_values", ".", "fetch", "(", "scope", ")", "{", "other", ".", "send", "(", "scope", ")", "}", "return", "false", "if", "scope_value", "!=", "other_scope_value", "end", "true", "end" ]
Is this document a sibling of the other document? @example Is this document a sibling of the other document? book.sibling_of?(other_book, scope: :author) @param [ Document ] other The document to check against. @param [ Hash ] options The options. @option options [ Array<Symbol>, Symbol ] scope One or more relations and attributes that siblings of this object need to have in common. @option options [ Hash<Symbol, Object> ] scope_values Optional alternative values for this document to use to determine siblings. @option options [ Hash<Symbol, Object> ] other_scope_values Optional alternative values for the other document to use to determine siblingship. @return [ Boolean ] True if the document is a sibling of the other document.
[ "Is", "this", "document", "a", "sibling", "of", "the", "other", "document?" ]
095c973628255eccf4a5341079d0dcac546df3a3
https://github.com/DouweM/mongoid-siblings/blob/095c973628255eccf4a5341079d0dcac546df3a3/lib/mongoid/siblings.rb#L116-L134
6,178
DouweM/mongoid-siblings
lib/mongoid/siblings.rb
Mongoid.Siblings.become_sibling_of
def become_sibling_of(other, options = {}) return true if self.sibling_of?(other, options) scopes = options[:scope] || self.default_sibling_scope other_scope_values = options[:other_scope_values] || {} scopes = Array.wrap(scopes).compact return false if base_document_class != base_document_class(other) scopes.each do |scope| other_scope_value = other_scope_values.fetch(scope) { other.send(scope) } relation_metadata = self.reflect_on_association(scope) if relation_metadata && other_scope_value inverse_metadata = other.intelligent_inverse_metadata(scope, other_scope_value) if inverse_metadata inverse = inverse_metadata.name if inverse_metadata.many? other_scope_value.send(inverse) << self else other_scope_value.send("#{inverse}=", self) end next end end self.send("#{scope}=", other_scope_value) end end
ruby
def become_sibling_of(other, options = {}) return true if self.sibling_of?(other, options) scopes = options[:scope] || self.default_sibling_scope other_scope_values = options[:other_scope_values] || {} scopes = Array.wrap(scopes).compact return false if base_document_class != base_document_class(other) scopes.each do |scope| other_scope_value = other_scope_values.fetch(scope) { other.send(scope) } relation_metadata = self.reflect_on_association(scope) if relation_metadata && other_scope_value inverse_metadata = other.intelligent_inverse_metadata(scope, other_scope_value) if inverse_metadata inverse = inverse_metadata.name if inverse_metadata.many? other_scope_value.send(inverse) << self else other_scope_value.send("#{inverse}=", self) end next end end self.send("#{scope}=", other_scope_value) end end
[ "def", "become_sibling_of", "(", "other", ",", "options", "=", "{", "}", ")", "return", "true", "if", "self", ".", "sibling_of?", "(", "other", ",", "options", ")", "scopes", "=", "options", "[", ":scope", "]", "||", "self", ".", "default_sibling_scope", "other_scope_values", "=", "options", "[", ":other_scope_values", "]", "||", "{", "}", "scopes", "=", "Array", ".", "wrap", "(", "scopes", ")", ".", "compact", "return", "false", "if", "base_document_class", "!=", "base_document_class", "(", "other", ")", "scopes", ".", "each", "do", "|", "scope", "|", "other_scope_value", "=", "other_scope_values", ".", "fetch", "(", "scope", ")", "{", "other", ".", "send", "(", "scope", ")", "}", "relation_metadata", "=", "self", ".", "reflect_on_association", "(", "scope", ")", "if", "relation_metadata", "&&", "other_scope_value", "inverse_metadata", "=", "other", ".", "intelligent_inverse_metadata", "(", "scope", ",", "other_scope_value", ")", "if", "inverse_metadata", "inverse", "=", "inverse_metadata", ".", "name", "if", "inverse_metadata", ".", "many?", "other_scope_value", ".", "send", "(", "inverse", ")", "<<", "self", "else", "other_scope_value", ".", "send", "(", "\"#{inverse}=\"", ",", "self", ")", "end", "next", "end", "end", "self", ".", "send", "(", "\"#{scope}=\"", ",", "other_scope_value", ")", "end", "end" ]
Makes this document a sibling of the other document. This is done by copying over the values used to determine siblingship from the other document. @example Make document a sibling of the other document. book.become_sibling_of(book_of_other_author, scope: :author) @param [ Document ] other The document to become a sibling of. @param [ Hash ] options The options. @option options [ Array<Symbol>, Symbol ] scope One or more relations and attributes that siblings of this object need to have in common. @option options [ Hash<Symbol, Object> ] other_scope_values Optional alternative values to use to determine siblingship. @return [ Boolean ] True if the document was made a sibling of the other document.
[ "Makes", "this", "document", "a", "sibling", "of", "the", "other", "document", "." ]
095c973628255eccf4a5341079d0dcac546df3a3
https://github.com/DouweM/mongoid-siblings/blob/095c973628255eccf4a5341079d0dcac546df3a3/lib/mongoid/siblings.rb#L154-L184
6,179
maccman/bowline-bundler
lib/bowline/bundler/finder.rb
Bundler.Finder.search
def search(dependency) @cache[dependency.hash] ||= begin find_by_name(dependency.name).select do |spec| dependency =~ spec end.sort_by {|s| s.version } end end
ruby
def search(dependency) @cache[dependency.hash] ||= begin find_by_name(dependency.name).select do |spec| dependency =~ spec end.sort_by {|s| s.version } end end
[ "def", "search", "(", "dependency", ")", "@cache", "[", "dependency", ".", "hash", "]", "||=", "begin", "find_by_name", "(", "dependency", ".", "name", ")", ".", "select", "do", "|", "spec", "|", "dependency", "=~", "spec", "end", ".", "sort_by", "{", "|", "s", "|", "s", ".", "version", "}", "end", "end" ]
Takes an array of gem sources and fetches the full index of gems from each one. It then combines the indexes together keeping track of the original source so that any resolved gem can be fetched from the correct source. ==== Parameters *sources<String>:: URI pointing to the gem repository Searches for a gem that matches the dependency ==== Parameters dependency<Gem::Dependency>:: The gem dependency to search for ==== Returns [Gem::Specification]:: A collection of gem specifications matching the search
[ "Takes", "an", "array", "of", "gem", "sources", "and", "fetches", "the", "full", "index", "of", "gems", "from", "each", "one", ".", "It", "then", "combines", "the", "indexes", "together", "keeping", "track", "of", "the", "original", "source", "so", "that", "any", "resolved", "gem", "can", "be", "fetched", "from", "the", "correct", "source", "." ]
cb1fb41942d018458f6671e4d5b859636eb0bd64
https://github.com/maccman/bowline-bundler/blob/cb1fb41942d018458f6671e4d5b859636eb0bd64/lib/bowline/bundler/finder.rb#L29-L35
6,180
hans/jido-rb
lib/jido/conjugator.rb
Jido.Conjugator.search_current_el
def search_current_el xpath # try to find the rule in the current verb desired_el = @current_el.at_xpath xpath return desired_el unless desired_el.nil? # check all the verb's parents, walking up the hierarchy @current_el_parents.each do |parent| desired_el = parent.at_xpath xpath return desired_el unless desired_el.nil? end nil end
ruby
def search_current_el xpath # try to find the rule in the current verb desired_el = @current_el.at_xpath xpath return desired_el unless desired_el.nil? # check all the verb's parents, walking up the hierarchy @current_el_parents.each do |parent| desired_el = parent.at_xpath xpath return desired_el unless desired_el.nil? end nil end
[ "def", "search_current_el", "xpath", "# try to find the rule in the current verb", "desired_el", "=", "@current_el", ".", "at_xpath", "xpath", "return", "desired_el", "unless", "desired_el", ".", "nil?", "# check all the verb's parents, walking up the hierarchy", "@current_el_parents", ".", "each", "do", "|", "parent", "|", "desired_el", "=", "parent", ".", "at_xpath", "xpath", "return", "desired_el", "unless", "desired_el", ".", "nil?", "end", "nil", "end" ]
Search each parent of some verb for a given element. Used for rule inheritance.
[ "Search", "each", "parent", "of", "some", "verb", "for", "a", "given", "element", ".", "Used", "for", "rule", "inheritance", "." ]
9dd6b776737cb045d08b37e1be7639b4d18ba709
https://github.com/hans/jido-rb/blob/9dd6b776737cb045d08b37e1be7639b4d18ba709/lib/jido/conjugator.rb#L243-L255
6,181
richard-viney/lightstreamer
lib/lightstreamer/stream_buffer.rb
Lightstreamer.StreamBuffer.process
def process(data) @buffer << data lines = @buffer.split "\n" @buffer = @buffer.end_with?("\n") ? '' : lines.pop lines.each do |line| yield line.strip end end
ruby
def process(data) @buffer << data lines = @buffer.split "\n" @buffer = @buffer.end_with?("\n") ? '' : lines.pop lines.each do |line| yield line.strip end end
[ "def", "process", "(", "data", ")", "@buffer", "<<", "data", "lines", "=", "@buffer", ".", "split", "\"\\n\"", "@buffer", "=", "@buffer", ".", "end_with?", "(", "\"\\n\"", ")", "?", "''", ":", "lines", ".", "pop", "lines", ".", "each", "do", "|", "line", "|", "yield", "line", ".", "strip", "end", "end" ]
Appends a new piece of ASCII data to this buffer and yields back any lines that are now complete. @param [String] data The new piece of ASCII data. @yieldparam [String] line The new line that is now complete.
[ "Appends", "a", "new", "piece", "of", "ASCII", "data", "to", "this", "buffer", "and", "yields", "back", "any", "lines", "that", "are", "now", "complete", "." ]
7be6350bd861495a52ca35a8640a1e6df34cf9d1
https://github.com/richard-viney/lightstreamer/blob/7be6350bd861495a52ca35a8640a1e6df34cf9d1/lib/lightstreamer/stream_buffer.rb#L16-L25
6,182
Latermedia/sidekiq_spread
lib/sidekiq_spread.rb
SidekiqSpread.ClassMethods.perform_spread
def perform_spread(*args) spread_duration = get_sidekiq_options['spread_duration'] || 1.hour spread_in = 0 spread_at = nil spread_method = get_sidekiq_options['spread_method'] || :rand spread_mod_value = nil spread_method = spread_method.to_sym if spread_method.present? # process spread_* options has_options = false opts = if !args.empty? && args.last.is_a?(::Hash) has_options = true args.pop else {} end sd = _extract_spread_opt(opts, :duration) spread_duration = sd if sd.present? si = _extract_spread_opt(opts, :in) spread_in = si if si.present? sa = _extract_spread_opt(opts, :at) spread_at = sa if sa.present? sm = _extract_spread_opt(opts, :method) spread_method = sm.to_sym if sm.present? smv = _extract_spread_opt(opts, :mod_value) spread_mod_value = smv if smv.present? # get left over options / keyword args remaining_opts = opts.reject { |o| PERFORM_SPREAD_OPTS.include?(o.to_sym) } # check args num_args = args.length # figure out the require params for #perform params = new.method(:perform).parameters num_req_args = params.select { |p| p[0] == :req }.length num_opt_args = params.select { |p| p[0] == :opt }.length num_req_key_args = params.select { |p| p[0] == :keyreq }.length num_opt_key_args = params.select { |p| p[0] == :key }.length # Sidekiq doesn't play nicely with named args raise ArgumentError, "#{name}#perform should not use keyword args" if num_req_key_args > 0 || num_opt_key_args > 0 if has_options # if we popped something off to process, push it back on # if it contains arguments we need if num_args < num_req_args args.push(remaining_opts) elsif num_args < (num_req_args + num_opt_args) && !remaining_opts.empty? args.push(remaining_opts) end end # if a spread_mod_value is not provided use the first argument, # assumes it is an Integer spread_mod_value = args.first if spread_mod_value.blank? && spread_method == :mod # validate the spread_* options _check_spread_args!(spread_duration, spread_method, spread_mod_value) # calculate the offset for this job spread = _set_spread(spread_method, spread_duration.to_i, spread_mod_value) # call the correct perform_* method if spread_at.present? t = spread_at.to_i + spread perform_at(t, *args) else t = spread_in.to_i + spread if t.zero? perform_async(*args) else perform_in(t, *args) end end end
ruby
def perform_spread(*args) spread_duration = get_sidekiq_options['spread_duration'] || 1.hour spread_in = 0 spread_at = nil spread_method = get_sidekiq_options['spread_method'] || :rand spread_mod_value = nil spread_method = spread_method.to_sym if spread_method.present? # process spread_* options has_options = false opts = if !args.empty? && args.last.is_a?(::Hash) has_options = true args.pop else {} end sd = _extract_spread_opt(opts, :duration) spread_duration = sd if sd.present? si = _extract_spread_opt(opts, :in) spread_in = si if si.present? sa = _extract_spread_opt(opts, :at) spread_at = sa if sa.present? sm = _extract_spread_opt(opts, :method) spread_method = sm.to_sym if sm.present? smv = _extract_spread_opt(opts, :mod_value) spread_mod_value = smv if smv.present? # get left over options / keyword args remaining_opts = opts.reject { |o| PERFORM_SPREAD_OPTS.include?(o.to_sym) } # check args num_args = args.length # figure out the require params for #perform params = new.method(:perform).parameters num_req_args = params.select { |p| p[0] == :req }.length num_opt_args = params.select { |p| p[0] == :opt }.length num_req_key_args = params.select { |p| p[0] == :keyreq }.length num_opt_key_args = params.select { |p| p[0] == :key }.length # Sidekiq doesn't play nicely with named args raise ArgumentError, "#{name}#perform should not use keyword args" if num_req_key_args > 0 || num_opt_key_args > 0 if has_options # if we popped something off to process, push it back on # if it contains arguments we need if num_args < num_req_args args.push(remaining_opts) elsif num_args < (num_req_args + num_opt_args) && !remaining_opts.empty? args.push(remaining_opts) end end # if a spread_mod_value is not provided use the first argument, # assumes it is an Integer spread_mod_value = args.first if spread_mod_value.blank? && spread_method == :mod # validate the spread_* options _check_spread_args!(spread_duration, spread_method, spread_mod_value) # calculate the offset for this job spread = _set_spread(spread_method, spread_duration.to_i, spread_mod_value) # call the correct perform_* method if spread_at.present? t = spread_at.to_i + spread perform_at(t, *args) else t = spread_in.to_i + spread if t.zero? perform_async(*args) else perform_in(t, *args) end end end
[ "def", "perform_spread", "(", "*", "args", ")", "spread_duration", "=", "get_sidekiq_options", "[", "'spread_duration'", "]", "||", "1", ".", "hour", "spread_in", "=", "0", "spread_at", "=", "nil", "spread_method", "=", "get_sidekiq_options", "[", "'spread_method'", "]", "||", ":rand", "spread_mod_value", "=", "nil", "spread_method", "=", "spread_method", ".", "to_sym", "if", "spread_method", ".", "present?", "# process spread_* options", "has_options", "=", "false", "opts", "=", "if", "!", "args", ".", "empty?", "&&", "args", ".", "last", ".", "is_a?", "(", "::", "Hash", ")", "has_options", "=", "true", "args", ".", "pop", "else", "{", "}", "end", "sd", "=", "_extract_spread_opt", "(", "opts", ",", ":duration", ")", "spread_duration", "=", "sd", "if", "sd", ".", "present?", "si", "=", "_extract_spread_opt", "(", "opts", ",", ":in", ")", "spread_in", "=", "si", "if", "si", ".", "present?", "sa", "=", "_extract_spread_opt", "(", "opts", ",", ":at", ")", "spread_at", "=", "sa", "if", "sa", ".", "present?", "sm", "=", "_extract_spread_opt", "(", "opts", ",", ":method", ")", "spread_method", "=", "sm", ".", "to_sym", "if", "sm", ".", "present?", "smv", "=", "_extract_spread_opt", "(", "opts", ",", ":mod_value", ")", "spread_mod_value", "=", "smv", "if", "smv", ".", "present?", "# get left over options / keyword args", "remaining_opts", "=", "opts", ".", "reject", "{", "|", "o", "|", "PERFORM_SPREAD_OPTS", ".", "include?", "(", "o", ".", "to_sym", ")", "}", "# check args", "num_args", "=", "args", ".", "length", "# figure out the require params for #perform", "params", "=", "new", ".", "method", "(", ":perform", ")", ".", "parameters", "num_req_args", "=", "params", ".", "select", "{", "|", "p", "|", "p", "[", "0", "]", "==", ":req", "}", ".", "length", "num_opt_args", "=", "params", ".", "select", "{", "|", "p", "|", "p", "[", "0", "]", "==", ":opt", "}", ".", "length", "num_req_key_args", "=", "params", ".", "select", "{", "|", "p", "|", "p", "[", "0", "]", "==", ":keyreq", "}", ".", "length", "num_opt_key_args", "=", "params", ".", "select", "{", "|", "p", "|", "p", "[", "0", "]", "==", ":key", "}", ".", "length", "# Sidekiq doesn't play nicely with named args", "raise", "ArgumentError", ",", "\"#{name}#perform should not use keyword args\"", "if", "num_req_key_args", ">", "0", "||", "num_opt_key_args", ">", "0", "if", "has_options", "# if we popped something off to process, push it back on", "# if it contains arguments we need", "if", "num_args", "<", "num_req_args", "args", ".", "push", "(", "remaining_opts", ")", "elsif", "num_args", "<", "(", "num_req_args", "+", "num_opt_args", ")", "&&", "!", "remaining_opts", ".", "empty?", "args", ".", "push", "(", "remaining_opts", ")", "end", "end", "# if a spread_mod_value is not provided use the first argument,", "# assumes it is an Integer", "spread_mod_value", "=", "args", ".", "first", "if", "spread_mod_value", ".", "blank?", "&&", "spread_method", "==", ":mod", "# validate the spread_* options", "_check_spread_args!", "(", "spread_duration", ",", "spread_method", ",", "spread_mod_value", ")", "# calculate the offset for this job", "spread", "=", "_set_spread", "(", "spread_method", ",", "spread_duration", ".", "to_i", ",", "spread_mod_value", ")", "# call the correct perform_* method", "if", "spread_at", ".", "present?", "t", "=", "spread_at", ".", "to_i", "+", "spread", "perform_at", "(", "t", ",", "args", ")", "else", "t", "=", "spread_in", ".", "to_i", "+", "spread", "if", "t", ".", "zero?", "perform_async", "(", "args", ")", "else", "perform_in", "(", "t", ",", "args", ")", "end", "end", "end" ]
Randomly schedule worker over a window of time. Arguments are keys of the final options hash. @param spread_duration [Number] Size of window to spread workers out over @param spread_in [Number] Start of window offset from now @param spread_at [Number] Start of window offset timestamp @param spread_method [rand|mod] perform either a random or modulo spread, default: *:rand* @param spread_mod_value [Integer] value to use for determining mod offset @return [String] Sidekiq job id
[ "Randomly", "schedule", "worker", "over", "a", "window", "of", "time", ".", "Arguments", "are", "keys", "of", "the", "final", "options", "hash", "." ]
e08c71ebdddbcb3cd16d6c9318573e13f3a249c4
https://github.com/Latermedia/sidekiq_spread/blob/e08c71ebdddbcb3cd16d6c9318573e13f3a249c4/lib/sidekiq_spread.rb#L32-L117
6,183
bemurphy/motivation
lib/motivation.rb
Motivation.ClassMethods.translation_key
def translation_key key = name.gsub(/Motivation\z/, '') key.gsub!(/^.*::/, '') key.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2') key.gsub!(/([a-z\d])([A-Z])/,'\1_\2') key.tr!("-", "_") key.downcase! end
ruby
def translation_key key = name.gsub(/Motivation\z/, '') key.gsub!(/^.*::/, '') key.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2') key.gsub!(/([a-z\d])([A-Z])/,'\1_\2') key.tr!("-", "_") key.downcase! end
[ "def", "translation_key", "key", "=", "name", ".", "gsub", "(", "/", "\\z", "/", ",", "''", ")", "key", ".", "gsub!", "(", "/", "/", ",", "''", ")", "key", ".", "gsub!", "(", "/", "\\d", "/", ",", "'\\1_\\2'", ")", "key", ".", "gsub!", "(", "/", "\\d", "/", ",", "'\\1_\\2'", ")", "key", ".", "tr!", "(", "\"-\"", ",", "\"_\"", ")", "key", ".", "downcase!", "end" ]
Returns the underscored name used in the full i18n translation key Example: UserProjectMotivation.translation_key # => "user_project"
[ "Returns", "the", "underscored", "name", "used", "in", "the", "full", "i18n", "translation", "key" ]
c545b6a3f23400557192f2ef17d08fd44264f2e2
https://github.com/bemurphy/motivation/blob/c545b6a3f23400557192f2ef17d08fd44264f2e2/lib/motivation.rb#L67-L74
6,184
bemurphy/motivation
lib/motivation.rb
Motivation.ClassMethods.check
def check(name = @current_step_name, &block) raise "No step name" unless name @current_step_name ||= name checks << CheckBlock.new("progression_name", name, &block) define_method("#{name}?") do check = checks.find { |s| s.name == name } !! check.run(self) end end
ruby
def check(name = @current_step_name, &block) raise "No step name" unless name @current_step_name ||= name checks << CheckBlock.new("progression_name", name, &block) define_method("#{name}?") do check = checks.find { |s| s.name == name } !! check.run(self) end end
[ "def", "check", "(", "name", "=", "@current_step_name", ",", "&", "block", ")", "raise", "\"No step name\"", "unless", "name", "@current_step_name", "||=", "name", "checks", "<<", "CheckBlock", ".", "new", "(", "\"progression_name\"", ",", "name", ",", "block", ")", "define_method", "(", "\"#{name}?\"", ")", "do", "check", "=", "checks", ".", "find", "{", "|", "s", "|", "s", ".", "name", "==", "name", "}", "!", "!", "check", ".", "run", "(", "self", ")", "end", "end" ]
Create a predicate method for the current step name to test if it's complete
[ "Create", "a", "predicate", "method", "for", "the", "current", "step", "name", "to", "test", "if", "it", "s", "complete" ]
c545b6a3f23400557192f2ef17d08fd44264f2e2
https://github.com/bemurphy/motivation/blob/c545b6a3f23400557192f2ef17d08fd44264f2e2/lib/motivation.rb#L100-L109
6,185
bemurphy/motivation
lib/motivation.rb
Motivation.ClassMethods.complete
def complete(&block) name = @current_step_name or raise "No step name" completions << CompletionBlock.new("progression_name", name, &block) define_method("complete_#{name}") do completion = completions.find { |c| c.name == name } completion.run(self) end end
ruby
def complete(&block) name = @current_step_name or raise "No step name" completions << CompletionBlock.new("progression_name", name, &block) define_method("complete_#{name}") do completion = completions.find { |c| c.name == name } completion.run(self) end end
[ "def", "complete", "(", "&", "block", ")", "name", "=", "@current_step_name", "or", "raise", "\"No step name\"", "completions", "<<", "CompletionBlock", ".", "new", "(", "\"progression_name\"", ",", "name", ",", "block", ")", "define_method", "(", "\"complete_#{name}\"", ")", "do", "completion", "=", "completions", ".", "find", "{", "|", "c", "|", "c", ".", "name", "==", "name", "}", "completion", ".", "run", "(", "self", ")", "end", "end" ]
Check a method like `complete_current_step_name` to mark a step complete. This is not always needed but useful if you want to persist a completion for performance purposes.
[ "Check", "a", "method", "like", "complete_current_step_name", "to", "mark", "a", "step", "complete", ".", "This", "is", "not", "always", "needed", "but", "useful", "if", "you", "want", "to", "persist", "a", "completion", "for", "performance", "purposes", "." ]
c545b6a3f23400557192f2ef17d08fd44264f2e2
https://github.com/bemurphy/motivation/blob/c545b6a3f23400557192f2ef17d08fd44264f2e2/lib/motivation.rb#L114-L122
6,186
fugroup/asset
lib/assets/helpers.rb
Asset.Helpers.tag
def tag(type, *paths, &block) paths.map do |path| # Yield the source back to the tag builder item = ::Asset.manifest.find{|i| i.path == path} # Src is same as path if item not found item ? item.sources.map{|f| yield(asset_url(f))} : yield(path) end.flatten.join("\n") end
ruby
def tag(type, *paths, &block) paths.map do |path| # Yield the source back to the tag builder item = ::Asset.manifest.find{|i| i.path == path} # Src is same as path if item not found item ? item.sources.map{|f| yield(asset_url(f))} : yield(path) end.flatten.join("\n") end
[ "def", "tag", "(", "type", ",", "*", "paths", ",", "&", "block", ")", "paths", ".", "map", "do", "|", "path", "|", "# Yield the source back to the tag builder", "item", "=", "::", "Asset", ".", "manifest", ".", "find", "{", "|", "i", "|", "i", ".", "path", "==", "path", "}", "# Src is same as path if item not found", "item", "?", "item", ".", "sources", ".", "map", "{", "|", "f", "|", "yield", "(", "asset_url", "(", "f", ")", ")", "}", ":", "yield", "(", "path", ")", "end", ".", "flatten", ".", "join", "(", "\"\\n\"", ")", "end" ]
Build the tags
[ "Build", "the", "tags" ]
3cc1aad0926d80653f25d5f0a8c9154d00049bc4
https://github.com/fugroup/asset/blob/3cc1aad0926d80653f25d5f0a8c9154d00049bc4/lib/assets/helpers.rb#L40-L48
6,187
DavidMikeSimon/offroad
lib/cargo_streamer.rb
Offroad.CargoStreamer.each_cargo_section
def each_cargo_section(name) raise CargoStreamerError.new("Mode must be 'r' to read cargo data") unless @mode == "r" locations = @cargo_locations[name] or return locations.each do |seek_location| @ioh.seek(seek_location) digest = "" encoded_data = "" @ioh.each_line do |line| line.chomp! if line == CARGO_END break elsif digest == "" digest = line else encoded_data += line end end yield verify_and_decode_cargo(digest, encoded_data) end end
ruby
def each_cargo_section(name) raise CargoStreamerError.new("Mode must be 'r' to read cargo data") unless @mode == "r" locations = @cargo_locations[name] or return locations.each do |seek_location| @ioh.seek(seek_location) digest = "" encoded_data = "" @ioh.each_line do |line| line.chomp! if line == CARGO_END break elsif digest == "" digest = line else encoded_data += line end end yield verify_and_decode_cargo(digest, encoded_data) end end
[ "def", "each_cargo_section", "(", "name", ")", "raise", "CargoStreamerError", ".", "new", "(", "\"Mode must be 'r' to read cargo data\"", ")", "unless", "@mode", "==", "\"r\"", "locations", "=", "@cargo_locations", "[", "name", "]", "or", "return", "locations", ".", "each", "do", "|", "seek_location", "|", "@ioh", ".", "seek", "(", "seek_location", ")", "digest", "=", "\"\"", "encoded_data", "=", "\"\"", "@ioh", ".", "each_line", "do", "|", "line", "|", "line", ".", "chomp!", "if", "line", "==", "CARGO_END", "break", "elsif", "digest", "==", "\"\"", "digest", "=", "line", "else", "encoded_data", "+=", "line", "end", "end", "yield", "verify_and_decode_cargo", "(", "digest", ",", "encoded_data", ")", "end", "end" ]
Reads, verifies, and decodes each cargo section with a given name, passing each section's decoded data to the block
[ "Reads", "verifies", "and", "decodes", "each", "cargo", "section", "with", "a", "given", "name", "passing", "each", "section", "s", "decoded", "data", "to", "the", "block" ]
0dee8935c6600428204494ba3c24e531277d57b0
https://github.com/DavidMikeSimon/offroad/blob/0dee8935c6600428204494ba3c24e531277d57b0/lib/cargo_streamer.rb#L124-L144
6,188
litenup/audio_hero
lib/audio_hero.rb
AudioHero.Sox.extract_features
def extract_features(options={}) rate = options[:sample_rate] || "8000" begin parameters = [] parameters << "-r #{rate}" parameters << ":source" parameters = parameters.flatten.compact.join(" ").strip.squeeze(" ") success = Cocaine::CommandLine.new("yaafehero", parameters).run(:source => get_path(@file)) rescue => e raise AudioHeroError, "These was an issue getting stats from #{@basename}" end garbage_collect(@file) if options[:gc] == "true" MessagePack.unpack(success) end
ruby
def extract_features(options={}) rate = options[:sample_rate] || "8000" begin parameters = [] parameters << "-r #{rate}" parameters << ":source" parameters = parameters.flatten.compact.join(" ").strip.squeeze(" ") success = Cocaine::CommandLine.new("yaafehero", parameters).run(:source => get_path(@file)) rescue => e raise AudioHeroError, "These was an issue getting stats from #{@basename}" end garbage_collect(@file) if options[:gc] == "true" MessagePack.unpack(success) end
[ "def", "extract_features", "(", "options", "=", "{", "}", ")", "rate", "=", "options", "[", ":sample_rate", "]", "||", "\"8000\"", "begin", "parameters", "=", "[", "]", "parameters", "<<", "\"-r #{rate}\"", "parameters", "<<", "\":source\"", "parameters", "=", "parameters", ".", "flatten", ".", "compact", ".", "join", "(", "\" \"", ")", ".", "strip", ".", "squeeze", "(", "\" \"", ")", "success", "=", "Cocaine", "::", "CommandLine", ".", "new", "(", "\"yaafehero\"", ",", "parameters", ")", ".", "run", "(", ":source", "=>", "get_path", "(", "@file", ")", ")", "rescue", "=>", "e", "raise", "AudioHeroError", ",", "\"These was an issue getting stats from #{@basename}\"", "end", "garbage_collect", "(", "@file", ")", "if", "options", "[", ":gc", "]", "==", "\"true\"", "MessagePack", ".", "unpack", "(", "success", ")", "end" ]
Requires custom version of yaafe
[ "Requires", "custom", "version", "of", "yaafe" ]
c682a8483c6646782804b9e4ff804a6c39240937
https://github.com/litenup/audio_hero/blob/c682a8483c6646782804b9e4ff804a6c39240937/lib/audio_hero.rb#L178-L191
6,189
mrsimonfletcher/roroacms
app/controllers/roroacms/admin/revisions_controller.rb
Roroacms.Admin::RevisionsController.restore
def restore post = Post.find(params[:id]) # do the restore restore = Post.restore(post) url = if restore.post_type == 'page' "/admin/pages/#{restore.id}/edit" elsif restore.post_type == 'post' "/admin/articles/#{restore.id}/edit" end # redirect to either the post or page area depending on what post_type the post has redirect_to URI.parse(url).path, notice: I18n.t("controllers.admin.revisions.restore.flash.notice", post_type: restore.post_type.capitalize) end
ruby
def restore post = Post.find(params[:id]) # do the restore restore = Post.restore(post) url = if restore.post_type == 'page' "/admin/pages/#{restore.id}/edit" elsif restore.post_type == 'post' "/admin/articles/#{restore.id}/edit" end # redirect to either the post or page area depending on what post_type the post has redirect_to URI.parse(url).path, notice: I18n.t("controllers.admin.revisions.restore.flash.notice", post_type: restore.post_type.capitalize) end
[ "def", "restore", "post", "=", "Post", ".", "find", "(", "params", "[", ":id", "]", ")", "# do the restore", "restore", "=", "Post", ".", "restore", "(", "post", ")", "url", "=", "if", "restore", ".", "post_type", "==", "'page'", "\"/admin/pages/#{restore.id}/edit\"", "elsif", "restore", ".", "post_type", "==", "'post'", "\"/admin/articles/#{restore.id}/edit\"", "end", "# redirect to either the post or page area depending on what post_type the post has", "redirect_to", "URI", ".", "parse", "(", "url", ")", ".", "path", ",", "notice", ":", "I18n", ".", "t", "(", "\"controllers.admin.revisions.restore.flash.notice\"", ",", "post_type", ":", "restore", ".", "post_type", ".", "capitalize", ")", "end" ]
restore the post to the given post data
[ "restore", "the", "post", "to", "the", "given", "post", "data" ]
62654a2f2a48e3adb3105f4dafb6e315b460eaf4
https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/revisions_controller.rb#L22-L36
6,190
steveh/fingerjam
lib/fingerjam/helpers.rb
Fingerjam.Helpers.rewrite_asset_path
def rewrite_asset_path(source, path = nil) if Fingerjam::Base.enabled? && Fingerjam::Base.cached?(source) Fingerjam::Base.cached_url(source) else if path && path.respond_to?(:call) return path.call(source) elsif path && path.is_a?(String) return path % [source] end asset_id = rails_asset_id(source) if asset_id.blank? source else source + "?#{asset_id}" end end end
ruby
def rewrite_asset_path(source, path = nil) if Fingerjam::Base.enabled? && Fingerjam::Base.cached?(source) Fingerjam::Base.cached_url(source) else if path && path.respond_to?(:call) return path.call(source) elsif path && path.is_a?(String) return path % [source] end asset_id = rails_asset_id(source) if asset_id.blank? source else source + "?#{asset_id}" end end end
[ "def", "rewrite_asset_path", "(", "source", ",", "path", "=", "nil", ")", "if", "Fingerjam", "::", "Base", ".", "enabled?", "&&", "Fingerjam", "::", "Base", ".", "cached?", "(", "source", ")", "Fingerjam", "::", "Base", ".", "cached_url", "(", "source", ")", "else", "if", "path", "&&", "path", ".", "respond_to?", "(", ":call", ")", "return", "path", ".", "call", "(", "source", ")", "elsif", "path", "&&", "path", ".", "is_a?", "(", "String", ")", "return", "path", "%", "[", "source", "]", "end", "asset_id", "=", "rails_asset_id", "(", "source", ")", "if", "asset_id", ".", "blank?", "source", "else", "source", "+", "\"?#{asset_id}\"", "end", "end", "end" ]
Used by Rails view helpers
[ "Used", "by", "Rails", "view", "helpers" ]
73681d3e3c147a7a294acc734a8c8abcce4dc1fc
https://github.com/steveh/fingerjam/blob/73681d3e3c147a7a294acc734a8c8abcce4dc1fc/lib/fingerjam/helpers.rb#L5-L22
6,191
nrser/nrser.rb
lib/nrser/props/mutable/stash.rb
NRSER::Props::Mutable::Stash.InstanceMethods.put
def put key, value key = convert_key key if (prop = self.class.metadata[ key ]) prop.set self, value else # We know {#convert_value} is a no-op so can skip it _raw_put key, value end end
ruby
def put key, value key = convert_key key if (prop = self.class.metadata[ key ]) prop.set self, value else # We know {#convert_value} is a no-op so can skip it _raw_put key, value end end
[ "def", "put", "key", ",", "value", "key", "=", "convert_key", "key", "if", "(", "prop", "=", "self", ".", "class", ".", "metadata", "[", "key", "]", ")", "prop", ".", "set", "self", ",", "value", "else", "# We know {#convert_value} is a no-op so can skip it", "_raw_put", "key", ",", "value", "end", "end" ]
Store a value at a key. If the key is a prop name, store it through the prop, which will check it's type. @param [Symbol | String] key @param [VALUE] value @return [VALUE] The stored value.
[ "Store", "a", "value", "at", "a", "key", ".", "If", "the", "key", "is", "a", "prop", "name", "store", "it", "through", "the", "prop", "which", "will", "check", "it", "s", "type", "." ]
7db9a729ec65894dfac13fd50851beae8b809738
https://github.com/nrser/nrser.rb/blob/7db9a729ec65894dfac13fd50851beae8b809738/lib/nrser/props/mutable/stash.rb#L172-L181
6,192
aseldawy/ruby_desk
lib/ruby_desk/connector.rb
RubyDesk.Connector.sign
def sign(params) RubyDesk.logger.debug {"Params to sign: #{params.inspect}"} # sort parameters by its names (keys) sorted_params = params.sort { |a, b| a.to_s <=> b.to_s} RubyDesk.logger.debug {"Sorted params: #{sorted_params.inspect}"} # Unescape escaped params sorted_params.map! do |k, v| [k, URI.unescape(v)] end # concatenate secret with names, values concatenated = @api_secret + sorted_params.join RubyDesk.logger.debug {"concatenated: #{concatenated}"} # Calculate and return md5 of concatenated string md5 = Digest::MD5.hexdigest(concatenated) RubyDesk.logger.debug {"md5: #{md5}"} return md5 end
ruby
def sign(params) RubyDesk.logger.debug {"Params to sign: #{params.inspect}"} # sort parameters by its names (keys) sorted_params = params.sort { |a, b| a.to_s <=> b.to_s} RubyDesk.logger.debug {"Sorted params: #{sorted_params.inspect}"} # Unescape escaped params sorted_params.map! do |k, v| [k, URI.unescape(v)] end # concatenate secret with names, values concatenated = @api_secret + sorted_params.join RubyDesk.logger.debug {"concatenated: #{concatenated}"} # Calculate and return md5 of concatenated string md5 = Digest::MD5.hexdigest(concatenated) RubyDesk.logger.debug {"md5: #{md5}"} return md5 end
[ "def", "sign", "(", "params", ")", "RubyDesk", ".", "logger", ".", "debug", "{", "\"Params to sign: #{params.inspect}\"", "}", "# sort parameters by its names (keys)", "sorted_params", "=", "params", ".", "sort", "{", "|", "a", ",", "b", "|", "a", ".", "to_s", "<=>", "b", ".", "to_s", "}", "RubyDesk", ".", "logger", ".", "debug", "{", "\"Sorted params: #{sorted_params.inspect}\"", "}", "# Unescape escaped params", "sorted_params", ".", "map!", "do", "|", "k", ",", "v", "|", "[", "k", ",", "URI", ".", "unescape", "(", "v", ")", "]", "end", "# concatenate secret with names, values", "concatenated", "=", "@api_secret", "+", "sorted_params", ".", "join", "RubyDesk", ".", "logger", ".", "debug", "{", "\"concatenated: #{concatenated}\"", "}", "# Calculate and return md5 of concatenated string", "md5", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "concatenated", ")", "RubyDesk", ".", "logger", ".", "debug", "{", "\"md5: #{md5}\"", "}", "return", "md5", "end" ]
Sign the given parameters and returns the signature
[ "Sign", "the", "given", "parameters", "and", "returns", "the", "signature" ]
3e62ae5002183b89c9e4c07b640e26c661b7644d
https://github.com/aseldawy/ruby_desk/blob/3e62ae5002183b89c9e4c07b640e26c661b7644d/lib/ruby_desk/connector.rb#L29-L52
6,193
aseldawy/ruby_desk
lib/ruby_desk/connector.rb
RubyDesk.Connector.invoke_api_call
def invoke_api_call(api_call) url = URI.parse(api_call[:url]) http = Net::HTTP.new(url.host, url.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE # Concatenate parameters to form data data = api_call[:params].to_a.map{|pair| pair.map{|x| URI.escape(x.to_s)}.join '='}.join('&') headers = { 'Content-Type' => 'application/x-www-form-urlencoded' } RubyDesk.logger.info "URL: #{api_call[:url]}" RubyDesk.logger.info "method: #{api_call[:method]}" RubyDesk.logger.info "Params: #{data}" case api_call[:method] when :get, 'get' then resp, data = http.request(Net::HTTP::Get.new(url.path+"?"+data, headers)) when :post, 'post' then resp, data = http.request(Net::HTTP::Post.new(url.path, headers), data) when :delete, 'delete' then resp, data = http.request(Net::HTTP::Delete.new(url.path, headers), data) end RubyDesk.logger.info "Response code: #{resp.code}" RubyDesk.logger.info "Returned data: #{data}" case resp.code when "200" then return data when "400" then raise RubyDesk::BadRequest, data when "401", "403" then raise RubyDesk::UnauthorizedError, data when "404" then raise RubyDesk::PageNotFound, data when "500" then raise RubyDesk::ServerError, data else raise RubyDesk::Error, data end end
ruby
def invoke_api_call(api_call) url = URI.parse(api_call[:url]) http = Net::HTTP.new(url.host, url.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE # Concatenate parameters to form data data = api_call[:params].to_a.map{|pair| pair.map{|x| URI.escape(x.to_s)}.join '='}.join('&') headers = { 'Content-Type' => 'application/x-www-form-urlencoded' } RubyDesk.logger.info "URL: #{api_call[:url]}" RubyDesk.logger.info "method: #{api_call[:method]}" RubyDesk.logger.info "Params: #{data}" case api_call[:method] when :get, 'get' then resp, data = http.request(Net::HTTP::Get.new(url.path+"?"+data, headers)) when :post, 'post' then resp, data = http.request(Net::HTTP::Post.new(url.path, headers), data) when :delete, 'delete' then resp, data = http.request(Net::HTTP::Delete.new(url.path, headers), data) end RubyDesk.logger.info "Response code: #{resp.code}" RubyDesk.logger.info "Returned data: #{data}" case resp.code when "200" then return data when "400" then raise RubyDesk::BadRequest, data when "401", "403" then raise RubyDesk::UnauthorizedError, data when "404" then raise RubyDesk::PageNotFound, data when "500" then raise RubyDesk::ServerError, data else raise RubyDesk::Error, data end end
[ "def", "invoke_api_call", "(", "api_call", ")", "url", "=", "URI", ".", "parse", "(", "api_call", "[", ":url", "]", ")", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "url", ".", "host", ",", "url", ".", "port", ")", "http", ".", "use_ssl", "=", "true", "http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "# Concatenate parameters to form data", "data", "=", "api_call", "[", ":params", "]", ".", "to_a", ".", "map", "{", "|", "pair", "|", "pair", ".", "map", "{", "|", "x", "|", "URI", ".", "escape", "(", "x", ".", "to_s", ")", "}", ".", "join", "'='", "}", ".", "join", "(", "'&'", ")", "headers", "=", "{", "'Content-Type'", "=>", "'application/x-www-form-urlencoded'", "}", "RubyDesk", ".", "logger", ".", "info", "\"URL: #{api_call[:url]}\"", "RubyDesk", ".", "logger", ".", "info", "\"method: #{api_call[:method]}\"", "RubyDesk", ".", "logger", ".", "info", "\"Params: #{data}\"", "case", "api_call", "[", ":method", "]", "when", ":get", ",", "'get'", "then", "resp", ",", "data", "=", "http", ".", "request", "(", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "url", ".", "path", "+", "\"?\"", "+", "data", ",", "headers", ")", ")", "when", ":post", ",", "'post'", "then", "resp", ",", "data", "=", "http", ".", "request", "(", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "url", ".", "path", ",", "headers", ")", ",", "data", ")", "when", ":delete", ",", "'delete'", "then", "resp", ",", "data", "=", "http", ".", "request", "(", "Net", "::", "HTTP", "::", "Delete", ".", "new", "(", "url", ".", "path", ",", "headers", ")", ",", "data", ")", "end", "RubyDesk", ".", "logger", ".", "info", "\"Response code: #{resp.code}\"", "RubyDesk", ".", "logger", ".", "info", "\"Returned data: #{data}\"", "case", "resp", ".", "code", "when", "\"200\"", "then", "return", "data", "when", "\"400\"", "then", "raise", "RubyDesk", "::", "BadRequest", ",", "data", "when", "\"401\"", ",", "\"403\"", "then", "raise", "RubyDesk", "::", "UnauthorizedError", ",", "data", "when", "\"404\"", "then", "raise", "RubyDesk", "::", "PageNotFound", ",", "data", "when", "\"500\"", "then", "raise", "RubyDesk", "::", "ServerError", ",", "data", "else", "raise", "RubyDesk", "::", "Error", ",", "data", "end", "end" ]
invokes the given API call and returns body of the response as text
[ "invokes", "the", "given", "API", "call", "and", "returns", "body", "of", "the", "response", "as", "text" ]
3e62ae5002183b89c9e4c07b640e26c661b7644d
https://github.com/aseldawy/ruby_desk/blob/3e62ae5002183b89c9e4c07b640e26c661b7644d/lib/ruby_desk/connector.rb#L79-L116
6,194
aseldawy/ruby_desk
lib/ruby_desk/connector.rb
RubyDesk.Connector.prepare_and_invoke_api_call
def prepare_and_invoke_api_call(path, options = {}) api_call = prepare_api_call(path, options) data = invoke_api_call(api_call) parsed_data = case options[:format] when 'json' then JSON.parse(data) when 'xml' then REXML::Document.new(data) else JSON.parse(data) rescue REXML::Document.new(data) rescue data end RubyDesk.logger.info "Parsed data: #{parsed_data.inspect}" return parsed_data end
ruby
def prepare_and_invoke_api_call(path, options = {}) api_call = prepare_api_call(path, options) data = invoke_api_call(api_call) parsed_data = case options[:format] when 'json' then JSON.parse(data) when 'xml' then REXML::Document.new(data) else JSON.parse(data) rescue REXML::Document.new(data) rescue data end RubyDesk.logger.info "Parsed data: #{parsed_data.inspect}" return parsed_data end
[ "def", "prepare_and_invoke_api_call", "(", "path", ",", "options", "=", "{", "}", ")", "api_call", "=", "prepare_api_call", "(", "path", ",", "options", ")", "data", "=", "invoke_api_call", "(", "api_call", ")", "parsed_data", "=", "case", "options", "[", ":format", "]", "when", "'json'", "then", "JSON", ".", "parse", "(", "data", ")", "when", "'xml'", "then", "REXML", "::", "Document", ".", "new", "(", "data", ")", "else", "JSON", ".", "parse", "(", "data", ")", "rescue", "REXML", "::", "Document", ".", "new", "(", "data", ")", "rescue", "data", "end", "RubyDesk", ".", "logger", ".", "info", "\"Parsed data: #{parsed_data.inspect}\"", "return", "parsed_data", "end" ]
Prepares an API call with the given arguments then invokes it and returns its body
[ "Prepares", "an", "API", "call", "with", "the", "given", "arguments", "then", "invokes", "it", "and", "returns", "its", "body" ]
3e62ae5002183b89c9e4c07b640e26c661b7644d
https://github.com/aseldawy/ruby_desk/blob/3e62ae5002183b89c9e4c07b640e26c661b7644d/lib/ruby_desk/connector.rb#L119-L130
6,195
aseldawy/ruby_desk
lib/ruby_desk/connector.rb
RubyDesk.Connector.auth_url
def auth_url auth_call = prepare_api_call("", :params=>{:api_key=>@api_key}, :base_url=>ODESK_AUTH_URL, :format=>nil, :method=>:get, :auth=>false) data = auth_call[:params].to_a.map{|pair| pair.join '='}.join('&') return auth_call[:url]+"?"+data end
ruby
def auth_url auth_call = prepare_api_call("", :params=>{:api_key=>@api_key}, :base_url=>ODESK_AUTH_URL, :format=>nil, :method=>:get, :auth=>false) data = auth_call[:params].to_a.map{|pair| pair.join '='}.join('&') return auth_call[:url]+"?"+data end
[ "def", "auth_url", "auth_call", "=", "prepare_api_call", "(", "\"\"", ",", ":params", "=>", "{", ":api_key", "=>", "@api_key", "}", ",", ":base_url", "=>", "ODESK_AUTH_URL", ",", ":format", "=>", "nil", ",", ":method", "=>", ":get", ",", ":auth", "=>", "false", ")", "data", "=", "auth_call", "[", ":params", "]", ".", "to_a", ".", "map", "{", "|", "pair", "|", "pair", ".", "join", "'='", "}", ".", "join", "(", "'&'", ")", "return", "auth_call", "[", ":url", "]", "+", "\"?\"", "+", "data", "end" ]
Returns the URL that authenticates the application for the current user. This is used for web applications only
[ "Returns", "the", "URL", "that", "authenticates", "the", "application", "for", "the", "current", "user", ".", "This", "is", "used", "for", "web", "applications", "only" ]
3e62ae5002183b89c9e4c07b640e26c661b7644d
https://github.com/aseldawy/ruby_desk/blob/3e62ae5002183b89c9e4c07b640e26c661b7644d/lib/ruby_desk/connector.rb#L134-L139
6,196
aseldawy/ruby_desk
lib/ruby_desk/connector.rb
RubyDesk.Connector.desktop_auth_url
def desktop_auth_url raise "Frob should be requested first. Use RubyDesk::Controller#get_frob()" unless @frob auth_call = prepare_api_call("", :params=>{:api_key=>@api_key, :frob=>@frob}, :base_url=>ODESK_AUTH_URL, :format=>nil, :method=>:get, :auth=>false) data = auth_call[:params].to_a.map{|pair| pair.join '='}.join('&') return auth_call[:url]+"?"+data end
ruby
def desktop_auth_url raise "Frob should be requested first. Use RubyDesk::Controller#get_frob()" unless @frob auth_call = prepare_api_call("", :params=>{:api_key=>@api_key, :frob=>@frob}, :base_url=>ODESK_AUTH_URL, :format=>nil, :method=>:get, :auth=>false) data = auth_call[:params].to_a.map{|pair| pair.join '='}.join('&') return auth_call[:url]+"?"+data end
[ "def", "desktop_auth_url", "raise", "\"Frob should be requested first. Use RubyDesk::Controller#get_frob()\"", "unless", "@frob", "auth_call", "=", "prepare_api_call", "(", "\"\"", ",", ":params", "=>", "{", ":api_key", "=>", "@api_key", ",", ":frob", "=>", "@frob", "}", ",", ":base_url", "=>", "ODESK_AUTH_URL", ",", ":format", "=>", "nil", ",", ":method", "=>", ":get", ",", ":auth", "=>", "false", ")", "data", "=", "auth_call", "[", ":params", "]", ".", "to_a", ".", "map", "{", "|", "pair", "|", "pair", ".", "join", "'='", "}", ".", "join", "(", "'&'", ")", "return", "auth_call", "[", ":url", "]", "+", "\"?\"", "+", "data", "end" ]
Returns a URL that the desktop user should visit to activate current frob. This method should not be called before a frob has been requested
[ "Returns", "a", "URL", "that", "the", "desktop", "user", "should", "visit", "to", "activate", "current", "frob", ".", "This", "method", "should", "not", "be", "called", "before", "a", "frob", "has", "been", "requested" ]
3e62ae5002183b89c9e4c07b640e26c661b7644d
https://github.com/aseldawy/ruby_desk/blob/3e62ae5002183b89c9e4c07b640e26c661b7644d/lib/ruby_desk/connector.rb#L143-L149
6,197
spllr/rack-secure_only
lib/rack/secure_only.rb
Rack.SecureOnly.handle?
def handle?(req) if @opts.key?(:if) cond = @opts[:if] cond = cond.call(req) if cond.respond_to?(:call) return cond end true end
ruby
def handle?(req) if @opts.key?(:if) cond = @opts[:if] cond = cond.call(req) if cond.respond_to?(:call) return cond end true end
[ "def", "handle?", "(", "req", ")", "if", "@opts", ".", "key?", "(", ":if", ")", "cond", "=", "@opts", "[", ":if", "]", "cond", "=", "cond", ".", "call", "(", "req", ")", "if", "cond", ".", "respond_to?", "(", ":call", ")", "return", "cond", "end", "true", "end" ]
Returns false if the current request should not be handled by the middleware
[ "Returns", "false", "if", "the", "current", "request", "should", "not", "be", "handled", "by", "the", "middleware" ]
1fff5d875ac41a89d7495f1e5b686d5a3032ee0c
https://github.com/spllr/rack-secure_only/blob/1fff5d875ac41a89d7495f1e5b686d5a3032ee0c/lib/rack/secure_only.rb#L55-L62
6,198
kunklejr/system-metrics
app/models/system_metrics/metric.rb
SystemMetrics.Metric.parent_of?
def parent_of?(metric) if new_record? start = (started_at - metric.started_at) * 1000.0 start <= 0 && (start + duration >= metric.duration) else self.id == metric.parent_id end end
ruby
def parent_of?(metric) if new_record? start = (started_at - metric.started_at) * 1000.0 start <= 0 && (start + duration >= metric.duration) else self.id == metric.parent_id end end
[ "def", "parent_of?", "(", "metric", ")", "if", "new_record?", "start", "=", "(", "started_at", "-", "metric", ".", "started_at", ")", "*", "1000.0", "start", "<=", "0", "&&", "(", "start", "+", "duration", ">=", "metric", ".", "duration", ")", "else", "self", ".", "id", "==", "metric", ".", "parent_id", "end", "end" ]
Returns if the current node is the parent of the given node. If this is a new record, we can use started_at values to detect parenting. However, if it was already saved, we lose microseconds information from timestamps and we must rely solely in id and parent_id information.
[ "Returns", "if", "the", "current", "node", "is", "the", "parent", "of", "the", "given", "node", ".", "If", "this", "is", "a", "new", "record", "we", "can", "use", "started_at", "values", "to", "detect", "parenting", ".", "However", "if", "it", "was", "already", "saved", "we", "lose", "microseconds", "information", "from", "timestamps", "and", "we", "must", "rely", "solely", "in", "id", "and", "parent_id", "information", "." ]
d1b23c88a2c3ce5dd77cb1118d6a539877002516
https://github.com/kunklejr/system-metrics/blob/d1b23c88a2c3ce5dd77cb1118d6a539877002516/app/models/system_metrics/metric.rb#L24-L31
6,199
qw3/superpay_api
lib/superpay_api/item_pedido.rb
SuperpayApi.ItemPedido.to_request
def to_request item_pedido = { codigo_produto: self.codigo_produto, codigo_categoria: self.codigo_categoria, nome_produto: self.nome_produto, quantidade_produto: self.quantidade_produto, valor_unitario_produto: self.valor_unitario_produto, nome_categoria: self.nome_categoria, } return item_pedido end
ruby
def to_request item_pedido = { codigo_produto: self.codigo_produto, codigo_categoria: self.codigo_categoria, nome_produto: self.nome_produto, quantidade_produto: self.quantidade_produto, valor_unitario_produto: self.valor_unitario_produto, nome_categoria: self.nome_categoria, } return item_pedido end
[ "def", "to_request", "item_pedido", "=", "{", "codigo_produto", ":", "self", ".", "codigo_produto", ",", "codigo_categoria", ":", "self", ".", "codigo_categoria", ",", "nome_produto", ":", "self", ".", "nome_produto", ",", "quantidade_produto", ":", "self", ".", "quantidade_produto", ",", "valor_unitario_produto", ":", "self", ".", "valor_unitario_produto", ",", "nome_categoria", ":", "self", ".", "nome_categoria", ",", "}", "return", "item_pedido", "end" ]
Nova instancia da classe ItemPedido @param [Hash] campos Montar o Hash de dados do ItemPedido no padrão utilizado pelo SuperPay
[ "Nova", "instancia", "da", "classe", "ItemPedido" ]
41bfc78f592956708b576f6d0f7c993fb8a3bc22
https://github.com/qw3/superpay_api/blob/41bfc78f592956708b576f6d0f7c993fb8a3bc22/lib/superpay_api/item_pedido.rb#L51-L61