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
partition
stringclasses
1 value
joshwlewis/unitwise
lib/unitwise/compatible.rb
Unitwise.Compatible.composition
def composition root_terms.reduce(SignedMultiset.new) do |s, t| s.increment(t.atom.dim, t.exponent) if t.atom s end end
ruby
def composition root_terms.reduce(SignedMultiset.new) do |s, t| s.increment(t.atom.dim, t.exponent) if t.atom s end end
[ "def", "composition", "root_terms", ".", "reduce", "(", "SignedMultiset", ".", "new", ")", "do", "|", "s", ",", "t", "|", "s", ".", "increment", "(", "t", ".", "atom", ".", "dim", ",", "t", ".", "exponent", ")", "if", "t", ".", "atom", "s", "end", "end" ]
A representation of a unit based on the atoms it's derived from. @return [SignedMultiset] @api public
[ "A", "representation", "of", "a", "unit", "based", "on", "the", "atoms", "it", "s", "derived", "from", "." ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/compatible.rb#L21-L26
train
joshwlewis/unitwise
lib/unitwise/compatible.rb
Unitwise.Compatible.composition_string
def composition_string composition.sort.map do |k, v| v == 1 ? k.to_s : "#{k}#{v}" end.join('.') end
ruby
def composition_string composition.sort.map do |k, v| v == 1 ? k.to_s : "#{k}#{v}" end.join('.') end
[ "def", "composition_string", "composition", ".", "sort", ".", "map", "do", "|", "k", ",", "v", "|", "v", "==", "1", "?", "k", ".", "to_s", ":", "\"#{k}#{v}\"", "end", ".", "join", "(", "'.'", ")", "end" ]
A string representation of a unit based on the atoms it's derived from @return [String] @api public
[ "A", "string", "representation", "of", "a", "unit", "based", "on", "the", "atoms", "it", "s", "derived", "from" ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/compatible.rb#L38-L42
train
joshwlewis/unitwise
lib/unitwise/unit.rb
Unitwise.Unit.terms
def terms unless frozen? unless @terms decomposer = Expression.decompose(@expression) @mode = decomposer.mode @terms = decomposer.terms end freeze end @terms end
ruby
def terms unless frozen? unless @terms decomposer = Expression.decompose(@expression) @mode = decomposer.mode @terms = decomposer.terms end freeze end @terms end
[ "def", "terms", "unless", "frozen?", "unless", "@terms", "decomposer", "=", "Expression", ".", "decompose", "(", "@expression", ")", "@mode", "=", "decomposer", ".", "mode", "@terms", "=", "decomposer", ".", "terms", "end", "freeze", "end", "@terms", "end" ]
Create a new unit. You can send an expression or a collection of terms @param input [String, Unit, [Term]] A string expression, a unit, or a collection of tems. @api public The collection of terms used by this unit. @return [Array] @api public
[ "Create", "a", "new", "unit", ".", "You", "can", "send", "an", "expression", "or", "a", "collection", "of", "terms" ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/unit.rb#L27-L37
train
joshwlewis/unitwise
lib/unitwise/unit.rb
Unitwise.Unit.expression
def expression(mode=nil) if @expression && (mode.nil? || mode == self.mode) @expression else Expression.compose(terms, mode || self.mode) end end
ruby
def expression(mode=nil) if @expression && (mode.nil? || mode == self.mode) @expression else Expression.compose(terms, mode || self.mode) end end
[ "def", "expression", "(", "mode", "=", "nil", ")", "if", "@expression", "&&", "(", "mode", ".", "nil?", "||", "mode", "==", "self", ".", "mode", ")", "@expression", "else", "Expression", ".", "compose", "(", "terms", ",", "mode", "||", "self", ".", "mode", ")", "end", "end" ]
Build a string representation of this unit by it's terms. @param mode [Symbol] The mode to use to stringify the atoms (:primary_code, :names, :secondary_code). @return [String] @api public
[ "Build", "a", "string", "representation", "of", "this", "unit", "by", "it", "s", "terms", "." ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/unit.rb#L44-L50
train
joshwlewis/unitwise
lib/unitwise/unit.rb
Unitwise.Unit.scalar
def scalar(magnitude = 1) terms.reduce(1) do |prod, term| prod * term.scalar(magnitude) end end
ruby
def scalar(magnitude = 1) terms.reduce(1) do |prod, term| prod * term.scalar(magnitude) end end
[ "def", "scalar", "(", "magnitude", "=", "1", ")", "terms", ".", "reduce", "(", "1", ")", "do", "|", "prod", ",", "term", "|", "prod", "*", "term", ".", "scalar", "(", "magnitude", ")", "end", "end" ]
Get a scalar value for this unit. @param magnitude [Numeric] An optional magnitude on this unit's scale. @return [Numeric] A scalar value on a linear scale @api public
[ "Get", "a", "scalar", "value", "for", "this", "unit", "." ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/unit.rb#L89-L93
train
joshwlewis/unitwise
lib/unitwise/unit.rb
Unitwise.Unit.**
def **(other) if other.is_a?(Numeric) self.class.new(terms.map { |t| t ** other }) else fail TypeError, "Can't raise #{self} to #{other}." end end
ruby
def **(other) if other.is_a?(Numeric) self.class.new(terms.map { |t| t ** other }) else fail TypeError, "Can't raise #{self} to #{other}." end end
[ "def", "**", "(", "other", ")", "if", "other", ".", "is_a?", "(", "Numeric", ")", "self", ".", "class", ".", "new", "(", "terms", ".", "map", "{", "|", "t", "|", "t", "**", "other", "}", ")", "else", "fail", "TypeError", ",", "\"Can't raise #{self} to #{other}.\"", "end", "end" ]
Raise this unit to a numeric power. @param other [Numeric] @return [Unitwise::Unit] @api public
[ "Raise", "this", "unit", "to", "a", "numeric", "power", "." ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/unit.rb#L129-L135
train
joshwlewis/unitwise
lib/unitwise/unit.rb
Unitwise.Unit.operate
def operate(operator, other) exp = operator == '/' ? -1 : 1 if other.respond_to?(:terms) self.class.new(terms + other.terms.map { |t| t ** exp }) elsif other.respond_to?(:atom) self.class.new(terms << other ** exp) elsif other.is_a?(Numeric) self.class.new(terms.map { |t| t.send(operator, other) }) end end
ruby
def operate(operator, other) exp = operator == '/' ? -1 : 1 if other.respond_to?(:terms) self.class.new(terms + other.terms.map { |t| t ** exp }) elsif other.respond_to?(:atom) self.class.new(terms << other ** exp) elsif other.is_a?(Numeric) self.class.new(terms.map { |t| t.send(operator, other) }) end end
[ "def", "operate", "(", "operator", ",", "other", ")", "exp", "=", "operator", "==", "'/'", "?", "-", "1", ":", "1", "if", "other", ".", "respond_to?", "(", ":terms", ")", "self", ".", "class", ".", "new", "(", "terms", "+", "other", ".", "terms", ".", "map", "{", "|", "t", "|", "t", "**", "exp", "}", ")", "elsif", "other", ".", "respond_to?", "(", ":atom", ")", "self", ".", "class", ".", "new", "(", "terms", "<<", "other", "**", "exp", ")", "elsif", "other", ".", "is_a?", "(", "Numeric", ")", "self", ".", "class", ".", "new", "(", "terms", ".", "map", "{", "|", "t", "|", "t", ".", "send", "(", "operator", ",", "other", ")", "}", ")", "end", "end" ]
Multiply or divide units @api private
[ "Multiply", "or", "divide", "units" ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/unit.rb#L169-L178
train
joshwlewis/unitwise
lib/unitwise/measurement.rb
Unitwise.Measurement.convert_to
def convert_to(other_unit) other_unit = Unit.new(other_unit) if compatible_with?(other_unit) new(converted_value(other_unit), other_unit) else fail ConversionError, "Can't convert #{self} to #{other_unit}." end end
ruby
def convert_to(other_unit) other_unit = Unit.new(other_unit) if compatible_with?(other_unit) new(converted_value(other_unit), other_unit) else fail ConversionError, "Can't convert #{self} to #{other_unit}." end end
[ "def", "convert_to", "(", "other_unit", ")", "other_unit", "=", "Unit", ".", "new", "(", "other_unit", ")", "if", "compatible_with?", "(", "other_unit", ")", "new", "(", "converted_value", "(", "other_unit", ")", ",", "other_unit", ")", "else", "fail", "ConversionError", ",", "\"Can't convert #{self} to #{other_unit}.\"", "end", "end" ]
Create a new Measurement @param value [Numeric] The scalar value for the measurement @param unit [String, Measurement::Unit] Either a string expression, or a Measurement::Unit @example Unitwise::Measurement.new(20, 'm/s') @api public Convert this measurement to a compatible unit. @param other_unit [String, Measurement::Unit] Either a string expression or a Measurement::Unit @example measurement1.convert_to('foot') measurement2.convert_to('kilogram') @api public
[ "Create", "a", "new", "Measurement" ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/measurement.rb#L26-L33
train
joshwlewis/unitwise
lib/unitwise/measurement.rb
Unitwise.Measurement.**
def **(other) if other.is_a?(Numeric) new(value ** other, unit ** other) else fail TypeError, "Can't raise #{self} to #{other} power." end end
ruby
def **(other) if other.is_a?(Numeric) new(value ** other, unit ** other) else fail TypeError, "Can't raise #{self} to #{other} power." end end
[ "def", "**", "(", "other", ")", "if", "other", ".", "is_a?", "(", "Numeric", ")", "new", "(", "value", "**", "other", ",", "unit", "**", "other", ")", "else", "fail", "TypeError", ",", "\"Can't raise #{self} to #{other} power.\"", "end", "end" ]
Raise a measurement to a numeric power. @param number [Numeric] @example measurement ** 2 @api public
[ "Raise", "a", "measurement", "to", "a", "numeric", "power", "." ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/measurement.rb#L80-L86
train
joshwlewis/unitwise
lib/unitwise/measurement.rb
Unitwise.Measurement.round
def round(digits = nil) rounded_value = digits ? value.round(digits) : value.round self.class.new(rounded_value, unit) end
ruby
def round(digits = nil) rounded_value = digits ? value.round(digits) : value.round self.class.new(rounded_value, unit) end
[ "def", "round", "(", "digits", "=", "nil", ")", "rounded_value", "=", "digits", "?", "value", ".", "round", "(", "digits", ")", ":", "value", ".", "round", "self", ".", "class", ".", "new", "(", "rounded_value", ",", "unit", ")", "end" ]
Round the measurement value. Delegates to the value's class. @return [Integer, Float] @api public
[ "Round", "the", "measurement", "value", ".", "Delegates", "to", "the", "value", "s", "class", "." ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/measurement.rb#L91-L94
train
joshwlewis/unitwise
lib/unitwise/measurement.rb
Unitwise.Measurement.method_missing
def method_missing(meth, *args, &block) if args.empty? && !block_given? && (match = /\Ato_(\w+)\Z/.match(meth.to_s)) begin convert_to(match[1]) rescue ExpressionError super(meth, *args, &block) end else super(meth, *args, &block) end end
ruby
def method_missing(meth, *args, &block) if args.empty? && !block_given? && (match = /\Ato_(\w+)\Z/.match(meth.to_s)) begin convert_to(match[1]) rescue ExpressionError super(meth, *args, &block) end else super(meth, *args, &block) end end
[ "def", "method_missing", "(", "meth", ",", "*", "args", ",", "&", "block", ")", "if", "args", ".", "empty?", "&&", "!", "block_given?", "&&", "(", "match", "=", "/", "\\A", "\\w", "\\Z", "/", ".", "match", "(", "meth", ".", "to_s", ")", ")", "begin", "convert_to", "(", "match", "[", "1", "]", ")", "rescue", "ExpressionError", "super", "(", "meth", ",", "*", "args", ",", "&", "block", ")", "end", "else", "super", "(", "meth", ",", "*", "args", ",", "&", "block", ")", "end", "end" ]
Will attempt to convert to a unit by method name. @example measurement.to_foot # => <Unitwise::Measurement 4 foot> @api semipublic
[ "Will", "attempt", "to", "convert", "to", "a", "unit", "by", "method", "name", "." ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/measurement.rb#L139-L149
train
joshwlewis/unitwise
lib/unitwise/measurement.rb
Unitwise.Measurement.converted_value
def converted_value(other_unit) if other_unit.special? other_unit.magnitude scalar else scalar / other_unit.scalar end end
ruby
def converted_value(other_unit) if other_unit.special? other_unit.magnitude scalar else scalar / other_unit.scalar end end
[ "def", "converted_value", "(", "other_unit", ")", "if", "other_unit", ".", "special?", "other_unit", ".", "magnitude", "scalar", "else", "scalar", "/", "other_unit", ".", "scalar", "end", "end" ]
Determine value of the unit after conversion to another unit @api private
[ "Determine", "value", "of", "the", "unit", "after", "conversion", "to", "another", "unit" ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/measurement.rb#L161-L167
train
joshwlewis/unitwise
lib/unitwise/measurement.rb
Unitwise.Measurement.combine
def combine(operator, other) if other.respond_to?(:composition) && compatible_with?(other) new(value.send(operator, other.convert_to(unit).value), unit) end end
ruby
def combine(operator, other) if other.respond_to?(:composition) && compatible_with?(other) new(value.send(operator, other.convert_to(unit).value), unit) end end
[ "def", "combine", "(", "operator", ",", "other", ")", "if", "other", ".", "respond_to?", "(", ":composition", ")", "&&", "compatible_with?", "(", "other", ")", "new", "(", "value", ".", "send", "(", "operator", ",", "other", ".", "convert_to", "(", "unit", ")", ".", "value", ")", ",", "unit", ")", "end", "end" ]
Add or subtract other unit @api private
[ "Add", "or", "subtract", "other", "unit" ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/measurement.rb#L171-L175
train
joshwlewis/unitwise
lib/unitwise/measurement.rb
Unitwise.Measurement.operate
def operate(operator, other) if other.is_a?(Numeric) new(value.send(operator, other), unit) elsif other.respond_to?(:composition) if compatible_with?(other) converted = other.convert_to(unit) new(value.send(operator, converted.value), unit.send(operator, converted.unit)) else new(value.send(operator, other.value), unit.send(operator, other.unit)) end end end
ruby
def operate(operator, other) if other.is_a?(Numeric) new(value.send(operator, other), unit) elsif other.respond_to?(:composition) if compatible_with?(other) converted = other.convert_to(unit) new(value.send(operator, converted.value), unit.send(operator, converted.unit)) else new(value.send(operator, other.value), unit.send(operator, other.unit)) end end end
[ "def", "operate", "(", "operator", ",", "other", ")", "if", "other", ".", "is_a?", "(", "Numeric", ")", "new", "(", "value", ".", "send", "(", "operator", ",", "other", ")", ",", "unit", ")", "elsif", "other", ".", "respond_to?", "(", ":composition", ")", "if", "compatible_with?", "(", "other", ")", "converted", "=", "other", ".", "convert_to", "(", "unit", ")", "new", "(", "value", ".", "send", "(", "operator", ",", "converted", ".", "value", ")", ",", "unit", ".", "send", "(", "operator", ",", "converted", ".", "unit", ")", ")", "else", "new", "(", "value", ".", "send", "(", "operator", ",", "other", ".", "value", ")", ",", "unit", ".", "send", "(", "operator", ",", "other", ".", "unit", ")", ")", "end", "end", "end" ]
Multiply or divide other unit @api private
[ "Multiply", "or", "divide", "other", "unit" ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/measurement.rb#L179-L192
train
joshwlewis/unitwise
lib/unitwise/scale.rb
Unitwise.Scale.scalar
def scalar(magnitude = value) if special? unit.scalar(magnitude) else Number.rationalize(value) * Number.rationalize(unit.scalar) end end
ruby
def scalar(magnitude = value) if special? unit.scalar(magnitude) else Number.rationalize(value) * Number.rationalize(unit.scalar) end end
[ "def", "scalar", "(", "magnitude", "=", "value", ")", "if", "special?", "unit", ".", "scalar", "(", "magnitude", ")", "else", "Number", ".", "rationalize", "(", "value", ")", "*", "Number", ".", "rationalize", "(", "unit", ".", "scalar", ")", "end", "end" ]
Get a scalar value for this scale. @param magnitude [Numeric] An optional magnitude on this scale. @return [Numeric] A scalar value on a linear scale @api public
[ "Get", "a", "scalar", "value", "for", "this", "scale", "." ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/scale.rb#L51-L57
train
joshwlewis/unitwise
lib/unitwise/scale.rb
Unitwise.Scale.magnitude
def magnitude(scalar = scalar()) if special? unit.magnitude(scalar) else value * unit.magnitude end end
ruby
def magnitude(scalar = scalar()) if special? unit.magnitude(scalar) else value * unit.magnitude end end
[ "def", "magnitude", "(", "scalar", "=", "scalar", "(", ")", ")", "if", "special?", "unit", ".", "magnitude", "(", "scalar", ")", "else", "value", "*", "unit", ".", "magnitude", "end", "end" ]
Get a magnitude based on a linear scale value. Only used by scales with special atoms in it's hierarchy. @param scalar [Numeric] A linear scalar value @return [Numeric] The equivalent magnitude on this scale @api public
[ "Get", "a", "magnitude", "based", "on", "a", "linear", "scale", "value", ".", "Only", "used", "by", "scales", "with", "special", "atoms", "in", "it", "s", "hierarchy", "." ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/scale.rb#L64-L70
train
joshwlewis/unitwise
lib/unitwise/scale.rb
Unitwise.Scale.to_s
def to_s(mode = nil) unit_string = unit.to_s(mode) if unit_string && unit_string != '1' "#{simplified_value} #{unit_string}" else simplified_value.to_s end end
ruby
def to_s(mode = nil) unit_string = unit.to_s(mode) if unit_string && unit_string != '1' "#{simplified_value} #{unit_string}" else simplified_value.to_s end end
[ "def", "to_s", "(", "mode", "=", "nil", ")", "unit_string", "=", "unit", ".", "to_s", "(", "mode", ")", "if", "unit_string", "&&", "unit_string", "!=", "'1'", "\"#{simplified_value} #{unit_string}\"", "else", "simplified_value", ".", "to_s", "end", "end" ]
Convert to a simple string representing the scale. @api public
[ "Convert", "to", "a", "simple", "string", "representing", "the", "scale", "." ]
f786d2e660721a0238949e7abce20852879de8ef
https://github.com/joshwlewis/unitwise/blob/f786d2e660721a0238949e7abce20852879de8ef/lib/unitwise/scale.rb#L104-L111
train
seanchas116/ruby-qml
lib/qml/engine.rb
QML.Engine.evaluate
def evaluate(str, file = '<in QML::Engine#evaluate>', lineno = 1) evaluate_impl(str, file, lineno).tap do |result| raise result.to_error if result.is_a?(JSObject) && result.error? end end
ruby
def evaluate(str, file = '<in QML::Engine#evaluate>', lineno = 1) evaluate_impl(str, file, lineno).tap do |result| raise result.to_error if result.is_a?(JSObject) && result.error? end end
[ "def", "evaluate", "(", "str", ",", "file", "=", "'<in QML::Engine#evaluate>'", ",", "lineno", "=", "1", ")", "evaluate_impl", "(", "str", ",", "file", ",", "lineno", ")", ".", "tap", "do", "|", "result", "|", "raise", "result", ".", "to_error", "if", "result", ".", "is_a?", "(", "JSObject", ")", "&&", "result", ".", "error?", "end", "end" ]
Evaluates an JavaScript expression @param [String] str The JavaScript string @param [String] file The file name @param [Integer] lineno The line number
[ "Evaluates", "an", "JavaScript", "expression" ]
8e809d1b1a03b856c4a4da6e221e5f8fcb0c3b9a
https://github.com/seanchas116/ruby-qml/blob/8e809d1b1a03b856c4a4da6e221e5f8fcb0c3b9a/lib/qml/engine.rb#L13-L17
train
seanchas116/ruby-qml
lib/qml/component.rb
QML.Component.load_path
def load_path(path) path = path.to_s check_error_string do @path = Pathname.new(path) load_path_impl(path) end self end
ruby
def load_path(path) path = path.to_s check_error_string do @path = Pathname.new(path) load_path_impl(path) end self end
[ "def", "load_path", "(", "path", ")", "path", "=", "path", ".", "to_s", "check_error_string", "do", "@path", "=", "Pathname", ".", "new", "(", "path", ")", "load_path_impl", "(", "path", ")", "end", "self", "end" ]
Creates an component. Either data or path must be specified. @param [String] data the QML file data. @param [#to_s] path the QML file path. @return QML::Component
[ "Creates", "an", "component", ".", "Either", "data", "or", "path", "must", "be", "specified", "." ]
8e809d1b1a03b856c4a4da6e221e5f8fcb0c3b9a
https://github.com/seanchas116/ruby-qml/blob/8e809d1b1a03b856c4a4da6e221e5f8fcb0c3b9a/lib/qml/component.rb#L32-L39
train
seanchas116/ruby-qml
lib/qml/signal.rb
QML.Signal.emit
def emit(*args) if args.size != @arity fail ::ArgumentError ,"wrong number of arguments for signal (#{args.size} for #{@arity})" end @listeners.each do |listener| listener.call(*args) end end
ruby
def emit(*args) if args.size != @arity fail ::ArgumentError ,"wrong number of arguments for signal (#{args.size} for #{@arity})" end @listeners.each do |listener| listener.call(*args) end end
[ "def", "emit", "(", "*", "args", ")", "if", "args", ".", "size", "!=", "@arity", "fail", "::", "ArgumentError", ",", "\"wrong number of arguments for signal (#{args.size} for #{@arity})\"", "end", "@listeners", ".", "each", "do", "|", "listener", "|", "listener", ".", "call", "(", "*", "args", ")", "end", "end" ]
Initializes the Signal. @param [Array<#to_sym>, nil] params the parameter names (the signal will be variadic if nil). Calls every connected procedure with given arguments. Raises an ArgumentError when the arity is wrong. @param args the arguments.
[ "Initializes", "the", "Signal", "." ]
8e809d1b1a03b856c4a4da6e221e5f8fcb0c3b9a
https://github.com/seanchas116/ruby-qml/blob/8e809d1b1a03b856c4a4da6e221e5f8fcb0c3b9a/lib/qml/signal.rb#L30-L37
train
seanchas116/ruby-qml
lib/qml/data/list_model.rb
QML.ListModel.moving
def moving(range, destination) return if range.count == 0 @access.begin_move(range.min, range.max, destination) ret = yield @access.end_move ret end
ruby
def moving(range, destination) return if range.count == 0 @access.begin_move(range.min, range.max, destination) ret = yield @access.end_move ret end
[ "def", "moving", "(", "range", ",", "destination", ")", "return", "if", "range", ".", "count", "==", "0", "@access", ".", "begin_move", "(", "range", ".", "min", ",", "range", ".", "max", ",", "destination", ")", "ret", "=", "yield", "@access", ".", "end_move", "ret", "end" ]
Notifies the list views that items are about to be and were moved. @param [Range<Integer>] range the index range of the item being moved. @param [Integer] destination the first index of the items after moved. @yield the block that actually do moving operation of the items. @return the result of given block. @see http://qt-project.org/doc/qt-5/qabstractitemmodel.html#beginMoveRows QAbstractItemModel::beginMoveRows @see http://qt-project.org/doc/qt-5/qabstractitemmodel.html#endMoveRows QAbstractItemModel::endMoveRows @see #inserting @see #removing
[ "Notifies", "the", "list", "views", "that", "items", "are", "about", "to", "be", "and", "were", "moved", "." ]
8e809d1b1a03b856c4a4da6e221e5f8fcb0c3b9a
https://github.com/seanchas116/ruby-qml/blob/8e809d1b1a03b856c4a4da6e221e5f8fcb0c3b9a/lib/qml/data/list_model.rb#L68-L75
train
seanchas116/ruby-qml
lib/qml/data/list_model.rb
QML.ListModel.inserting
def inserting(range, &block) return if range.count == 0 @access.begin_insert(range.min, range.max) ret = yield @access.end_insert ret end
ruby
def inserting(range, &block) return if range.count == 0 @access.begin_insert(range.min, range.max) ret = yield @access.end_insert ret end
[ "def", "inserting", "(", "range", ",", "&", "block", ")", "return", "if", "range", ".", "count", "==", "0", "@access", ".", "begin_insert", "(", "range", ".", "min", ",", "range", ".", "max", ")", "ret", "=", "yield", "@access", ".", "end_insert", "ret", "end" ]
Notifies the list views that items are about to be and were inserted. @param [Range<Integer>] range the index range of the items after inserted. @yield the block that actually do insertion of the items. @return the result of give block. @example inserting(index ... index + items.size) do @array.insert(index, *items) end @see http://qt-project.org/doc/qt-5/qabstractitemmodel.html#beginInsertRows QAbstractItemModel::beginInsertRows @see http://qt-project.org/doc/qt-5/qabstractitemmodel.html#endInsertRows QAbstractItemModel::endInsertRows @see #removing @see #moving
[ "Notifies", "the", "list", "views", "that", "items", "are", "about", "to", "be", "and", "were", "inserted", "." ]
8e809d1b1a03b856c4a4da6e221e5f8fcb0c3b9a
https://github.com/seanchas116/ruby-qml/blob/8e809d1b1a03b856c4a4da6e221e5f8fcb0c3b9a/lib/qml/data/list_model.rb#L89-L96
train
seanchas116/ruby-qml
lib/qml/data/list_model.rb
QML.ListModel.removing
def removing(range, &block) return if range.count == 0 @access.begin_remove(range.min, range.max) ret = yield @access.end_remove ret end
ruby
def removing(range, &block) return if range.count == 0 @access.begin_remove(range.min, range.max) ret = yield @access.end_remove ret end
[ "def", "removing", "(", "range", ",", "&", "block", ")", "return", "if", "range", ".", "count", "==", "0", "@access", ".", "begin_remove", "(", "range", ".", "min", ",", "range", ".", "max", ")", "ret", "=", "yield", "@access", ".", "end_remove", "ret", "end" ]
Notifies the list views that items are about to be and were removed. @param [Range<Integer>] range the index range of the items before removed. @yield the block that actually do removal of the items. @return the result of give block. @see http://qt-project.org/doc/qt-5/qabstractitemmodel.html#beginRemoveRows QAbstractItemModel::beginRemoveRows @see http://qt-project.org/doc/qt-5/qabstractitemmodel.html#endRemoveRows QAbstractItemModel::endRemoveRows @see #inserting @see #moving
[ "Notifies", "the", "list", "views", "that", "items", "are", "about", "to", "be", "and", "were", "removed", "." ]
8e809d1b1a03b856c4a4da6e221e5f8fcb0c3b9a
https://github.com/seanchas116/ruby-qml/blob/8e809d1b1a03b856c4a4da6e221e5f8fcb0c3b9a/lib/qml/data/list_model.rb#L106-L113
train
seanchas116/ruby-qml
lib/qml/data/array_model.rb
QML.ArrayModel.insert
def insert(index, *items) inserting(index ... index + items.size) do @array.insert(index, *items) end self end
ruby
def insert(index, *items) inserting(index ... index + items.size) do @array.insert(index, *items) end self end
[ "def", "insert", "(", "index", ",", "*", "items", ")", "inserting", "(", "index", "...", "index", "+", "items", ".", "size", ")", "do", "@array", ".", "insert", "(", "index", ",", "*", "items", ")", "end", "self", "end" ]
Inserts items. @param [Integer] index @return [self]
[ "Inserts", "items", "." ]
8e809d1b1a03b856c4a4da6e221e5f8fcb0c3b9a
https://github.com/seanchas116/ruby-qml/blob/8e809d1b1a03b856c4a4da6e221e5f8fcb0c3b9a/lib/qml/data/array_model.rb#L42-L47
train
seanchas116/ruby-qml
lib/qml/js_object.rb
QML.JSObject.method_missing
def method_missing(method, *args, &block) if method[-1] == '=' # setter key = method.slice(0...-1).to_sym unless has_key?(key) super end self[key] = args[0] else unless has_key?(method) super end prop = self[method] if prop.is_a? JSFunction prop.call_with_instance(self, *args, &block) else prop end end end
ruby
def method_missing(method, *args, &block) if method[-1] == '=' # setter key = method.slice(0...-1).to_sym unless has_key?(key) super end self[key] = args[0] else unless has_key?(method) super end prop = self[method] if prop.is_a? JSFunction prop.call_with_instance(self, *args, &block) else prop end end end
[ "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "if", "method", "[", "-", "1", "]", "==", "'='", "key", "=", "method", ".", "slice", "(", "0", "...", "-", "1", ")", ".", "to_sym", "unless", "has_key?", "(", "key", ")", "super", "end", "self", "[", "key", "]", "=", "args", "[", "0", "]", "else", "unless", "has_key?", "(", "method", ")", "super", "end", "prop", "=", "self", "[", "method", "]", "if", "prop", ".", "is_a?", "JSFunction", "prop", ".", "call_with_instance", "(", "self", ",", "*", "args", ",", "&", "block", ")", "else", "prop", "end", "end", "end" ]
Gets or sets a JS property, or call it as a method if it is a function.
[ "Gets", "or", "sets", "a", "JS", "property", "or", "call", "it", "as", "a", "method", "if", "it", "is", "a", "function", "." ]
8e809d1b1a03b856c4a4da6e221e5f8fcb0c3b9a
https://github.com/seanchas116/ruby-qml/blob/8e809d1b1a03b856c4a4da6e221e5f8fcb0c3b9a/lib/qml/js_object.rb#L41-L62
train
zed-0xff/zpng
lib/zpng/adam7_decoder.rb
ZPNG.Adam7Decoder.convert_coords
def convert_coords x,y # optimizing this into one switch/case statement gives # about 1-2% speed increase (ruby 1.9.3p286) if y%2 == 1 # 7th pass: last height/2 full scanlines [x, y/2 + @pass_starts[7]] elsif x%2 == 1 && y%2 == 0 # 6th pass [x/2, y/2 + @pass_starts[6]] elsif x%8 == 0 && y%8 == 0 # 1st pass, starts at 0 [x/8, y/8] elsif x%8 == 4 && y%8 == 0 # 2nd pass [x/8, y/8 + @pass_starts[2]] elsif x%4 == 0 && y%8 == 4 # 3rd pass [x/4, y/8 + @pass_starts[3]] elsif x%4 == 2 && y%4 == 0 # 4th pass [x/4, y/4 + @pass_starts[4]] elsif x%2 == 0 && y%4 == 2 # 5th pass [x/2, y/4 + @pass_starts[5]] else raise "invalid coords" end end
ruby
def convert_coords x,y # optimizing this into one switch/case statement gives # about 1-2% speed increase (ruby 1.9.3p286) if y%2 == 1 # 7th pass: last height/2 full scanlines [x, y/2 + @pass_starts[7]] elsif x%2 == 1 && y%2 == 0 # 6th pass [x/2, y/2 + @pass_starts[6]] elsif x%8 == 0 && y%8 == 0 # 1st pass, starts at 0 [x/8, y/8] elsif x%8 == 4 && y%8 == 0 # 2nd pass [x/8, y/8 + @pass_starts[2]] elsif x%4 == 0 && y%8 == 4 # 3rd pass [x/4, y/8 + @pass_starts[3]] elsif x%4 == 2 && y%4 == 0 # 4th pass [x/4, y/4 + @pass_starts[4]] elsif x%2 == 0 && y%4 == 2 # 5th pass [x/2, y/4 + @pass_starts[5]] else raise "invalid coords" end end
[ "def", "convert_coords", "x", ",", "y", "if", "y", "%", "2", "==", "1", "[", "x", ",", "y", "/", "2", "+", "@pass_starts", "[", "7", "]", "]", "elsif", "x", "%", "2", "==", "1", "&&", "y", "%", "2", "==", "0", "[", "x", "/", "2", ",", "y", "/", "2", "+", "@pass_starts", "[", "6", "]", "]", "elsif", "x", "%", "8", "==", "0", "&&", "y", "%", "8", "==", "0", "[", "x", "/", "8", ",", "y", "/", "8", "]", "elsif", "x", "%", "8", "==", "4", "&&", "y", "%", "8", "==", "0", "[", "x", "/", "8", ",", "y", "/", "8", "+", "@pass_starts", "[", "2", "]", "]", "elsif", "x", "%", "4", "==", "0", "&&", "y", "%", "8", "==", "4", "[", "x", "/", "4", ",", "y", "/", "8", "+", "@pass_starts", "[", "3", "]", "]", "elsif", "x", "%", "4", "==", "2", "&&", "y", "%", "4", "==", "0", "[", "x", "/", "4", ",", "y", "/", "4", "+", "@pass_starts", "[", "4", "]", "]", "elsif", "x", "%", "2", "==", "0", "&&", "y", "%", "4", "==", "2", "[", "x", "/", "2", ",", "y", "/", "4", "+", "@pass_starts", "[", "5", "]", "]", "else", "raise", "\"invalid coords\"", "end", "end" ]
convert "flat" coords in scanline number & pos in scanline
[ "convert", "flat", "coords", "in", "scanline", "number", "&", "pos", "in", "scanline" ]
d356182ab9bbc2ed3fe5c064488498cf1678b0f0
https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/adam7_decoder.rb#L41-L69
train
zed-0xff/zpng
lib/zpng/image.rb
ZPNG.Image.save
def save fname, options={} File.open(fname,"wb"){ |f| f << export(options) } end
ruby
def save fname, options={} File.open(fname,"wb"){ |f| f << export(options) } end
[ "def", "save", "fname", ",", "options", "=", "{", "}", "File", ".", "open", "(", "fname", ",", "\"wb\"", ")", "{", "|", "f", "|", "f", "<<", "export", "(", "options", ")", "}", "end" ]
save image to file
[ "save", "image", "to", "file" ]
d356182ab9bbc2ed3fe5c064488498cf1678b0f0
https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/image.rb#L80-L82
train
zed-0xff/zpng
lib/zpng/image.rb
ZPNG.Image._safe_inflate
def _safe_inflate data zi = Zlib::Inflate.new pos = 0; r = '' begin # save some memory by not using String#[] when not necessary r << zi.inflate(pos==0 ? data : data[pos..-1]) if zi.total_in < data.size @extradata << data[zi.total_in..-1] puts "[?] #{@extradata.last.size} bytes of extra data after zlib stream".red if @verbose >= 1 end # decompress OK rescue Zlib::BufError # tried to decompress, but got EOF - need more data puts "[!] #{$!.inspect}".red if @verbose >= -1 # collect any remaining data in decompress buffer r << zi.flush_next_out rescue Zlib::DataError puts "[!] #{$!.inspect}".red if @verbose >= -1 #p [pos, zi.total_in, zi.total_out, data.size, r.size] r << zi.flush_next_out # XXX TODO try to skip error and continue # printf "[d] pos=%d/%d t_in=%d t_out=%d bytes_ok=%d\n".gray, pos, data.size, # zi.total_in, zi.total_out, r.size # if pos < zi.total_in # pos = zi.total_in # else # pos += 1 # end # pos = 0 # retry if pos < data.size rescue Zlib::NeedDict puts "[!] #{$!.inspect}".red if @verbose >= -1 # collect any remaining data in decompress buffer r << zi.flush_next_out end r == "" ? nil : r ensure zi.close if zi && !zi.closed? end
ruby
def _safe_inflate data zi = Zlib::Inflate.new pos = 0; r = '' begin # save some memory by not using String#[] when not necessary r << zi.inflate(pos==0 ? data : data[pos..-1]) if zi.total_in < data.size @extradata << data[zi.total_in..-1] puts "[?] #{@extradata.last.size} bytes of extra data after zlib stream".red if @verbose >= 1 end # decompress OK rescue Zlib::BufError # tried to decompress, but got EOF - need more data puts "[!] #{$!.inspect}".red if @verbose >= -1 # collect any remaining data in decompress buffer r << zi.flush_next_out rescue Zlib::DataError puts "[!] #{$!.inspect}".red if @verbose >= -1 #p [pos, zi.total_in, zi.total_out, data.size, r.size] r << zi.flush_next_out # XXX TODO try to skip error and continue # printf "[d] pos=%d/%d t_in=%d t_out=%d bytes_ok=%d\n".gray, pos, data.size, # zi.total_in, zi.total_out, r.size # if pos < zi.total_in # pos = zi.total_in # else # pos += 1 # end # pos = 0 # retry if pos < data.size rescue Zlib::NeedDict puts "[!] #{$!.inspect}".red if @verbose >= -1 # collect any remaining data in decompress buffer r << zi.flush_next_out end r == "" ? nil : r ensure zi.close if zi && !zi.closed? end
[ "def", "_safe_inflate", "data", "zi", "=", "Zlib", "::", "Inflate", ".", "new", "pos", "=", "0", ";", "r", "=", "''", "begin", "r", "<<", "zi", ".", "inflate", "(", "pos", "==", "0", "?", "data", ":", "data", "[", "pos", "..", "-", "1", "]", ")", "if", "zi", ".", "total_in", "<", "data", ".", "size", "@extradata", "<<", "data", "[", "zi", ".", "total_in", "..", "-", "1", "]", "puts", "\"[?] #{@extradata.last.size} bytes of extra data after zlib stream\"", ".", "red", "if", "@verbose", ">=", "1", "end", "rescue", "Zlib", "::", "BufError", "puts", "\"[!] #{$!.inspect}\"", ".", "red", "if", "@verbose", ">=", "-", "1", "r", "<<", "zi", ".", "flush_next_out", "rescue", "Zlib", "::", "DataError", "puts", "\"[!] #{$!.inspect}\"", ".", "red", "if", "@verbose", ">=", "-", "1", "r", "<<", "zi", ".", "flush_next_out", "rescue", "Zlib", "::", "NeedDict", "puts", "\"[!] #{$!.inspect}\"", ".", "red", "if", "@verbose", ">=", "-", "1", "r", "<<", "zi", ".", "flush_next_out", "end", "r", "==", "\"\"", "?", "nil", ":", "r", "ensure", "zi", ".", "close", "if", "zi", "&&", "!", "zi", ".", "closed?", "end" ]
unpack zlib, on errors keep going and try to return maximum possible data
[ "unpack", "zlib", "on", "errors", "keep", "going", "and", "try", "to", "return", "maximum", "possible", "data" ]
d356182ab9bbc2ed3fe5c064488498cf1678b0f0
https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/image.rb#L245-L284
train
zed-0xff/zpng
lib/zpng/image.rb
ZPNG.Image.crop!
def crop! params decode_all_scanlines x,y,h,w = (params[:x]||0), (params[:y]||0), params[:height], params[:width] raise ArgumentError, "negative params not allowed" if [x,y,h,w].any?{ |x| x < 0 } # adjust crop sizes if they greater than image sizes h = self.height-y if (y+h) > self.height w = self.width-x if (x+w) > self.width raise ArgumentError, "negative params not allowed (p2)" if [x,y,h,w].any?{ |x| x < 0 } # delete excess scanlines at tail scanlines[(y+h)..-1] = [] if (y+h) < scanlines.size # delete excess scanlines at head scanlines[0,y] = [] if y > 0 # crop remaining scanlines scanlines.each{ |l| l.crop!(x,w) } # modify header hdr.height, hdr.width = h, w # return self self end
ruby
def crop! params decode_all_scanlines x,y,h,w = (params[:x]||0), (params[:y]||0), params[:height], params[:width] raise ArgumentError, "negative params not allowed" if [x,y,h,w].any?{ |x| x < 0 } # adjust crop sizes if they greater than image sizes h = self.height-y if (y+h) > self.height w = self.width-x if (x+w) > self.width raise ArgumentError, "negative params not allowed (p2)" if [x,y,h,w].any?{ |x| x < 0 } # delete excess scanlines at tail scanlines[(y+h)..-1] = [] if (y+h) < scanlines.size # delete excess scanlines at head scanlines[0,y] = [] if y > 0 # crop remaining scanlines scanlines.each{ |l| l.crop!(x,w) } # modify header hdr.height, hdr.width = h, w # return self self end
[ "def", "crop!", "params", "decode_all_scanlines", "x", ",", "y", ",", "h", ",", "w", "=", "(", "params", "[", ":x", "]", "||", "0", ")", ",", "(", "params", "[", ":y", "]", "||", "0", ")", ",", "params", "[", ":height", "]", ",", "params", "[", ":width", "]", "raise", "ArgumentError", ",", "\"negative params not allowed\"", "if", "[", "x", ",", "y", ",", "h", ",", "w", "]", ".", "any?", "{", "|", "x", "|", "x", "<", "0", "}", "h", "=", "self", ".", "height", "-", "y", "if", "(", "y", "+", "h", ")", ">", "self", ".", "height", "w", "=", "self", ".", "width", "-", "x", "if", "(", "x", "+", "w", ")", ">", "self", ".", "width", "raise", "ArgumentError", ",", "\"negative params not allowed (p2)\"", "if", "[", "x", ",", "y", ",", "h", ",", "w", "]", ".", "any?", "{", "|", "x", "|", "x", "<", "0", "}", "scanlines", "[", "(", "y", "+", "h", ")", "..", "-", "1", "]", "=", "[", "]", "if", "(", "y", "+", "h", ")", "<", "scanlines", ".", "size", "scanlines", "[", "0", ",", "y", "]", "=", "[", "]", "if", "y", ">", "0", "scanlines", ".", "each", "{", "|", "l", "|", "l", ".", "crop!", "(", "x", ",", "w", ")", "}", "hdr", ".", "height", ",", "hdr", ".", "width", "=", "h", ",", "w", "self", "end" ]
modifies this image
[ "modifies", "this", "image" ]
d356182ab9bbc2ed3fe5c064488498cf1678b0f0
https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/image.rb#L430-L455
train
zed-0xff/zpng
lib/zpng/image.rb
ZPNG.Image.deinterlace
def deinterlace return self unless interlaced? # copy all but 'interlace' header params h = Hash[*%w'width height depth color compression filter'.map{ |k| [k.to_sym, hdr.send(k)] }.flatten] # don't auto-add palette chunk h[:palette] = nil # create new img new_img = self.class.new h # copy all but hdr/imagedata/end chunks chunks.each do |chunk| next if chunk.is_a?(Chunk::IHDR) next if chunk.is_a?(Chunk::IDAT) next if chunk.is_a?(Chunk::IEND) new_img.chunks << chunk.deep_copy end # pixel-by-pixel copy each_pixel do |c,x,y| new_img[x,y] = c end new_img end
ruby
def deinterlace return self unless interlaced? # copy all but 'interlace' header params h = Hash[*%w'width height depth color compression filter'.map{ |k| [k.to_sym, hdr.send(k)] }.flatten] # don't auto-add palette chunk h[:palette] = nil # create new img new_img = self.class.new h # copy all but hdr/imagedata/end chunks chunks.each do |chunk| next if chunk.is_a?(Chunk::IHDR) next if chunk.is_a?(Chunk::IDAT) next if chunk.is_a?(Chunk::IEND) new_img.chunks << chunk.deep_copy end # pixel-by-pixel copy each_pixel do |c,x,y| new_img[x,y] = c end new_img end
[ "def", "deinterlace", "return", "self", "unless", "interlaced?", "h", "=", "Hash", "[", "*", "%w'", "width", "height", "depth", "color", "compression", "filter", "'", ".", "map", "{", "|", "k", "|", "[", "k", ".", "to_sym", ",", "hdr", ".", "send", "(", "k", ")", "]", "}", ".", "flatten", "]", "h", "[", ":palette", "]", "=", "nil", "new_img", "=", "self", ".", "class", ".", "new", "h", "chunks", ".", "each", "do", "|", "chunk", "|", "next", "if", "chunk", ".", "is_a?", "(", "Chunk", "::", "IHDR", ")", "next", "if", "chunk", ".", "is_a?", "(", "Chunk", "::", "IDAT", ")", "next", "if", "chunk", ".", "is_a?", "(", "Chunk", "::", "IEND", ")", "new_img", ".", "chunks", "<<", "chunk", ".", "deep_copy", "end", "each_pixel", "do", "|", "c", ",", "x", ",", "y", "|", "new_img", "[", "x", ",", "y", "]", "=", "c", "end", "new_img", "end" ]
returns new deinterlaced image if deinterlaced OR returns self if no need to deinterlace
[ "returns", "new", "deinterlaced", "image", "if", "deinterlaced", "OR", "returns", "self", "if", "no", "need", "to", "deinterlace" ]
d356182ab9bbc2ed3fe5c064488498cf1678b0f0
https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/image.rb#L488-L514
train
zed-0xff/zpng
lib/zpng/color.rb
ZPNG.Color.to_ansi
def to_ansi return to_depth(8).to_ansi if depth != 8 a = ANSI_COLORS.map{|c| self.class.const_get(c.to_s.upcase) } a.map!{ |c| self.euclidian(c) } ANSI_COLORS[a.index(a.min)] end
ruby
def to_ansi return to_depth(8).to_ansi if depth != 8 a = ANSI_COLORS.map{|c| self.class.const_get(c.to_s.upcase) } a.map!{ |c| self.euclidian(c) } ANSI_COLORS[a.index(a.min)] end
[ "def", "to_ansi", "return", "to_depth", "(", "8", ")", ".", "to_ansi", "if", "depth", "!=", "8", "a", "=", "ANSI_COLORS", ".", "map", "{", "|", "c", "|", "self", ".", "class", ".", "const_get", "(", "c", ".", "to_s", ".", "upcase", ")", "}", "a", ".", "map!", "{", "|", "c", "|", "self", ".", "euclidian", "(", "c", ")", "}", "ANSI_COLORS", "[", "a", ".", "index", "(", "a", ".", "min", ")", "]", "end" ]
convert to ANSI color name
[ "convert", "to", "ANSI", "color", "name" ]
d356182ab9bbc2ed3fe5c064488498cf1678b0f0
https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/color.rb#L142-L147
train
zed-0xff/zpng
lib/zpng/color.rb
ZPNG.Color.to_depth
def to_depth new_depth return self if depth == new_depth color = Color.new :depth => new_depth if new_depth > self.depth %w'r g b a'.each do |part| color.send("#{part}=", (2**new_depth-1)/(2**depth-1)*self.send(part)) end else # new_depth < self.depth %w'r g b a'.each do |part| color.send("#{part}=", self.send(part)>>(self.depth-new_depth)) end end color end
ruby
def to_depth new_depth return self if depth == new_depth color = Color.new :depth => new_depth if new_depth > self.depth %w'r g b a'.each do |part| color.send("#{part}=", (2**new_depth-1)/(2**depth-1)*self.send(part)) end else # new_depth < self.depth %w'r g b a'.each do |part| color.send("#{part}=", self.send(part)>>(self.depth-new_depth)) end end color end
[ "def", "to_depth", "new_depth", "return", "self", "if", "depth", "==", "new_depth", "color", "=", "Color", ".", "new", ":depth", "=>", "new_depth", "if", "new_depth", ">", "self", ".", "depth", "%w'", "r", "g", "b", "a", "'", ".", "each", "do", "|", "part", "|", "color", ".", "send", "(", "\"#{part}=\"", ",", "(", "2", "**", "new_depth", "-", "1", ")", "/", "(", "2", "**", "depth", "-", "1", ")", "*", "self", ".", "send", "(", "part", ")", ")", "end", "else", "%w'", "r", "g", "b", "a", "'", ".", "each", "do", "|", "part", "|", "color", ".", "send", "(", "\"#{part}=\"", ",", "self", ".", "send", "(", "part", ")", ">>", "(", "self", ".", "depth", "-", "new_depth", ")", ")", "end", "end", "color", "end" ]
change bit depth, return new Color
[ "change", "bit", "depth", "return", "new", "Color" ]
d356182ab9bbc2ed3fe5c064488498cf1678b0f0
https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/color.rb#L159-L174
train
zed-0xff/zpng
lib/zpng/color.rb
ZPNG.Color.op
def op op, c=nil # XXX what to do with alpha? max = 2**depth-1 if c c = c.to_depth(depth) Color.new( @r.send(op, c.r) & max, @g.send(op, c.g) & max, @b.send(op, c.b) & max, :depth => self.depth ) else Color.new( @r.send(op) & max, @g.send(op) & max, @b.send(op) & max, :depth => self.depth ) end end
ruby
def op op, c=nil # XXX what to do with alpha? max = 2**depth-1 if c c = c.to_depth(depth) Color.new( @r.send(op, c.r) & max, @g.send(op, c.g) & max, @b.send(op, c.b) & max, :depth => self.depth ) else Color.new( @r.send(op) & max, @g.send(op) & max, @b.send(op) & max, :depth => self.depth ) end end
[ "def", "op", "op", ",", "c", "=", "nil", "max", "=", "2", "**", "depth", "-", "1", "if", "c", "c", "=", "c", ".", "to_depth", "(", "depth", ")", "Color", ".", "new", "(", "@r", ".", "send", "(", "op", ",", "c", ".", "r", ")", "&", "max", ",", "@g", ".", "send", "(", "op", ",", "c", ".", "g", ")", "&", "max", ",", "@b", ".", "send", "(", "op", ",", "c", ".", "b", ")", "&", "max", ",", ":depth", "=>", "self", ".", "depth", ")", "else", "Color", ".", "new", "(", "@r", ".", "send", "(", "op", ")", "&", "max", ",", "@g", ".", "send", "(", "op", ")", "&", "max", ",", "@b", ".", "send", "(", "op", ")", "&", "max", ",", ":depth", "=>", "self", ".", "depth", ")", "end", "end" ]
Op! op! op! Op!! Oppan Gangnam Style!!
[ "Op!", "op!", "op!", "Op!!", "Oppan", "Gangnam", "Style!!" ]
d356182ab9bbc2ed3fe5c064488498cf1678b0f0
https://github.com/zed-0xff/zpng/blob/d356182ab9bbc2ed3fe5c064488498cf1678b0f0/lib/zpng/color.rb#L245-L264
train
socrata/soda-ruby
lib/soda/client.rb
SODA.Client.handle_response
def handle_response(response) # Check our response code check_response_fail(response) return nil if blank?(response.body) # Return a bunch of mashes as the body if we're JSON begin response.body = JSON.parse(response.body, max_nesting: false) response.body = if response.body.is_a? Array response.body.map { |r| Hashie::Mash.new(r) } else Hashie::Mash.new(response.body) end rescue => exception raise "JSON parsing failed. Error details: #{exception}" ensure return response end end
ruby
def handle_response(response) # Check our response code check_response_fail(response) return nil if blank?(response.body) # Return a bunch of mashes as the body if we're JSON begin response.body = JSON.parse(response.body, max_nesting: false) response.body = if response.body.is_a? Array response.body.map { |r| Hashie::Mash.new(r) } else Hashie::Mash.new(response.body) end rescue => exception raise "JSON parsing failed. Error details: #{exception}" ensure return response end end
[ "def", "handle_response", "(", "response", ")", "check_response_fail", "(", "response", ")", "return", "nil", "if", "blank?", "(", "response", ".", "body", ")", "begin", "response", ".", "body", "=", "JSON", ".", "parse", "(", "response", ".", "body", ",", "max_nesting", ":", "false", ")", "response", ".", "body", "=", "if", "response", ".", "body", ".", "is_a?", "Array", "response", ".", "body", ".", "map", "{", "|", "r", "|", "Hashie", "::", "Mash", ".", "new", "(", "r", ")", "}", "else", "Hashie", "::", "Mash", ".", "new", "(", "response", ".", "body", ")", "end", "rescue", "=>", "exception", "raise", "\"JSON parsing failed. Error details: #{exception}\"", "ensure", "return", "response", "end", "end" ]
Returns a response with a parsed body
[ "Returns", "a", "response", "with", "a", "parsed", "body" ]
7d3174b78fc6723ed30561a30e682d14bf6d62af
https://github.com/socrata/soda-ruby/blob/7d3174b78fc6723ed30561a30e682d14bf6d62af/lib/soda/client.rb#L186-L204
train
jpablobr/active_paypal_adaptive_payment
lib/active_merchant/billing/gateways/paypal_adaptive_payments/ext.rb
Hashie.Rash.underscore_string
def underscore_string(str) str.to_s.strip. gsub(' ', '_'). gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). squeeze("_"). downcase end
ruby
def underscore_string(str) str.to_s.strip. gsub(' ', '_'). gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). squeeze("_"). downcase end
[ "def", "underscore_string", "(", "str", ")", "str", ".", "to_s", ".", "strip", ".", "gsub", "(", "' '", ",", "'_'", ")", ".", "gsub", "(", "/", "/", ",", "'/'", ")", ".", "gsub", "(", "/", "/", ",", "'\\1_\\2'", ")", ".", "gsub", "(", "/", "\\d", "/", ",", "'\\1_\\2'", ")", ".", "tr", "(", "\"-\"", ",", "\"_\"", ")", ".", "squeeze", "(", "\"_\"", ")", ".", "downcase", "end" ]
converts a camel_cased string to a underscore string subs spaces with underscores, strips whitespace Same way ActiveSupport does string.underscore
[ "converts", "a", "camel_cased", "string", "to", "a", "underscore", "string", "subs", "spaces", "with", "underscores", "strips", "whitespace", "Same", "way", "ActiveSupport", "does", "string", ".", "underscore" ]
e2b215fda00d9430c4b2433c592718b128da92e6
https://github.com/jpablobr/active_paypal_adaptive_payment/blob/e2b215fda00d9430c4b2433c592718b128da92e6/lib/active_merchant/billing/gateways/paypal_adaptive_payments/ext.rb#L18-L27
train
hexdigest/ruby-nfc
lib/ruby-nfc/reader.rb
NFC.Reader.discover
def discover(*card_types) # TODO: по правильному здесь надо делать низкоуровневый card_types.inject([]) do |tags, card_type| raise NFC::Error.new('Wrong card type') unless card_type.respond_to? :discover tags += card_type.discover(connect) end end
ruby
def discover(*card_types) # TODO: по правильному здесь надо делать низкоуровневый card_types.inject([]) do |tags, card_type| raise NFC::Error.new('Wrong card type') unless card_type.respond_to? :discover tags += card_type.discover(connect) end end
[ "def", "discover", "(", "*", "card_types", ")", "card_types", ".", "inject", "(", "[", "]", ")", "do", "|", "tags", ",", "card_type", "|", "raise", "NFC", "::", "Error", ".", "new", "(", "'Wrong card type'", ")", "unless", "card_type", ".", "respond_to?", ":discover", "tags", "+=", "card_type", ".", "discover", "(", "connect", ")", "end", "end" ]
Returns list of tags applied to reader
[ "Returns", "list", "of", "tags", "applied", "to", "reader" ]
fa53d263ae37d565a41a0fbb238601b85bd53a59
https://github.com/hexdigest/ruby-nfc/blob/fa53d263ae37d565a41a0fbb238601b85bd53a59/lib/ruby-nfc/reader.rb#L21-L27
train
ncgr/quorum
app/controllers/quorum/jobs_controller.rb
Quorum.JobsController.search
def search data = Job.search(params) # Respond with :json, :txt (tab delimited Blast results), or GFF3. respond_with data.flatten!(1) do |format| format.json { render :json => Quorum::JobSerializer.as_json(data) } format.gff { render :text => Quorum::JobSerializer.as_gff(data) } format.txt { render :text => Quorum::JobSerializer.as_txt(data) } end end
ruby
def search data = Job.search(params) # Respond with :json, :txt (tab delimited Blast results), or GFF3. respond_with data.flatten!(1) do |format| format.json { render :json => Quorum::JobSerializer.as_json(data) } format.gff { render :text => Quorum::JobSerializer.as_gff(data) } format.txt { render :text => Quorum::JobSerializer.as_txt(data) } end end
[ "def", "search", "data", "=", "Job", ".", "search", "(", "params", ")", "respond_with", "data", ".", "flatten!", "(", "1", ")", "do", "|", "format", "|", "format", ".", "json", "{", "render", ":json", "=>", "Quorum", "::", "JobSerializer", ".", "as_json", "(", "data", ")", "}", "format", ".", "gff", "{", "render", ":text", "=>", "Quorum", "::", "JobSerializer", ".", "as_gff", "(", "data", ")", "}", "format", ".", "txt", "{", "render", ":text", "=>", "Quorum", "::", "JobSerializer", ".", "as_txt", "(", "data", ")", "}", "end", "end" ]
Returns Quorum's search results. This method should be used to gather Resque worker results, or user supplied query params.
[ "Returns", "Quorum", "s", "search", "results", "." ]
0309cbdf38aab64ff4c002dec34e01fd10e0c823
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/app/controllers/quorum/jobs_controller.rb#L43-L58
train
ncgr/quorum
app/controllers/quorum/jobs_controller.rb
Quorum.JobsController.build_blast_jobs
def build_blast_jobs @job ||= Job.new @job.build_blastn_job if @job.blastn_job.nil? @job.build_blastx_job if @job.blastx_job.nil? @job.build_tblastn_job if @job.tblastn_job.nil? @job.build_blastp_job if @job.blastp_job.nil? end
ruby
def build_blast_jobs @job ||= Job.new @job.build_blastn_job if @job.blastn_job.nil? @job.build_blastx_job if @job.blastx_job.nil? @job.build_tblastn_job if @job.tblastn_job.nil? @job.build_blastp_job if @job.blastp_job.nil? end
[ "def", "build_blast_jobs", "@job", "||=", "Job", ".", "new", "@job", ".", "build_blastn_job", "if", "@job", ".", "blastn_job", ".", "nil?", "@job", ".", "build_blastx_job", "if", "@job", ".", "blastx_job", ".", "nil?", "@job", ".", "build_tblastn_job", "if", "@job", ".", "tblastn_job", ".", "nil?", "@job", ".", "build_blastp_job", "if", "@job", ".", "blastp_job", ".", "nil?", "end" ]
Create new Job and build associations.
[ "Create", "new", "Job", "and", "build", "associations", "." ]
0309cbdf38aab64ff4c002dec34e01fd10e0c823
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/app/controllers/quorum/jobs_controller.rb#L86-L92
train
ncgr/quorum
lib/tasks/blastdb/build_blast_db.rb
Quorum.BuildBlastDB.create_file_name
def create_file_name(file, base_dir) file_name = file.split("/").delete_if { |f| f.include?(".") }.first unless File.exists?(File.join(base_dir, file_name)) Dir.mkdir(File.join(base_dir, file_name)) end file_name end
ruby
def create_file_name(file, base_dir) file_name = file.split("/").delete_if { |f| f.include?(".") }.first unless File.exists?(File.join(base_dir, file_name)) Dir.mkdir(File.join(base_dir, file_name)) end file_name end
[ "def", "create_file_name", "(", "file", ",", "base_dir", ")", "file_name", "=", "file", ".", "split", "(", "\"/\"", ")", ".", "delete_if", "{", "|", "f", "|", "f", ".", "include?", "(", "\".\"", ")", "}", ".", "first", "unless", "File", ".", "exists?", "(", "File", ".", "join", "(", "base_dir", ",", "file_name", ")", ")", "Dir", ".", "mkdir", "(", "File", ".", "join", "(", "base_dir", ",", "file_name", ")", ")", "end", "file_name", "end" ]
Create directories per tarball and return tarball file name minus the file extension.
[ "Create", "directories", "per", "tarball", "and", "return", "tarball", "file", "name", "minus", "the", "file", "extension", "." ]
0309cbdf38aab64ff4c002dec34e01fd10e0c823
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/lib/tasks/blastdb/build_blast_db.rb#L69-L75
train
ncgr/quorum
lib/tasks/blastdb/build_blast_db.rb
Quorum.BuildBlastDB.extract_files
def extract_files(src, file, flag, path) extract_data_error = File.join(@log_dir, "extract_data_error.log") cmd = "tar -x#{flag}Of #{src} #{file} >> #{path} 2>> " << "#{extract_data_error}" system(cmd) if $?.exitstatus > 0 raise "Data extraction error. " << "See #{extract_data_error} for details." end end
ruby
def extract_files(src, file, flag, path) extract_data_error = File.join(@log_dir, "extract_data_error.log") cmd = "tar -x#{flag}Of #{src} #{file} >> #{path} 2>> " << "#{extract_data_error}" system(cmd) if $?.exitstatus > 0 raise "Data extraction error. " << "See #{extract_data_error} for details." end end
[ "def", "extract_files", "(", "src", ",", "file", ",", "flag", ",", "path", ")", "extract_data_error", "=", "File", ".", "join", "(", "@log_dir", ",", "\"extract_data_error.log\"", ")", "cmd", "=", "\"tar -x#{flag}Of #{src} #{file} >> #{path} 2>> \"", "<<", "\"#{extract_data_error}\"", "system", "(", "cmd", ")", "if", "$?", ".", "exitstatus", ">", "0", "raise", "\"Data extraction error. \"", "<<", "\"See #{extract_data_error} for details.\"", "end", "end" ]
Extracts and concatenates files from tarballs.
[ "Extracts", "and", "concatenates", "files", "from", "tarballs", "." ]
0309cbdf38aab64ff4c002dec34e01fd10e0c823
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/lib/tasks/blastdb/build_blast_db.rb#L80-L90
train
ncgr/quorum
lib/tasks/blastdb/build_blast_db.rb
Quorum.BuildBlastDB.execute_makeblastdb
def execute_makeblastdb(type, title, input) @output.puts "Executing makeblastdb for #{title} dbtype #{type}..." makeblast_log = File.join(@log_dir, "makeblastdb.log") output = File.dirname(input) cmd = "makeblastdb " << "-dbtype #{type} " << "-title #{title} " << "-in #{input} " << "-out #{output} " << "-hash_index >> #{makeblast_log}" system(cmd) if $?.exitstatus > 0 raise "makeblastdb error. " << "See #{makeblast_log} for details." end end
ruby
def execute_makeblastdb(type, title, input) @output.puts "Executing makeblastdb for #{title} dbtype #{type}..." makeblast_log = File.join(@log_dir, "makeblastdb.log") output = File.dirname(input) cmd = "makeblastdb " << "-dbtype #{type} " << "-title #{title} " << "-in #{input} " << "-out #{output} " << "-hash_index >> #{makeblast_log}" system(cmd) if $?.exitstatus > 0 raise "makeblastdb error. " << "See #{makeblast_log} for details." end end
[ "def", "execute_makeblastdb", "(", "type", ",", "title", ",", "input", ")", "@output", ".", "puts", "\"Executing makeblastdb for #{title} dbtype #{type}...\"", "makeblast_log", "=", "File", ".", "join", "(", "@log_dir", ",", "\"makeblastdb.log\"", ")", "output", "=", "File", ".", "dirname", "(", "input", ")", "cmd", "=", "\"makeblastdb \"", "<<", "\"-dbtype #{type} \"", "<<", "\"-title #{title} \"", "<<", "\"-in #{input} \"", "<<", "\"-out #{output} \"", "<<", "\"-hash_index >> #{makeblast_log}\"", "system", "(", "cmd", ")", "if", "$?", ".", "exitstatus", ">", "0", "raise", "\"makeblastdb error. \"", "<<", "\"See #{makeblast_log} for details.\"", "end", "end" ]
Execute makeblastdb on an extracted dataset.
[ "Execute", "makeblastdb", "on", "an", "extracted", "dataset", "." ]
0309cbdf38aab64ff4c002dec34e01fd10e0c823
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/lib/tasks/blastdb/build_blast_db.rb#L95-L112
train
ncgr/quorum
lib/tasks/blastdb/build_blast_db.rb
Quorum.BuildBlastDB.build_blast_db
def build_blast_db(blastdb) Dir.glob(File.expand_path(blastdb) + "/*").each do |d| if File.directory?(d) contigs = File.join(d, "contigs.fa") peptides = File.join(d, "peptides.fa") found = false if File.exists?(contigs) && File.readable?(contigs) execute_makeblastdb("nucl", d, contigs) found = true end if File.exists?(peptides) && File.readable?(peptides) execute_makeblastdb("prot", d, peptides) found = true end unless found raise "Extracted data not found for #{contigs} or #{peptides}. " << "Make sure you supplied the correct data directory and file names." end end end end
ruby
def build_blast_db(blastdb) Dir.glob(File.expand_path(blastdb) + "/*").each do |d| if File.directory?(d) contigs = File.join(d, "contigs.fa") peptides = File.join(d, "peptides.fa") found = false if File.exists?(contigs) && File.readable?(contigs) execute_makeblastdb("nucl", d, contigs) found = true end if File.exists?(peptides) && File.readable?(peptides) execute_makeblastdb("prot", d, peptides) found = true end unless found raise "Extracted data not found for #{contigs} or #{peptides}. " << "Make sure you supplied the correct data directory and file names." end end end end
[ "def", "build_blast_db", "(", "blastdb", ")", "Dir", ".", "glob", "(", "File", ".", "expand_path", "(", "blastdb", ")", "+", "\"/*\"", ")", ".", "each", "do", "|", "d", "|", "if", "File", ".", "directory?", "(", "d", ")", "contigs", "=", "File", ".", "join", "(", "d", ",", "\"contigs.fa\"", ")", "peptides", "=", "File", ".", "join", "(", "d", ",", "\"peptides.fa\"", ")", "found", "=", "false", "if", "File", ".", "exists?", "(", "contigs", ")", "&&", "File", ".", "readable?", "(", "contigs", ")", "execute_makeblastdb", "(", "\"nucl\"", ",", "d", ",", "contigs", ")", "found", "=", "true", "end", "if", "File", ".", "exists?", "(", "peptides", ")", "&&", "File", ".", "readable?", "(", "peptides", ")", "execute_makeblastdb", "(", "\"prot\"", ",", "d", ",", "peptides", ")", "found", "=", "true", "end", "unless", "found", "raise", "\"Extracted data not found for #{contigs} or #{peptides}. \"", "<<", "\"Make sure you supplied the correct data directory and file names.\"", "end", "end", "end", "end" ]
Builds a Blast database from parse_blast_db_data.
[ "Builds", "a", "Blast", "database", "from", "parse_blast_db_data", "." ]
0309cbdf38aab64ff4c002dec34e01fd10e0c823
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/lib/tasks/blastdb/build_blast_db.rb#L117-L140
train
ncgr/quorum
lib/generators/templates/logger.rb
Quorum.Logger.log
def log(program, message, exit_status = nil, files = nil) File.open(File.join(@log_directory, @log_file), "a") do |log| log.puts "" log.puts Time.now.to_s + " " + program log.puts message log.puts "" end if exit_status remove_files(files) unless files.nil? exit exit_status.to_i end end
ruby
def log(program, message, exit_status = nil, files = nil) File.open(File.join(@log_directory, @log_file), "a") do |log| log.puts "" log.puts Time.now.to_s + " " + program log.puts message log.puts "" end if exit_status remove_files(files) unless files.nil? exit exit_status.to_i end end
[ "def", "log", "(", "program", ",", "message", ",", "exit_status", "=", "nil", ",", "files", "=", "nil", ")", "File", ".", "open", "(", "File", ".", "join", "(", "@log_directory", ",", "@log_file", ")", ",", "\"a\"", ")", "do", "|", "log", "|", "log", ".", "puts", "\"\"", "log", ".", "puts", "Time", ".", "now", ".", "to_s", "+", "\" \"", "+", "program", "log", ".", "puts", "message", "log", ".", "puts", "\"\"", "end", "if", "exit_status", "remove_files", "(", "files", ")", "unless", "files", ".", "nil?", "exit", "exit_status", ".", "to_i", "end", "end" ]
Write to log file and exit if exit_status is present.
[ "Write", "to", "log", "file", "and", "exit", "if", "exit_status", "is", "present", "." ]
0309cbdf38aab64ff4c002dec34e01fd10e0c823
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/lib/generators/templates/logger.rb#L12-L24
train
ncgr/quorum
app/models/quorum/job.rb
Quorum.Job.algorithm_selected
def algorithm_selected in_queue = false if (self.blastn_job && self.blastn_job.queue) || (self.blastx_job && self.blastx_job.queue) || (self.tblastn_job && self.tblastn_job.queue) || (self.blastp_job && self.blastp_job.queue) in_queue = true end unless in_queue errors.add( :algorithm, " - Please select at least one algorithm to continue." ) end end
ruby
def algorithm_selected in_queue = false if (self.blastn_job && self.blastn_job.queue) || (self.blastx_job && self.blastx_job.queue) || (self.tblastn_job && self.tblastn_job.queue) || (self.blastp_job && self.blastp_job.queue) in_queue = true end unless in_queue errors.add( :algorithm, " - Please select at least one algorithm to continue." ) end end
[ "def", "algorithm_selected", "in_queue", "=", "false", "if", "(", "self", ".", "blastn_job", "&&", "self", ".", "blastn_job", ".", "queue", ")", "||", "(", "self", ".", "blastx_job", "&&", "self", ".", "blastx_job", ".", "queue", ")", "||", "(", "self", ".", "tblastn_job", "&&", "self", ".", "tblastn_job", ".", "queue", ")", "||", "(", "self", ".", "blastp_job", "&&", "self", ".", "blastp_job", ".", "queue", ")", "in_queue", "=", "true", "end", "unless", "in_queue", "errors", ".", "add", "(", ":algorithm", ",", "\" - Please select at least one algorithm to continue.\"", ")", "end", "end" ]
Make sure an algorithm is selected.
[ "Make", "sure", "an", "algorithm", "is", "selected", "." ]
0309cbdf38aab64ff4c002dec34e01fd10e0c823
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/app/models/quorum/job.rb#L173-L187
train
pivotal-legacy/saucelabs-adapter
lib/saucelabs_adapter/utilities.rb
SaucelabsAdapter.Utilities.start_mongrel
def start_mongrel(suite_name = {}) pid_file = File.join(RAILS_ROOT, "tmp", "pids", "mongrel_selenium.pid") port = suite_name[:port] rescue @selenium_config.application_port say "Starting mongrel at #{pid_file}, port #{port}" system "mongrel_rails start -d --chdir='#{RAILS_ROOT}' --port=#{port} --environment=test --pid #{pid_file} %" end
ruby
def start_mongrel(suite_name = {}) pid_file = File.join(RAILS_ROOT, "tmp", "pids", "mongrel_selenium.pid") port = suite_name[:port] rescue @selenium_config.application_port say "Starting mongrel at #{pid_file}, port #{port}" system "mongrel_rails start -d --chdir='#{RAILS_ROOT}' --port=#{port} --environment=test --pid #{pid_file} %" end
[ "def", "start_mongrel", "(", "suite_name", "=", "{", "}", ")", "pid_file", "=", "File", ".", "join", "(", "RAILS_ROOT", ",", "\"tmp\"", ",", "\"pids\"", ",", "\"mongrel_selenium.pid\"", ")", "port", "=", "suite_name", "[", ":port", "]", "rescue", "@selenium_config", ".", "application_port", "say", "\"Starting mongrel at #{pid_file}, port #{port}\"", "system", "\"mongrel_rails start -d --chdir='#{RAILS_ROOT}' --port=#{port} --environment=test --pid #{pid_file} %\"", "end" ]
parameters required when invoked by test_unit
[ "parameters", "required", "when", "invoked", "by", "test_unit" ]
b9b66094aba315af164f9d57e3743534006cec9f
https://github.com/pivotal-legacy/saucelabs-adapter/blob/b9b66094aba315af164f9d57e3743534006cec9f/lib/saucelabs_adapter/utilities.rb#L39-L44
train
ncgr/quorum
lib/quorum/sequence.rb
Quorum.Sequence.create_hash
def create_hash(sequence) Digest::MD5.hexdigest(sequence).to_s + "-" + Time.now.to_f.to_s end
ruby
def create_hash(sequence) Digest::MD5.hexdigest(sequence).to_s + "-" + Time.now.to_f.to_s end
[ "def", "create_hash", "(", "sequence", ")", "Digest", "::", "MD5", ".", "hexdigest", "(", "sequence", ")", ".", "to_s", "+", "\"-\"", "+", "Time", ".", "now", ".", "to_f", ".", "to_s", "end" ]
Create a unique hash plus timestamp.
[ "Create", "a", "unique", "hash", "plus", "timestamp", "." ]
0309cbdf38aab64ff4c002dec34e01fd10e0c823
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/lib/quorum/sequence.rb#L7-L9
train
ncgr/quorum
lib/quorum/sequence.rb
Quorum.Sequence.write_input_sequence_to_file
def write_input_sequence_to_file(tmp_dir, hash, sequence) seq = File.join(tmp_dir, hash + ".seq") File.open(seq, "w") do |f| f << sequence end fasta = File.join(tmp_dir, hash + ".fa") # Force FASTA format. cmd = "seqret -filter -sformat pearson -osformat fasta < #{seq} " << "> #{fasta} 2> /dev/null" system(cmd) if $?.exitstatus > 0 raise " - Please enter your sequence(s) in Plain Text as " << "FASTA." end end
ruby
def write_input_sequence_to_file(tmp_dir, hash, sequence) seq = File.join(tmp_dir, hash + ".seq") File.open(seq, "w") do |f| f << sequence end fasta = File.join(tmp_dir, hash + ".fa") # Force FASTA format. cmd = "seqret -filter -sformat pearson -osformat fasta < #{seq} " << "> #{fasta} 2> /dev/null" system(cmd) if $?.exitstatus > 0 raise " - Please enter your sequence(s) in Plain Text as " << "FASTA." end end
[ "def", "write_input_sequence_to_file", "(", "tmp_dir", ",", "hash", ",", "sequence", ")", "seq", "=", "File", ".", "join", "(", "tmp_dir", ",", "hash", "+", "\".seq\"", ")", "File", ".", "open", "(", "seq", ",", "\"w\"", ")", "do", "|", "f", "|", "f", "<<", "sequence", "end", "fasta", "=", "File", ".", "join", "(", "tmp_dir", ",", "hash", "+", "\".fa\"", ")", "cmd", "=", "\"seqret -filter -sformat pearson -osformat fasta < #{seq} \"", "<<", "\"> #{fasta} 2> /dev/null\"", "system", "(", "cmd", ")", "if", "$?", ".", "exitstatus", ">", "0", "raise", "\" - Please enter your sequence(s) in Plain Text as \"", "<<", "\"FASTA.\"", "end", "end" ]
Write input sequence to file. Pass the raw input data through seqret to ensure FASTA format.
[ "Write", "input", "sequence", "to", "file", ".", "Pass", "the", "raw", "input", "data", "through", "seqret", "to", "ensure", "FASTA", "format", "." ]
0309cbdf38aab64ff4c002dec34e01fd10e0c823
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/lib/quorum/sequence.rb#L15-L31
train
ncgr/quorum
lib/quorum/helpers.rb
Quorum.Helpers.set_flash_message
def set_flash_message(key, kind, options = {}) options[:scope] = "quorum.#{controller_name}" options[:scope] << ".errors" if key.to_s == "error" options[:scope] << ".notices" if key.to_s == "notice" options[:scope] << ".alerts" if key.to_s == "alert" message = I18n.t("#{kind}", options) flash[key] = message if message.present? end
ruby
def set_flash_message(key, kind, options = {}) options[:scope] = "quorum.#{controller_name}" options[:scope] << ".errors" if key.to_s == "error" options[:scope] << ".notices" if key.to_s == "notice" options[:scope] << ".alerts" if key.to_s == "alert" message = I18n.t("#{kind}", options) flash[key] = message if message.present? end
[ "def", "set_flash_message", "(", "key", ",", "kind", ",", "options", "=", "{", "}", ")", "options", "[", ":scope", "]", "=", "\"quorum.#{controller_name}\"", "options", "[", ":scope", "]", "<<", "\".errors\"", "if", "key", ".", "to_s", "==", "\"error\"", "options", "[", ":scope", "]", "<<", "\".notices\"", "if", "key", ".", "to_s", "==", "\"notice\"", "options", "[", ":scope", "]", "<<", "\".alerts\"", "if", "key", ".", "to_s", "==", "\"alert\"", "message", "=", "I18n", ".", "t", "(", "\"#{kind}\"", ",", "options", ")", "flash", "[", "key", "]", "=", "message", "if", "message", ".", "present?", "end" ]
I18n flash helper. Set flash message based on key.
[ "I18n", "flash", "helper", ".", "Set", "flash", "message", "based", "on", "key", "." ]
0309cbdf38aab64ff4c002dec34e01fd10e0c823
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/lib/quorum/helpers.rb#L7-L14
train
ncgr/quorum
app/models/quorum/blastx_job.rb
Quorum.BlastxJob.gap_opening_extension=
def gap_opening_extension=(value) v = value.split(',') self.gap_opening_penalty = v.first self.gap_extension_penalty = v.last end
ruby
def gap_opening_extension=(value) v = value.split(',') self.gap_opening_penalty = v.first self.gap_extension_penalty = v.last end
[ "def", "gap_opening_extension", "=", "(", "value", ")", "v", "=", "value", ".", "split", "(", "','", ")", "self", ".", "gap_opening_penalty", "=", "v", ".", "first", "self", ".", "gap_extension_penalty", "=", "v", ".", "last", "end" ]
Virtual attribute setter.
[ "Virtual", "attribute", "setter", "." ]
0309cbdf38aab64ff4c002dec34e01fd10e0c823
https://github.com/ncgr/quorum/blob/0309cbdf38aab64ff4c002dec34e01fd10e0c823/app/models/quorum/blastx_job.rb#L75-L79
train
zokioki/fitbit_api
lib/fitbit_api/helpers/utils.rb
FitbitAPI.Client.deep_transform_keys!
def deep_transform_keys!(object, &block) case object when Hash object.keys.each do |key| value = object.delete(key) object[yield(key)] = deep_transform_keys!(value) { |key| yield(key) } end object when Array object.map! { |e| deep_transform_keys!(e) { |key| yield(key) } } else object end end
ruby
def deep_transform_keys!(object, &block) case object when Hash object.keys.each do |key| value = object.delete(key) object[yield(key)] = deep_transform_keys!(value) { |key| yield(key) } end object when Array object.map! { |e| deep_transform_keys!(e) { |key| yield(key) } } else object end end
[ "def", "deep_transform_keys!", "(", "object", ",", "&", "block", ")", "case", "object", "when", "Hash", "object", ".", "keys", ".", "each", "do", "|", "key", "|", "value", "=", "object", ".", "delete", "(", "key", ")", "object", "[", "yield", "(", "key", ")", "]", "=", "deep_transform_keys!", "(", "value", ")", "{", "|", "key", "|", "yield", "(", "key", ")", "}", "end", "object", "when", "Array", "object", ".", "map!", "{", "|", "e", "|", "deep_transform_keys!", "(", "e", ")", "{", "|", "key", "|", "yield", "(", "key", ")", "}", "}", "else", "object", "end", "end" ]
Inspired by ActiveSupport's implementation
[ "Inspired", "by", "ActiveSupport", "s", "implementation" ]
13c8cf99fbab2327e3429d590a71ccfc4b633045
https://github.com/zokioki/fitbit_api/blob/13c8cf99fbab2327e3429d590a71ccfc4b633045/lib/fitbit_api/helpers/utils.rb#L51-L64
train
crate/crate_ruby
lib/crate_ruby/client.rb
CrateRuby.Client.execute
def execute(sql, args = nil, bulk_args = nil, http_options = {}) @logger.debug sql req = Net::HTTP::Post.new('/_sql', headers) body = { 'stmt' => sql } body['args'] = args if args body['bulk_args'] = bulk_args if bulk_args req.body = body.to_json response = request(req, http_options) @logger.debug response.body case response.code when /^2\d{2}/ ResultSet.new response.body else @logger.info(response.body) raise CrateRuby::CrateError, response.body end end
ruby
def execute(sql, args = nil, bulk_args = nil, http_options = {}) @logger.debug sql req = Net::HTTP::Post.new('/_sql', headers) body = { 'stmt' => sql } body['args'] = args if args body['bulk_args'] = bulk_args if bulk_args req.body = body.to_json response = request(req, http_options) @logger.debug response.body case response.code when /^2\d{2}/ ResultSet.new response.body else @logger.info(response.body) raise CrateRuby::CrateError, response.body end end
[ "def", "execute", "(", "sql", ",", "args", "=", "nil", ",", "bulk_args", "=", "nil", ",", "http_options", "=", "{", "}", ")", "@logger", ".", "debug", "sql", "req", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "'/_sql'", ",", "headers", ")", "body", "=", "{", "'stmt'", "=>", "sql", "}", "body", "[", "'args'", "]", "=", "args", "if", "args", "body", "[", "'bulk_args'", "]", "=", "bulk_args", "if", "bulk_args", "req", ".", "body", "=", "body", ".", "to_json", "response", "=", "request", "(", "req", ",", "http_options", ")", "@logger", ".", "debug", "response", ".", "body", "case", "response", ".", "code", "when", "/", "\\d", "/", "ResultSet", ".", "new", "response", ".", "body", "else", "@logger", ".", "info", "(", "response", ".", "body", ")", "raise", "CrateRuby", "::", "CrateError", ",", "response", ".", "body", "end", "end" ]
Executes a SQL statement against the Crate HTTP REST endpoint. @param [String] sql statement to execute @param [Array] args Array of values used for parameter substitution @param [Array] bulk_args List of lists containing records to be processed @param [Hash] http_options Net::HTTP options (open_timeout, read_timeout) @return [ResultSet]
[ "Executes", "a", "SQL", "statement", "against", "the", "Crate", "HTTP", "REST", "endpoint", "." ]
64015c0ad2ae7914329f8107eae6b689e45a48af
https://github.com/crate/crate_ruby/blob/64015c0ad2ae7914329f8107eae6b689e45a48af/lib/crate_ruby/client.rb#L115-L132
train
crate/crate_ruby
lib/crate_ruby/client.rb
CrateRuby.Client.blob_put
def blob_put(table, digest, data) uri = blob_path(table, digest) @logger.debug("BLOB PUT #{uri}") req = Net::HTTP::Put.new(blob_path(table, digest), headers) req.body = data response = request(req) case response.code when '201' true else @logger.info("Response #{response.code}: " + response.body) false end end
ruby
def blob_put(table, digest, data) uri = blob_path(table, digest) @logger.debug("BLOB PUT #{uri}") req = Net::HTTP::Put.new(blob_path(table, digest), headers) req.body = data response = request(req) case response.code when '201' true else @logger.info("Response #{response.code}: " + response.body) false end end
[ "def", "blob_put", "(", "table", ",", "digest", ",", "data", ")", "uri", "=", "blob_path", "(", "table", ",", "digest", ")", "@logger", ".", "debug", "(", "\"BLOB PUT #{uri}\"", ")", "req", "=", "Net", "::", "HTTP", "::", "Put", ".", "new", "(", "blob_path", "(", "table", ",", "digest", ")", ",", "headers", ")", "req", ".", "body", "=", "data", "response", "=", "request", "(", "req", ")", "case", "response", ".", "code", "when", "'201'", "true", "else", "@logger", ".", "info", "(", "\"Response #{response.code}: \"", "+", "response", ".", "body", ")", "false", "end", "end" ]
Upload a File to a blob table @param [String] table @param [String] digest SHA1 hexdigest @param [Boolean] data Can be any payload object that can be sent via HTTP, e.g. STRING, FILE
[ "Upload", "a", "File", "to", "a", "blob", "table" ]
64015c0ad2ae7914329f8107eae6b689e45a48af
https://github.com/crate/crate_ruby/blob/64015c0ad2ae7914329f8107eae6b689e45a48af/lib/crate_ruby/client.rb#L138-L151
train
dazzl-tv/ruby-rabbitmq-janus
lib/rrj/admin.rb
RubyRabbitmqJanus.RRJAdmin.start_transaction_admin
def start_transaction_admin(options = {}) transaction = Janus::Transactions::Admin.new(options) transaction.connect { yield(transaction) } rescue raise Errors::RRJAdmin::StartTransactionAdmin, options end
ruby
def start_transaction_admin(options = {}) transaction = Janus::Transactions::Admin.new(options) transaction.connect { yield(transaction) } rescue raise Errors::RRJAdmin::StartTransactionAdmin, options end
[ "def", "start_transaction_admin", "(", "options", "=", "{", "}", ")", "transaction", "=", "Janus", "::", "Transactions", "::", "Admin", ".", "new", "(", "options", ")", "transaction", ".", "connect", "{", "yield", "(", "transaction", ")", "}", "rescue", "raise", "Errors", "::", "RRJAdmin", "::", "StartTransactionAdmin", ",", "options", "end" ]
Create a transaction between apps and Janus for request without handle @param [Hash] options Give a session number for use another session in Janus @example Get Janus session @rrj.start_transaction_admin do |transaction| response = transaction.publish_message('admin:sessions').sessions end @since 2.0.0
[ "Create", "a", "transaction", "between", "apps", "and", "Janus", "for", "request", "without", "handle" ]
680fca9260b10191ca8dfbcac83d315dce895206
https://github.com/dazzl-tv/ruby-rabbitmq-janus/blob/680fca9260b10191ca8dfbcac83d315dce895206/lib/rrj/admin.rb#L28-L33
train
wycats/rake-pipeline-web-filters
lib/rake-pipeline-web-filters/coffee_script_filter.rb
Rake::Pipeline::Web::Filters.CoffeeScriptFilter.generate_output
def generate_output(inputs, output) inputs.each do |input| begin output.write CoffeeScript.compile(input, options) rescue ExecJS::Error => error raise error, "Error compiling #{input.path}. #{error.message}" end end end
ruby
def generate_output(inputs, output) inputs.each do |input| begin output.write CoffeeScript.compile(input, options) rescue ExecJS::Error => error raise error, "Error compiling #{input.path}. #{error.message}" end end end
[ "def", "generate_output", "(", "inputs", ",", "output", ")", "inputs", ".", "each", "do", "|", "input", "|", "begin", "output", ".", "write", "CoffeeScript", ".", "compile", "(", "input", ",", "options", ")", "rescue", "ExecJS", "::", "Error", "=>", "error", "raise", "error", ",", "\"Error compiling #{input.path}. #{error.message}\"", "end", "end", "end" ]
By default, the CoffeeScriptFilter converts inputs with the extension +.coffee+ to +.js+. @param [Hash] options options to pass to the CoffeeScript compiler. @param [Proc] block the output name generator block The body of the filter. Compile each input file into a CoffeeScript compiled output file. @param [Array] inputs an Array of FileWrapper objects. @param [FileWrapper] output a FileWrapper object
[ "By", "default", "the", "CoffeeScriptFilter", "converts", "inputs", "with", "the", "extension", "+", ".", "coffee", "+", "to", "+", ".", "js", "+", "." ]
7bd283aac83d7c46a8908f089033a6087d7cd68f
https://github.com/wycats/rake-pipeline-web-filters/blob/7bd283aac83d7c46a8908f089033a6087d7cd68f/lib/rake-pipeline-web-filters/coffee_script_filter.rb#L27-L35
train
dazzl-tv/ruby-rabbitmq-janus
lib/rrj/init.rb
RubyRabbitmqJanus.RRJ.start_transaction
def start_transaction(exclusive = true, options = {}) session = @option.use_current_session?(options) transaction = Janus::Transactions::Session.new(exclusive, session) transaction.connect { yield(transaction) } rescue raise Errors::RRJ::StartTransaction.new(exclusive, options) end
ruby
def start_transaction(exclusive = true, options = {}) session = @option.use_current_session?(options) transaction = Janus::Transactions::Session.new(exclusive, session) transaction.connect { yield(transaction) } rescue raise Errors::RRJ::StartTransaction.new(exclusive, options) end
[ "def", "start_transaction", "(", "exclusive", "=", "true", ",", "options", "=", "{", "}", ")", "session", "=", "@option", ".", "use_current_session?", "(", "options", ")", "transaction", "=", "Janus", "::", "Transactions", "::", "Session", ".", "new", "(", "exclusive", ",", "session", ")", "transaction", ".", "connect", "{", "yield", "(", "transaction", ")", "}", "rescue", "raise", "Errors", "::", "RRJ", "::", "StartTransaction", ".", "new", "(", "exclusive", ",", "options", ")", "end" ]
Return a new instance of RubyRabbitmqJanus. @example Create a instance to this gem @rrj = RubyRabbitmqJanus::RRJ.new => #<RubyRabbitmqJanus::RRJ:0x007 @session=123> Start a transaction with Janus. Request use session_id information. @param [Boolean] exclusive Choose if message is storage in exclusive queue @param [Hash] options Give a session number for use another session in Janus @example Get Janus information @rrj.start_transaction do |transaction| response = transaction.publish_message('base::info').to_hash end @since 2.0.0
[ "Return", "a", "new", "instance", "of", "RubyRabbitmqJanus", "." ]
680fca9260b10191ca8dfbcac83d315dce895206
https://github.com/dazzl-tv/ruby-rabbitmq-janus/blob/680fca9260b10191ca8dfbcac83d315dce895206/lib/rrj/init.rb#L58-L64
train
wycats/rake-pipeline-web-filters
lib/rake-pipeline-web-filters/es6_module_filter.rb
Rake::Pipeline::Web::Filters.ES6ModuleFilter.generate_output
def generate_output(inputs, output) inputs.each do |input| begin body = input.read if input.respond_to?(:read) local_opts = {} if @module_id_generator local_opts[:moduleName] = @module_id_generator.call(input) end opts = @options.merge(local_opts) opts.delete(:module_id_generator) output.write RubyES6ModuleTranspiler.transpile(body, opts) rescue ExecJS::Error => error raise error, "Error compiling #{input.path}. #{error.message}" end end end
ruby
def generate_output(inputs, output) inputs.each do |input| begin body = input.read if input.respond_to?(:read) local_opts = {} if @module_id_generator local_opts[:moduleName] = @module_id_generator.call(input) end opts = @options.merge(local_opts) opts.delete(:module_id_generator) output.write RubyES6ModuleTranspiler.transpile(body, opts) rescue ExecJS::Error => error raise error, "Error compiling #{input.path}. #{error.message}" end end end
[ "def", "generate_output", "(", "inputs", ",", "output", ")", "inputs", ".", "each", "do", "|", "input", "|", "begin", "body", "=", "input", ".", "read", "if", "input", ".", "respond_to?", "(", ":read", ")", "local_opts", "=", "{", "}", "if", "@module_id_generator", "local_opts", "[", ":moduleName", "]", "=", "@module_id_generator", ".", "call", "(", "input", ")", "end", "opts", "=", "@options", ".", "merge", "(", "local_opts", ")", "opts", ".", "delete", "(", ":module_id_generator", ")", "output", ".", "write", "RubyES6ModuleTranspiler", ".", "transpile", "(", "body", ",", "opts", ")", "rescue", "ExecJS", "::", "Error", "=>", "error", "raise", "error", ",", "\"Error compiling #{input.path}. #{error.message}\"", "end", "end", "end" ]
Create an instance of this filter. Possible options: module_id_generator: provide a Proc to convert an input to a module identifier (AMD only) Other options are passed along to the RubyES6ModuleTranspiler and then to the node transpiler. See https://github.com/square/es6-module-transpiler for more info. @param [Hash] options options (see above) @param [Proc] block the output name generator block The body of the filter. Compile each input file into a ES6 Module Transpiled output file. @param [Array] inputs an Array of FileWrapper objects. @param [FileWrapper] output a FileWrapper object
[ "Create", "an", "instance", "of", "this", "filter", "." ]
7bd283aac83d7c46a8908f089033a6087d7cd68f
https://github.com/wycats/rake-pipeline-web-filters/blob/7bd283aac83d7c46a8908f089033a6087d7cd68f/lib/rake-pipeline-web-filters/es6_module_filter.rb#L31-L46
train
dazzl-tv/ruby-rabbitmq-janus
lib/rrj/task.rb
RubyRabbitmqJanus.RRJTask.start_transaction_handle
def start_transaction_handle(exclusive = true, options = {}) janus = session_instance(options) handle = 0 # Create always a new handle transaction = Janus::Transactions::Handle.new(exclusive, janus.session, handle, janus.instance) transaction.connect { yield(transaction) } rescue raise Errors::RRJTask::StartTransactionHandle.new(exclusive, options) end
ruby
def start_transaction_handle(exclusive = true, options = {}) janus = session_instance(options) handle = 0 # Create always a new handle transaction = Janus::Transactions::Handle.new(exclusive, janus.session, handle, janus.instance) transaction.connect { yield(transaction) } rescue raise Errors::RRJTask::StartTransactionHandle.new(exclusive, options) end
[ "def", "start_transaction_handle", "(", "exclusive", "=", "true", ",", "options", "=", "{", "}", ")", "janus", "=", "session_instance", "(", "options", ")", "handle", "=", "0", "transaction", "=", "Janus", "::", "Transactions", "::", "Handle", ".", "new", "(", "exclusive", ",", "janus", ".", "session", ",", "handle", ",", "janus", ".", "instance", ")", "transaction", ".", "connect", "{", "yield", "(", "transaction", ")", "}", "rescue", "raise", "Errors", "::", "RRJTask", "::", "StartTransactionHandle", ".", "new", "(", "exclusive", ",", "options", ")", "end" ]
Create a transaction between apps and janus with a handle @since 2.1.0
[ "Create", "a", "transaction", "between", "apps", "and", "janus", "with", "a", "handle" ]
680fca9260b10191ca8dfbcac83d315dce895206
https://github.com/dazzl-tv/ruby-rabbitmq-janus/blob/680fca9260b10191ca8dfbcac83d315dce895206/lib/rrj/task.rb#L42-L52
train
dazzl-tv/ruby-rabbitmq-janus
lib/generators/ruby_rabbitmq_janus/templates/actions.rb
RubyRabbitmqJanus.ActionEvents.actions
def actions lambda do |reason, data| Rails.logger.debug "Execute block code with reason : #{reason}" case reason when event then case_events(data.to_hash) end end end
ruby
def actions lambda do |reason, data| Rails.logger.debug "Execute block code with reason : #{reason}" case reason when event then case_events(data.to_hash) end end end
[ "def", "actions", "lambda", "do", "|", "reason", ",", "data", "|", "Rails", ".", "logger", ".", "debug", "\"Execute block code with reason : #{reason}\"", "case", "reason", "when", "event", "then", "case_events", "(", "data", ".", "to_hash", ")", "end", "end", "end" ]
Default method using for sending a block of code
[ "Default", "method", "using", "for", "sending", "a", "block", "of", "code" ]
680fca9260b10191ca8dfbcac83d315dce895206
https://github.com/dazzl-tv/ruby-rabbitmq-janus/blob/680fca9260b10191ca8dfbcac83d315dce895206/lib/generators/ruby_rabbitmq_janus/templates/actions.rb#L7-L14
train
wvk/railsdav
lib/railsdav/renderer.rb
Railsdav.Renderer.response
def response(options = {}) elements = options.slice(:error) render do response_for options[:href] do |dav| elements.each do |name, value| status_for options[:status] dav.__send__ name, value end end end end
ruby
def response(options = {}) elements = options.slice(:error) render do response_for options[:href] do |dav| elements.each do |name, value| status_for options[:status] dav.__send__ name, value end end end end
[ "def", "response", "(", "options", "=", "{", "}", ")", "elements", "=", "options", ".", "slice", "(", ":error", ")", "render", "do", "response_for", "options", "[", ":href", "]", "do", "|", "dav", "|", "elements", ".", "each", "do", "|", "name", ",", "value", "|", "status_for", "options", "[", ":status", "]", "dav", ".", "__send__", "name", ",", "value", "end", "end", "end", "end" ]
Render a WebDAV multistatus response with a single "response" element. This is primarily intended vor responding to single resource errors. Arguments: options: - href: the requested resource URL, usually request.url - status: the response status, something like :unprocessable_entity or 204. - error: an Error description, if any.
[ "Render", "a", "WebDAV", "multistatus", "response", "with", "a", "single", "response", "element", ".", "This", "is", "primarily", "intended", "vor", "responding", "to", "single", "resource", "errors", "." ]
2a51bf43a726175eaa93bdfe7ba2bed0248d3d87
https://github.com/wvk/railsdav/blob/2a51bf43a726175eaa93bdfe7ba2bed0248d3d87/lib/railsdav/renderer.rb#L86-L97
train
simplelogica/nocms-blocks
app/models/no_cms/blocks/block.rb
NoCms::Blocks.Block.duplicate_self
def duplicate_self new_self new_self.translations = translations.map(&:dup) new_self.translations.each { |t| t.globalized_model = new_self } children.each do |child| new_self.children << child.dup end end
ruby
def duplicate_self new_self new_self.translations = translations.map(&:dup) new_self.translations.each { |t| t.globalized_model = new_self } children.each do |child| new_self.children << child.dup end end
[ "def", "duplicate_self", "new_self", "new_self", ".", "translations", "=", "translations", ".", "map", "(", "&", ":dup", ")", "new_self", ".", "translations", ".", "each", "{", "|", "t", "|", "t", ".", "globalized_model", "=", "new_self", "}", "children", ".", "each", "do", "|", "child", "|", "new_self", ".", "children", "<<", "child", ".", "dup", "end", "end" ]
A block dups all it's children and the translations
[ "A", "block", "dups", "all", "it", "s", "children", "and", "the", "translations" ]
30c69ce0ce0867244604ea59e8252f761d6b508e
https://github.com/simplelogica/nocms-blocks/blob/30c69ce0ce0867244604ea59e8252f761d6b508e/app/models/no_cms/blocks/block.rb#L25-L33
train
tuskenraiders/degu
lib/degu/has_set.rb
Degu.HasSet.has_set_coerce_argument_value
def has_set_coerce_argument_value(enum_class, argument_value) invalid_set_elements = [] set_elements = if String === argument_value argument_value.split(',').map(&:strip) else Array(argument_value) end.map do |set_element| if result = enum_class[set_element] result else invalid_set_elements << set_element nil end end invalid_set_elements.empty? or raise ArgumentError, "element #{argument_value.inspect} contains invalid elements: #{invalid_set_elements.inspect}" set_elements end
ruby
def has_set_coerce_argument_value(enum_class, argument_value) invalid_set_elements = [] set_elements = if String === argument_value argument_value.split(',').map(&:strip) else Array(argument_value) end.map do |set_element| if result = enum_class[set_element] result else invalid_set_elements << set_element nil end end invalid_set_elements.empty? or raise ArgumentError, "element #{argument_value.inspect} contains invalid elements: #{invalid_set_elements.inspect}" set_elements end
[ "def", "has_set_coerce_argument_value", "(", "enum_class", ",", "argument_value", ")", "invalid_set_elements", "=", "[", "]", "set_elements", "=", "if", "String", "===", "argument_value", "argument_value", ".", "split", "(", "','", ")", ".", "map", "(", "&", ":strip", ")", "else", "Array", "(", "argument_value", ")", "end", ".", "map", "do", "|", "set_element", "|", "if", "result", "=", "enum_class", "[", "set_element", "]", "result", "else", "invalid_set_elements", "<<", "set_element", "nil", "end", "end", "invalid_set_elements", ".", "empty?", "or", "raise", "ArgumentError", ",", "\"element #{argument_value.inspect} contains invalid elements: #{invalid_set_elements.inspect}\"", "set_elements", "end" ]
Understands the arguments as the list of enum values The argument value can be - a `string` of enum values joined by a comma - an enum constant - a `symbol` which resolves to the enum constant - an `integer` as the index of the enum class If you have just 1 value, you do not need to enclose it in an `Array`
[ "Understands", "the", "arguments", "as", "the", "list", "of", "enum", "values", "The", "argument", "value", "can", "be", "-", "a", "string", "of", "enum", "values", "joined", "by", "a", "comma", "-", "an", "enum", "constant", "-", "a", "symbol", "which", "resolves", "to", "the", "enum", "constant", "-", "an", "integer", "as", "the", "index", "of", "the", "enum", "class", "If", "you", "have", "just", "1", "value", "you", "do", "not", "need", "to", "enclose", "it", "in", "an", "Array" ]
b968b5d3c7a995a0650faad32a2d89a394c11364
https://github.com/tuskenraiders/degu/blob/b968b5d3c7a995a0650faad32a2d89a394c11364/lib/degu/has_set.rb#L111-L129
train
crystalcommerce/hijacker
lib/hijacker/redis_keys.rb
Hijacker.RedisKeys.unresponsive_dbhost_count
def unresponsive_dbhost_count(db_host) begin count = $hijacker_redis.hget( redis_keys(:unresponsive_dbhosts), db_host) unless db_host.nil? (count or 0).to_i rescue 0 end end
ruby
def unresponsive_dbhost_count(db_host) begin count = $hijacker_redis.hget( redis_keys(:unresponsive_dbhosts), db_host) unless db_host.nil? (count or 0).to_i rescue 0 end end
[ "def", "unresponsive_dbhost_count", "(", "db_host", ")", "begin", "count", "=", "$hijacker_redis", ".", "hget", "(", "redis_keys", "(", ":unresponsive_dbhosts", ")", ",", "db_host", ")", "unless", "db_host", ".", "nil?", "(", "count", "or", "0", ")", ".", "to_i", "rescue", "0", "end", "end" ]
Get the current count for the number of times requests were not able to connect to a given database host
[ "Get", "the", "current", "count", "for", "the", "number", "of", "times", "requests", "were", "not", "able", "to", "connect", "to", "a", "given", "database", "host" ]
71bb89ff3c1d1bf7517958989ae1fdf529721a6c
https://github.com/crystalcommerce/hijacker/blob/71bb89ff3c1d1bf7517958989ae1fdf529721a6c/lib/hijacker/redis_keys.rb#L83-L90
train
blahah/datastructures
lib/datastructures/linked_list.rb
DataStructures.LinkedList.to_a
def to_a current = @first array = [] while !current.nil? array << current.data current = current.next end array end
ruby
def to_a current = @first array = [] while !current.nil? array << current.data current = current.next end array end
[ "def", "to_a", "current", "=", "@first", "array", "=", "[", "]", "while", "!", "current", ".", "nil?", "array", "<<", "current", ".", "data", "current", "=", "current", ".", "next", "end", "array", "end" ]
Returns an array containing the data from the nodes in the list
[ "Returns", "an", "array", "containing", "the", "data", "from", "the", "nodes", "in", "the", "list" ]
09bcca77118320278f4772ddce53081c446eb7c1
https://github.com/blahah/datastructures/blob/09bcca77118320278f4772ddce53081c446eb7c1/lib/datastructures/linked_list.rb#L160-L168
train
osulp/triplestore-adapter
lib/triplestore_adapter/providers/blazegraph.rb
TriplestoreAdapter::Providers.Blazegraph.delete
def delete(statements) raise(TriplestoreAdapter::TriplestoreException, "delete received invalid array of statements") unless statements.any? #TODO: Evaluate that all statements are singular, and without bnodes? writer = RDF::Writer.for(:jsonld) uri = URI.parse("#{@uri}?delete") request = Net::HTTP::Post.new(uri) request['Content-Type'] = 'application/ld+json' request.body = writer.dump(statements) @http.request(uri, request) return true end
ruby
def delete(statements) raise(TriplestoreAdapter::TriplestoreException, "delete received invalid array of statements") unless statements.any? #TODO: Evaluate that all statements are singular, and without bnodes? writer = RDF::Writer.for(:jsonld) uri = URI.parse("#{@uri}?delete") request = Net::HTTP::Post.new(uri) request['Content-Type'] = 'application/ld+json' request.body = writer.dump(statements) @http.request(uri, request) return true end
[ "def", "delete", "(", "statements", ")", "raise", "(", "TriplestoreAdapter", "::", "TriplestoreException", ",", "\"delete received invalid array of statements\"", ")", "unless", "statements", ".", "any?", "writer", "=", "RDF", "::", "Writer", ".", "for", "(", ":jsonld", ")", "uri", "=", "URI", ".", "parse", "(", "\"#{@uri}?delete\"", ")", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "uri", ")", "request", "[", "'Content-Type'", "]", "=", "'application/ld+json'", "request", ".", "body", "=", "writer", ".", "dump", "(", "statements", ")", "@http", ".", "request", "(", "uri", ",", "request", ")", "return", "true", "end" ]
Delete the provided statements from the triplestore @param [RDF::Enumerable] statements to delete from the triplestore @return [Boolean] true if the delete was successful
[ "Delete", "the", "provided", "statements", "from", "the", "triplestore" ]
597fa5842f846e57cba7574da873f1412ab76ffa
https://github.com/osulp/triplestore-adapter/blob/597fa5842f846e57cba7574da873f1412ab76ffa/lib/triplestore_adapter/providers/blazegraph.rb#L39-L50
train
osulp/triplestore-adapter
lib/triplestore_adapter/providers/blazegraph.rb
TriplestoreAdapter::Providers.Blazegraph.get_statements
def get_statements(subject: nil) raise(TriplestoreAdapter::TriplestoreException, "get_statements received blank subject") if subject.empty? subject = URI.escape(subject.to_s) uri = URI.parse(format("%{uri}?GETSTMTS&s=<%{subject}>&includeInferred=false", {uri: @uri, subject: subject})) request = Net::HTTP::Get.new(uri) response = @http.request(uri, request) RDF::Reader.for(:ntriples).new(response.body) end
ruby
def get_statements(subject: nil) raise(TriplestoreAdapter::TriplestoreException, "get_statements received blank subject") if subject.empty? subject = URI.escape(subject.to_s) uri = URI.parse(format("%{uri}?GETSTMTS&s=<%{subject}>&includeInferred=false", {uri: @uri, subject: subject})) request = Net::HTTP::Get.new(uri) response = @http.request(uri, request) RDF::Reader.for(:ntriples).new(response.body) end
[ "def", "get_statements", "(", "subject", ":", "nil", ")", "raise", "(", "TriplestoreAdapter", "::", "TriplestoreException", ",", "\"get_statements received blank subject\"", ")", "if", "subject", ".", "empty?", "subject", "=", "URI", ".", "escape", "(", "subject", ".", "to_s", ")", "uri", "=", "URI", ".", "parse", "(", "format", "(", "\"%{uri}?GETSTMTS&s=<%{subject}>&includeInferred=false\"", ",", "{", "uri", ":", "@uri", ",", "subject", ":", "subject", "}", ")", ")", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "uri", ")", "response", "=", "@http", ".", "request", "(", "uri", ",", "request", ")", "RDF", "::", "Reader", ".", "for", "(", ":ntriples", ")", ".", "new", "(", "response", ".", "body", ")", "end" ]
Returns statements matching the subject @param [String] subject url @return [RDF::Enumerable] RDF statements
[ "Returns", "statements", "matching", "the", "subject" ]
597fa5842f846e57cba7574da873f1412ab76ffa
https://github.com/osulp/triplestore-adapter/blob/597fa5842f846e57cba7574da873f1412ab76ffa/lib/triplestore_adapter/providers/blazegraph.rb#L56-L63
train
osulp/triplestore-adapter
lib/triplestore_adapter/providers/blazegraph.rb
TriplestoreAdapter::Providers.Blazegraph.build_namespace
def build_namespace(namespace) raise(TriplestoreAdapter::TriplestoreException, "build_namespace received blank namespace") if namespace.empty? request = Net::HTTP::Post.new("#{build_url}/blazegraph/namespace") request['Content-Type'] = 'text/plain' request.body = "com.bigdata.rdf.sail.namespace=#{namespace}" @http.request(@uri, request) "#{build_url}/blazegraph/namespace/#{namespace}/sparql" end
ruby
def build_namespace(namespace) raise(TriplestoreAdapter::TriplestoreException, "build_namespace received blank namespace") if namespace.empty? request = Net::HTTP::Post.new("#{build_url}/blazegraph/namespace") request['Content-Type'] = 'text/plain' request.body = "com.bigdata.rdf.sail.namespace=#{namespace}" @http.request(@uri, request) "#{build_url}/blazegraph/namespace/#{namespace}/sparql" end
[ "def", "build_namespace", "(", "namespace", ")", "raise", "(", "TriplestoreAdapter", "::", "TriplestoreException", ",", "\"build_namespace received blank namespace\"", ")", "if", "namespace", ".", "empty?", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "\"#{build_url}/blazegraph/namespace\"", ")", "request", "[", "'Content-Type'", "]", "=", "'text/plain'", "request", ".", "body", "=", "\"com.bigdata.rdf.sail.namespace=#{namespace}\"", "@http", ".", "request", "(", "@uri", ",", "request", ")", "\"#{build_url}/blazegraph/namespace/#{namespace}/sparql\"", "end" ]
Create a new namespace on the triplestore @param [String] namespace to be built @return [String] URI for the new namespace
[ "Create", "a", "new", "namespace", "on", "the", "triplestore" ]
597fa5842f846e57cba7574da873f1412ab76ffa
https://github.com/osulp/triplestore-adapter/blob/597fa5842f846e57cba7574da873f1412ab76ffa/lib/triplestore_adapter/providers/blazegraph.rb#L79-L86
train
osulp/triplestore-adapter
lib/triplestore_adapter/triplestore.rb
TriplestoreAdapter.Triplestore.store
def store(graph) begin statements = graph.each_statement.to_a @client.insert(statements) graph rescue => e raise TriplestoreAdapter::TriplestoreException, "store graph in triplestore cache failed with exception: #{e.message}" end end
ruby
def store(graph) begin statements = graph.each_statement.to_a @client.insert(statements) graph rescue => e raise TriplestoreAdapter::TriplestoreException, "store graph in triplestore cache failed with exception: #{e.message}" end end
[ "def", "store", "(", "graph", ")", "begin", "statements", "=", "graph", ".", "each_statement", ".", "to_a", "@client", ".", "insert", "(", "statements", ")", "graph", "rescue", "=>", "e", "raise", "TriplestoreAdapter", "::", "TriplestoreException", ",", "\"store graph in triplestore cache failed with exception: #{e.message}\"", "end", "end" ]
Store the graph in the triplestore cache @param [RDF::Graph] graph @return [RDF::Graph] @raise [Exception] if client fails to store the graph
[ "Store", "the", "graph", "in", "the", "triplestore", "cache" ]
597fa5842f846e57cba7574da873f1412ab76ffa
https://github.com/osulp/triplestore-adapter/blob/597fa5842f846e57cba7574da873f1412ab76ffa/lib/triplestore_adapter/triplestore.rb#L42-L50
train
osulp/triplestore-adapter
lib/triplestore_adapter/triplestore.rb
TriplestoreAdapter.Triplestore.delete
def delete(rdf_url) begin graph = fetch_cached_graph(rdf_url) puts "[INFO] did not delete #{rdf_url}, it doesn't exist in the triplestore cache" if graph.nil? return true if graph.nil? statements = graph.each_statement.to_a @client.delete(statements) return true rescue => e raise TriplestoreAdapter::TriplestoreException, "delete #{rdf_url} from triplestore cache failed with exception: #{e.message}" end end
ruby
def delete(rdf_url) begin graph = fetch_cached_graph(rdf_url) puts "[INFO] did not delete #{rdf_url}, it doesn't exist in the triplestore cache" if graph.nil? return true if graph.nil? statements = graph.each_statement.to_a @client.delete(statements) return true rescue => e raise TriplestoreAdapter::TriplestoreException, "delete #{rdf_url} from triplestore cache failed with exception: #{e.message}" end end
[ "def", "delete", "(", "rdf_url", ")", "begin", "graph", "=", "fetch_cached_graph", "(", "rdf_url", ")", "puts", "\"[INFO] did not delete #{rdf_url}, it doesn't exist in the triplestore cache\"", "if", "graph", ".", "nil?", "return", "true", "if", "graph", ".", "nil?", "statements", "=", "graph", ".", "each_statement", ".", "to_a", "@client", ".", "delete", "(", "statements", ")", "return", "true", "rescue", "=>", "e", "raise", "TriplestoreAdapter", "::", "TriplestoreException", ",", "\"delete #{rdf_url} from triplestore cache failed with exception: #{e.message}\"", "end", "end" ]
Delete the graph from the triplestore cache @param [String] rdf_url @return [Boolean]
[ "Delete", "the", "graph", "from", "the", "triplestore", "cache" ]
597fa5842f846e57cba7574da873f1412ab76ffa
https://github.com/osulp/triplestore-adapter/blob/597fa5842f846e57cba7574da873f1412ab76ffa/lib/triplestore_adapter/triplestore.rb#L57-L69
train
osulp/triplestore-adapter
lib/triplestore_adapter/triplestore.rb
TriplestoreAdapter.Triplestore.fetch_cached_graph
def fetch_cached_graph(rdf_url) statements = @client.get_statements(subject: rdf_url.to_s) if statements.count == 0 puts "[INFO] fetch_cached_graph(#{rdf_url.to_s}) not found in triplestore cache (#{@client.url})" return nil end RDF::Graph.new.insert(*statements) end
ruby
def fetch_cached_graph(rdf_url) statements = @client.get_statements(subject: rdf_url.to_s) if statements.count == 0 puts "[INFO] fetch_cached_graph(#{rdf_url.to_s}) not found in triplestore cache (#{@client.url})" return nil end RDF::Graph.new.insert(*statements) end
[ "def", "fetch_cached_graph", "(", "rdf_url", ")", "statements", "=", "@client", ".", "get_statements", "(", "subject", ":", "rdf_url", ".", "to_s", ")", "if", "statements", ".", "count", "==", "0", "puts", "\"[INFO] fetch_cached_graph(#{rdf_url.to_s}) not found in triplestore cache (#{@client.url})\"", "return", "nil", "end", "RDF", "::", "Graph", ".", "new", ".", "insert", "(", "*", "statements", ")", "end" ]
Fetch the graph from the triplestore cache @private @param [String] url @return [RDF::Graph] if the graph is found in the cache @return [nil] if the graph was not in the cache
[ "Fetch", "the", "graph", "from", "the", "triplestore", "cache" ]
597fa5842f846e57cba7574da873f1412ab76ffa
https://github.com/osulp/triplestore-adapter/blob/597fa5842f846e57cba7574da873f1412ab76ffa/lib/triplestore_adapter/triplestore.rb#L92-L99
train
osulp/triplestore-adapter
lib/triplestore_adapter/triplestore.rb
TriplestoreAdapter.Triplestore.fetch_and_cache_graph
def fetch_and_cache_graph(rdf_url) begin graph = RDF::Graph.load(rdf_url) store(graph) graph rescue TriplestoreAdapter::TriplestoreException => tse puts "[ERROR] *****\n[ERROR] Unable to store graph in triplestore cache! Returning graph fetched from source.\n[ERROR] *****\n#{tse.message}" graph rescue => e raise TriplestoreAdapter::TriplestoreException, "fetch_and_cache_graph(#{rdf_url}) failed to load the graph with exception: #{e.message}" end end
ruby
def fetch_and_cache_graph(rdf_url) begin graph = RDF::Graph.load(rdf_url) store(graph) graph rescue TriplestoreAdapter::TriplestoreException => tse puts "[ERROR] *****\n[ERROR] Unable to store graph in triplestore cache! Returning graph fetched from source.\n[ERROR] *****\n#{tse.message}" graph rescue => e raise TriplestoreAdapter::TriplestoreException, "fetch_and_cache_graph(#{rdf_url}) failed to load the graph with exception: #{e.message}" end end
[ "def", "fetch_and_cache_graph", "(", "rdf_url", ")", "begin", "graph", "=", "RDF", "::", "Graph", ".", "load", "(", "rdf_url", ")", "store", "(", "graph", ")", "graph", "rescue", "TriplestoreAdapter", "::", "TriplestoreException", "=>", "tse", "puts", "\"[ERROR] *****\\n[ERROR] Unable to store graph in triplestore cache! Returning graph fetched from source.\\n[ERROR] *****\\n#{tse.message}\"", "graph", "rescue", "=>", "e", "raise", "TriplestoreAdapter", "::", "TriplestoreException", ",", "\"fetch_and_cache_graph(#{rdf_url}) failed to load the graph with exception: #{e.message}\"", "end", "end" ]
Fetch the graph from the source URL, and cache it for future use @private @param [String] url @return [RDF::Graph] if a graph is found @raise [Exception] if fetching the graph failed
[ "Fetch", "the", "graph", "from", "the", "source", "URL", "and", "cache", "it", "for", "future", "use" ]
597fa5842f846e57cba7574da873f1412ab76ffa
https://github.com/osulp/triplestore-adapter/blob/597fa5842f846e57cba7574da873f1412ab76ffa/lib/triplestore_adapter/triplestore.rb#L108-L119
train
osulp/triplestore-adapter
lib/triplestore_adapter/client.rb
TriplestoreAdapter.Client.get_statements
def get_statements(subject: nil) raise TriplestoreAdapter::TriplestoreException.new("#{@provider.class.name} missing get_statements method.") unless @provider.respond_to?(:get_statements) @provider.get_statements(subject: subject) end
ruby
def get_statements(subject: nil) raise TriplestoreAdapter::TriplestoreException.new("#{@provider.class.name} missing get_statements method.") unless @provider.respond_to?(:get_statements) @provider.get_statements(subject: subject) end
[ "def", "get_statements", "(", "subject", ":", "nil", ")", "raise", "TriplestoreAdapter", "::", "TriplestoreException", ".", "new", "(", "\"#{@provider.class.name} missing get_statements method.\"", ")", "unless", "@provider", ".", "respond_to?", "(", ":get_statements", ")", "@provider", ".", "get_statements", "(", "subject", ":", "subject", ")", "end" ]
Get statements from the server @param [String] subject url @raise [TriplestoreAdapter::TriplestoreException] if the provider doesn't implement this method
[ "Get", "statements", "from", "the", "server" ]
597fa5842f846e57cba7574da873f1412ab76ffa
https://github.com/osulp/triplestore-adapter/blob/597fa5842f846e57cba7574da873f1412ab76ffa/lib/triplestore_adapter/client.rb#L41-L44
train
toasterlovin/csv_party
lib/csv_party/validations.rb
CSVParty.Validations.raise_unless_all_named_parsers_exist!
def raise_unless_all_named_parsers_exist! config.columns_with_named_parsers.each do |name, options| parser = options[:parser] next if named_parsers.include? parser raise UnknownParserError.new(name, parser, named_parsers) end end
ruby
def raise_unless_all_named_parsers_exist! config.columns_with_named_parsers.each do |name, options| parser = options[:parser] next if named_parsers.include? parser raise UnknownParserError.new(name, parser, named_parsers) end end
[ "def", "raise_unless_all_named_parsers_exist!", "config", ".", "columns_with_named_parsers", ".", "each", "do", "|", "name", ",", "options", "|", "parser", "=", "options", "[", ":parser", "]", "next", "if", "named_parsers", ".", "include?", "parser", "raise", "UnknownParserError", ".", "new", "(", "name", ",", "parser", ",", "named_parsers", ")", "end", "end" ]
This error has to be raised at runtime because, when the class body is being executed, the parser methods won't be available unless they are defined above the column definitions in the class body
[ "This", "error", "has", "to", "be", "raised", "at", "runtime", "because", "when", "the", "class", "body", "is", "being", "executed", "the", "parser", "methods", "won", "t", "be", "available", "unless", "they", "are", "defined", "above", "the", "column", "definitions", "in", "the", "class", "body" ]
4f6ad97cc8d9a93c60cbd44df257ec2253c371b4
https://github.com/toasterlovin/csv_party/blob/4f6ad97cc8d9a93c60cbd44df257ec2253c371b4/lib/csv_party/validations.rb#L26-L33
train
piotrmurach/tty-which
lib/tty/which.rb
TTY.Which.which
def which(cmd, paths: search_paths) if file_with_path?(cmd) return cmd if executable_file?(cmd) extensions.each do |ext| exe = ::File.join(cmd, ext) return ::File.absolute_path(exe) if executable_file?(exe) end return nil end paths.each do |path| if file_with_exec_ext?(cmd) exe = ::File.join(path, cmd) return ::File.absolute_path(exe) if executable_file?(exe) end extensions.each do |ext| exe = ::File.join(path, "#{cmd}#{ext}") return ::File.absolute_path(exe) if executable_file?(exe) end end nil end
ruby
def which(cmd, paths: search_paths) if file_with_path?(cmd) return cmd if executable_file?(cmd) extensions.each do |ext| exe = ::File.join(cmd, ext) return ::File.absolute_path(exe) if executable_file?(exe) end return nil end paths.each do |path| if file_with_exec_ext?(cmd) exe = ::File.join(path, cmd) return ::File.absolute_path(exe) if executable_file?(exe) end extensions.each do |ext| exe = ::File.join(path, "#{cmd}#{ext}") return ::File.absolute_path(exe) if executable_file?(exe) end end nil end
[ "def", "which", "(", "cmd", ",", "paths", ":", "search_paths", ")", "if", "file_with_path?", "(", "cmd", ")", "return", "cmd", "if", "executable_file?", "(", "cmd", ")", "extensions", ".", "each", "do", "|", "ext", "|", "exe", "=", "::", "File", ".", "join", "(", "cmd", ",", "ext", ")", "return", "::", "File", ".", "absolute_path", "(", "exe", ")", "if", "executable_file?", "(", "exe", ")", "end", "return", "nil", "end", "paths", ".", "each", "do", "|", "path", "|", "if", "file_with_exec_ext?", "(", "cmd", ")", "exe", "=", "::", "File", ".", "join", "(", "path", ",", "cmd", ")", "return", "::", "File", ".", "absolute_path", "(", "exe", ")", "if", "executable_file?", "(", "exe", ")", "end", "extensions", ".", "each", "do", "|", "ext", "|", "exe", "=", "::", "File", ".", "join", "(", "path", ",", "\"#{cmd}#{ext}\"", ")", "return", "::", "File", ".", "absolute_path", "(", "exe", ")", "if", "executable_file?", "(", "exe", ")", "end", "end", "nil", "end" ]
Find an executable in a platform independent way @param [String] command the command to search for @param [Array[String]] paths the paths to look through @example which('ruby') # => '/usr/local/bin/ruby' which('/usr/local/bin/ruby') # => '/usr/local/bin/ruby' which('foo') # => nil @example which('ruby', paths: ['/usr/locale/bin', '/usr/bin', '/bin']) @return [String, nil] the absolute path to executable if found, `nil` otherwise @api public
[ "Find", "an", "executable", "in", "a", "platform", "independent", "way" ]
ae541cb7b4020eb291ebe0aca498ac24f183c8f5
https://github.com/piotrmurach/tty-which/blob/ae541cb7b4020eb291ebe0aca498ac24f183c8f5/lib/tty/which.rb#L27-L48
train
piotrmurach/tty-which
lib/tty/which.rb
TTY.Which.search_paths
def search_paths(path = ENV['PATH']) paths = if path && !path.empty? path.split(::File::PATH_SEPARATOR) else %w(/usr/local/bin /usr/ucb /usr/bin /bin) end paths.select(&Dir.method(:exist?)) end
ruby
def search_paths(path = ENV['PATH']) paths = if path && !path.empty? path.split(::File::PATH_SEPARATOR) else %w(/usr/local/bin /usr/ucb /usr/bin /bin) end paths.select(&Dir.method(:exist?)) end
[ "def", "search_paths", "(", "path", "=", "ENV", "[", "'PATH'", "]", ")", "paths", "=", "if", "path", "&&", "!", "path", ".", "empty?", "path", ".", "split", "(", "::", "File", "::", "PATH_SEPARATOR", ")", "else", "%w(", "/usr/local/bin", "/usr/ucb", "/usr/bin", "/bin", ")", "end", "paths", ".", "select", "(", "&", "Dir", ".", "method", "(", ":exist?", ")", ")", "end" ]
Find default system paths @param [String] path the path to search through @example search_paths("/usr/local/bin:/bin") # => ['/bin'] @return [Array[String]] the array of paths to search @api private
[ "Find", "default", "system", "paths" ]
ae541cb7b4020eb291ebe0aca498ac24f183c8f5
https://github.com/piotrmurach/tty-which/blob/ae541cb7b4020eb291ebe0aca498ac24f183c8f5/lib/tty/which.rb#L80-L87
train
piotrmurach/tty-which
lib/tty/which.rb
TTY.Which.extensions
def extensions(path_ext = ENV['PATHEXT']) return [''] unless path_ext path_ext.split(::File::PATH_SEPARATOR).select { |part| part.include?('.') } end
ruby
def extensions(path_ext = ENV['PATHEXT']) return [''] unless path_ext path_ext.split(::File::PATH_SEPARATOR).select { |part| part.include?('.') } end
[ "def", "extensions", "(", "path_ext", "=", "ENV", "[", "'PATHEXT'", "]", ")", "return", "[", "''", "]", "unless", "path_ext", "path_ext", ".", "split", "(", "::", "File", "::", "PATH_SEPARATOR", ")", ".", "select", "{", "|", "part", "|", "part", ".", "include?", "(", "'.'", ")", "}", "end" ]
All possible file extensions @example extensions('.exe;cmd;.bat') # => ['.exe','.bat'] @param [String] path_ext a string of semicolon separated filename extensions @return [Array[String]] an array with valid file extensions @api private
[ "All", "possible", "file", "extensions" ]
ae541cb7b4020eb291ebe0aca498ac24f183c8f5
https://github.com/piotrmurach/tty-which/blob/ae541cb7b4020eb291ebe0aca498ac24f183c8f5/lib/tty/which.rb#L103-L106
train
piotrmurach/tty-which
lib/tty/which.rb
TTY.Which.executable_file?
def executable_file?(filename, dir = nil) path = ::File.join(dir, filename) if dir path ||= filename ::File.file?(path) && ::File.executable?(path) end
ruby
def executable_file?(filename, dir = nil) path = ::File.join(dir, filename) if dir path ||= filename ::File.file?(path) && ::File.executable?(path) end
[ "def", "executable_file?", "(", "filename", ",", "dir", "=", "nil", ")", "path", "=", "::", "File", ".", "join", "(", "dir", ",", "filename", ")", "if", "dir", "path", "||=", "filename", "::", "File", ".", "file?", "(", "path", ")", "&&", "::", "File", ".", "executable?", "(", "path", ")", "end" ]
Determines if filename is an executable file @example Basic usage executable_file?('/usr/bin/less') # => true @example Executable in directory executable_file?('less', '/usr/bin') # => true executable_file?('less', '/usr') # => false @param [String] filename the path to file @param [String] dir the directory within which to search for filename @return [Boolean] @api private
[ "Determines", "if", "filename", "is", "an", "executable", "file" ]
ae541cb7b4020eb291ebe0aca498ac24f183c8f5
https://github.com/piotrmurach/tty-which/blob/ae541cb7b4020eb291ebe0aca498ac24f183c8f5/lib/tty/which.rb#L126-L130
train
piotrmurach/tty-which
lib/tty/which.rb
TTY.Which.file_with_exec_ext?
def file_with_exec_ext?(filename) extension = ::File.extname(filename) return false if extension.empty? extensions.any? { |ext| extension.casecmp(ext).zero? } end
ruby
def file_with_exec_ext?(filename) extension = ::File.extname(filename) return false if extension.empty? extensions.any? { |ext| extension.casecmp(ext).zero? } end
[ "def", "file_with_exec_ext?", "(", "filename", ")", "extension", "=", "::", "File", ".", "extname", "(", "filename", ")", "return", "false", "if", "extension", ".", "empty?", "extensions", ".", "any?", "{", "|", "ext", "|", "extension", ".", "casecmp", "(", "ext", ")", ".", "zero?", "}", "end" ]
Check if command itself has executable extension @param [String] filename the path to executable file @example file_with_exec_ext?("file.bat") # => true @return [Boolean] @api private
[ "Check", "if", "command", "itself", "has", "executable", "extension" ]
ae541cb7b4020eb291ebe0aca498ac24f183c8f5
https://github.com/piotrmurach/tty-which/blob/ae541cb7b4020eb291ebe0aca498ac24f183c8f5/lib/tty/which.rb#L145-L149
train
iainbeeston/nickel
lib/nickel/construct_finder.rb
Nickel.ConstructFinder.found_now_through_following_dayname
def found_now_through_following_dayname @constructs << DateSpanConstruct.new(start_date: @curdate, end_date: @curdate.this(@day_index), comp_start: @pos, comp_end: @pos += 3, found_in: __method__) end
ruby
def found_now_through_following_dayname @constructs << DateSpanConstruct.new(start_date: @curdate, end_date: @curdate.this(@day_index), comp_start: @pos, comp_end: @pos += 3, found_in: __method__) end
[ "def", "found_now_through_following_dayname", "@constructs", "<<", "DateSpanConstruct", ".", "new", "(", "start_date", ":", "@curdate", ",", "end_date", ":", "@curdate", ".", "this", "(", "@day_index", ")", ",", "comp_start", ":", "@pos", ",", "comp_end", ":", "@pos", "+=", "3", ",", "found_in", ":", "__method__", ")", "end" ]
redundant!! preprocess this out of here!
[ "redundant!!", "preprocess", "this", "out", "of", "here!" ]
47755277499db945f5eb65a4c0fb27c0e344c90b
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/construct_finder.rb#L1067-L1069
train
iainbeeston/nickel
lib/nickel/nlp.rb
Nickel.NLP.correct_case
def correct_case orig = @query.split latest = @message.split orig.each_with_index do |original_word, j| if i = latest.index(original_word.downcase) latest[i] = original_word end end @message = latest.join(' ') end
ruby
def correct_case orig = @query.split latest = @message.split orig.each_with_index do |original_word, j| if i = latest.index(original_word.downcase) latest[i] = original_word end end @message = latest.join(' ') end
[ "def", "correct_case", "orig", "=", "@query", ".", "split", "latest", "=", "@message", ".", "split", "orig", ".", "each_with_index", "do", "|", "original_word", ",", "j", "|", "if", "i", "=", "latest", ".", "index", "(", "original_word", ".", "downcase", ")", "latest", "[", "i", "]", "=", "original_word", "end", "end", "@message", "=", "latest", ".", "join", "(", "' '", ")", "end" ]
returns any words in the query that appeared as input to their original case
[ "returns", "any", "words", "in", "the", "query", "that", "appeared", "as", "input", "to", "their", "original", "case" ]
47755277499db945f5eb65a4c0fb27c0e344c90b
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/nlp.rb#L83-L92
train
iainbeeston/nickel
lib/nickel/zdate.rb
Nickel.ZDate.ordinal_dayindex
def ordinal_dayindex(num, day_index) # create a date object at the first occurrence of day_index first_occ_date = ZDate.new(ZDate.format_date(year_str, month_str)).this(day_index) # if num is 1 through 4, we can just add (num-1) weeks if num <= 4 d = first_occ_date.add_weeks(num - 1) else # we want the last occurrence of this month # add 4 weeks to first occurrence, see if we are in the same month, subtract 1 week if we are not d = first_occ_date.add_weeks(4) if d.month != month d = d.sub_weeks(1) end end d end
ruby
def ordinal_dayindex(num, day_index) # create a date object at the first occurrence of day_index first_occ_date = ZDate.new(ZDate.format_date(year_str, month_str)).this(day_index) # if num is 1 through 4, we can just add (num-1) weeks if num <= 4 d = first_occ_date.add_weeks(num - 1) else # we want the last occurrence of this month # add 4 weeks to first occurrence, see if we are in the same month, subtract 1 week if we are not d = first_occ_date.add_weeks(4) if d.month != month d = d.sub_weeks(1) end end d end
[ "def", "ordinal_dayindex", "(", "num", ",", "day_index", ")", "first_occ_date", "=", "ZDate", ".", "new", "(", "ZDate", ".", "format_date", "(", "year_str", ",", "month_str", ")", ")", ".", "this", "(", "day_index", ")", "if", "num", "<=", "4", "d", "=", "first_occ_date", ".", "add_weeks", "(", "num", "-", "1", ")", "else", "d", "=", "first_occ_date", ".", "add_weeks", "(", "4", ")", "if", "d", ".", "month", "!=", "month", "d", "=", "d", ".", "sub_weeks", "(", "1", ")", "end", "end", "d", "end" ]
for example, "1st friday", uses self as the reference month
[ "for", "example", "1st", "friday", "uses", "self", "as", "the", "reference", "month" ]
47755277499db945f5eb65a4c0fb27c0e344c90b
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/zdate.rb#L100-L115
train
iainbeeston/nickel
lib/nickel/zdate.rb
Nickel.ZDate.x_weeks_from_day
def x_weeks_from_day(weeks_away, day2index) day1index = dayindex if day1index > day2index days_away = 7 * (weeks_away + 1) - (day1index - day2index) elsif day1index < day2index days_away = (weeks_away * 7) + (day2index - day1index) elsif day1index == day2index days_away = 7 * weeks_away end add_days(days_away) # returns a new date object end
ruby
def x_weeks_from_day(weeks_away, day2index) day1index = dayindex if day1index > day2index days_away = 7 * (weeks_away + 1) - (day1index - day2index) elsif day1index < day2index days_away = (weeks_away * 7) + (day2index - day1index) elsif day1index == day2index days_away = 7 * weeks_away end add_days(days_away) # returns a new date object end
[ "def", "x_weeks_from_day", "(", "weeks_away", ",", "day2index", ")", "day1index", "=", "dayindex", "if", "day1index", ">", "day2index", "days_away", "=", "7", "*", "(", "weeks_away", "+", "1", ")", "-", "(", "day1index", "-", "day2index", ")", "elsif", "day1index", "<", "day2index", "days_away", "=", "(", "weeks_away", "*", "7", ")", "+", "(", "day2index", "-", "day1index", ")", "elsif", "day1index", "==", "day2index", "days_away", "=", "7", "*", "weeks_away", "end", "add_days", "(", "days_away", ")", "end" ]
returns a new date object
[ "returns", "a", "new", "date", "object" ]
47755277499db945f5eb65a4c0fb27c0e344c90b
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/zdate.rb#L133-L143
train
iainbeeston/nickel
lib/nickel/zdate.rb
Nickel.ZDate.add_days
def add_days(number) if number < 0 return sub_days(number.abs) end o = dup # new ZDate object # Let's see what month we are going to end in while number > 0 if o.days_left_in_month >= number o.date = ZDate.format_date(o.year_str, o.month_str, o.day + number) number = 0 else number = number - 1 - o.days_left_in_month # it costs 1 day to increment the month o.increment_month! end end o end
ruby
def add_days(number) if number < 0 return sub_days(number.abs) end o = dup # new ZDate object # Let's see what month we are going to end in while number > 0 if o.days_left_in_month >= number o.date = ZDate.format_date(o.year_str, o.month_str, o.day + number) number = 0 else number = number - 1 - o.days_left_in_month # it costs 1 day to increment the month o.increment_month! end end o end
[ "def", "add_days", "(", "number", ")", "if", "number", "<", "0", "return", "sub_days", "(", "number", ".", "abs", ")", "end", "o", "=", "dup", "while", "number", ">", "0", "if", "o", ".", "days_left_in_month", ">=", "number", "o", ".", "date", "=", "ZDate", ".", "format_date", "(", "o", ".", "year_str", ",", "o", ".", "month_str", ",", "o", ".", "day", "+", "number", ")", "number", "=", "0", "else", "number", "=", "number", "-", "1", "-", "o", ".", "days_left_in_month", "o", ".", "increment_month!", "end", "end", "o", "end" ]
add_ methods return new ZDate object, they DO NOT modify self
[ "add_", "methods", "return", "new", "ZDate", "object", "they", "DO", "NOT", "modify", "self" ]
47755277499db945f5eb65a4c0fb27c0e344c90b
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/zdate.rb#L146-L162
train
iainbeeston/nickel
lib/nickel/zdate.rb
Nickel.ZDate.sub_days
def sub_days(number) o = dup while number > 0 if (o.day - 1) >= number o.date = ZDate.format_date(o.year_str, o.month_str, o.day - number) number = 0 else number -= o.day o.decrement_month! end end o end
ruby
def sub_days(number) o = dup while number > 0 if (o.day - 1) >= number o.date = ZDate.format_date(o.year_str, o.month_str, o.day - number) number = 0 else number -= o.day o.decrement_month! end end o end
[ "def", "sub_days", "(", "number", ")", "o", "=", "dup", "while", "number", ">", "0", "if", "(", "o", ".", "day", "-", "1", ")", ">=", "number", "o", ".", "date", "=", "ZDate", ".", "format_date", "(", "o", ".", "year_str", ",", "o", ".", "month_str", ",", "o", ".", "day", "-", "number", ")", "number", "=", "0", "else", "number", "-=", "o", ".", "day", "o", ".", "decrement_month!", "end", "end", "o", "end" ]
sub_ methods return new ZDate object, they do not modify self.
[ "sub_", "methods", "return", "new", "ZDate", "object", "they", "do", "not", "modify", "self", "." ]
47755277499db945f5eb65a4c0fb27c0e344c90b
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/zdate.rb#L224-L236
train
iainbeeston/nickel
lib/nickel/zdate.rb
Nickel.ZDate.diff_in_days
def diff_in_days(date_to_compare) # d1 will be the earlier date, d2 the later if date_to_compare > self d1, d2 = dup, date_to_compare.dup elsif self > date_to_compare d1, d2 = date_to_compare.dup, dup else return 0 # same date end total = 0 while d1.year != d2.year total += d1.days_left_in_year + 1 # need one extra day to push us to jan 1 d1 = ZDate.new(ZDate.format_date(d1.year + 1)) end total += d2.day_of_year - d1.day_of_year total end
ruby
def diff_in_days(date_to_compare) # d1 will be the earlier date, d2 the later if date_to_compare > self d1, d2 = dup, date_to_compare.dup elsif self > date_to_compare d1, d2 = date_to_compare.dup, dup else return 0 # same date end total = 0 while d1.year != d2.year total += d1.days_left_in_year + 1 # need one extra day to push us to jan 1 d1 = ZDate.new(ZDate.format_date(d1.year + 1)) end total += d2.day_of_year - d1.day_of_year total end
[ "def", "diff_in_days", "(", "date_to_compare", ")", "if", "date_to_compare", ">", "self", "d1", ",", "d2", "=", "dup", ",", "date_to_compare", ".", "dup", "elsif", "self", ">", "date_to_compare", "d1", ",", "d2", "=", "date_to_compare", ".", "dup", ",", "dup", "else", "return", "0", "end", "total", "=", "0", "while", "d1", ".", "year", "!=", "d2", ".", "year", "total", "+=", "d1", ".", "days_left_in_year", "+", "1", "d1", "=", "ZDate", ".", "new", "(", "ZDate", ".", "format_date", "(", "d1", ".", "year", "+", "1", ")", ")", "end", "total", "+=", "d2", ".", "day_of_year", "-", "d1", ".", "day_of_year", "total", "end" ]
Gets the absolute difference in days between self and date_to_compare, order is not important.
[ "Gets", "the", "absolute", "difference", "in", "days", "between", "self", "and", "date_to_compare", "order", "is", "not", "important", "." ]
47755277499db945f5eb65a4c0fb27c0e344c90b
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/zdate.rb#L251-L268
train
iainbeeston/nickel
lib/nickel/zdate.rb
Nickel.ZDate.diff_in_months
def diff_in_months(date2) if date2 > self ZDate.diff_in_months(month, year, date2.month, date2.year) else ZDate.diff_in_months(date2.month, date2.year, month, year) * -1 end end
ruby
def diff_in_months(date2) if date2 > self ZDate.diff_in_months(month, year, date2.month, date2.year) else ZDate.diff_in_months(date2.month, date2.year, month, year) * -1 end end
[ "def", "diff_in_months", "(", "date2", ")", "if", "date2", ">", "self", "ZDate", ".", "diff_in_months", "(", "month", ",", "year", ",", "date2", ".", "month", ",", "date2", ".", "year", ")", "else", "ZDate", ".", "diff_in_months", "(", "date2", ".", "month", ",", "date2", ".", "year", ",", "month", ",", "year", ")", "*", "-", "1", "end", "end" ]
difference in months FROM self TO date2, for instance, if self is oct 1 and date2 is nov 14, will return 1 if self is nov 14 and date2 is oct 1, will return -1
[ "difference", "in", "months", "FROM", "self", "TO", "date2", "for", "instance", "if", "self", "is", "oct", "1", "and", "date2", "is", "nov", "14", "will", "return", "1", "if", "self", "is", "nov", "14", "and", "date2", "is", "oct", "1", "will", "return", "-", "1" ]
47755277499db945f5eb65a4c0fb27c0e344c90b
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/zdate.rb#L399-L405
train
iainbeeston/nickel
lib/nickel/zdate.rb
Nickel.ZDate.increment_month!
def increment_month! if month != 12 # just bump up a number self.date = ZDate.format_date(year_str, month + 1) else self.date = ZDate.format_date(year + 1) end end
ruby
def increment_month! if month != 12 # just bump up a number self.date = ZDate.format_date(year_str, month + 1) else self.date = ZDate.format_date(year + 1) end end
[ "def", "increment_month!", "if", "month", "!=", "12", "self", ".", "date", "=", "ZDate", ".", "format_date", "(", "year_str", ",", "month", "+", "1", ")", "else", "self", ".", "date", "=", "ZDate", ".", "format_date", "(", "year", "+", "1", ")", "end", "end" ]
Modifies self. bumps self to first day of next month
[ "Modifies", "self", ".", "bumps", "self", "to", "first", "day", "of", "next", "month" ]
47755277499db945f5eb65a4c0fb27c0e344c90b
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/zdate.rb#L538-L545
train
iainbeeston/nickel
lib/nickel/ztime.rb
Nickel.ZTime.modify_such_that_is_before
def modify_such_that_is_before(time2) fail 'ZTime#modify_such_that_is_before says: trying to modify time that has @firm set' if @firm fail 'ZTime#modify_such_that_is_before says: time2 does not have @firm set' unless time2.firm # self cannot have @firm set, so all hours will be between 1 and 12 # time2 is an end time, self could be its current setting, or off by 12 hours # self to time2 --> self to time2 # 12 to 2am --> 1200 to 0200 # 12 to 12am --> 1200 to 0000 # 1220 to 12am --> 1220 to 0000 # 11 to 2am or 1100 to 0200 if self > time2 if hour == 12 && time2.hour == 0 # do nothing else hour == 12 ? change_hour_to(0) : change_hour_to(hour + 12) end elsif self < time2 if time2.hour >= 12 && ZTime.new(ZTime.format_time(time2.hour - 12, time2.min_str, time2.sec_str)) > self # 4 to 5pm or 0400 to 1700 change_hour_to(hour + 12) else # 4 to 1pm or 0400 to 1300 # do nothing end else # the times are equal, and self can only be between 0100 and 1200, so move self forward 12 hours, unless hour is 12 hour == 12 ? change_hour_to(0) : change_hour_to(hour + 12) end self.firm = true self end
ruby
def modify_such_that_is_before(time2) fail 'ZTime#modify_such_that_is_before says: trying to modify time that has @firm set' if @firm fail 'ZTime#modify_such_that_is_before says: time2 does not have @firm set' unless time2.firm # self cannot have @firm set, so all hours will be between 1 and 12 # time2 is an end time, self could be its current setting, or off by 12 hours # self to time2 --> self to time2 # 12 to 2am --> 1200 to 0200 # 12 to 12am --> 1200 to 0000 # 1220 to 12am --> 1220 to 0000 # 11 to 2am or 1100 to 0200 if self > time2 if hour == 12 && time2.hour == 0 # do nothing else hour == 12 ? change_hour_to(0) : change_hour_to(hour + 12) end elsif self < time2 if time2.hour >= 12 && ZTime.new(ZTime.format_time(time2.hour - 12, time2.min_str, time2.sec_str)) > self # 4 to 5pm or 0400 to 1700 change_hour_to(hour + 12) else # 4 to 1pm or 0400 to 1300 # do nothing end else # the times are equal, and self can only be between 0100 and 1200, so move self forward 12 hours, unless hour is 12 hour == 12 ? change_hour_to(0) : change_hour_to(hour + 12) end self.firm = true self end
[ "def", "modify_such_that_is_before", "(", "time2", ")", "fail", "'ZTime#modify_such_that_is_before says: trying to modify time that has @firm set'", "if", "@firm", "fail", "'ZTime#modify_such_that_is_before says: time2 does not have @firm set'", "unless", "time2", ".", "firm", "if", "self", ">", "time2", "if", "hour", "==", "12", "&&", "time2", ".", "hour", "==", "0", "else", "hour", "==", "12", "?", "change_hour_to", "(", "0", ")", ":", "change_hour_to", "(", "hour", "+", "12", ")", "end", "elsif", "self", "<", "time2", "if", "time2", ".", "hour", ">=", "12", "&&", "ZTime", ".", "new", "(", "ZTime", ".", "format_time", "(", "time2", ".", "hour", "-", "12", ",", "time2", ".", "min_str", ",", "time2", ".", "sec_str", ")", ")", ">", "self", "change_hour_to", "(", "hour", "+", "12", ")", "else", "end", "else", "hour", "==", "12", "?", "change_hour_to", "(", "0", ")", ":", "change_hour_to", "(", "hour", "+", "12", ")", "end", "self", ".", "firm", "=", "true", "self", "end" ]
this can very easily be cleaned up
[ "this", "can", "very", "easily", "be", "cleaned", "up" ]
47755277499db945f5eb65a4c0fb27c0e344c90b
https://github.com/iainbeeston/nickel/blob/47755277499db945f5eb65a4c0fb27c0e344c90b/lib/nickel/ztime.rb#L269-L300
train
madeindjs/active_storage-send_zip
lib/active_storage/send_zip.rb
ActiveStorage.SendZip.send_zip
def send_zip(active_storages, filename: 'my.zip') require 'zip' files = SendZipHelper.save_files_on_server active_storages zip_data = SendZipHelper.create_temporary_zip_file files send_data(zip_data, type: 'application/zip', filename: filename) end
ruby
def send_zip(active_storages, filename: 'my.zip') require 'zip' files = SendZipHelper.save_files_on_server active_storages zip_data = SendZipHelper.create_temporary_zip_file files send_data(zip_data, type: 'application/zip', filename: filename) end
[ "def", "send_zip", "(", "active_storages", ",", "filename", ":", "'my.zip'", ")", "require", "'zip'", "files", "=", "SendZipHelper", ".", "save_files_on_server", "active_storages", "zip_data", "=", "SendZipHelper", ".", "create_temporary_zip_file", "files", "send_data", "(", "zip_data", ",", "type", ":", "'application/zip'", ",", "filename", ":", "filename", ")", "end" ]
Zip all given files into a zip and send it with `send_data` @param active_storages [ActiveStorage::Attached::Many] files to save @param filename [ActiveStorage::Attached::Many] files to save
[ "Zip", "all", "given", "files", "into", "a", "zip", "and", "send", "it", "with", "send_data" ]
65921be2a3273aa0a2f84d5aa7780c2086ae05b9
https://github.com/madeindjs/active_storage-send_zip/blob/65921be2a3273aa0a2f84d5aa7780c2086ae05b9/lib/active_storage/send_zip.rb#L17-L23
train
jdennes/contribution-checker
lib/contribution-checker/checker.rb
ContributionChecker.Checker.check
def check @nwo, @sha = parse_commit_url @commit_url begin @commit = @client.commit @nwo, @sha rescue ArgumentError raise ContributionChecker::InvalidCommitUrlError rescue Octokit::NotFound raise ContributionChecker::InvalidCommitUrlError rescue Octokit::Unauthorized raise ContributionChecker::InvalidAccessTokenError end @repo = @client.repository @nwo @user = @client.user @commit_email_is_not_generic = commit_email_is_not_generic? @commit_in_valid_branch = commit_in_valid_branch? @repo_not_a_fork = !repository_is_fork? @commit_email_linked_to_user = commit_email_linked_to_user? @user_has_starred_repo = user_has_starred_repo? @user_can_push_to_repo = user_can_push_to_repo? @user_is_repo_org_member = user_is_repo_org_member? @user_has_fork_of_repo = user_has_fork_of_repo? @user_has_opened_issue_or_pr_in_repo = user_has_opened_issue_or_pr_in_repo? { :contribution => and_criteria_met? && or_criteria_met?, :and_criteria => { :commit_email_is_not_generic => @commit_email_is_not_generic, :commit_in_valid_branch => @commit_in_valid_branch, :repo_not_a_fork => @repo_not_a_fork, :commit_email_linked_to_user => @commit_email_linked_to_user, :commit_email => @commit[:commit][:author][:email], :default_branch => @repo[:default_branch], }, :or_criteria => { :user_has_starred_repo => @user_has_starred_repo, :user_can_push_to_repo => @user_can_push_to_repo, :user_is_repo_org_member => @user_is_repo_org_member, :user_has_fork_of_repo => @user_has_fork_of_repo, :user_has_opened_issue_or_pr_in_repo => @user_has_opened_issue_or_pr_in_repo, } } end
ruby
def check @nwo, @sha = parse_commit_url @commit_url begin @commit = @client.commit @nwo, @sha rescue ArgumentError raise ContributionChecker::InvalidCommitUrlError rescue Octokit::NotFound raise ContributionChecker::InvalidCommitUrlError rescue Octokit::Unauthorized raise ContributionChecker::InvalidAccessTokenError end @repo = @client.repository @nwo @user = @client.user @commit_email_is_not_generic = commit_email_is_not_generic? @commit_in_valid_branch = commit_in_valid_branch? @repo_not_a_fork = !repository_is_fork? @commit_email_linked_to_user = commit_email_linked_to_user? @user_has_starred_repo = user_has_starred_repo? @user_can_push_to_repo = user_can_push_to_repo? @user_is_repo_org_member = user_is_repo_org_member? @user_has_fork_of_repo = user_has_fork_of_repo? @user_has_opened_issue_or_pr_in_repo = user_has_opened_issue_or_pr_in_repo? { :contribution => and_criteria_met? && or_criteria_met?, :and_criteria => { :commit_email_is_not_generic => @commit_email_is_not_generic, :commit_in_valid_branch => @commit_in_valid_branch, :repo_not_a_fork => @repo_not_a_fork, :commit_email_linked_to_user => @commit_email_linked_to_user, :commit_email => @commit[:commit][:author][:email], :default_branch => @repo[:default_branch], }, :or_criteria => { :user_has_starred_repo => @user_has_starred_repo, :user_can_push_to_repo => @user_can_push_to_repo, :user_is_repo_org_member => @user_is_repo_org_member, :user_has_fork_of_repo => @user_has_fork_of_repo, :user_has_opened_issue_or_pr_in_repo => @user_has_opened_issue_or_pr_in_repo, } } end
[ "def", "check", "@nwo", ",", "@sha", "=", "parse_commit_url", "@commit_url", "begin", "@commit", "=", "@client", ".", "commit", "@nwo", ",", "@sha", "rescue", "ArgumentError", "raise", "ContributionChecker", "::", "InvalidCommitUrlError", "rescue", "Octokit", "::", "NotFound", "raise", "ContributionChecker", "::", "InvalidCommitUrlError", "rescue", "Octokit", "::", "Unauthorized", "raise", "ContributionChecker", "::", "InvalidAccessTokenError", "end", "@repo", "=", "@client", ".", "repository", "@nwo", "@user", "=", "@client", ".", "user", "@commit_email_is_not_generic", "=", "commit_email_is_not_generic?", "@commit_in_valid_branch", "=", "commit_in_valid_branch?", "@repo_not_a_fork", "=", "!", "repository_is_fork?", "@commit_email_linked_to_user", "=", "commit_email_linked_to_user?", "@user_has_starred_repo", "=", "user_has_starred_repo?", "@user_can_push_to_repo", "=", "user_can_push_to_repo?", "@user_is_repo_org_member", "=", "user_is_repo_org_member?", "@user_has_fork_of_repo", "=", "user_has_fork_of_repo?", "@user_has_opened_issue_or_pr_in_repo", "=", "user_has_opened_issue_or_pr_in_repo?", "{", ":contribution", "=>", "and_criteria_met?", "&&", "or_criteria_met?", ",", ":and_criteria", "=>", "{", ":commit_email_is_not_generic", "=>", "@commit_email_is_not_generic", ",", ":commit_in_valid_branch", "=>", "@commit_in_valid_branch", ",", ":repo_not_a_fork", "=>", "@repo_not_a_fork", ",", ":commit_email_linked_to_user", "=>", "@commit_email_linked_to_user", ",", ":commit_email", "=>", "@commit", "[", ":commit", "]", "[", ":author", "]", "[", ":email", "]", ",", ":default_branch", "=>", "@repo", "[", ":default_branch", "]", ",", "}", ",", ":or_criteria", "=>", "{", ":user_has_starred_repo", "=>", "@user_has_starred_repo", ",", ":user_can_push_to_repo", "=>", "@user_can_push_to_repo", ",", ":user_is_repo_org_member", "=>", "@user_is_repo_org_member", ",", ":user_has_fork_of_repo", "=>", "@user_has_fork_of_repo", ",", ":user_has_opened_issue_or_pr_in_repo", "=>", "@user_has_opened_issue_or_pr_in_repo", ",", "}", "}", "end" ]
Initialise a new Checker instance with an API access token and commit URL. @param options [Hash] Options which should take the form: { :access_token => "<Your 40 char GitHub API token>", :commit_url => "https://github.com/user/repo/commit/sha" } @return [ContributionChecker::Checker] Contribution checker initialised for an authenticated user and a specific commit Checks whether the commit is counted as a contribution for the authenticated user. @return [Hash] The return value takes the following form: { :contribution => true, :and_criteria => { :commit_email_is_not_generic => true, :commit_in_valid_branch => true, :repo_not_a_fork => true, :commit_email_linked_to_user => true, :commit_email => "[email protected]", :default_branch => "master" }, :or_criteria => { :user_has_starred_repo => false, :user_can_push_to_repo => false, :user_is_repo_org_member => true, :user_has_fork_of_repo => false, :user_has_opened_issue_or_pr_in_repo => false } }
[ "Initialise", "a", "new", "Checker", "instance", "with", "an", "API", "access", "token", "and", "commit", "URL", "." ]
1370314972a404642321b19cc1c5e0d99d54dfc6
https://github.com/jdennes/contribution-checker/blob/1370314972a404642321b19cc1c5e0d99d54dfc6/lib/contribution-checker/checker.rb#L51-L93
train
jdennes/contribution-checker
lib/contribution-checker/checker.rb
ContributionChecker.Checker.parse_commit_url
def parse_commit_url(url) begin parts = URI.parse(@commit_url).path.split("/") nwo = "#{parts[1]}/#{parts[2]}" sha = parts[4] return nwo, sha rescue raise ContributionChecker::InvalidCommitUrlError end end
ruby
def parse_commit_url(url) begin parts = URI.parse(@commit_url).path.split("/") nwo = "#{parts[1]}/#{parts[2]}" sha = parts[4] return nwo, sha rescue raise ContributionChecker::InvalidCommitUrlError end end
[ "def", "parse_commit_url", "(", "url", ")", "begin", "parts", "=", "URI", ".", "parse", "(", "@commit_url", ")", ".", "path", ".", "split", "(", "\"/\"", ")", "nwo", "=", "\"#{parts[1]}/#{parts[2]}\"", "sha", "=", "parts", "[", "4", "]", "return", "nwo", ",", "sha", "rescue", "raise", "ContributionChecker", "::", "InvalidCommitUrlError", "end", "end" ]
Parses the commit URL provided. @return [Array] URL parts: nwo, sha
[ "Parses", "the", "commit", "URL", "provided", "." ]
1370314972a404642321b19cc1c5e0d99d54dfc6
https://github.com/jdennes/contribution-checker/blob/1370314972a404642321b19cc1c5e0d99d54dfc6/lib/contribution-checker/checker.rb#L100-L109
train
jdennes/contribution-checker
lib/contribution-checker/checker.rb
ContributionChecker.Checker.user_has_fork_of_repo?
def user_has_fork_of_repo? # The API doesn't provide a simple means of checking whether a user has # forked a repository. # First, if there are no forks for the repository, return false. return false if @repo[:forks_count] == 0 # Then check whether it's worth getting the list of forks if @repo[:forks_count] <= 100 repo_forks = @client.forks @repo[:full_name], :per_page => 100 repo_forks.each do |f| return true if f[:owner][:login] == @user[:login] end end # Then try to directly find a repository with the same name as the # repository in which the commit exists. potential_fork_nwo = "#{@user[:login]}/#{@repo[:name]}" begin potential_fork = @client.repository potential_fork_nwo if potential_fork[:fork] return true if potential_fork[:parent][:full_name] == @repo[:full_name] end rescue Octokit::NotFound # Keep going... end # Otherwise, get the user's forks and check the `parent` field of each # fork to see whether it matches @repo. @client.auto_paginate = true @user_repos = @client.repos @user_forks = @user_repos.select { |r| r[:fork] } @user_forks.each do |f| r = @client.repository f[:full_name] if r[:parent][:full_name] == @repo[:full_name] @client.auto_paginate = false return true end end @client.auto_paginate = false false end
ruby
def user_has_fork_of_repo? # The API doesn't provide a simple means of checking whether a user has # forked a repository. # First, if there are no forks for the repository, return false. return false if @repo[:forks_count] == 0 # Then check whether it's worth getting the list of forks if @repo[:forks_count] <= 100 repo_forks = @client.forks @repo[:full_name], :per_page => 100 repo_forks.each do |f| return true if f[:owner][:login] == @user[:login] end end # Then try to directly find a repository with the same name as the # repository in which the commit exists. potential_fork_nwo = "#{@user[:login]}/#{@repo[:name]}" begin potential_fork = @client.repository potential_fork_nwo if potential_fork[:fork] return true if potential_fork[:parent][:full_name] == @repo[:full_name] end rescue Octokit::NotFound # Keep going... end # Otherwise, get the user's forks and check the `parent` field of each # fork to see whether it matches @repo. @client.auto_paginate = true @user_repos = @client.repos @user_forks = @user_repos.select { |r| r[:fork] } @user_forks.each do |f| r = @client.repository f[:full_name] if r[:parent][:full_name] == @repo[:full_name] @client.auto_paginate = false return true end end @client.auto_paginate = false false end
[ "def", "user_has_fork_of_repo?", "return", "false", "if", "@repo", "[", ":forks_count", "]", "==", "0", "if", "@repo", "[", ":forks_count", "]", "<=", "100", "repo_forks", "=", "@client", ".", "forks", "@repo", "[", ":full_name", "]", ",", ":per_page", "=>", "100", "repo_forks", ".", "each", "do", "|", "f", "|", "return", "true", "if", "f", "[", ":owner", "]", "[", ":login", "]", "==", "@user", "[", ":login", "]", "end", "end", "potential_fork_nwo", "=", "\"#{@user[:login]}/#{@repo[:name]}\"", "begin", "potential_fork", "=", "@client", ".", "repository", "potential_fork_nwo", "if", "potential_fork", "[", ":fork", "]", "return", "true", "if", "potential_fork", "[", ":parent", "]", "[", ":full_name", "]", "==", "@repo", "[", ":full_name", "]", "end", "rescue", "Octokit", "::", "NotFound", "end", "@client", ".", "auto_paginate", "=", "true", "@user_repos", "=", "@client", ".", "repos", "@user_forks", "=", "@user_repos", ".", "select", "{", "|", "r", "|", "r", "[", ":fork", "]", "}", "@user_forks", ".", "each", "do", "|", "f", "|", "r", "=", "@client", ".", "repository", "f", "[", ":full_name", "]", "if", "r", "[", ":parent", "]", "[", ":full_name", "]", "==", "@repo", "[", ":full_name", "]", "@client", ".", "auto_paginate", "=", "false", "return", "true", "end", "end", "@client", ".", "auto_paginate", "=", "false", "false", "end" ]
Checks whether the authenticated user has forked the repository in which the commit exists. @return [Boolean]
[ "Checks", "whether", "the", "authenticated", "user", "has", "forked", "the", "repository", "in", "which", "the", "commit", "exists", "." ]
1370314972a404642321b19cc1c5e0d99d54dfc6
https://github.com/jdennes/contribution-checker/blob/1370314972a404642321b19cc1c5e0d99d54dfc6/lib/contribution-checker/checker.rb#L202-L243
train
kreynolds/phidgets-ffi
lib/phidgets-ffi/encoder.rb
Phidgets.Encoder.on_input_change
def on_input_change(obj=nil, &block) @on_input_change_obj = obj @on_input_change = Proc.new { |device, obj_ptr, index, state| yield self, @inputs[index], (state == 0 ? false : true), object_for(obj_ptr) } Klass.set_OnInputChange_Handler(@handle, @on_input_change, pointer_for(obj)) end
ruby
def on_input_change(obj=nil, &block) @on_input_change_obj = obj @on_input_change = Proc.new { |device, obj_ptr, index, state| yield self, @inputs[index], (state == 0 ? false : true), object_for(obj_ptr) } Klass.set_OnInputChange_Handler(@handle, @on_input_change, pointer_for(obj)) end
[ "def", "on_input_change", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_input_change_obj", "=", "obj", "@on_input_change", "=", "Proc", ".", "new", "{", "|", "device", ",", "obj_ptr", ",", "index", ",", "state", "|", "yield", "self", ",", "@inputs", "[", "index", "]", ",", "(", "state", "==", "0", "?", "false", ":", "true", ")", ",", "object_for", "(", "obj_ptr", ")", "}", "Klass", ".", "set_OnInputChange_Handler", "(", "@handle", ",", "@on_input_change", ",", "pointer_for", "(", "obj", ")", ")", "end" ]
Sets an input change handler callback function. This is called when a digital input on the PhidgetEncoder board has changed. @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example en.on_input_change do |device, input, state, obj| print "Digital Input #{input.index}, changed to #{state}\n" end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "an", "input", "change", "handler", "callback", "function", ".", "This", "is", "called", "when", "a", "digital", "input", "on", "the", "PhidgetEncoder", "board", "has", "changed", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/encoder.rb#L37-L43
train
elektronaut/dynamic_image
lib/dynamic_image/image_sizing.rb
DynamicImage.ImageSizing.crop_geometry
def crop_geometry(ratio_vector) # Maximize the crop area to fit the image size crop_size = ratio_vector.fit(size).round # Ignore pixels outside the pre-cropped area for now center = crop_gravity - crop_start start = center - (crop_size / 2).floor start = clamp(start, crop_size, size) [crop_size, (start + crop_start)] end
ruby
def crop_geometry(ratio_vector) # Maximize the crop area to fit the image size crop_size = ratio_vector.fit(size).round # Ignore pixels outside the pre-cropped area for now center = crop_gravity - crop_start start = center - (crop_size / 2).floor start = clamp(start, crop_size, size) [crop_size, (start + crop_start)] end
[ "def", "crop_geometry", "(", "ratio_vector", ")", "crop_size", "=", "ratio_vector", ".", "fit", "(", "size", ")", ".", "round", "center", "=", "crop_gravity", "-", "crop_start", "start", "=", "center", "-", "(", "crop_size", "/", "2", ")", ".", "floor", "start", "=", "clamp", "(", "start", ",", "crop_size", ",", "size", ")", "[", "crop_size", ",", "(", "start", "+", "crop_start", ")", "]", "end" ]
Calculates crop geometry. The given vector is scaled to match the image size, since DynamicImage performs cropping before resizing. ==== Example image = Image.find(params[:id]) # 320x200 image sizing = DynamicImage::ImageSizing.new(image) sizing.crop_geometry(Vector2d(100, 100)) # => [Vector2d(200, 200), Vector2d(60, 0)] Returns a tuple with crop size and crop start vectors.
[ "Calculates", "crop", "geometry", ".", "The", "given", "vector", "is", "scaled", "to", "match", "the", "image", "size", "since", "DynamicImage", "performs", "cropping", "before", "resizing", "." ]
d711f8f5d8385fb36d7ff9a6012f3fd123005c18
https://github.com/elektronaut/dynamic_image/blob/d711f8f5d8385fb36d7ff9a6012f3fd123005c18/lib/dynamic_image/image_sizing.rb#L26-L37
train
elektronaut/dynamic_image
lib/dynamic_image/image_sizing.rb
DynamicImage.ImageSizing.fit
def fit(fit_size, options = {}) fit_size = parse_vector(fit_size) require_dimensions!(fit_size) if options[:crop] fit_size = size.fit(fit_size) unless options[:crop] fit_size = size.contain(fit_size) unless options[:upscale] fit_size end
ruby
def fit(fit_size, options = {}) fit_size = parse_vector(fit_size) require_dimensions!(fit_size) if options[:crop] fit_size = size.fit(fit_size) unless options[:crop] fit_size = size.contain(fit_size) unless options[:upscale] fit_size end
[ "def", "fit", "(", "fit_size", ",", "options", "=", "{", "}", ")", "fit_size", "=", "parse_vector", "(", "fit_size", ")", "require_dimensions!", "(", "fit_size", ")", "if", "options", "[", ":crop", "]", "fit_size", "=", "size", ".", "fit", "(", "fit_size", ")", "unless", "options", "[", ":crop", "]", "fit_size", "=", "size", ".", "contain", "(", "fit_size", ")", "unless", "options", "[", ":upscale", "]", "fit_size", "end" ]
Adjusts +fit_size+ to fit the image dimensions. Any dimension set to zero will be ignored. ==== Options * <tt>:crop</tt> - Don't keep aspect ratio. This will allow the image to be cropped to the requested size. * <tt>:upscale</tt> - Don't limit to the size of the image. Images smaller than the given size will be scaled up. ==== Examples image = Image.find(params[:id]) # 320x200 image sizing = DynamicImage::ImageSizing.new(image) sizing.fit(Vector2d(0, 100)) # => Vector2d(160.0, 100.0) sizing.fit(Vector2d(500, 500)) # => Vector2d(320.0, 200.0) sizing.fit(Vector2d(500, 500), crop: true) # => Vector2d(200.0, 200.0) sizing.fit(Vector2d(500, 500), upscale: true) # => Vector2d(500.0, 312.5)
[ "Adjusts", "+", "fit_size", "+", "to", "fit", "the", "image", "dimensions", ".", "Any", "dimension", "set", "to", "zero", "will", "be", "ignored", "." ]
d711f8f5d8385fb36d7ff9a6012f3fd123005c18
https://github.com/elektronaut/dynamic_image/blob/d711f8f5d8385fb36d7ff9a6012f3fd123005c18/lib/dynamic_image/image_sizing.rb#L79-L85
train
elektronaut/dynamic_image
lib/dynamic_image/image_sizing.rb
DynamicImage.ImageSizing.clamp
def clamp(start, size, max_size) start += shift_vector(start) start -= shift_vector(max_size - (start + size)) start end
ruby
def clamp(start, size, max_size) start += shift_vector(start) start -= shift_vector(max_size - (start + size)) start end
[ "def", "clamp", "(", "start", ",", "size", ",", "max_size", ")", "start", "+=", "shift_vector", "(", "start", ")", "start", "-=", "shift_vector", "(", "max_size", "-", "(", "start", "+", "size", ")", ")", "start", "end" ]
Clamps the rectangle defined by +start+ and +size+ to fit inside 0, 0 and +max_size+. It is assumed that +size+ will always be smaller than +max_size+. Returns the start vector.
[ "Clamps", "the", "rectangle", "defined", "by", "+", "start", "+", "and", "+", "size", "+", "to", "fit", "inside", "0", "0", "and", "+", "max_size", "+", ".", "It", "is", "assumed", "that", "+", "size", "+", "will", "always", "be", "smaller", "than", "+", "max_size", "+", "." ]
d711f8f5d8385fb36d7ff9a6012f3fd123005c18
https://github.com/elektronaut/dynamic_image/blob/d711f8f5d8385fb36d7ff9a6012f3fd123005c18/lib/dynamic_image/image_sizing.rb#L118-L122
train
kreynolds/phidgets-ffi
lib/phidgets-ffi/frequency_counter.rb
Phidgets.FrequencyCounter.on_count
def on_count(obj=nil, &block) @on_count_obj = obj @on_count = Proc.new { |device, obj_ptr, index, time, counts| yield self, @inputs[index], time, counts, object_for(obj_ptr) } Klass.set_OnCount_Handler(@handle, @on_count, pointer_for(obj)) end
ruby
def on_count(obj=nil, &block) @on_count_obj = obj @on_count = Proc.new { |device, obj_ptr, index, time, counts| yield self, @inputs[index], time, counts, object_for(obj_ptr) } Klass.set_OnCount_Handler(@handle, @on_count, pointer_for(obj)) end
[ "def", "on_count", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_count_obj", "=", "obj", "@on_count", "=", "Proc", ".", "new", "{", "|", "device", ",", "obj_ptr", ",", "index", ",", "time", ",", "counts", "|", "yield", "self", ",", "@inputs", "[", "index", "]", ",", "time", ",", "counts", ",", "object_for", "(", "obj_ptr", ")", "}", "Klass", ".", "set_OnCount_Handler", "(", "@handle", ",", "@on_count", ",", "pointer_for", "(", "obj", ")", ")", "end" ]
Sets an count handler callback function. This is called when ticks are counted on an frequency counter input, or when the timeout expires @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example fc.on_count do |device, input, time, count, obj| puts "Channel #{input.index}: #{count} pulses in #{time} microseconds" end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "an", "count", "handler", "callback", "function", ".", "This", "is", "called", "when", "ticks", "are", "counted", "on", "an", "frequency", "counter", "input", "or", "when", "the", "timeout", "expires" ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/frequency_counter.rb#L32-L38
train
kreynolds/phidgets-ffi
lib/phidgets-ffi/common.rb
Phidgets.Common.create
def create ptr = ::FFI::MemoryPointer.new(:pointer, 1) self.class::Klass.create(ptr) @handle = ptr.get_pointer(0) true end
ruby
def create ptr = ::FFI::MemoryPointer.new(:pointer, 1) self.class::Klass.create(ptr) @handle = ptr.get_pointer(0) true end
[ "def", "create", "ptr", "=", "::", "FFI", "::", "MemoryPointer", ".", "new", "(", ":pointer", ",", "1", ")", "self", ".", "class", "::", "Klass", ".", "create", "(", "ptr", ")", "@handle", "=", "ptr", ".", "get_pointer", "(", "0", ")", "true", "end" ]
Create a pointer for this Device handle .. must be called before open or anything else. Called automatically when objects are instantiated in block form.
[ "Create", "a", "pointer", "for", "this", "Device", "handle", "..", "must", "be", "called", "before", "open", "or", "anything", "else", ".", "Called", "automatically", "when", "objects", "are", "instantiated", "in", "block", "form", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/common.rb#L185-L190
train
kreynolds/phidgets-ffi
lib/phidgets-ffi/common.rb
Phidgets.Common.close
def close remove_common_event_handlers remove_specific_event_handlers sleep 0.2 Phidgets::FFI::Common.close(@handle) delete true end
ruby
def close remove_common_event_handlers remove_specific_event_handlers sleep 0.2 Phidgets::FFI::Common.close(@handle) delete true end
[ "def", "close", "remove_common_event_handlers", "remove_specific_event_handlers", "sleep", "0.2", "Phidgets", "::", "FFI", "::", "Common", ".", "close", "(", "@handle", ")", "delete", "true", "end" ]
Closes and frees a Phidget. This should be called before closing your application or things may not shut down cleanly. @return [Boolean] returns true or raises an error
[ "Closes", "and", "frees", "a", "Phidget", ".", "This", "should", "be", "called", "before", "closing", "your", "application", "or", "things", "may", "not", "shut", "down", "cleanly", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/common.rb#L253-L260
train
kreynolds/phidgets-ffi
lib/phidgets-ffi/common.rb
Phidgets.Common.on_attach
def on_attach(obj=nil, &block) @on_attach_obj = obj @on_attach = Proc.new { |handle, obj_ptr| load_device_attributes yield self, object_for(obj_ptr) } Phidgets::FFI::Common.set_OnAttach_Handler(@handle, @on_attach, pointer_for(obj)) true end
ruby
def on_attach(obj=nil, &block) @on_attach_obj = obj @on_attach = Proc.new { |handle, obj_ptr| load_device_attributes yield self, object_for(obj_ptr) } Phidgets::FFI::Common.set_OnAttach_Handler(@handle, @on_attach, pointer_for(obj)) true end
[ "def", "on_attach", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_attach_obj", "=", "obj", "@on_attach", "=", "Proc", ".", "new", "{", "|", "handle", ",", "obj_ptr", "|", "load_device_attributes", "yield", "self", ",", "object_for", "(", "obj_ptr", ")", "}", "Phidgets", "::", "FFI", "::", "Common", ".", "set_OnAttach_Handler", "(", "@handle", ",", "@on_attach", ",", "pointer_for", "(", "obj", ")", ")", "true", "end" ]
Sets an attach handler callback function. This is called when the Phidget is plugged into the system, and is ready for use. @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example ifkit.on_attach do |device, obj| puts "InterfaceKit attached #{device.attributes.inspect}" end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "an", "attach", "handler", "callback", "function", ".", "This", "is", "called", "when", "the", "Phidget", "is", "plugged", "into", "the", "system", "and", "is", "ready", "for", "use", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/common.rb#L364-L372
train
kreynolds/phidgets-ffi
lib/phidgets-ffi/common.rb
Phidgets.Common.on_detach
def on_detach(obj=nil, &block) @on_detach_obj = obj @on_detach = Proc.new { |handle, obj_ptr| yield self, object_for(obj_ptr) } Phidgets::FFI::Common.set_OnDetach_Handler(@handle, @on_detach, pointer_for(obj)) true end
ruby
def on_detach(obj=nil, &block) @on_detach_obj = obj @on_detach = Proc.new { |handle, obj_ptr| yield self, object_for(obj_ptr) } Phidgets::FFI::Common.set_OnDetach_Handler(@handle, @on_detach, pointer_for(obj)) true end
[ "def", "on_detach", "(", "obj", "=", "nil", ",", "&", "block", ")", "@on_detach_obj", "=", "obj", "@on_detach", "=", "Proc", ".", "new", "{", "|", "handle", ",", "obj_ptr", "|", "yield", "self", ",", "object_for", "(", "obj_ptr", ")", "}", "Phidgets", "::", "FFI", "::", "Common", ".", "set_OnDetach_Handler", "(", "@handle", ",", "@on_detach", ",", "pointer_for", "(", "obj", ")", ")", "true", "end" ]
Sets a detach handler callback function. This is called when the Phidget is physically detached from the system, and is no longer available. @param [String] obj Object to pass to the callback function. This is optional. @param [Proc] Block When the callback is executed, the device and object are yielded to this block. @example ifkit.on_detach do |device, obj| puts "InterfaceKit detached #{device.attributes.inspect}" end As this runs in it's own thread, be sure that all errors are properly handled or the thread will halt and not fire any more. @return [Boolean] returns true or raises an error
[ "Sets", "a", "detach", "handler", "callback", "function", ".", "This", "is", "called", "when", "the", "Phidget", "is", "physically", "detached", "from", "the", "system", "and", "is", "no", "longer", "available", "." ]
5c22e206804dc47e8ad37173baf952c874845973
https://github.com/kreynolds/phidgets-ffi/blob/5c22e206804dc47e8ad37173baf952c874845973/lib/phidgets-ffi/common.rb#L384-L391
train