repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.[]
def [](*input_indexes) # Get array of positions indexes positions = @index.pos(*input_indexes) # If one object is asked return it return @data[positions] if positions.is_a? Numeric # Form a new Vector using positional indexes Daru::Vector.new( positions.map { |loc| @data[loc] }, name: @name, index: @index.subset(*input_indexes), dtype: @dtype ) end
ruby
def [](*input_indexes) # Get array of positions indexes positions = @index.pos(*input_indexes) # If one object is asked return it return @data[positions] if positions.is_a? Numeric # Form a new Vector using positional indexes Daru::Vector.new( positions.map { |loc| @data[loc] }, name: @name, index: @index.subset(*input_indexes), dtype: @dtype ) end
[ "def", "[]", "(", "*", "input_indexes", ")", "# Get array of positions indexes", "positions", "=", "@index", ".", "pos", "(", "input_indexes", ")", "# If one object is asked return it", "return", "@data", "[", "positions", "]", "if", "positions", ".", "is_a?", "Numeric", "# Form a new Vector using positional indexes", "Daru", "::", "Vector", ".", "new", "(", "positions", ".", "map", "{", "|", "loc", "|", "@data", "[", "loc", "]", "}", ",", "name", ":", "@name", ",", "index", ":", "@index", ".", "subset", "(", "input_indexes", ")", ",", "dtype", ":", "@dtype", ")", "end" ]
Get one or more elements with specified index or a range. == Usage # For vectors employing single layer Index v[:one, :two] # => Daru::Vector with indexes :one and :two v[:one] # => Single element v[:one..:three] # => Daru::Vector with indexes :one, :two and :three # For vectors employing hierarchial multi index
[ "Get", "one", "or", "more", "elements", "with", "specified", "index", "or", "a", "range", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L238-L251
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.at
def at *positions # to be used to form index original_positions = positions positions = coerce_positions(*positions) validate_positions(*positions) if positions.is_a? Integer @data[positions] else values = positions.map { |pos| @data[pos] } Daru::Vector.new values, index: @index.at(*original_positions), dtype: dtype end end
ruby
def at *positions # to be used to form index original_positions = positions positions = coerce_positions(*positions) validate_positions(*positions) if positions.is_a? Integer @data[positions] else values = positions.map { |pos| @data[pos] } Daru::Vector.new values, index: @index.at(*original_positions), dtype: dtype end end
[ "def", "at", "*", "positions", "# to be used to form index", "original_positions", "=", "positions", "positions", "=", "coerce_positions", "(", "positions", ")", "validate_positions", "(", "positions", ")", "if", "positions", ".", "is_a?", "Integer", "@data", "[", "positions", "]", "else", "values", "=", "positions", ".", "map", "{", "|", "pos", "|", "@data", "[", "pos", "]", "}", "Daru", "::", "Vector", ".", "new", "values", ",", "index", ":", "@index", ".", "at", "(", "original_positions", ")", ",", "dtype", ":", "dtype", "end", "end" ]
Returns vector of values given positional values @param positions [Array<object>] positional values @return [object] vector @example dv = Daru::Vector.new 'a'..'e' dv.at 0, 1, 2 # => #<Daru::Vector(3)> # 0 a # 1 b # 2 c
[ "Returns", "vector", "of", "values", "given", "positional", "values" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L263-L275
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.set_at
def set_at positions, val validate_positions(*positions) positions.map { |pos| @data[pos] = val } update_position_cache end
ruby
def set_at positions, val validate_positions(*positions) positions.map { |pos| @data[pos] = val } update_position_cache end
[ "def", "set_at", "positions", ",", "val", "validate_positions", "(", "positions", ")", "positions", ".", "map", "{", "|", "pos", "|", "@data", "[", "pos", "]", "=", "val", "}", "update_position_cache", "end" ]
Change value at given positions @param positions [Array<object>] positional values @param [object] val value to assign @example dv = Daru::Vector.new 'a'..'e' dv.set_at [0, 1], 'x' dv # => #<Daru::Vector(5)> # 0 x # 1 x # 2 c # 3 d # 4 e
[ "Change", "value", "at", "given", "positions" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L290-L294
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.concat
def concat element, index raise IndexError, 'Expected new unique index' if @index.include? index @index |= [index] @data[@index[index]] = element update_position_cache end
ruby
def concat element, index raise IndexError, 'Expected new unique index' if @index.include? index @index |= [index] @data[@index[index]] = element update_position_cache end
[ "def", "concat", "element", ",", "index", "raise", "IndexError", ",", "'Expected new unique index'", "if", "@index", ".", "include?", "index", "@index", "|=", "[", "index", "]", "@data", "[", "@index", "[", "index", "]", "]", "=", "element", "update_position_cache", "end" ]
Append an element to the vector by specifying the element and index
[ "Append", "an", "element", "to", "the", "vector", "by", "specifying", "the", "element", "and", "index" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L509-L516
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.cast
def cast opts={} dt = opts[:dtype] raise ArgumentError, "Unsupported dtype #{opts[:dtype]}" unless %i[array nmatrix gsl].include?(dt) @data = cast_vector_to dt unless @dtype == dt end
ruby
def cast opts={} dt = opts[:dtype] raise ArgumentError, "Unsupported dtype #{opts[:dtype]}" unless %i[array nmatrix gsl].include?(dt) @data = cast_vector_to dt unless @dtype == dt end
[ "def", "cast", "opts", "=", "{", "}", "dt", "=", "opts", "[", ":dtype", "]", "raise", "ArgumentError", ",", "\"Unsupported dtype #{opts[:dtype]}\"", "unless", "%i[", "array", "nmatrix", "gsl", "]", ".", "include?", "(", "dt", ")", "@data", "=", "cast_vector_to", "dt", "unless", "@dtype", "==", "dt", "end" ]
Cast a vector to a new data type. == Options * +:dtype+ - :array for Ruby Array. :nmatrix for NMatrix.
[ "Cast", "a", "vector", "to", "a", "new", "data", "type", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L525-L530
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.delete_at
def delete_at index @data.delete_at @index[index] @index = Daru::Index.new(@index.to_a - [index]) update_position_cache end
ruby
def delete_at index @data.delete_at @index[index] @index = Daru::Index.new(@index.to_a - [index]) update_position_cache end
[ "def", "delete_at", "index", "@data", ".", "delete_at", "@index", "[", "index", "]", "@index", "=", "Daru", "::", "Index", ".", "new", "(", "@index", ".", "to_a", "-", "[", "index", "]", ")", "update_position_cache", "end" ]
Delete element by index
[ "Delete", "element", "by", "index" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L538-L543
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.index_of
def index_of element case dtype when :array then @index.key(@data.index { |x| x.eql? element }) else @index.key @data.index(element) end end
ruby
def index_of element case dtype when :array then @index.key(@data.index { |x| x.eql? element }) else @index.key @data.index(element) end end
[ "def", "index_of", "element", "case", "dtype", "when", ":array", "then", "@index", ".", "key", "(", "@data", ".", "index", "{", "|", "x", "|", "x", ".", "eql?", "element", "}", ")", "else", "@index", ".", "key", "@data", ".", "index", "(", "element", ")", "end", "end" ]
Get index of element
[ "Get", "index", "of", "element" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L578-L583
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.uniq
def uniq uniq_vector = @data.uniq new_index = uniq_vector.map { |element| index_of(element) } Daru::Vector.new uniq_vector, name: @name, index: new_index, dtype: @dtype end
ruby
def uniq uniq_vector = @data.uniq new_index = uniq_vector.map { |element| index_of(element) } Daru::Vector.new uniq_vector, name: @name, index: new_index, dtype: @dtype end
[ "def", "uniq", "uniq_vector", "=", "@data", ".", "uniq", "new_index", "=", "uniq_vector", ".", "map", "{", "|", "element", "|", "index_of", "(", "element", ")", "}", "Daru", "::", "Vector", ".", "new", "uniq_vector", ",", "name", ":", "@name", ",", "index", ":", "new_index", ",", "dtype", ":", "@dtype", "end" ]
Keep only unique elements of the vector alongwith their indexes.
[ "Keep", "only", "unique", "elements", "of", "the", "vector", "alongwith", "their", "indexes", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L586-L591
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.sort_by_index
def sort_by_index opts={} opts = {ascending: true}.merge(opts) _, new_order = resort_index(@index.each_with_index, opts).transpose reorder new_order end
ruby
def sort_by_index opts={} opts = {ascending: true}.merge(opts) _, new_order = resort_index(@index.each_with_index, opts).transpose reorder new_order end
[ "def", "sort_by_index", "opts", "=", "{", "}", "opts", "=", "{", "ascending", ":", "true", "}", ".", "merge", "(", "opts", ")", "_", ",", "new_order", "=", "resort_index", "(", "@index", ".", "each_with_index", ",", "opts", ")", ".", "transpose", "reorder", "new_order", "end" ]
Sorts the vector according to it's`Index` values. Defaults to ascending order sorting. @param [Hash] opts the options for sort_by_index method. @option opts [Boolean] :ascending false, will sort `index` in descending order. @return [Vector] new sorted `Vector` according to the index values. @example dv = Daru::Vector.new [11, 13, 12], index: [23, 21, 22] # Say you want to sort index in ascending order dv.sort_by_index(ascending: true) #=> Daru::Vector.new [13, 12, 11], index: [21, 22, 23] # Say you want to sort index in descending order dv.sort_by_index(ascending: false) #=> Daru::Vector.new [11, 12, 13], index: [23, 22, 21]
[ "Sorts", "the", "vector", "according", "to", "it", "s", "Index", "values", ".", "Defaults", "to", "ascending", "order", "sorting", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L646-L651
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.recode!
def recode! dt=nil, &block return to_enum(:recode!) unless block_given? @data.map!(&block).data @data = cast_vector_to(dt || @dtype) self end
ruby
def recode! dt=nil, &block return to_enum(:recode!) unless block_given? @data.map!(&block).data @data = cast_vector_to(dt || @dtype) self end
[ "def", "recode!", "dt", "=", "nil", ",", "&", "block", "return", "to_enum", "(", ":recode!", ")", "unless", "block_given?", "@data", ".", "map!", "(", "block", ")", ".", "data", "@data", "=", "cast_vector_to", "(", "dt", "||", "@dtype", ")", "self", "end" ]
Destructive version of recode!
[ "Destructive", "version", "of", "recode!" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L682-L688
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.delete_if
def delete_if return to_enum(:delete_if) unless block_given? keep_e, keep_i = each_with_index.reject { |n, _i| yield(n) }.transpose @data = cast_vector_to @dtype, keep_e @index = Daru::Index.new(keep_i) update_position_cache self end
ruby
def delete_if return to_enum(:delete_if) unless block_given? keep_e, keep_i = each_with_index.reject { |n, _i| yield(n) }.transpose @data = cast_vector_to @dtype, keep_e @index = Daru::Index.new(keep_i) update_position_cache self end
[ "def", "delete_if", "return", "to_enum", "(", ":delete_if", ")", "unless", "block_given?", "keep_e", ",", "keep_i", "=", "each_with_index", ".", "reject", "{", "|", "n", ",", "_i", "|", "yield", "(", "n", ")", "}", ".", "transpose", "@data", "=", "cast_vector_to", "@dtype", ",", "keep_e", "@index", "=", "Daru", "::", "Index", ".", "new", "(", "keep_i", ")", "update_position_cache", "self", "end" ]
Delete an element if block returns true. Destructive.
[ "Delete", "an", "element", "if", "block", "returns", "true", ".", "Destructive", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L691-L702
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.verify
def verify (0...size) .map { |i| [i, @data[i]] } .reject { |_i, val| yield(val) } .to_h end
ruby
def verify (0...size) .map { |i| [i, @data[i]] } .reject { |_i, val| yield(val) } .to_h end
[ "def", "verify", "(", "0", "...", "size", ")", ".", "map", "{", "|", "i", "|", "[", "i", ",", "@data", "[", "i", "]", "]", "}", ".", "reject", "{", "|", "_i", ",", "val", "|", "yield", "(", "val", ")", "}", ".", "to_h", "end" ]
Reports all values that doesn't comply with a condition. Returns a hash with the index of data and the invalid data.
[ "Reports", "all", "values", "that", "doesn", "t", "comply", "with", "a", "condition", ".", "Returns", "a", "hash", "with", "the", "index", "of", "data", "and", "the", "invalid", "data", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L713-L718
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.lag
def lag k=1 case k when 0 then dup when 1...size copy([nil] * k + data.to_a) when -size..-1 copy(data.to_a[k.abs...size]) else copy([]) end end
ruby
def lag k=1 case k when 0 then dup when 1...size copy([nil] * k + data.to_a) when -size..-1 copy(data.to_a[k.abs...size]) else copy([]) end end
[ "def", "lag", "k", "=", "1", "case", "k", "when", "0", "then", "dup", "when", "1", "...", "size", "copy", "(", "[", "nil", "]", "*", "k", "+", "data", ".", "to_a", ")", "when", "-", "size", "..", "-", "1", "copy", "(", "data", ".", "to_a", "[", "k", ".", "abs", "...", "size", "]", ")", "else", "copy", "(", "[", "]", ")", "end", "end" ]
Lags the series by `k` periods. Lags the series by `k` periods, "shifting" data and inserting `nil`s from beginning or end of a vector, while preserving original vector's size. `k` can be positive or negative integer. If `k` is positive, `nil`s are inserted at the beginning of the vector, otherwise they are inserted at the end. @param [Integer] k "shift" the series by `k` periods. `k` can be positive or negative. (default = 1) @return [Daru::Vector] a new vector with "shifted" inital values and `nil` values inserted. The return vector is the same length as the orignal vector. @example Lag a vector with different periods `k` ts = Daru::Vector.new(1..5) # => [1, 2, 3, 4, 5] ts.lag # => [nil, 1, 2, 3, 4] ts.lag(1) # => [nil, 1, 2, 3, 4] ts.lag(2) # => [nil, nil, 1, 2, 3] ts.lag(-1) # => [2, 3, 4, 5, nil]
[ "Lags", "the", "series", "by", "k", "periods", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L851-L861
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.to_matrix
def to_matrix axis=:horizontal if axis == :horizontal Matrix[to_a] elsif axis == :vertical Matrix.columns([to_a]) else raise ArgumentError, "axis should be either :horizontal or :vertical, not #{axis}" end end
ruby
def to_matrix axis=:horizontal if axis == :horizontal Matrix[to_a] elsif axis == :vertical Matrix.columns([to_a]) else raise ArgumentError, "axis should be either :horizontal or :vertical, not #{axis}" end end
[ "def", "to_matrix", "axis", "=", ":horizontal", "if", "axis", "==", ":horizontal", "Matrix", "[", "to_a", "]", "elsif", "axis", "==", ":vertical", "Matrix", ".", "columns", "(", "[", "to_a", "]", ")", "else", "raise", "ArgumentError", ",", "\"axis should be either :horizontal or :vertical, not #{axis}\"", "end", "end" ]
Convert Vector to a horizontal or vertical Ruby Matrix. == Arguments * +axis+ - Specify whether you want a *:horizontal* or a *:vertical* matrix.
[ "Convert", "Vector", "to", "a", "horizontal", "or", "vertical", "Ruby", "Matrix", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L920-L928
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.to_nmatrix
def to_nmatrix axis=:horizontal unless numeric? && !include?(nil) raise ArgumentError, 'Can not convert to nmatrix'\ 'because the vector is numeric' end case axis when :horizontal NMatrix.new [1, size], to_a when :vertical NMatrix.new [size, 1], to_a else raise ArgumentError, 'Invalid axis specified. '\ 'Valid axis are :horizontal and :vertical' end end
ruby
def to_nmatrix axis=:horizontal unless numeric? && !include?(nil) raise ArgumentError, 'Can not convert to nmatrix'\ 'because the vector is numeric' end case axis when :horizontal NMatrix.new [1, size], to_a when :vertical NMatrix.new [size, 1], to_a else raise ArgumentError, 'Invalid axis specified. '\ 'Valid axis are :horizontal and :vertical' end end
[ "def", "to_nmatrix", "axis", "=", ":horizontal", "unless", "numeric?", "&&", "!", "include?", "(", "nil", ")", "raise", "ArgumentError", ",", "'Can not convert to nmatrix'", "'because the vector is numeric'", "end", "case", "axis", "when", ":horizontal", "NMatrix", ".", "new", "[", "1", ",", "size", "]", ",", "to_a", "when", ":vertical", "NMatrix", ".", "new", "[", "size", ",", "1", "]", ",", "to_a", "else", "raise", "ArgumentError", ",", "'Invalid axis specified. '", "'Valid axis are :horizontal and :vertical'", "end", "end" ]
Convert vector to nmatrix object @param [Symbol] axis :horizontal or :vertical @return [NMatrix] NMatrix object containing all values of the vector @example dv = Daru::Vector.new [1, 2, 3] dv.to_nmatrix # => # [ # [1, 2, 3] ]
[ "Convert", "vector", "to", "nmatrix", "object" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L939-L954
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.object_summary
def object_summary nval = count_values(*Daru::MISSING_VALUES) summary = "\n factors: #{factors.to_a.join(',')}" \ "\n mode: #{mode.to_a.join(',')}" \ "\n Distribution\n" data = frequencies.sort.each_with_index.map do |v, k| [k, v, '%0.2f%%' % ((nval.zero? ? 1 : v.quo(nval))*100)] end summary + Formatters::Table.format(data) end
ruby
def object_summary nval = count_values(*Daru::MISSING_VALUES) summary = "\n factors: #{factors.to_a.join(',')}" \ "\n mode: #{mode.to_a.join(',')}" \ "\n Distribution\n" data = frequencies.sort.each_with_index.map do |v, k| [k, v, '%0.2f%%' % ((nval.zero? ? 1 : v.quo(nval))*100)] end summary + Formatters::Table.format(data) end
[ "def", "object_summary", "nval", "=", "count_values", "(", "Daru", "::", "MISSING_VALUES", ")", "summary", "=", "\"\\n factors: #{factors.to_a.join(',')}\"", "\"\\n mode: #{mode.to_a.join(',')}\"", "\"\\n Distribution\\n\"", "data", "=", "frequencies", ".", "sort", ".", "each_with_index", ".", "map", "do", "|", "v", ",", "k", "|", "[", "k", ",", "v", ",", "'%0.2f%%'", "%", "(", "(", "nval", ".", "zero?", "?", "1", ":", "v", ".", "quo", "(", "nval", ")", ")", "*", "100", ")", "]", "end", "summary", "+", "Formatters", "::", "Table", ".", "format", "(", "data", ")", "end" ]
Displays summary for an object type Vector @return [String] String containing object vector summary
[ "Displays", "summary", "for", "an", "object", "type", "Vector" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1050-L1061
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.numeric_summary
def numeric_summary summary = "\n median: #{median}" + "\n mean: %0.4f" % mean if sd summary << "\n std.dev.: %0.4f" % sd + "\n std.err.: %0.4f" % se end if count_values(*Daru::MISSING_VALUES).zero? summary << "\n skew: %0.4f" % skew + "\n kurtosis: %0.4f" % kurtosis end summary end
ruby
def numeric_summary summary = "\n median: #{median}" + "\n mean: %0.4f" % mean if sd summary << "\n std.dev.: %0.4f" % sd + "\n std.err.: %0.4f" % se end if count_values(*Daru::MISSING_VALUES).zero? summary << "\n skew: %0.4f" % skew + "\n kurtosis: %0.4f" % kurtosis end summary end
[ "def", "numeric_summary", "summary", "=", "\"\\n median: #{median}\"", "+", "\"\\n mean: %0.4f\"", "%", "mean", "if", "sd", "summary", "<<", "\"\\n std.dev.: %0.4f\"", "%", "sd", "+", "\"\\n std.err.: %0.4f\"", "%", "se", "end", "if", "count_values", "(", "Daru", "::", "MISSING_VALUES", ")", ".", "zero?", "summary", "<<", "\"\\n skew: %0.4f\"", "%", "skew", "+", "\"\\n kurtosis: %0.4f\"", "%", "kurtosis", "end", "summary", "end" ]
Displays summary for an numeric type Vector @return [String] String containing numeric vector summary
[ "Displays", "summary", "for", "an", "numeric", "type", "Vector" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1065-L1078
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.inspect
def inspect spacing=20, threshold=15 row_headers = index.is_a?(MultiIndex) ? index.sparse_tuples : index.to_a "#<#{self.class}(#{size})#{':category' if category?}>\n" + Formatters::Table.format( to_a.lazy.map { |v| [v] }, headers: @name && [@name], row_headers: row_headers, threshold: threshold, spacing: spacing ) end
ruby
def inspect spacing=20, threshold=15 row_headers = index.is_a?(MultiIndex) ? index.sparse_tuples : index.to_a "#<#{self.class}(#{size})#{':category' if category?}>\n" + Formatters::Table.format( to_a.lazy.map { |v| [v] }, headers: @name && [@name], row_headers: row_headers, threshold: threshold, spacing: spacing ) end
[ "def", "inspect", "spacing", "=", "20", ",", "threshold", "=", "15", "row_headers", "=", "index", ".", "is_a?", "(", "MultiIndex", ")", "?", "index", ".", "sparse_tuples", ":", "index", ".", "to_a", "\"#<#{self.class}(#{size})#{':category' if category?}>\\n\"", "+", "Formatters", "::", "Table", ".", "format", "(", "to_a", ".", "lazy", ".", "map", "{", "|", "v", "|", "[", "v", "]", "}", ",", "headers", ":", "@name", "&&", "[", "@name", "]", ",", "row_headers", ":", "row_headers", ",", "threshold", ":", "threshold", ",", "spacing", ":", "spacing", ")", "end" ]
Over rides original inspect for pretty printing in irb
[ "Over", "rides", "original", "inspect", "for", "pretty", "printing", "in", "irb" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1081-L1092
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.reindex!
def reindex! new_index values = [] each_with_index do |val, i| values[new_index[i]] = val if new_index.include?(i) end values.fill(nil, values.size, new_index.size - values.size) @data = cast_vector_to @dtype, values @index = new_index update_position_cache self end
ruby
def reindex! new_index values = [] each_with_index do |val, i| values[new_index[i]] = val if new_index.include?(i) end values.fill(nil, values.size, new_index.size - values.size) @data = cast_vector_to @dtype, values @index = new_index update_position_cache self end
[ "def", "reindex!", "new_index", "values", "=", "[", "]", "each_with_index", "do", "|", "val", ",", "i", "|", "values", "[", "new_index", "[", "i", "]", "]", "=", "val", "if", "new_index", ".", "include?", "(", "i", ")", "end", "values", ".", "fill", "(", "nil", ",", "values", ".", "size", ",", "new_index", ".", "size", "-", "values", ".", "size", ")", "@data", "=", "cast_vector_to", "@dtype", ",", "values", "@index", "=", "new_index", "update_position_cache", "self", "end" ]
Sets new index for vector. Preserves index->value correspondence. Sets nil for new index keys absent from original index. @note Unlike #reorder! which takes positions as input it takes index as an input to reorder the vector @param [Daru::Index, Daru::MultiIndex] new_index new index to order with @return [Daru::Vector] vector reindexed with new index
[ "Sets", "new", "index", "for", "vector", ".", "Preserves", "index", "-", ">", "value", "correspondence", ".", "Sets", "nil", "for", "new", "index", "keys", "absent", "from", "original", "index", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1100-L1113
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.only_valid
def only_valid as_a=:vector, _duplicate=true # FIXME: Now duplicate is just ignored. # There are no spec that fail on this case, so I'll leave it # this way for now - zverok, 2016-05-07 new_index = @index.to_a - indexes(*Daru::MISSING_VALUES) new_vector = new_index.map { |idx| self[idx] } if as_a == :vector Daru::Vector.new new_vector, index: new_index, name: @name, dtype: dtype else new_vector end end
ruby
def only_valid as_a=:vector, _duplicate=true # FIXME: Now duplicate is just ignored. # There are no spec that fail on this case, so I'll leave it # this way for now - zverok, 2016-05-07 new_index = @index.to_a - indexes(*Daru::MISSING_VALUES) new_vector = new_index.map { |idx| self[idx] } if as_a == :vector Daru::Vector.new new_vector, index: new_index, name: @name, dtype: dtype else new_vector end end
[ "def", "only_valid", "as_a", "=", ":vector", ",", "_duplicate", "=", "true", "# FIXME: Now duplicate is just ignored.", "# There are no spec that fail on this case, so I'll leave it", "# this way for now - zverok, 2016-05-07", "new_index", "=", "@index", ".", "to_a", "-", "indexes", "(", "Daru", "::", "MISSING_VALUES", ")", "new_vector", "=", "new_index", ".", "map", "{", "|", "idx", "|", "self", "[", "idx", "]", "}", "if", "as_a", "==", ":vector", "Daru", "::", "Vector", ".", "new", "new_vector", ",", "index", ":", "new_index", ",", "name", ":", "@name", ",", "dtype", ":", "dtype", "else", "new_vector", "end", "end" ]
Creates a new vector consisting only of non-nil data == Arguments @param as_a [Symbol] Passing :array will return only the elements as an Array. Otherwise will return a Daru::Vector. @param _duplicate [Symbol] In case no missing data is found in the vector, setting this to false will return the same vector. Otherwise, a duplicate will be returned irrespective of presence of missing data.
[ "Creates", "a", "new", "vector", "consisting", "only", "of", "non", "-", "nil", "data" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1267-L1280
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.only_numerics
def only_numerics numeric_indexes = each_with_index .select { |v, _i| v.is_a?(Numeric) || v.nil? } .map(&:last) self[*numeric_indexes] end
ruby
def only_numerics numeric_indexes = each_with_index .select { |v, _i| v.is_a?(Numeric) || v.nil? } .map(&:last) self[*numeric_indexes] end
[ "def", "only_numerics", "numeric_indexes", "=", "each_with_index", ".", "select", "{", "|", "v", ",", "_i", "|", "v", ".", "is_a?", "(", "Numeric", ")", "||", "v", ".", "nil?", "}", ".", "map", "(", ":last", ")", "self", "[", "numeric_indexes", "]", "end" ]
Returns a Vector with only numerical data. Missing data is included but non-Numeric objects are excluded. Preserves index.
[ "Returns", "a", "Vector", "with", "only", "numerical", "data", ".", "Missing", "data", "is", "included", "but", "non", "-", "Numeric", "objects", "are", "excluded", ".", "Preserves", "index", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1353-L1360
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.db_type
def db_type # first, detect any character not number case when @data.any? { |v| v.to_s =~ DATE_REGEXP } 'DATE' when @data.any? { |v| v.to_s =~ /[^0-9e.-]/ } 'VARCHAR (255)' when @data.any? { |v| v.to_s =~ /\./ } 'DOUBLE' else 'INTEGER' end end
ruby
def db_type # first, detect any character not number case when @data.any? { |v| v.to_s =~ DATE_REGEXP } 'DATE' when @data.any? { |v| v.to_s =~ /[^0-9e.-]/ } 'VARCHAR (255)' when @data.any? { |v| v.to_s =~ /\./ } 'DOUBLE' else 'INTEGER' end end
[ "def", "db_type", "# first, detect any character not number", "case", "when", "@data", ".", "any?", "{", "|", "v", "|", "v", ".", "to_s", "=~", "DATE_REGEXP", "}", "'DATE'", "when", "@data", ".", "any?", "{", "|", "v", "|", "v", ".", "to_s", "=~", "/", "/", "}", "'VARCHAR (255)'", "when", "@data", ".", "any?", "{", "|", "v", "|", "v", ".", "to_s", "=~", "/", "\\.", "/", "}", "'DOUBLE'", "else", "'INTEGER'", "end", "end" ]
Returns the database type for the vector, according to its content
[ "Returns", "the", "database", "type", "for", "the", "vector", "according", "to", "its", "content" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1365-L1377
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.to_category
def to_category opts={} dv = Daru::Vector.new to_a, type: :category, name: @name, index: @index dv.ordered = opts[:ordered] || false dv.categories = opts[:categories] if opts[:categories] dv end
ruby
def to_category opts={} dv = Daru::Vector.new to_a, type: :category, name: @name, index: @index dv.ordered = opts[:ordered] || false dv.categories = opts[:categories] if opts[:categories] dv end
[ "def", "to_category", "opts", "=", "{", "}", "dv", "=", "Daru", "::", "Vector", ".", "new", "to_a", ",", "type", ":", ":category", ",", "name", ":", "@name", ",", "index", ":", "@index", "dv", ".", "ordered", "=", "opts", "[", ":ordered", "]", "||", "false", "dv", ".", "categories", "=", "opts", "[", ":categories", "]", "if", "opts", "[", ":categories", "]", "dv", "end" ]
Converts a non category type vector to category type vector. @param [Hash] opts options to convert to category @option opts [true, false] :ordered Specify if vector is ordered or not. If it is ordered, it can be sorted and min, max like functions would work @option opts [Array] :categories set categories in the specified order @return [Daru::Vector] vector with type category
[ "Converts", "a", "non", "category", "type", "vector", "to", "category", "type", "vector", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1417-L1422
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.cut
def cut partitions, opts={} close_at, labels = opts[:close_at] || :right, opts[:labels] partitions = partitions.to_a values = to_a.map { |val| cut_find_category partitions, val, close_at } cats = cut_categories(partitions, close_at) dv = Daru::Vector.new values, index: @index, type: :category, categories: cats # Rename categories if new labels provided if labels dv.rename_categories Hash[cats.zip(labels)] else dv end end
ruby
def cut partitions, opts={} close_at, labels = opts[:close_at] || :right, opts[:labels] partitions = partitions.to_a values = to_a.map { |val| cut_find_category partitions, val, close_at } cats = cut_categories(partitions, close_at) dv = Daru::Vector.new values, index: @index, type: :category, categories: cats # Rename categories if new labels provided if labels dv.rename_categories Hash[cats.zip(labels)] else dv end end
[ "def", "cut", "partitions", ",", "opts", "=", "{", "}", "close_at", ",", "labels", "=", "opts", "[", ":close_at", "]", "||", ":right", ",", "opts", "[", ":labels", "]", "partitions", "=", "partitions", ".", "to_a", "values", "=", "to_a", ".", "map", "{", "|", "val", "|", "cut_find_category", "partitions", ",", "val", ",", "close_at", "}", "cats", "=", "cut_categories", "(", "partitions", ",", "close_at", ")", "dv", "=", "Daru", "::", "Vector", ".", "new", "values", ",", "index", ":", "@index", ",", "type", ":", ":category", ",", "categories", ":", "cats", "# Rename categories if new labels provided", "if", "labels", "dv", ".", "rename_categories", "Hash", "[", "cats", ".", "zip", "(", "labels", ")", "]", "else", "dv", "end", "end" ]
Partition a numeric variable into categories. @param [Array<Numeric>] partitions an array whose consecutive elements provide intervals for categories @param [Hash] opts options to cut the partition @option opts [:left, :right] :close_at specifies whether the interval closes at the right side of left side @option opts [Array] :labels names of the categories @return [Daru::Vector] numeric variable converted to categorical variable @example heights = Daru::Vector.new [30, 35, 32, 50, 42, 51] height_cat = heights.cut [30, 40, 50, 60], labels=['low', 'medium', 'high'] # => #<Daru::Vector(6)> # 0 low # 1 low # 2 low # 3 high # 4 medium # 5 high
[ "Partition", "a", "numeric", "variable", "into", "categories", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1458-L1475
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.valid_value?
def valid_value?(v) v.respond_to?(:nan?) && v.nan? || v.nil? ? false : true end
ruby
def valid_value?(v) v.respond_to?(:nan?) && v.nan? || v.nil? ? false : true end
[ "def", "valid_value?", "(", "v", ")", "v", ".", "respond_to?", "(", ":nan?", ")", "&&", "v", ".", "nan?", "||", "v", ".", "nil?", "?", "false", ":", "true", "end" ]
Helper method returning validity of arbitrary value
[ "Helper", "method", "returning", "validity", "of", "arbitrary", "value" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1520-L1522
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.prepare_bootstrap
def prepare_bootstrap(estimators) h_est = estimators h_est = [h_est] unless h_est.is_a?(Array) || h_est.is_a?(Hash) if h_est.is_a? Array h_est = h_est.map do |est| [est, ->(v) { Daru::Vector.new(v).send(est) }] end.to_h end bss = h_est.keys.map { |v| [v, []] }.to_h [h_est, h_est.keys, bss] end
ruby
def prepare_bootstrap(estimators) h_est = estimators h_est = [h_est] unless h_est.is_a?(Array) || h_est.is_a?(Hash) if h_est.is_a? Array h_est = h_est.map do |est| [est, ->(v) { Daru::Vector.new(v).send(est) }] end.to_h end bss = h_est.keys.map { |v| [v, []] }.to_h [h_est, h_est.keys, bss] end
[ "def", "prepare_bootstrap", "(", "estimators", ")", "h_est", "=", "estimators", "h_est", "=", "[", "h_est", "]", "unless", "h_est", ".", "is_a?", "(", "Array", ")", "||", "h_est", ".", "is_a?", "(", "Hash", ")", "if", "h_est", ".", "is_a?", "Array", "h_est", "=", "h_est", ".", "map", "do", "|", "est", "|", "[", "est", ",", "->", "(", "v", ")", "{", "Daru", "::", "Vector", ".", "new", "(", "v", ")", ".", "send", "(", "est", ")", "}", "]", "end", ".", "to_h", "end", "bss", "=", "h_est", ".", "keys", ".", "map", "{", "|", "v", "|", "[", "v", ",", "[", "]", "]", "}", ".", "to_h", "[", "h_est", ",", "h_est", ".", "keys", ",", "bss", "]", "end" ]
For an array or hash of estimators methods, returns an array with three elements 1.- A hash with estimators names as keys and lambdas as values 2.- An array with estimators names 3.- A Hash with estimators names as keys and empty arrays as values
[ "For", "an", "array", "or", "hash", "of", "estimators", "methods", "returns", "an", "array", "with", "three", "elements", "1", ".", "-", "A", "hash", "with", "estimators", "names", "as", "keys", "and", "lambdas", "as", "values", "2", ".", "-", "An", "array", "with", "estimators", "names", "3", ".", "-", "A", "Hash", "with", "estimators", "names", "as", "keys", "and", "empty", "arrays", "as", "values" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1572-L1584
train
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.coerce_positions
def coerce_positions *positions if positions.size == 1 case positions.first when Integer positions.first when Range size.times.to_a[positions.first] else raise ArgumentError, 'Unkown position type.' end else positions end end
ruby
def coerce_positions *positions if positions.size == 1 case positions.first when Integer positions.first when Range size.times.to_a[positions.first] else raise ArgumentError, 'Unkown position type.' end else positions end end
[ "def", "coerce_positions", "*", "positions", "if", "positions", ".", "size", "==", "1", "case", "positions", ".", "first", "when", "Integer", "positions", ".", "first", "when", "Range", "size", ".", "times", ".", "to_a", "[", "positions", ".", "first", "]", "else", "raise", "ArgumentError", ",", "'Unkown position type.'", "end", "else", "positions", "end", "end" ]
coerce ranges, integers and array in appropriate ways
[ "coerce", "ranges", "integers", "and", "array", "in", "appropriate", "ways" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1622-L1635
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.row_at
def row_at *positions original_positions = positions positions = coerce_positions(*positions, nrows) validate_positions(*positions, nrows) if positions.is_a? Integer row = get_rows_for([positions]) Daru::Vector.new row, index: @vectors else new_rows = get_rows_for(original_positions) Daru::DataFrame.new new_rows, index: @index.at(*original_positions), order: @vectors end end
ruby
def row_at *positions original_positions = positions positions = coerce_positions(*positions, nrows) validate_positions(*positions, nrows) if positions.is_a? Integer row = get_rows_for([positions]) Daru::Vector.new row, index: @vectors else new_rows = get_rows_for(original_positions) Daru::DataFrame.new new_rows, index: @index.at(*original_positions), order: @vectors end end
[ "def", "row_at", "*", "positions", "original_positions", "=", "positions", "positions", "=", "coerce_positions", "(", "positions", ",", "nrows", ")", "validate_positions", "(", "positions", ",", "nrows", ")", "if", "positions", ".", "is_a?", "Integer", "row", "=", "get_rows_for", "(", "[", "positions", "]", ")", "Daru", "::", "Vector", ".", "new", "row", ",", "index", ":", "@vectors", "else", "new_rows", "=", "get_rows_for", "(", "original_positions", ")", "Daru", "::", "DataFrame", ".", "new", "new_rows", ",", "index", ":", "@index", ".", "at", "(", "original_positions", ")", ",", "order", ":", "@vectors", "end", "end" ]
Retrive rows by positions @param [Array<Integer>] positions of rows to retrive @return [Daru::Vector, Daru::DataFrame] vector for single position and dataframe for multiple positions @example df = Daru::DataFrame.new({ a: [1, 2, 3], b: ['a', 'b', 'c'] }) df.row_at 1, 2 # => #<Daru::DataFrame(2x2)> # a b # 1 2 b # 2 3 c
[ "Retrive", "rows", "by", "positions" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L408-L420
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.set_row_at
def set_row_at positions, vector validate_positions(*positions, nrows) vector = if vector.is_a? Daru::Vector vector.reindex @vectors else Daru::Vector.new vector end raise SizeError, 'Vector length should match row length' if vector.size != @vectors.size @data.each_with_index do |vec, pos| vec.set_at(positions, vector.at(pos)) end @index = @data[0].index set_size end
ruby
def set_row_at positions, vector validate_positions(*positions, nrows) vector = if vector.is_a? Daru::Vector vector.reindex @vectors else Daru::Vector.new vector end raise SizeError, 'Vector length should match row length' if vector.size != @vectors.size @data.each_with_index do |vec, pos| vec.set_at(positions, vector.at(pos)) end @index = @data[0].index set_size end
[ "def", "set_row_at", "positions", ",", "vector", "validate_positions", "(", "positions", ",", "nrows", ")", "vector", "=", "if", "vector", ".", "is_a?", "Daru", "::", "Vector", "vector", ".", "reindex", "@vectors", "else", "Daru", "::", "Vector", ".", "new", "vector", "end", "raise", "SizeError", ",", "'Vector length should match row length'", "if", "vector", ".", "size", "!=", "@vectors", ".", "size", "@data", ".", "each_with_index", "do", "|", "vec", ",", "pos", "|", "vec", ".", "set_at", "(", "positions", ",", "vector", ".", "at", "(", "pos", ")", ")", "end", "@index", "=", "@data", "[", "0", "]", ".", "index", "set_size", "end" ]
Set rows by positions @param [Array<Integer>] positions positions of rows to set @param [Array, Daru::Vector] vector vector to be assigned @example df = Daru::DataFrame.new({ a: [1, 2, 3], b: ['a', 'b', 'c'] }) df.set_row_at [0, 1], ['x', 'x'] df #=> #<Daru::DataFrame(3x2)> # a b # 0 x x # 1 x x # 2 3 c
[ "Set", "rows", "by", "positions" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L437-L454
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.at
def at *positions if AXES.include? positions.last axis = positions.pop return row_at(*positions) if axis == :row end original_positions = positions positions = coerce_positions(*positions, ncols) validate_positions(*positions, ncols) if positions.is_a? Integer @data[positions].dup else Daru::DataFrame.new positions.map { |pos| @data[pos].dup }, index: @index, order: @vectors.at(*original_positions), name: @name end end
ruby
def at *positions if AXES.include? positions.last axis = positions.pop return row_at(*positions) if axis == :row end original_positions = positions positions = coerce_positions(*positions, ncols) validate_positions(*positions, ncols) if positions.is_a? Integer @data[positions].dup else Daru::DataFrame.new positions.map { |pos| @data[pos].dup }, index: @index, order: @vectors.at(*original_positions), name: @name end end
[ "def", "at", "*", "positions", "if", "AXES", ".", "include?", "positions", ".", "last", "axis", "=", "positions", ".", "pop", "return", "row_at", "(", "positions", ")", "if", "axis", "==", ":row", "end", "original_positions", "=", "positions", "positions", "=", "coerce_positions", "(", "positions", ",", "ncols", ")", "validate_positions", "(", "positions", ",", "ncols", ")", "if", "positions", ".", "is_a?", "Integer", "@data", "[", "positions", "]", ".", "dup", "else", "Daru", "::", "DataFrame", ".", "new", "positions", ".", "map", "{", "|", "pos", "|", "@data", "[", "pos", "]", ".", "dup", "}", ",", "index", ":", "@index", ",", "order", ":", "@vectors", ".", "at", "(", "original_positions", ")", ",", "name", ":", "@name", "end", "end" ]
Retrive vectors by positions @param [Array<Integer>] positions of vectors to retrive @return [Daru::Vector, Daru::DataFrame] vector for single position and dataframe for multiple positions @example df = Daru::DataFrame.new({ a: [1, 2, 3], b: ['a', 'b', 'c'] }) df.at 0 # => #<Daru::Vector(3)> # a # 0 1 # 1 2 # 2 3
[ "Retrive", "vectors", "by", "positions" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L470-L488
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.set_at
def set_at positions, vector if positions.last == :row positions.pop return set_row_at(positions, vector) end validate_positions(*positions, ncols) vector = if vector.is_a? Daru::Vector vector.reindex @index else Daru::Vector.new vector end raise SizeError, 'Vector length should match index length' if vector.size != @index.size positions.each { |pos| @data[pos] = vector } end
ruby
def set_at positions, vector if positions.last == :row positions.pop return set_row_at(positions, vector) end validate_positions(*positions, ncols) vector = if vector.is_a? Daru::Vector vector.reindex @index else Daru::Vector.new vector end raise SizeError, 'Vector length should match index length' if vector.size != @index.size positions.each { |pos| @data[pos] = vector } end
[ "def", "set_at", "positions", ",", "vector", "if", "positions", ".", "last", "==", ":row", "positions", ".", "pop", "return", "set_row_at", "(", "positions", ",", "vector", ")", "end", "validate_positions", "(", "positions", ",", "ncols", ")", "vector", "=", "if", "vector", ".", "is_a?", "Daru", "::", "Vector", "vector", ".", "reindex", "@index", "else", "Daru", "::", "Vector", ".", "new", "vector", "end", "raise", "SizeError", ",", "'Vector length should match index length'", "if", "vector", ".", "size", "!=", "@index", ".", "size", "positions", ".", "each", "{", "|", "pos", "|", "@data", "[", "pos", "]", "=", "vector", "}", "end" ]
Set vectors by positions @param [Array<Integer>] positions positions of vectors to set @param [Array, Daru::Vector] vector vector to be assigned @example df = Daru::DataFrame.new({ a: [1, 2, 3], b: ['a', 'b', 'c'] }) df.set_at [0], ['x', 'y', 'z'] df #=> #<Daru::DataFrame(3x2)> # a b # 0 x a # 1 y b # 2 z c
[ "Set", "vectors", "by", "positions" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L505-L523
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.get_sub_dataframe
def get_sub_dataframe(keys, by_position: true) return Daru::DataFrame.new({}) if keys == [] keys = @index.pos(*keys) unless by_position sub_df = row_at(*keys) sub_df = sub_df.to_df.transpose if sub_df.is_a?(Daru::Vector) sub_df end
ruby
def get_sub_dataframe(keys, by_position: true) return Daru::DataFrame.new({}) if keys == [] keys = @index.pos(*keys) unless by_position sub_df = row_at(*keys) sub_df = sub_df.to_df.transpose if sub_df.is_a?(Daru::Vector) sub_df end
[ "def", "get_sub_dataframe", "(", "keys", ",", "by_position", ":", "true", ")", "return", "Daru", "::", "DataFrame", ".", "new", "(", "{", "}", ")", "if", "keys", "==", "[", "]", "keys", "=", "@index", ".", "pos", "(", "keys", ")", "unless", "by_position", "sub_df", "=", "row_at", "(", "keys", ")", "sub_df", "=", "sub_df", ".", "to_df", ".", "transpose", "if", "sub_df", ".", "is_a?", "(", "Daru", "::", "Vector", ")", "sub_df", "end" ]
Extract a dataframe given row indexes or positions @param keys [Array] can be positions (if by_position is true) or indexes (if by_position if false) @return [Daru::Dataframe]
[ "Extract", "a", "dataframe", "given", "row", "indexes", "or", "positions" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L560-L569
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.dup_only_valid
def dup_only_valid vecs=nil rows_with_nil = @data.map { |vec| vec.indexes(*Daru::MISSING_VALUES) } .inject(&:concat) .uniq row_indexes = @index.to_a (vecs.nil? ? self : dup(vecs)).row[*(row_indexes - rows_with_nil)] end
ruby
def dup_only_valid vecs=nil rows_with_nil = @data.map { |vec| vec.indexes(*Daru::MISSING_VALUES) } .inject(&:concat) .uniq row_indexes = @index.to_a (vecs.nil? ? self : dup(vecs)).row[*(row_indexes - rows_with_nil)] end
[ "def", "dup_only_valid", "vecs", "=", "nil", "rows_with_nil", "=", "@data", ".", "map", "{", "|", "vec", "|", "vec", ".", "indexes", "(", "Daru", "::", "MISSING_VALUES", ")", "}", ".", "inject", "(", ":concat", ")", ".", "uniq", "row_indexes", "=", "@index", ".", "to_a", "(", "vecs", ".", "nil?", "?", "self", ":", "dup", "(", "vecs", ")", ")", ".", "row", "[", "(", "row_indexes", "-", "rows_with_nil", ")", "]", "end" ]
Creates a new duplicate dataframe containing only rows without a single missing value.
[ "Creates", "a", "new", "duplicate", "dataframe", "containing", "only", "rows", "without", "a", "single", "missing", "value", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L618-L625
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.reject_values
def reject_values(*values) positions = size.times.to_a - @data.flat_map { |vec| vec.positions(*values) } # Handle the case when positions size is 1 and #row_at wouldn't return a df if positions.size == 1 pos = positions.first row_at(pos..pos) else row_at(*positions) end end
ruby
def reject_values(*values) positions = size.times.to_a - @data.flat_map { |vec| vec.positions(*values) } # Handle the case when positions size is 1 and #row_at wouldn't return a df if positions.size == 1 pos = positions.first row_at(pos..pos) else row_at(*positions) end end
[ "def", "reject_values", "(", "*", "values", ")", "positions", "=", "size", ".", "times", ".", "to_a", "-", "@data", ".", "flat_map", "{", "|", "vec", "|", "vec", ".", "positions", "(", "values", ")", "}", "# Handle the case when positions size is 1 and #row_at wouldn't return a df", "if", "positions", ".", "size", "==", "1", "pos", "=", "positions", ".", "first", "row_at", "(", "pos", "..", "pos", ")", "else", "row_at", "(", "positions", ")", "end", "end" ]
Returns a dataframe in which rows with any of the mentioned values are ignored. @param [Array] values to reject to form the new dataframe @return [Daru::DataFrame] Data Frame with only rows which doesn't contain the mentioned values @example df = Daru::DataFrame.new({ a: [1, 2, 3, nil, Float::NAN, nil, 1, 7], b: [:a, :b, nil, Float::NAN, nil, 3, 5, 8], c: ['a', Float::NAN, 3, 4, 3, 5, nil, 7] }, index: 11..18) df.reject_values nil, Float::NAN # => #<Daru::DataFrame(2x3)> # a b c # 11 1 a a # 18 7 8 7
[ "Returns", "a", "dataframe", "in", "which", "rows", "with", "any", "of", "the", "mentioned", "values", "are", "ignored", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L644-L654
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.uniq
def uniq(*vtrs) vecs = vtrs.empty? ? vectors.to_a : Array(vtrs) grouped = group_by(vecs) indexes = grouped.groups.values.map { |v| v[0] }.sort row[*indexes] end
ruby
def uniq(*vtrs) vecs = vtrs.empty? ? vectors.to_a : Array(vtrs) grouped = group_by(vecs) indexes = grouped.groups.values.map { |v| v[0] }.sort row[*indexes] end
[ "def", "uniq", "(", "*", "vtrs", ")", "vecs", "=", "vtrs", ".", "empty?", "?", "vectors", ".", "to_a", ":", "Array", "(", "vtrs", ")", "grouped", "=", "group_by", "(", "vecs", ")", "indexes", "=", "grouped", ".", "groups", ".", "values", ".", "map", "{", "|", "v", "|", "v", "[", "0", "]", "}", ".", "sort", "row", "[", "indexes", "]", "end" ]
Return unique rows by vector specified or all vectors @param vtrs [String][Symbol] vector names(s) that should be considered @example => #<Daru::DataFrame(6x2)> a b 0 1 a 1 2 b 2 3 c 3 4 d 2 3 c 3 4 f 2.3.3 :> df.unique => #<Daru::DataFrame(5x2)> a b 0 1 a 1 2 b 2 3 c 3 4 d 3 4 f 2.3.3 :> df.unique(:a) => #<Daru::DataFrame(5x2)> a b 0 1 a 1 2 b 2 3 c 3 4 d
[ "Return", "unique", "rows", "by", "vector", "specified", "or", "all", "vectors" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L759-L764
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.collect_matrix
def collect_matrix return to_enum(:collect_matrix) unless block_given? vecs = vectors.to_a rows = vecs.collect { |row| vecs.collect { |col| yield row,col } } Matrix.rows(rows) end
ruby
def collect_matrix return to_enum(:collect_matrix) unless block_given? vecs = vectors.to_a rows = vecs.collect { |row| vecs.collect { |col| yield row,col } } Matrix.rows(rows) end
[ "def", "collect_matrix", "return", "to_enum", "(", ":collect_matrix", ")", "unless", "block_given?", "vecs", "=", "vectors", ".", "to_a", "rows", "=", "vecs", ".", "collect", "{", "|", "row", "|", "vecs", ".", "collect", "{", "|", "col", "|", "yield", "row", ",", "col", "}", "}", "Matrix", ".", "rows", "(", "rows", ")", "end" ]
Generate a matrix, based on vector names of the DataFrame. @return {::Matrix} :nocov: FIXME: Even not trying to cover this: I can't get, how it is expected to work.... -- zverok
[ "Generate", "a", "matrix", "based", "on", "vector", "names", "of", "the", "DataFrame", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L1059-L1070
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.delete_row
def delete_row index idx = named_index_for index raise IndexError, "Index #{index} does not exist." unless @index.include? idx @index = Daru::Index.new(@index.to_a - [idx]) each_vector do |vector| vector.delete_at idx end set_size end
ruby
def delete_row index idx = named_index_for index raise IndexError, "Index #{index} does not exist." unless @index.include? idx @index = Daru::Index.new(@index.to_a - [idx]) each_vector do |vector| vector.delete_at idx end set_size end
[ "def", "delete_row", "index", "idx", "=", "named_index_for", "index", "raise", "IndexError", ",", "\"Index #{index} does not exist.\"", "unless", "@index", ".", "include?", "idx", "@index", "=", "Daru", "::", "Index", ".", "new", "(", "@index", ".", "to_a", "-", "[", "idx", "]", ")", "each_vector", "do", "|", "vector", "|", "vector", ".", "delete_at", "idx", "end", "set_size", "end" ]
Delete a row
[ "Delete", "a", "row" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L1091-L1101
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.bootstrap
def bootstrap(n=nil) n ||= nrows Daru::DataFrame.new({}, order: @vectors).tap do |df_boot| n.times do df_boot.add_row(row[rand(n)]) end df_boot.update end end
ruby
def bootstrap(n=nil) n ||= nrows Daru::DataFrame.new({}, order: @vectors).tap do |df_boot| n.times do df_boot.add_row(row[rand(n)]) end df_boot.update end end
[ "def", "bootstrap", "(", "n", "=", "nil", ")", "n", "||=", "nrows", "Daru", "::", "DataFrame", ".", "new", "(", "{", "}", ",", "order", ":", "@vectors", ")", ".", "tap", "do", "|", "df_boot", "|", "n", ".", "times", "do", "df_boot", ".", "add_row", "(", "row", "[", "rand", "(", "n", ")", "]", ")", "end", "df_boot", ".", "update", "end", "end" ]
Creates a DataFrame with the random data, of n size. If n not given, uses original number of rows. @return {Daru::DataFrame}
[ "Creates", "a", "DataFrame", "with", "the", "random", "data", "of", "n", "size", ".", "If", "n", "not", "given", "uses", "original", "number", "of", "rows", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L1107-L1115
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.filter_vector
def filter_vector vec, &block Daru::Vector.new(each_row.select(&block).map { |row| row[vec] }) end
ruby
def filter_vector vec, &block Daru::Vector.new(each_row.select(&block).map { |row| row[vec] }) end
[ "def", "filter_vector", "vec", ",", "&", "block", "Daru", "::", "Vector", ".", "new", "(", "each_row", ".", "select", "(", "block", ")", ".", "map", "{", "|", "row", "|", "row", "[", "vec", "]", "}", ")", "end" ]
creates a new vector with the data of a given field which the block returns true
[ "creates", "a", "new", "vector", "with", "the", "data", "of", "a", "given", "field", "which", "the", "block", "returns", "true" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L1130-L1132
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.filter_rows
def filter_rows return to_enum(:filter_rows) unless block_given? keep_rows = @index.map { |index| yield access_row(index) } where keep_rows end
ruby
def filter_rows return to_enum(:filter_rows) unless block_given? keep_rows = @index.map { |index| yield access_row(index) } where keep_rows end
[ "def", "filter_rows", "return", "to_enum", "(", ":filter_rows", ")", "unless", "block_given?", "keep_rows", "=", "@index", ".", "map", "{", "|", "index", "|", "yield", "access_row", "(", "index", ")", "}", "where", "keep_rows", "end" ]
Iterates over each row and retains it in a new DataFrame if the block returns true for that row.
[ "Iterates", "over", "each", "row", "and", "retains", "it", "in", "a", "new", "DataFrame", "if", "the", "block", "returns", "true", "for", "that", "row", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L1136-L1142
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.filter_vectors
def filter_vectors &block return to_enum(:filter_vectors) unless block_given? dup.tap { |df| df.keep_vector_if(&block) } end
ruby
def filter_vectors &block return to_enum(:filter_vectors) unless block_given? dup.tap { |df| df.keep_vector_if(&block) } end
[ "def", "filter_vectors", "&", "block", "return", "to_enum", "(", ":filter_vectors", ")", "unless", "block_given?", "dup", ".", "tap", "{", "|", "df", "|", "df", ".", "keep_vector_if", "(", "block", ")", "}", "end" ]
Iterates over each vector and retains it in a new DataFrame if the block returns true for that vector.
[ "Iterates", "over", "each", "vector", "and", "retains", "it", "in", "a", "new", "DataFrame", "if", "the", "block", "returns", "true", "for", "that", "vector", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L1146-L1150
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.order=
def order=(order_array) raise ArgumentError, 'Invalid order' unless order_array.sort == vectors.to_a.sort initialize(to_h, order: order_array) end
ruby
def order=(order_array) raise ArgumentError, 'Invalid order' unless order_array.sort == vectors.to_a.sort initialize(to_h, order: order_array) end
[ "def", "order", "=", "(", "order_array", ")", "raise", "ArgumentError", ",", "'Invalid order'", "unless", "order_array", ".", "sort", "==", "vectors", ".", "to_a", ".", "sort", "initialize", "(", "to_h", ",", "order", ":", "order_array", ")", "end" ]
Reorder the vectors in a dataframe @param [Array] order_array new order of the vectors @example df = Daru::DataFrame({ a: [1, 2, 3], b: [4, 5, 6] }, order: [:a, :b]) df.order = [:b, :a] df # => #<Daru::DataFrame(3x2)> # b a # 0 4 1 # 1 5 2 # 2 6 3
[ "Reorder", "the", "vectors", "in", "a", "dataframe" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L1208-L1212
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.missing_values_rows
def missing_values_rows missing_values=[nil] number_of_missing = each_row.map do |row| row.indexes(*missing_values).size end Daru::Vector.new number_of_missing, index: @index, name: "#{@name}_missing_rows" end
ruby
def missing_values_rows missing_values=[nil] number_of_missing = each_row.map do |row| row.indexes(*missing_values).size end Daru::Vector.new number_of_missing, index: @index, name: "#{@name}_missing_rows" end
[ "def", "missing_values_rows", "missing_values", "=", "[", "nil", "]", "number_of_missing", "=", "each_row", ".", "map", "do", "|", "row", "|", "row", ".", "indexes", "(", "missing_values", ")", ".", "size", "end", "Daru", "::", "Vector", ".", "new", "number_of_missing", ",", "index", ":", "@index", ",", "name", ":", "\"#{@name}_missing_rows\"", "end" ]
Return a vector with the number of missing values in each row. == Arguments * +missing_values+ - An Array of the values that should be treated as 'missing'. The default missing value is *nil*.
[ "Return", "a", "vector", "with", "the", "number", "of", "missing", "values", "in", "each", "row", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L1237-L1243
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.nest
def nest *tree_keys, &_block tree_keys = tree_keys[0] if tree_keys[0].is_a? Array each_row.each_with_object({}) do |row, current| # Create tree *keys, last = tree_keys current = keys.inject(current) { |c, f| c[row[f]] ||= {} } name = row[last] if block_given? current[name] = yield(row, current, name) else current[name] ||= [] current[name].push(row.to_h.delete_if { |key,_value| tree_keys.include? key }) end end end
ruby
def nest *tree_keys, &_block tree_keys = tree_keys[0] if tree_keys[0].is_a? Array each_row.each_with_object({}) do |row, current| # Create tree *keys, last = tree_keys current = keys.inject(current) { |c, f| c[row[f]] ||= {} } name = row[last] if block_given? current[name] = yield(row, current, name) else current[name] ||= [] current[name].push(row.to_h.delete_if { |key,_value| tree_keys.include? key }) end end end
[ "def", "nest", "*", "tree_keys", ",", "&", "_block", "tree_keys", "=", "tree_keys", "[", "0", "]", "if", "tree_keys", "[", "0", "]", ".", "is_a?", "Array", "each_row", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "row", ",", "current", "|", "# Create tree", "*", "keys", ",", "last", "=", "tree_keys", "current", "=", "keys", ".", "inject", "(", "current", ")", "{", "|", "c", ",", "f", "|", "c", "[", "row", "[", "f", "]", "]", "||=", "{", "}", "}", "name", "=", "row", "[", "last", "]", "if", "block_given?", "current", "[", "name", "]", "=", "yield", "(", "row", ",", "current", ",", "name", ")", "else", "current", "[", "name", "]", "||=", "[", "]", "current", "[", "name", "]", ".", "push", "(", "row", ".", "to_h", ".", "delete_if", "{", "|", "key", ",", "_value", "|", "tree_keys", ".", "include?", "key", "}", ")", "end", "end", "end" ]
Return a nested hash using vector names as keys and an array constructed of hashes with other values. If block provided, is used to provide the values, with parameters +row+ of dataset, +current+ last hash on hierarchy and +name+ of the key to include
[ "Return", "a", "nested", "hash", "using", "vector", "names", "as", "keys", "and", "an", "array", "constructed", "of", "hashes", "with", "other", "values", ".", "If", "block", "provided", "is", "used", "to", "provide", "the", "values", "with", "parameters", "+", "row", "+", "of", "dataset", "+", "current", "+", "last", "hash", "on", "hierarchy", "and", "+", "name", "+", "of", "the", "key", "to", "include" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L1275-L1291
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.vector_mean
def vector_mean max_missing=0 # FIXME: in vector_sum we preserve created vector dtype, but # here we are not. Is this by design or ...? - zverok, 2016-05-18 mean_vec = Daru::Vector.new [0]*@size, index: @index, name: "mean_#{@name}" each_row_with_index.each_with_object(mean_vec) do |(row, i), memo| memo[i] = row.indexes(*Daru::MISSING_VALUES).size > max_missing ? nil : row.mean end end
ruby
def vector_mean max_missing=0 # FIXME: in vector_sum we preserve created vector dtype, but # here we are not. Is this by design or ...? - zverok, 2016-05-18 mean_vec = Daru::Vector.new [0]*@size, index: @index, name: "mean_#{@name}" each_row_with_index.each_with_object(mean_vec) do |(row, i), memo| memo[i] = row.indexes(*Daru::MISSING_VALUES).size > max_missing ? nil : row.mean end end
[ "def", "vector_mean", "max_missing", "=", "0", "# FIXME: in vector_sum we preserve created vector dtype, but", "# here we are not. Is this by design or ...? - zverok, 2016-05-18", "mean_vec", "=", "Daru", "::", "Vector", ".", "new", "[", "0", "]", "*", "@size", ",", "index", ":", "@index", ",", "name", ":", "\"mean_#{@name}\"", "each_row_with_index", ".", "each_with_object", "(", "mean_vec", ")", "do", "|", "(", "row", ",", "i", ")", ",", "memo", "|", "memo", "[", "i", "]", "=", "row", ".", "indexes", "(", "Daru", "::", "MISSING_VALUES", ")", ".", "size", ">", "max_missing", "?", "nil", ":", "row", ".", "mean", "end", "end" ]
Calculate mean of the rows of the dataframe. == Arguments * +max_missing+ - The maximum number of elements in the row that can be zero for the mean calculation to happen. Default to 0.
[ "Calculate", "mean", "of", "the", "rows", "of", "the", "dataframe", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L1449-L1457
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.concat
def concat other_df vectors = (@vectors.to_a + other_df.vectors.to_a).uniq data = vectors.map do |v| get_vector_anyways(v).dup.concat(other_df.get_vector_anyways(v)) end Daru::DataFrame.new(data, order: vectors) end
ruby
def concat other_df vectors = (@vectors.to_a + other_df.vectors.to_a).uniq data = vectors.map do |v| get_vector_anyways(v).dup.concat(other_df.get_vector_anyways(v)) end Daru::DataFrame.new(data, order: vectors) end
[ "def", "concat", "other_df", "vectors", "=", "(", "@vectors", ".", "to_a", "+", "other_df", ".", "vectors", ".", "to_a", ")", ".", "uniq", "data", "=", "vectors", ".", "map", "do", "|", "v", "|", "get_vector_anyways", "(", "v", ")", ".", "dup", ".", "concat", "(", "other_df", ".", "get_vector_anyways", "(", "v", ")", ")", "end", "Daru", "::", "DataFrame", ".", "new", "(", "data", ",", "order", ":", "vectors", ")", "end" ]
Concatenate another DataFrame along corresponding columns. If columns do not exist in both dataframes, they are filled with nils
[ "Concatenate", "another", "DataFrame", "along", "corresponding", "columns", ".", "If", "columns", "do", "not", "exist", "in", "both", "dataframes", "they", "are", "filled", "with", "nils" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L1513-L1521
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.set_index
def set_index new_index_col, opts={} if new_index_col.respond_to?(:to_a) strategy = SetMultiIndexStrategy new_index_col = new_index_col.to_a else strategy = SetSingleIndexStrategy end uniq_size = strategy.uniq_size(self, new_index_col) raise ArgumentError, 'All elements in new index must be unique.' if @size != uniq_size self.index = strategy.new_index(self, new_index_col) strategy.delete_vector(self, new_index_col) unless opts[:keep] self end
ruby
def set_index new_index_col, opts={} if new_index_col.respond_to?(:to_a) strategy = SetMultiIndexStrategy new_index_col = new_index_col.to_a else strategy = SetSingleIndexStrategy end uniq_size = strategy.uniq_size(self, new_index_col) raise ArgumentError, 'All elements in new index must be unique.' if @size != uniq_size self.index = strategy.new_index(self, new_index_col) strategy.delete_vector(self, new_index_col) unless opts[:keep] self end
[ "def", "set_index", "new_index_col", ",", "opts", "=", "{", "}", "if", "new_index_col", ".", "respond_to?", "(", ":to_a", ")", "strategy", "=", "SetMultiIndexStrategy", "new_index_col", "=", "new_index_col", ".", "to_a", "else", "strategy", "=", "SetSingleIndexStrategy", "end", "uniq_size", "=", "strategy", ".", "uniq_size", "(", "self", ",", "new_index_col", ")", "raise", "ArgumentError", ",", "'All elements in new index must be unique.'", "if", "@size", "!=", "uniq_size", "self", ".", "index", "=", "strategy", ".", "new_index", "(", "self", ",", "new_index_col", ")", "strategy", ".", "delete_vector", "(", "self", ",", "new_index_col", ")", "unless", "opts", "[", ":keep", "]", "self", "end" ]
Set a particular column as the new DF
[ "Set", "a", "particular", "column", "as", "the", "new", "DF" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L1568-L1583
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.rename_vectors
def rename_vectors name_map existing_targets = name_map.reject { |k,v| k == v }.values & vectors.to_a delete_vectors(*existing_targets) new_names = vectors.to_a.map { |v| name_map[v] ? name_map[v] : v } self.vectors = Daru::Index.new new_names end
ruby
def rename_vectors name_map existing_targets = name_map.reject { |k,v| k == v }.values & vectors.to_a delete_vectors(*existing_targets) new_names = vectors.to_a.map { |v| name_map[v] ? name_map[v] : v } self.vectors = Daru::Index.new new_names end
[ "def", "rename_vectors", "name_map", "existing_targets", "=", "name_map", ".", "reject", "{", "|", "k", ",", "v", "|", "k", "==", "v", "}", ".", "values", "&", "vectors", ".", "to_a", "delete_vectors", "(", "existing_targets", ")", "new_names", "=", "vectors", ".", "to_a", ".", "map", "{", "|", "v", "|", "name_map", "[", "v", "]", "?", "name_map", "[", "v", "]", ":", "v", "}", "self", ".", "vectors", "=", "Daru", "::", "Index", ".", "new", "new_names", "end" ]
Renames the vectors == Arguments * name_map - A hash where the keys are the exising vector names and the values are the new names. If a vector is renamed to a vector name that is already in use, the existing one is overwritten. == Usage df = Daru::DataFrame.new({ a: [1,2,3,4], b: [:a,:b,:c,:d], c: [11,22,33,44] }) df.rename_vectors :a => :alpha, :c => :gamma df.vectors.to_a #=> [:alpha, :b, :gamma]
[ "Renames", "the", "vectors" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L1691-L1697
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.summary
def summary summary = "= #{name}" summary << "\n Number of rows: #{nrows}" @vectors.each do |v| summary << "\n Element:[#{v}]\n" summary << self[v].summary(1) end summary end
ruby
def summary summary = "= #{name}" summary << "\n Number of rows: #{nrows}" @vectors.each do |v| summary << "\n Element:[#{v}]\n" summary << self[v].summary(1) end summary end
[ "def", "summary", "summary", "=", "\"= #{name}\"", "summary", "<<", "\"\\n Number of rows: #{nrows}\"", "@vectors", ".", "each", "do", "|", "v", "|", "summary", "<<", "\"\\n Element:[#{v}]\\n\"", "summary", "<<", "self", "[", "v", "]", ".", "summary", "(", "1", ")", "end", "summary", "end" ]
Generate a summary of this DataFrame based on individual vectors in the DataFrame @return [String] String containing the summary of the DataFrame
[ "Generate", "a", "summary", "of", "this", "DataFrame", "based", "on", "individual", "vectors", "in", "the", "DataFrame" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L1725-L1733
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.pivot_table
def pivot_table opts={} raise ArgumentError, 'Specify grouping index' if Array(opts[:index]).empty? index = opts[:index] vectors = opts[:vectors] || [] aggregate_function = opts[:agg] || :mean values = prepare_pivot_values index, vectors, opts raise IndexError, 'No numeric vectors to aggregate' if values.empty? grouped = group_by(index) return grouped.send(aggregate_function) if vectors.empty? super_hash = make_pivot_hash grouped, vectors, values, aggregate_function pivot_dataframe super_hash end
ruby
def pivot_table opts={} raise ArgumentError, 'Specify grouping index' if Array(opts[:index]).empty? index = opts[:index] vectors = opts[:vectors] || [] aggregate_function = opts[:agg] || :mean values = prepare_pivot_values index, vectors, opts raise IndexError, 'No numeric vectors to aggregate' if values.empty? grouped = group_by(index) return grouped.send(aggregate_function) if vectors.empty? super_hash = make_pivot_hash grouped, vectors, values, aggregate_function pivot_dataframe super_hash end
[ "def", "pivot_table", "opts", "=", "{", "}", "raise", "ArgumentError", ",", "'Specify grouping index'", "if", "Array", "(", "opts", "[", ":index", "]", ")", ".", "empty?", "index", "=", "opts", "[", ":index", "]", "vectors", "=", "opts", "[", ":vectors", "]", "||", "[", "]", "aggregate_function", "=", "opts", "[", ":agg", "]", "||", ":mean", "values", "=", "prepare_pivot_values", "index", ",", "vectors", ",", "opts", "raise", "IndexError", ",", "'No numeric vectors to aggregate'", "if", "values", ".", "empty?", "grouped", "=", "group_by", "(", "index", ")", "return", "grouped", ".", "send", "(", "aggregate_function", ")", "if", "vectors", ".", "empty?", "super_hash", "=", "make_pivot_hash", "grouped", ",", "vectors", ",", "values", ",", "aggregate_function", "pivot_dataframe", "super_hash", "end" ]
Pivots a data frame on specified vectors and applies an aggregate function to quickly generate a summary. == Options +:index+ - Keys to group by on the pivot table row index. Pass vector names contained in an Array. +:vectors+ - Keys to group by on the pivot table column index. Pass vector names contained in an Array. +:agg+ - Function to aggregate the grouped values. Default to *:mean*. Can use any of the statistics functions applicable on Vectors that can be found in the Daru::Statistics::Vector module. +:values+ - Columns to aggregate. Will consider all numeric columns not specified in *:index* or *:vectors*. Optional. == Usage df = Daru::DataFrame.new({ a: ['foo' , 'foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar'], b: ['one' , 'one', 'one', 'two', 'two', 'one', 'one', 'two', 'two'], c: ['small','large','large','small','small','large','small','large','small'], d: [1,2,2,3,3,4,5,6,7], e: [2,4,4,6,6,8,10,12,14] }) df.pivot_table(index: [:a], vectors: [:b], agg: :sum, values: :e) #=> # #<Daru::DataFrame:88342020 @name = 08cdaf4e-b154-4186-9084-e76dd191b2c9 @size = 2> # [:e, :one] [:e, :two] # [:bar] 18 26 # [:foo] 10 12
[ "Pivots", "a", "data", "frame", "on", "specified", "vectors", "and", "applies", "an", "aggregate", "function", "to", "quickly", "generate", "a", "summary", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L1880-L1895
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.one_to_many
def one_to_many(parent_fields, pattern) vars, numbers = one_to_many_components(pattern) DataFrame.new([], order: [*parent_fields, '_col_id', *vars]).tap do |ds| each_row do |row| verbatim = parent_fields.map { |f| [f, row[f]] }.to_h numbers.each do |n| generated = one_to_many_row row, n, vars, pattern next if generated.values.all?(&:nil?) ds.add_row(verbatim.merge(generated).merge('_col_id' => n)) end end ds.update end end
ruby
def one_to_many(parent_fields, pattern) vars, numbers = one_to_many_components(pattern) DataFrame.new([], order: [*parent_fields, '_col_id', *vars]).tap do |ds| each_row do |row| verbatim = parent_fields.map { |f| [f, row[f]] }.to_h numbers.each do |n| generated = one_to_many_row row, n, vars, pattern next if generated.values.all?(&:nil?) ds.add_row(verbatim.merge(generated).merge('_col_id' => n)) end end ds.update end end
[ "def", "one_to_many", "(", "parent_fields", ",", "pattern", ")", "vars", ",", "numbers", "=", "one_to_many_components", "(", "pattern", ")", "DataFrame", ".", "new", "(", "[", "]", ",", "order", ":", "[", "parent_fields", ",", "'_col_id'", ",", "vars", "]", ")", ".", "tap", "do", "|", "ds", "|", "each_row", "do", "|", "row", "|", "verbatim", "=", "parent_fields", ".", "map", "{", "|", "f", "|", "[", "f", ",", "row", "[", "f", "]", "]", "}", ".", "to_h", "numbers", ".", "each", "do", "|", "n", "|", "generated", "=", "one_to_many_row", "row", ",", "n", ",", "vars", ",", "pattern", "next", "if", "generated", ".", "values", ".", "all?", "(", ":nil?", ")", "ds", ".", "add_row", "(", "verbatim", ".", "merge", "(", "generated", ")", ".", "merge", "(", "'_col_id'", "=>", "n", ")", ")", "end", "end", "ds", ".", "update", "end", "end" ]
Creates a new dataset for one to many relations on a dataset, based on pattern of field names. for example, you have a survey for number of children with this structure: id, name, child_name_1, child_age_1, child_name_2, child_age_2 with ds.one_to_many([:id], "child_%v_%n" the field of first parameters will be copied verbatim to new dataset, and fields which responds to second pattern will be added one case for each different %n. @example cases=[ ['1','george','red',10,'blue',20,nil,nil], ['2','fred','green',15,'orange',30,'white',20], ['3','alfred',nil,nil,nil,nil,nil,nil] ] ds=Daru::DataFrame.rows(cases, order: [:id, :name, :car_color1, :car_value1, :car_color2, :car_value2, :car_color3, :car_value3]) ds.one_to_many([:id],'car_%v%n').to_matrix #=> Matrix[ # ["red", "1", 10], # ["blue", "1", 20], # ["green", "2", 15], # ["orange", "2", 30], # ["white", "2", 20] # ]
[ "Creates", "a", "new", "dataset", "for", "one", "to", "many", "relations", "on", "a", "dataset", "based", "on", "pattern", "of", "field", "names", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L1981-L1996
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.create_sql
def create_sql(table,charset='UTF8') sql = "CREATE TABLE #{table} (" fields = vectors.to_a.collect do |f| v = self[f] f.to_s + ' ' + v.db_type end sql + fields.join(",\n ")+") CHARACTER SET=#{charset};" end
ruby
def create_sql(table,charset='UTF8') sql = "CREATE TABLE #{table} (" fields = vectors.to_a.collect do |f| v = self[f] f.to_s + ' ' + v.db_type end sql + fields.join(",\n ")+") CHARACTER SET=#{charset};" end
[ "def", "create_sql", "(", "table", ",", "charset", "=", "'UTF8'", ")", "sql", "=", "\"CREATE TABLE #{table} (\"", "fields", "=", "vectors", ".", "to_a", ".", "collect", "do", "|", "f", "|", "v", "=", "self", "[", "f", "]", "f", ".", "to_s", "+", "' '", "+", "v", ".", "db_type", "end", "sql", "+", "fields", ".", "join", "(", "\",\\n \"", ")", "+", "\") CHARACTER SET=#{charset};\"", "end" ]
Create a sql, basen on a given Dataset == Arguments * table - String specifying name of the table that will created in SQL. * charset - Character set. Default is "UTF8". @example ds = Daru::DataFrame.new({ :id => Daru::Vector.new([1,2,3,4,5]), :name => Daru::Vector.new(%w{Alex Peter Susan Mary John}) }) ds.create_sql('names') #=>"CREATE TABLE names (id INTEGER,\n name VARCHAR (255)) CHARACTER SET=UTF8;"
[ "Create", "a", "sql", "basen", "on", "a", "given", "Dataset" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L2023-L2031
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.to_html
def to_html(threshold=30) table_thead = to_html_thead table_tbody = to_html_tbody(threshold) path = if index.is_a?(MultiIndex) File.expand_path('../iruby/templates/dataframe_mi.html.erb', __FILE__) else File.expand_path('../iruby/templates/dataframe.html.erb', __FILE__) end ERB.new(File.read(path).strip).result(binding) end
ruby
def to_html(threshold=30) table_thead = to_html_thead table_tbody = to_html_tbody(threshold) path = if index.is_a?(MultiIndex) File.expand_path('../iruby/templates/dataframe_mi.html.erb', __FILE__) else File.expand_path('../iruby/templates/dataframe.html.erb', __FILE__) end ERB.new(File.read(path).strip).result(binding) end
[ "def", "to_html", "(", "threshold", "=", "30", ")", "table_thead", "=", "to_html_thead", "table_tbody", "=", "to_html_tbody", "(", "threshold", ")", "path", "=", "if", "index", ".", "is_a?", "(", "MultiIndex", ")", "File", ".", "expand_path", "(", "'../iruby/templates/dataframe_mi.html.erb'", ",", "__FILE__", ")", "else", "File", ".", "expand_path", "(", "'../iruby/templates/dataframe.html.erb'", ",", "__FILE__", ")", "end", "ERB", ".", "new", "(", "File", ".", "read", "(", "path", ")", ".", "strip", ")", ".", "result", "(", "binding", ")", "end" ]
Convert to html for IRuby.
[ "Convert", "to", "html", "for", "IRuby", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L2094-L2103
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.transpose
def transpose Daru::DataFrame.new( each_vector.map(&:to_a).transpose, index: @vectors, order: @index, dtype: @dtype, name: @name ) end
ruby
def transpose Daru::DataFrame.new( each_vector.map(&:to_a).transpose, index: @vectors, order: @index, dtype: @dtype, name: @name ) end
[ "def", "transpose", "Daru", "::", "DataFrame", ".", "new", "(", "each_vector", ".", "map", "(", ":to_a", ")", ".", "transpose", ",", "index", ":", "@vectors", ",", "order", ":", "@index", ",", "dtype", ":", "@dtype", ",", "name", ":", "@name", ")", "end" ]
Transpose a DataFrame, tranposing elements and row, column indexing.
[ "Transpose", "a", "DataFrame", "tranposing", "elements", "and", "row", "column", "indexing", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L2221-L2229
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.aggregate
def aggregate(options={}, multi_index_level=-1) if block_given? positions_tuples, new_index = yield(@index) # note: use of yield is private for now else positions_tuples, new_index = group_index_for_aggregation(@index, multi_index_level) end colmn_value = aggregate_by_positions_tuples(options, positions_tuples) Daru::DataFrame.new(colmn_value, index: new_index, order: options.keys) end
ruby
def aggregate(options={}, multi_index_level=-1) if block_given? positions_tuples, new_index = yield(@index) # note: use of yield is private for now else positions_tuples, new_index = group_index_for_aggregation(@index, multi_index_level) end colmn_value = aggregate_by_positions_tuples(options, positions_tuples) Daru::DataFrame.new(colmn_value, index: new_index, order: options.keys) end
[ "def", "aggregate", "(", "options", "=", "{", "}", ",", "multi_index_level", "=", "-", "1", ")", "if", "block_given?", "positions_tuples", ",", "new_index", "=", "yield", "(", "@index", ")", "# note: use of yield is private for now", "else", "positions_tuples", ",", "new_index", "=", "group_index_for_aggregation", "(", "@index", ",", "multi_index_level", ")", "end", "colmn_value", "=", "aggregate_by_positions_tuples", "(", "options", ",", "positions_tuples", ")", "Daru", "::", "DataFrame", ".", "new", "(", "colmn_value", ",", "index", ":", "new_index", ",", "order", ":", "options", ".", "keys", ")", "end" ]
Function to use for aggregating the data. @param options [Hash] options for column, you want in resultant dataframe @return [Daru::DataFrame] @example df = Daru::DataFrame.new( {col: [:a, :b, :c, :d, :e], num: [52,12,07,17,01]}) => #<Daru::DataFrame(5x2)> col num 0 a 52 1 b 12 2 c 7 3 d 17 4 e 1 df.aggregate(num_100_times: ->(df) { (df.num*100).first }) => #<Daru::DataFrame(5x1)> num_100_ti 0 5200 1 1200 2 700 3 1700 4 100 When we have duplicate index : idx = Daru::CategoricalIndex.new [:a, :b, :a, :a, :c] df = Daru::DataFrame.new({num: [52,12,07,17,01]}, index: idx) => #<Daru::DataFrame(5x1)> num a 52 b 12 a 7 a 17 c 1 df.aggregate(num: :mean) => #<Daru::DataFrame(3x1)> num a 25.3333333 b 12 c 1 Note: `GroupBy` class `aggregate` method uses this `aggregate` method internally.
[ "Function", "to", "use", "for", "aggregating", "the", "data", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L2425-L2435
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.validate_positions
def validate_positions *positions, size positions.each do |pos| raise IndexError, "#{pos} is not a valid position." if pos >= size end end
ruby
def validate_positions *positions, size positions.each do |pos| raise IndexError, "#{pos} is not a valid position." if pos >= size end end
[ "def", "validate_positions", "*", "positions", ",", "size", "positions", ".", "each", "do", "|", "pos", "|", "raise", "IndexError", ",", "\"#{pos} is not a valid position.\"", "if", "pos", ">=", "size", "end", "end" ]
Raises IndexError when one of the positions is not a valid position
[ "Raises", "IndexError", "when", "one", "of", "the", "positions", "is", "not", "a", "valid", "position" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L3005-L3009
train
SciRuby/daru
lib/daru/dataframe.rb
Daru.DataFrame.coerce_vector
def coerce_vector vector case vector when Daru::Vector vector.reindex @vectors when Hash Daru::Vector.new(vector).reindex @vectors else Daru::Vector.new vector end end
ruby
def coerce_vector vector case vector when Daru::Vector vector.reindex @vectors when Hash Daru::Vector.new(vector).reindex @vectors else Daru::Vector.new vector end end
[ "def", "coerce_vector", "vector", "case", "vector", "when", "Daru", "::", "Vector", "vector", ".", "reindex", "@vectors", "when", "Hash", "Daru", "::", "Vector", ".", "new", "(", "vector", ")", ".", "reindex", "@vectors", "else", "Daru", "::", "Vector", ".", "new", "vector", "end", "end" ]
Accepts hash, enumerable and vector and align it properly so it can be added
[ "Accepts", "hash", "enumerable", "and", "vector", "and", "align", "it", "properly", "so", "it", "can", "be", "added" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L3012-L3021
train
SciRuby/daru
lib/daru/index/index.rb
Daru.Index.valid?
def valid? *indexes indexes.all? { |i| to_a.include?(i) || (i.is_a?(Numeric) && i < size) } end
ruby
def valid? *indexes indexes.all? { |i| to_a.include?(i) || (i.is_a?(Numeric) && i < size) } end
[ "def", "valid?", "*", "indexes", "indexes", ".", "all?", "{", "|", "i", "|", "to_a", ".", "include?", "(", "i", ")", "||", "(", "i", ".", "is_a?", "(", "Numeric", ")", "&&", "i", "<", "size", ")", "}", "end" ]
Returns true if all arguments are either a valid category or position @param indexes [Array<object>] categories or positions @return [true, false] @example idx.valid? :a, 2 # => true idx.valid? 3 # => false
[ "Returns", "true", "if", "all", "arguments", "are", "either", "a", "valid", "category", "or", "position" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/index/index.rb#L100-L102
train
SciRuby/daru
lib/daru/index/index.rb
Daru.Index.sort
def sort opts={} opts = {ascending: true}.merge(opts) new_index = @keys.sort new_index = new_index.reverse unless opts[:ascending] self.class.new(new_index) end
ruby
def sort opts={} opts = {ascending: true}.merge(opts) new_index = @keys.sort new_index = new_index.reverse unless opts[:ascending] self.class.new(new_index) end
[ "def", "sort", "opts", "=", "{", "}", "opts", "=", "{", "ascending", ":", "true", "}", ".", "merge", "(", "opts", ")", "new_index", "=", "@keys", ".", "sort", "new_index", "=", "new_index", ".", "reverse", "unless", "opts", "[", ":ascending", "]", "self", ".", "class", ".", "new", "(", "new_index", ")", "end" ]
Sorts a `Index`, according to its values. Defaults to ascending order sorting. @param [Hash] opts the options for sort method. @option opts [Boolean] :ascending False, to get descending order. @return [Index] sorted `Index` according to its values. @example di = Daru::Index.new [100, 99, 101, 1, 2] # Say you want to sort in descending order di.sort(ascending: false) #=> Daru::Index.new [101, 100, 99, 2, 1] # Say you want to sort in ascending order di.sort #=> Daru::Index.new [1, 2, 99, 100, 101]
[ "Sorts", "a", "Index", "according", "to", "its", "values", ".", "Defaults", "to", "ascending", "order", "sorting", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/index/index.rb#L286-L293
train
SciRuby/daru
lib/daru/date_time/index.rb
Daru.DateTimeIndex.[]
def [] *key return slice(*key) if key.size != 1 key = key[0] case key when Numeric key when DateTime Helper.find_index_of_date(@data, key) when Range # FIXME: get_by_range is suspiciously close to just #slice, # but one of specs fails when replacing it with just slice get_by_range(key.first, key.last) else raise ArgumentError, "Key #{key} is out of bounds" if Helper.key_out_of_bounds?(key, @data) slice(*Helper.find_date_string_bounds(key)) end end
ruby
def [] *key return slice(*key) if key.size != 1 key = key[0] case key when Numeric key when DateTime Helper.find_index_of_date(@data, key) when Range # FIXME: get_by_range is suspiciously close to just #slice, # but one of specs fails when replacing it with just slice get_by_range(key.first, key.last) else raise ArgumentError, "Key #{key} is out of bounds" if Helper.key_out_of_bounds?(key, @data) slice(*Helper.find_date_string_bounds(key)) end end
[ "def", "[]", "*", "key", "return", "slice", "(", "key", ")", "if", "key", ".", "size", "!=", "1", "key", "=", "key", "[", "0", "]", "case", "key", "when", "Numeric", "key", "when", "DateTime", "Helper", ".", "find_index_of_date", "(", "@data", ",", "key", ")", "when", "Range", "# FIXME: get_by_range is suspiciously close to just #slice,", "# but one of specs fails when replacing it with just slice", "get_by_range", "(", "key", ".", "first", ",", "key", ".", "last", ")", "else", "raise", "ArgumentError", ",", "\"Key #{key} is out of bounds\"", "if", "Helper", ".", "key_out_of_bounds?", "(", "key", ",", "@data", ")", "slice", "(", "Helper", ".", "find_date_string_bounds", "(", "key", ")", ")", "end", "end" ]
Retreive a slice or a an individual index number from the index. @param key [String, DateTime] Specify a date partially (as a String) or completely to retrieve.
[ "Retreive", "a", "slice", "or", "a", "an", "individual", "index", "number", "from", "the", "index", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/date_time/index.rb#L349-L367
train
SciRuby/daru
lib/daru/date_time/index.rb
Daru.DateTimeIndex.slice
def slice first, last if first.is_a?(Integer) && last.is_a?(Integer) DateTimeIndex.new(to_a[first..last], freq: @offset) else first = Helper.find_date_string_bounds(first)[0] if first.is_a?(String) last = Helper.find_date_string_bounds(last)[1] if last.is_a?(String) slice_between_dates first, last end end
ruby
def slice first, last if first.is_a?(Integer) && last.is_a?(Integer) DateTimeIndex.new(to_a[first..last], freq: @offset) else first = Helper.find_date_string_bounds(first)[0] if first.is_a?(String) last = Helper.find_date_string_bounds(last)[1] if last.is_a?(String) slice_between_dates first, last end end
[ "def", "slice", "first", ",", "last", "if", "first", ".", "is_a?", "(", "Integer", ")", "&&", "last", ".", "is_a?", "(", "Integer", ")", "DateTimeIndex", ".", "new", "(", "to_a", "[", "first", "..", "last", "]", ",", "freq", ":", "@offset", ")", "else", "first", "=", "Helper", ".", "find_date_string_bounds", "(", "first", ")", "[", "0", "]", "if", "first", ".", "is_a?", "(", "String", ")", "last", "=", "Helper", ".", "find_date_string_bounds", "(", "last", ")", "[", "1", "]", "if", "last", ".", "is_a?", "(", "String", ")", "slice_between_dates", "first", ",", "last", "end", "end" ]
Retrive a slice of the index by specifying first and last members of the slice. @param [String, DateTime] first Start of the slice as a string or DateTime. @param [String, DateTime] last End of the slice as a string or DateTime.
[ "Retrive", "a", "slice", "of", "the", "index", "by", "specifying", "first", "and", "last", "members", "of", "the", "slice", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/date_time/index.rb#L391-L400
train
SciRuby/daru
lib/daru/date_time/index.rb
Daru.DateTimeIndex.shift
def shift distance distance.is_a?(Integer) && distance < 0 and raise IndexError, "Distance #{distance} cannot be negative" _shift(distance) end
ruby
def shift distance distance.is_a?(Integer) && distance < 0 and raise IndexError, "Distance #{distance} cannot be negative" _shift(distance) end
[ "def", "shift", "distance", "distance", ".", "is_a?", "(", "Integer", ")", "&&", "distance", "<", "0", "and", "raise", "IndexError", ",", "\"Distance #{distance} cannot be negative\"", "_shift", "(", "distance", ")", "end" ]
Shift all dates in the index by a positive number in the future. The dates are shifted by the same amount as that specified in the offset. @param [Integer, Daru::DateOffset, Daru::Offsets::*] distance Distance by which each date should be shifted. Passing an offset object to #shift will offset each data point by the offset value. Passing a positive integer will offset each data point by the same offset that it was created with. @return [DateTimeIndex] Returns a new, shifted DateTimeIndex object. @example Using the shift method index = Daru::DateTimeIndex.date_range( :start => '2012', :periods => 10, :freq => 'YEAR') # Passing a offset to shift index.shift(Daru::Offsets::Hour.new(3)) #=>#<DateTimeIndex:84038960 offset=nil periods=10 data=[2012-01-01T03:00:00+00:00...2021-01-01T03:00:00+00:00]> # Pass an integer to shift index.shift(4) #=>#<DateTimeIndex:83979630 offset=YEAR periods=10 data=[2016-01-01T00:00:00+00:00...2025-01-01T00:00:00+00:00]>
[ "Shift", "all", "dates", "in", "the", "index", "by", "a", "positive", "number", "in", "the", "future", ".", "The", "dates", "are", "shifted", "by", "the", "same", "amount", "as", "that", "specified", "in", "the", "offset", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/date_time/index.rb#L448-L453
train
SciRuby/daru
lib/daru/date_time/index.rb
Daru.DateTimeIndex.lag
def lag distance distance.is_a?(Integer) && distance < 0 and raise IndexError, "Distance #{distance} cannot be negative" _shift(-distance) end
ruby
def lag distance distance.is_a?(Integer) && distance < 0 and raise IndexError, "Distance #{distance} cannot be negative" _shift(-distance) end
[ "def", "lag", "distance", "distance", ".", "is_a?", "(", "Integer", ")", "&&", "distance", "<", "0", "and", "raise", "IndexError", ",", "\"Distance #{distance} cannot be negative\"", "_shift", "(", "-", "distance", ")", "end" ]
Shift all dates in the index to the past. The dates are shifted by the same amount as that specified in the offset. @param [Integer, Daru::DateOffset, Daru::Offsets::*] distance Integer or Daru::DateOffset. Distance by which each date should be shifted. Passing an offset object to #lag will offset each data point by the offset value. Passing a positive integer will offset each data point by the same offset that it was created with. @return [DateTimeIndex] A new lagged DateTimeIndex object.
[ "Shift", "all", "dates", "in", "the", "index", "to", "the", "past", ".", "The", "dates", "are", "shifted", "by", "the", "same", "amount", "as", "that", "specified", "in", "the", "offset", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/date_time/index.rb#L464-L469
train
SciRuby/daru
lib/daru/date_time/index.rb
Daru.DateTimeIndex.include?
def include? date_time return false unless date_time.is_a?(String) || date_time.is_a?(DateTime) if date_time.is_a?(String) date_precision = Helper.determine_date_precision_of date_time date_time = Helper.date_time_from date_time, date_precision end result, = @data.bsearch { |d| d[0] >= date_time } result && result == date_time end
ruby
def include? date_time return false unless date_time.is_a?(String) || date_time.is_a?(DateTime) if date_time.is_a?(String) date_precision = Helper.determine_date_precision_of date_time date_time = Helper.date_time_from date_time, date_precision end result, = @data.bsearch { |d| d[0] >= date_time } result && result == date_time end
[ "def", "include?", "date_time", "return", "false", "unless", "date_time", ".", "is_a?", "(", "String", ")", "||", "date_time", ".", "is_a?", "(", "DateTime", ")", "if", "date_time", ".", "is_a?", "(", "String", ")", "date_precision", "=", "Helper", ".", "determine_date_precision_of", "date_time", "date_time", "=", "Helper", ".", "date_time_from", "date_time", ",", "date_precision", "end", "result", ",", "=", "@data", ".", "bsearch", "{", "|", "d", "|", "d", "[", "0", "]", ">=", "date_time", "}", "result", "&&", "result", "==", "date_time", "end" ]
Check if a date exists in the index. Will be inferred from string in case you pass a string. Recommened specifying the full date as a DateTime object.
[ "Check", "if", "a", "date", "exists", "in", "the", "index", ".", "Will", "be", "inferred", "from", "string", "in", "case", "you", "pass", "a", "string", ".", "Recommened", "specifying", "the", "full", "date", "as", "a", "DateTime", "object", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/date_time/index.rb#L505-L515
train
SciRuby/daru
lib/daru/category.rb
Daru.Category.initialize_category
def initialize_category data, opts={} @type = :category initialize_core_attributes data if opts[:categories] validate_categories(opts[:categories]) add_extra_categories(opts[:categories] - categories) order_with opts[:categories] end # Specify if the categories are ordered or not. # By default its unordered @ordered = opts[:ordered] || false # The coding scheme to code with. Default is dummy coding. @coding_scheme = :dummy # Base category which won't be present in the coding @base_category = @cat_hash.keys.first # Stores the name of the vector @name = opts[:name] # Index of the vector @index = coerce_index opts[:index] self end
ruby
def initialize_category data, opts={} @type = :category initialize_core_attributes data if opts[:categories] validate_categories(opts[:categories]) add_extra_categories(opts[:categories] - categories) order_with opts[:categories] end # Specify if the categories are ordered or not. # By default its unordered @ordered = opts[:ordered] || false # The coding scheme to code with. Default is dummy coding. @coding_scheme = :dummy # Base category which won't be present in the coding @base_category = @cat_hash.keys.first # Stores the name of the vector @name = opts[:name] # Index of the vector @index = coerce_index opts[:index] self end
[ "def", "initialize_category", "data", ",", "opts", "=", "{", "}", "@type", "=", ":category", "initialize_core_attributes", "data", "if", "opts", "[", ":categories", "]", "validate_categories", "(", "opts", "[", ":categories", "]", ")", "add_extra_categories", "(", "opts", "[", ":categories", "]", "-", "categories", ")", "order_with", "opts", "[", ":categories", "]", "end", "# Specify if the categories are ordered or not.", "# By default its unordered", "@ordered", "=", "opts", "[", ":ordered", "]", "||", "false", "# The coding scheme to code with. Default is dummy coding.", "@coding_scheme", "=", ":dummy", "# Base category which won't be present in the coding", "@base_category", "=", "@cat_hash", ".", "keys", ".", "first", "# Stores the name of the vector", "@name", "=", "opts", "[", ":name", "]", "# Index of the vector", "@index", "=", "coerce_index", "opts", "[", ":index", "]", "self", "end" ]
Initializes a vector to store categorical data. @note Base category is set to the first category encountered in the vector. @param [Array] data the categorical data @param [Hash] opts the options @option opts [Boolean] :ordered true if data is ordered, false otherwise @option opts [Array] :categories categories to associate with the vector. It add extra categories if specified and provides order of categories also. @option opts [object] :index gives index to vector. By default its from 0 to size-1 @return the categorical data created @example dv = Daru::Vector.new [:a, 1, :a, 1, :c], type: :category, ordered: true, categories: [:a, :b, :c, 1] # => #<Daru::Vector(5)> # 0 a # 1 1 # 2 a # 3 1 # 4 c
[ "Initializes", "a", "vector", "to", "store", "categorical", "data", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/category.rb#L28-L55
train
SciRuby/daru
lib/daru/category.rb
Daru.Category.count
def count category=UNDEFINED return @cat_hash.values.map(&:size).inject(&:+) if category == UNDEFINED # count all raise ArgumentError, "Invalid category #{category}" unless categories.include?(category) @cat_hash[category].size end
ruby
def count category=UNDEFINED return @cat_hash.values.map(&:size).inject(&:+) if category == UNDEFINED # count all raise ArgumentError, "Invalid category #{category}" unless categories.include?(category) @cat_hash[category].size end
[ "def", "count", "category", "=", "UNDEFINED", "return", "@cat_hash", ".", "values", ".", "map", "(", ":size", ")", ".", "inject", "(", ":+", ")", "if", "category", "==", "UNDEFINED", "# count all", "raise", "ArgumentError", ",", "\"Invalid category #{category}\"", "unless", "categories", ".", "include?", "(", "category", ")", "@cat_hash", "[", "category", "]", ".", "size", "end" ]
Returns frequency of given category @param [object] category given category whose count has to be founded @return count/frequency of given category @example dv = Daru::Vector.new [:a, 1, :a, 1, :c], type: :category dv.count :a # => 2 dv.count # => 5
[ "Returns", "frequency", "of", "given", "category" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/category.rb#L145-L151
train
SciRuby/daru
lib/daru/category.rb
Daru.Category.at
def at *positions original_positions = positions positions = coerce_positions(*positions) validate_positions(*positions) return category_from_position(positions) if positions.is_a? Integer Daru::Vector.new positions.map { |pos| category_from_position(pos) }, index: @index.at(*original_positions), name: @name, type: :category, ordered: @ordered, categories: categories end
ruby
def at *positions original_positions = positions positions = coerce_positions(*positions) validate_positions(*positions) return category_from_position(positions) if positions.is_a? Integer Daru::Vector.new positions.map { |pos| category_from_position(pos) }, index: @index.at(*original_positions), name: @name, type: :category, ordered: @ordered, categories: categories end
[ "def", "at", "*", "positions", "original_positions", "=", "positions", "positions", "=", "coerce_positions", "(", "positions", ")", "validate_positions", "(", "positions", ")", "return", "category_from_position", "(", "positions", ")", "if", "positions", ".", "is_a?", "Integer", "Daru", "::", "Vector", ".", "new", "positions", ".", "map", "{", "|", "pos", "|", "category_from_position", "(", "pos", ")", "}", ",", "index", ":", "@index", ".", "at", "(", "original_positions", ")", ",", "name", ":", "@name", ",", "type", ":", ":category", ",", "ordered", ":", "@ordered", ",", "categories", ":", "categories", "end" ]
Returns vector for positions specified. @param [Array] positions at which values to be retrived. @return vector containing values specified at specified positions @example dv = Daru::Vector.new [:a, 1, :a, 1, :c], type: :category dv.at 0..-2 # => #<Daru::Vector(4)> # 0 a # 1 1 # 2 a # 3 1
[ "Returns", "vector", "for", "positions", "specified", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/category.rb#L221-L234
train
SciRuby/daru
lib/daru/category.rb
Daru.Category.set_at
def set_at positions, val validate_positions(*positions) positions.map { |pos| modify_category_at pos, val } self end
ruby
def set_at positions, val validate_positions(*positions) positions.map { |pos| modify_category_at pos, val } self end
[ "def", "set_at", "positions", ",", "val", "validate_positions", "(", "positions", ")", "positions", ".", "map", "{", "|", "pos", "|", "modify_category_at", "pos", ",", "val", "}", "self", "end" ]
Modifies values at specified positions. @param [Array] positions positions at which to modify value @param [object] val value to assign at specific positions @return modified vector @example dv = Daru::Vector.new [:a, 1, :a, 1, :c], type: :category dv.add_category :b dv.set_at [0, 1], :b # => #<Daru::Vector(5)> # 0 b # 1 b # 2 a # 3 1 # 4 c
[ "Modifies", "values", "at", "specified", "positions", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/category.rb#L277-L281
train
SciRuby/daru
lib/daru/category.rb
Daru.Category.rename_categories
def rename_categories old_to_new old_categories = categories data = to_a.map do |cat| old_to_new.include?(cat) ? old_to_new[cat] : cat end initialize_core_attributes data self.categories = (old_categories - old_to_new.keys) | old_to_new.values self.base_category = old_to_new[base_category] if old_to_new.include? base_category self end
ruby
def rename_categories old_to_new old_categories = categories data = to_a.map do |cat| old_to_new.include?(cat) ? old_to_new[cat] : cat end initialize_core_attributes data self.categories = (old_categories - old_to_new.keys) | old_to_new.values self.base_category = old_to_new[base_category] if old_to_new.include? base_category self end
[ "def", "rename_categories", "old_to_new", "old_categories", "=", "categories", "data", "=", "to_a", ".", "map", "do", "|", "cat", "|", "old_to_new", ".", "include?", "(", "cat", ")", "?", "old_to_new", "[", "cat", "]", ":", "cat", "end", "initialize_core_attributes", "data", "self", ".", "categories", "=", "(", "old_categories", "-", "old_to_new", ".", "keys", ")", "|", "old_to_new", ".", "values", "self", ".", "base_category", "=", "old_to_new", "[", "base_category", "]", "if", "old_to_new", ".", "include?", "base_category", "self", "end" ]
Rename categories. @note The order of categories after renaming is preserved but new categories are added at the end in the order. Also the base-category is reassigned to new value if it is renamed @param [Hash] old_to_new a hash mapping categories whose name to be changed to their new names @example dv = Daru::Vector.new [:a, 1, :a, 1, :c], type: :category dv.rename_categories :a => :b dv # => #<Daru::Vector(5)> # 0 b # 1 1 # 2 b # 3 1 # 4 c
[ "Rename", "categories", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/category.rb#L358-L369
train
SciRuby/daru
lib/daru/category.rb
Daru.Category.remove_unused_categories
def remove_unused_categories old_categories = categories initialize_core_attributes to_a self.categories = old_categories & categories self.base_category = @cat_hash.keys.first unless categories.include? base_category self end
ruby
def remove_unused_categories old_categories = categories initialize_core_attributes to_a self.categories = old_categories & categories self.base_category = @cat_hash.keys.first unless categories.include? base_category self end
[ "def", "remove_unused_categories", "old_categories", "=", "categories", "initialize_core_attributes", "to_a", "self", ".", "categories", "=", "old_categories", "&", "categories", "self", ".", "base_category", "=", "@cat_hash", ".", "keys", ".", "first", "unless", "categories", ".", "include?", "base_category", "self", "end" ]
Removes the unused categories @note If base category is removed, then the first occuring category in the data is taken as base category. Order of the undeleted categories remains preserved. @return [Daru::Vector] Makes changes in the vector itself i.e. deletes the unused categories and returns itself @example dv = Daru::Vector.new [:one, :two, :one], type: :category, categories: [:three, :two, :one] dv.remove_unused_categories dv.categories # => [:two, :one]
[ "Removes", "the", "unused", "categories" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/category.rb#L383-L391
train
SciRuby/daru
lib/daru/category.rb
Daru.Category.sort!
def sort! # rubocop:disable Metrics/AbcSize # TODO: Simply the code assert_ordered :sort # Build sorted index old_index = @index.to_a new_index = @cat_hash.values.map do |positions| old_index.values_at(*positions) end.flatten @index = @index.class.new new_index # Build sorted data @cat_hash = categories.inject([{}, 0]) do |acc, cat| hash, count = acc cat_count = @cat_hash[cat].size cat_count.times { |i| @array[count+i] = int_from_cat(cat) } hash[cat] = (count...(cat_count+count)).to_a [hash, count + cat_count] end.first self end
ruby
def sort! # rubocop:disable Metrics/AbcSize # TODO: Simply the code assert_ordered :sort # Build sorted index old_index = @index.to_a new_index = @cat_hash.values.map do |positions| old_index.values_at(*positions) end.flatten @index = @index.class.new new_index # Build sorted data @cat_hash = categories.inject([{}, 0]) do |acc, cat| hash, count = acc cat_count = @cat_hash[cat].size cat_count.times { |i| @array[count+i] = int_from_cat(cat) } hash[cat] = (count...(cat_count+count)).to_a [hash, count + cat_count] end.first self end
[ "def", "sort!", "# rubocop:disable Metrics/AbcSize", "# TODO: Simply the code", "assert_ordered", ":sort", "# Build sorted index", "old_index", "=", "@index", ".", "to_a", "new_index", "=", "@cat_hash", ".", "values", ".", "map", "do", "|", "positions", "|", "old_index", ".", "values_at", "(", "positions", ")", "end", ".", "flatten", "@index", "=", "@index", ".", "class", ".", "new", "new_index", "# Build sorted data", "@cat_hash", "=", "categories", ".", "inject", "(", "[", "{", "}", ",", "0", "]", ")", "do", "|", "acc", ",", "cat", "|", "hash", ",", "count", "=", "acc", "cat_count", "=", "@cat_hash", "[", "cat", "]", ".", "size", "cat_count", ".", "times", "{", "|", "i", "|", "@array", "[", "count", "+", "i", "]", "=", "int_from_cat", "(", "cat", ")", "}", "hash", "[", "cat", "]", "=", "(", "count", "...", "(", "cat_count", "+", "count", ")", ")", ".", "to_a", "[", "hash", ",", "count", "+", "cat_count", "]", "end", ".", "first", "self", "end" ]
Sorts the vector in the order specified. @note This operation will only work if vector is ordered. To set the vector ordered, do `vector.ordered = true` @return [Daru::Vector] sorted vector @example dv = Daru::Vector.new ['second', 'second', 'third', 'first'], categories: ['first', 'second', 'thrid'], type: :categories, ordered: true dv.sort! # => #<Daru::Vector(4)> # 3 first # 0 second # 1 second # 2 third
[ "Sorts", "the", "vector", "in", "the", "order", "specified", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/category.rb#L436-L457
train
SciRuby/daru
lib/daru/category.rb
Daru.Category.reindex!
def reindex! idx idx = Daru::Index.new idx unless idx.is_a? Daru::Index raise ArgumentError, 'Invalid index specified' unless idx.to_a.sort == index.to_a.sort old_categories = categories data = idx.map { |i| self[i] } initialize_core_attributes data self.categories = old_categories self.index = idx self end
ruby
def reindex! idx idx = Daru::Index.new idx unless idx.is_a? Daru::Index raise ArgumentError, 'Invalid index specified' unless idx.to_a.sort == index.to_a.sort old_categories = categories data = idx.map { |i| self[i] } initialize_core_attributes data self.categories = old_categories self.index = idx self end
[ "def", "reindex!", "idx", "idx", "=", "Daru", "::", "Index", ".", "new", "idx", "unless", "idx", ".", "is_a?", "Daru", "::", "Index", "raise", "ArgumentError", ",", "'Invalid index specified'", "unless", "idx", ".", "to_a", ".", "sort", "==", "index", ".", "to_a", ".", "sort", "old_categories", "=", "categories", "data", "=", "idx", ".", "map", "{", "|", "i", "|", "self", "[", "i", "]", "}", "initialize_core_attributes", "data", "self", ".", "categories", "=", "old_categories", "self", ".", "index", "=", "idx", "self", "end" ]
Sets new index for vector. Preserves index->value correspondence. @note Unlike #reorder! which takes positions as input it takes index as an input to reorder the vector @param [Daru::Index, Daru::MultiIndex, Array] idx new index to order with @return [Daru::Vector] vector reindexed with new index @example dv = Daru::Vector.new [3, 2, 1], index: ['c', 'b', 'a'], type: :category dv.reindex! ['a', 'b', 'c'] # => #<Daru::Vector(3)> # a 1 # b 2 # c 3
[ "Sets", "new", "index", "for", "vector", ".", "Preserves", "index", "-", ">", "value", "correspondence", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/category.rb#L565-L576
train
SciRuby/daru
lib/daru/category.rb
Daru.Category.count_values
def count_values(*values) values.map { |v| @cat_hash[v].size if @cat_hash.include? v } .compact .inject(0, :+) end
ruby
def count_values(*values) values.map { |v| @cat_hash[v].size if @cat_hash.include? v } .compact .inject(0, :+) end
[ "def", "count_values", "(", "*", "values", ")", "values", ".", "map", "{", "|", "v", "|", "@cat_hash", "[", "v", "]", ".", "size", "if", "@cat_hash", ".", "include?", "v", "}", ".", "compact", ".", "inject", "(", "0", ",", ":+", ")", "end" ]
Count the number of values specified @param [Array] values to count for @return [Integer] the number of times the values mentioned occurs @example dv = Daru::Vector.new [1, 2, 1, 2, 3, 4, nil, nil] dv.count_values nil # => 2
[ "Count", "the", "number", "of", "values", "specified" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/category.rb#L710-L714
train
SciRuby/daru
lib/daru/category.rb
Daru.Category.indexes
def indexes(*values) values &= categories index.to_a.values_at(*values.flat_map { |v| @cat_hash[v] }.sort) end
ruby
def indexes(*values) values &= categories index.to_a.values_at(*values.flat_map { |v| @cat_hash[v] }.sort) end
[ "def", "indexes", "(", "*", "values", ")", "values", "&=", "categories", "index", ".", "to_a", ".", "values_at", "(", "values", ".", "flat_map", "{", "|", "v", "|", "@cat_hash", "[", "v", "]", "}", ".", "sort", ")", "end" ]
Return indexes of values specified @param [Array] values to find indexes for @return [Array] array of indexes of values specified @example dv = Daru::Vector.new [1, 2, nil, Float::NAN], index: 11..14 dv.indexes nil, Float::NAN # => [13, 14]
[ "Return", "indexes", "of", "values", "specified" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/category.rb#L723-L726
train
lsegal/yard
lib/yard/logging.rb
YARD.Logger.progress
def progress(msg, nontty_log = :debug) send(nontty_log, msg) if nontty_log return unless show_progress icon = "" if defined?(::Encoding) icon = PROGRESS_INDICATORS[@progress_indicator] + " " end @mutex.synchronize do print("\e[2K\e[?25l\e[1m#{icon}#{msg}\e[0m\r") @progress_msg = msg if Time.now - @progress_last_update > 0.2 @progress_indicator += 1 @progress_indicator %= PROGRESS_INDICATORS.size @progress_last_update = Time.now end end Thread.new do sleep(0.05) progress(msg + ".", nil) if @progress_msg == msg end end
ruby
def progress(msg, nontty_log = :debug) send(nontty_log, msg) if nontty_log return unless show_progress icon = "" if defined?(::Encoding) icon = PROGRESS_INDICATORS[@progress_indicator] + " " end @mutex.synchronize do print("\e[2K\e[?25l\e[1m#{icon}#{msg}\e[0m\r") @progress_msg = msg if Time.now - @progress_last_update > 0.2 @progress_indicator += 1 @progress_indicator %= PROGRESS_INDICATORS.size @progress_last_update = Time.now end end Thread.new do sleep(0.05) progress(msg + ".", nil) if @progress_msg == msg end end
[ "def", "progress", "(", "msg", ",", "nontty_log", "=", ":debug", ")", "send", "(", "nontty_log", ",", "msg", ")", "if", "nontty_log", "return", "unless", "show_progress", "icon", "=", "\"\"", "if", "defined?", "(", "::", "Encoding", ")", "icon", "=", "PROGRESS_INDICATORS", "[", "@progress_indicator", "]", "+", "\" \"", "end", "@mutex", ".", "synchronize", "do", "print", "(", "\"\\e[2K\\e[?25l\\e[1m#{icon}#{msg}\\e[0m\\r\"", ")", "@progress_msg", "=", "msg", "if", "Time", ".", "now", "-", "@progress_last_update", ">", "0.2", "@progress_indicator", "+=", "1", "@progress_indicator", "%=", "PROGRESS_INDICATORS", ".", "size", "@progress_last_update", "=", "Time", ".", "now", "end", "end", "Thread", ".", "new", "do", "sleep", "(", "0.05", ")", "progress", "(", "msg", "+", "\".\"", ",", "nil", ")", "if", "@progress_msg", "==", "msg", "end", "end" ]
Displays a progress indicator for a given message. This progress report is only displayed on TTY displays, otherwise the message is passed to the +nontty_log+ level. @param [String] msg the message to log @param [Symbol, nil] nontty_log the level to log as if the output stream is not a TTY. Use +nil+ for no alternate logging. @return [void] @since 0.8.2
[ "Displays", "a", "progress", "indicator", "for", "a", "given", "message", ".", "This", "progress", "report", "is", "only", "displayed", "on", "TTY", "displays", "otherwise", "the", "message", "is", "passed", "to", "the", "+", "nontty_log", "+", "level", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/logging.rb#L96-L116
train
lsegal/yard
lib/yard/logging.rb
YARD.Logger.backtrace
def backtrace(exc, level_meth = :error) return unless show_backtraces send(level_meth, "#{exc.class.class_name}: #{exc.message}") send(level_meth, "Stack trace:" + exc.backtrace[0..5].map {|x| "\n\t#{x}" }.join + "\n") end
ruby
def backtrace(exc, level_meth = :error) return unless show_backtraces send(level_meth, "#{exc.class.class_name}: #{exc.message}") send(level_meth, "Stack trace:" + exc.backtrace[0..5].map {|x| "\n\t#{x}" }.join + "\n") end
[ "def", "backtrace", "(", "exc", ",", "level_meth", "=", ":error", ")", "return", "unless", "show_backtraces", "send", "(", "level_meth", ",", "\"#{exc.class.class_name}: #{exc.message}\"", ")", "send", "(", "level_meth", ",", "\"Stack trace:\"", "+", "exc", ".", "backtrace", "[", "0", "..", "5", "]", ".", "map", "{", "|", "x", "|", "\"\\n\\t#{x}\"", "}", ".", "join", "+", "\"\\n\"", ")", "end" ]
Prints the backtrace +exc+ to the logger as error data. @param [Array<String>] exc the backtrace list @param [Symbol] level_meth the level to log backtrace at @return [void]
[ "Prints", "the", "backtrace", "+", "exc", "+", "to", "the", "logger", "as", "error", "data", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/logging.rb#L154-L159
train
lsegal/yard
lib/yard/docstring_parser.rb
YARD.DocstringParser.tag_is_directive?
def tag_is_directive?(tag_name) list = %w(attribute endgroup group macro method scope visibility) list.include?(tag_name) end
ruby
def tag_is_directive?(tag_name) list = %w(attribute endgroup group macro method scope visibility) list.include?(tag_name) end
[ "def", "tag_is_directive?", "(", "tag_name", ")", "list", "=", "%w(", "attribute", "endgroup", "group", "macro", "method", "scope", "visibility", ")", "list", ".", "include?", "(", "tag_name", ")", "end" ]
Backward compatibility to detect old tags that should be specified as directives in 0.8 and onward.
[ "Backward", "compatibility", "to", "detect", "old", "tags", "that", "should", "be", "specified", "as", "directives", "in", "0", ".", "8", "and", "onward", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/docstring_parser.rb#L252-L255
train
lsegal/yard
lib/yard/verifier.rb
YARD.Verifier.call
def call(object) return true if object.is_a?(CodeObjects::Proxy) modify_nilclass @object = object retval = __execute ? true : false unmodify_nilclass retval end
ruby
def call(object) return true if object.is_a?(CodeObjects::Proxy) modify_nilclass @object = object retval = __execute ? true : false unmodify_nilclass retval end
[ "def", "call", "(", "object", ")", "return", "true", "if", "object", ".", "is_a?", "(", "CodeObjects", "::", "Proxy", ")", "modify_nilclass", "@object", "=", "object", "retval", "=", "__execute", "?", "true", ":", "false", "unmodify_nilclass", "retval", "end" ]
Tests the expressions on the object. @note If the object is a {CodeObjects::Proxy} the result will always be true. @param [CodeObjects::Base] object the object to verify @return [Boolean] the result of the expressions
[ "Tests", "the", "expressions", "on", "the", "object", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/verifier.rb#L76-L83
train
lsegal/yard
lib/yard/code_objects/class_object.rb
YARD::CodeObjects.ClassObject.inheritance_tree
def inheritance_tree(include_mods = false) list = (include_mods ? mixins(:instance, :class) : []) if superclass.is_a?(Proxy) || superclass.respond_to?(:inheritance_tree) list += [superclass] unless superclass == P(:Object) || superclass == P(:BasicObject) end [self] + list.map do |m| next m if m == self next m unless m.respond_to?(:inheritance_tree) m.inheritance_tree(include_mods) end.flatten.uniq end
ruby
def inheritance_tree(include_mods = false) list = (include_mods ? mixins(:instance, :class) : []) if superclass.is_a?(Proxy) || superclass.respond_to?(:inheritance_tree) list += [superclass] unless superclass == P(:Object) || superclass == P(:BasicObject) end [self] + list.map do |m| next m if m == self next m unless m.respond_to?(:inheritance_tree) m.inheritance_tree(include_mods) end.flatten.uniq end
[ "def", "inheritance_tree", "(", "include_mods", "=", "false", ")", "list", "=", "(", "include_mods", "?", "mixins", "(", ":instance", ",", ":class", ")", ":", "[", "]", ")", "if", "superclass", ".", "is_a?", "(", "Proxy", ")", "||", "superclass", ".", "respond_to?", "(", ":inheritance_tree", ")", "list", "+=", "[", "superclass", "]", "unless", "superclass", "==", "P", "(", ":Object", ")", "||", "superclass", "==", "P", "(", ":BasicObject", ")", "end", "[", "self", "]", "+", "list", ".", "map", "do", "|", "m", "|", "next", "m", "if", "m", "==", "self", "next", "m", "unless", "m", ".", "respond_to?", "(", ":inheritance_tree", ")", "m", ".", "inheritance_tree", "(", "include_mods", ")", "end", ".", "flatten", ".", "uniq", "end" ]
Returns the inheritance tree of the object including self. @param [Boolean] include_mods whether or not to include mixins in the inheritance tree. @return [Array<NamespaceObject>] the list of code objects that make up the inheritance tree.
[ "Returns", "the", "inheritance", "tree", "of", "the", "object", "including", "self", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/class_object.rb#L45-L55
train
lsegal/yard
lib/yard/code_objects/class_object.rb
YARD::CodeObjects.ClassObject.meths
def meths(opts = {}) opts = SymbolHash[:inherited => true].update(opts) list = super(opts) list += inherited_meths(opts).reject do |o| next(false) if opts[:all] list.find {|o2| o2.name == o.name && o2.scope == o.scope } end if opts[:inherited] list end
ruby
def meths(opts = {}) opts = SymbolHash[:inherited => true].update(opts) list = super(opts) list += inherited_meths(opts).reject do |o| next(false) if opts[:all] list.find {|o2| o2.name == o.name && o2.scope == o.scope } end if opts[:inherited] list end
[ "def", "meths", "(", "opts", "=", "{", "}", ")", "opts", "=", "SymbolHash", "[", ":inherited", "=>", "true", "]", ".", "update", "(", "opts", ")", "list", "=", "super", "(", "opts", ")", "list", "+=", "inherited_meths", "(", "opts", ")", ".", "reject", "do", "|", "o", "|", "next", "(", "false", ")", "if", "opts", "[", ":all", "]", "list", ".", "find", "{", "|", "o2", "|", "o2", ".", "name", "==", "o", ".", "name", "&&", "o2", ".", "scope", "==", "o", ".", "scope", "}", "end", "if", "opts", "[", ":inherited", "]", "list", "end" ]
Returns the list of methods matching the options hash. Returns all methods if hash is empty. @param [Hash] opts the options hash to match @option opts [Boolean] :inherited (true) whether inherited methods should be included in the list @option opts [Boolean] :included (true) whether mixed in methods should be included in the list @return [Array<MethodObject>] the list of methods that matched
[ "Returns", "the", "list", "of", "methods", "matching", "the", "options", "hash", ".", "Returns", "all", "methods", "if", "hash", "is", "empty", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/class_object.rb#L66-L74
train
lsegal/yard
lib/yard/code_objects/class_object.rb
YARD::CodeObjects.ClassObject.inherited_meths
def inherited_meths(opts = {}) inheritance_tree[1..-1].inject([]) do |list, superclass| if superclass.is_a?(Proxy) list else list += superclass.meths(opts).reject do |o| next(false) if opts[:all] child(:name => o.name, :scope => o.scope) || list.find {|o2| o2.name == o.name && o2.scope == o.scope } end end end end
ruby
def inherited_meths(opts = {}) inheritance_tree[1..-1].inject([]) do |list, superclass| if superclass.is_a?(Proxy) list else list += superclass.meths(opts).reject do |o| next(false) if opts[:all] child(:name => o.name, :scope => o.scope) || list.find {|o2| o2.name == o.name && o2.scope == o.scope } end end end end
[ "def", "inherited_meths", "(", "opts", "=", "{", "}", ")", "inheritance_tree", "[", "1", "..", "-", "1", "]", ".", "inject", "(", "[", "]", ")", "do", "|", "list", ",", "superclass", "|", "if", "superclass", ".", "is_a?", "(", "Proxy", ")", "list", "else", "list", "+=", "superclass", ".", "meths", "(", "opts", ")", ".", "reject", "do", "|", "o", "|", "next", "(", "false", ")", "if", "opts", "[", ":all", "]", "child", "(", ":name", "=>", "o", ".", "name", ",", ":scope", "=>", "o", ".", "scope", ")", "||", "list", ".", "find", "{", "|", "o2", "|", "o2", ".", "name", "==", "o", ".", "name", "&&", "o2", ".", "scope", "==", "o", ".", "scope", "}", "end", "end", "end", "end" ]
Returns only the methods that were inherited. @return [Array<MethodObject>] the list of inherited method objects
[ "Returns", "only", "the", "methods", "that", "were", "inherited", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/class_object.rb#L79-L91
train
lsegal/yard
lib/yard/code_objects/class_object.rb
YARD::CodeObjects.ClassObject.constants
def constants(opts = {}) opts = SymbolHash[:inherited => true].update(opts) super(opts) + (opts[:inherited] ? inherited_constants : []) end
ruby
def constants(opts = {}) opts = SymbolHash[:inherited => true].update(opts) super(opts) + (opts[:inherited] ? inherited_constants : []) end
[ "def", "constants", "(", "opts", "=", "{", "}", ")", "opts", "=", "SymbolHash", "[", ":inherited", "=>", "true", "]", ".", "update", "(", "opts", ")", "super", "(", "opts", ")", "+", "(", "opts", "[", ":inherited", "]", "?", "inherited_constants", ":", "[", "]", ")", "end" ]
Returns the list of constants matching the options hash. @param [Hash] opts the options hash to match @option opts [Boolean] :inherited (true) whether inherited constant should be included in the list @option opts [Boolean] :included (true) whether mixed in constant should be included in the list @return [Array<ConstantObject>] the list of constant that matched
[ "Returns", "the", "list", "of", "constants", "matching", "the", "options", "hash", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/class_object.rb#L101-L104
train
lsegal/yard
lib/yard/code_objects/class_object.rb
YARD::CodeObjects.ClassObject.inherited_constants
def inherited_constants inheritance_tree[1..-1].inject([]) do |list, superclass| if superclass.is_a?(Proxy) list else list += superclass.constants.reject do |o| child(:name => o.name) || list.find {|o2| o2.name == o.name } end end end end
ruby
def inherited_constants inheritance_tree[1..-1].inject([]) do |list, superclass| if superclass.is_a?(Proxy) list else list += superclass.constants.reject do |o| child(:name => o.name) || list.find {|o2| o2.name == o.name } end end end end
[ "def", "inherited_constants", "inheritance_tree", "[", "1", "..", "-", "1", "]", ".", "inject", "(", "[", "]", ")", "do", "|", "list", ",", "superclass", "|", "if", "superclass", ".", "is_a?", "(", "Proxy", ")", "list", "else", "list", "+=", "superclass", ".", "constants", ".", "reject", "do", "|", "o", "|", "child", "(", ":name", "=>", "o", ".", "name", ")", "||", "list", ".", "find", "{", "|", "o2", "|", "o2", ".", "name", "==", "o", ".", "name", "}", "end", "end", "end", "end" ]
Returns only the constants that were inherited. @return [Array<ConstantObject>] the list of inherited constant objects
[ "Returns", "only", "the", "constants", "that", "were", "inherited", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/class_object.rb#L109-L119
train
lsegal/yard
lib/yard/code_objects/class_object.rb
YARD::CodeObjects.ClassObject.superclass=
def superclass=(object) case object when Base, Proxy, NilClass @superclass = object when String, Symbol @superclass = Proxy.new(namespace, object) else raise ArgumentError, "superclass must be CodeObject, Proxy, String or Symbol" end if name == @superclass.name && namespace != YARD::Registry.root && !object.is_a?(Base) @superclass = Proxy.new(namespace.namespace, object) end if @superclass == self msg = "superclass #{@superclass.inspect} cannot be the same as the declared class #{inspect}" @superclass = P("::Object") raise ArgumentError, msg end end
ruby
def superclass=(object) case object when Base, Proxy, NilClass @superclass = object when String, Symbol @superclass = Proxy.new(namespace, object) else raise ArgumentError, "superclass must be CodeObject, Proxy, String or Symbol" end if name == @superclass.name && namespace != YARD::Registry.root && !object.is_a?(Base) @superclass = Proxy.new(namespace.namespace, object) end if @superclass == self msg = "superclass #{@superclass.inspect} cannot be the same as the declared class #{inspect}" @superclass = P("::Object") raise ArgumentError, msg end end
[ "def", "superclass", "=", "(", "object", ")", "case", "object", "when", "Base", ",", "Proxy", ",", "NilClass", "@superclass", "=", "object", "when", "String", ",", "Symbol", "@superclass", "=", "Proxy", ".", "new", "(", "namespace", ",", "object", ")", "else", "raise", "ArgumentError", ",", "\"superclass must be CodeObject, Proxy, String or Symbol\"", "end", "if", "name", "==", "@superclass", ".", "name", "&&", "namespace", "!=", "YARD", "::", "Registry", ".", "root", "&&", "!", "object", ".", "is_a?", "(", "Base", ")", "@superclass", "=", "Proxy", ".", "new", "(", "namespace", ".", "namespace", ",", "object", ")", "end", "if", "@superclass", "==", "self", "msg", "=", "\"superclass #{@superclass.inspect} cannot be the same as the declared class #{inspect}\"", "@superclass", "=", "P", "(", "\"::Object\"", ")", "raise", "ArgumentError", ",", "msg", "end", "end" ]
Sets the superclass of the object @param [Base, Proxy, String, Symbol, nil] object the superclass value @return [void]
[ "Sets", "the", "superclass", "of", "the", "object" ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/class_object.rb#L125-L144
train
lsegal/yard
lib/yard/registry_resolver.rb
YARD.RegistryResolver.collect_namespaces
def collect_namespaces(object) return [] unless object.respond_to?(:inheritance_tree) nss = object.inheritance_tree(true) if object.respond_to?(:superclass) nss |= [P('Object')] if object.superclass != P('BasicObject') nss |= [P('BasicObject')] end nss end
ruby
def collect_namespaces(object) return [] unless object.respond_to?(:inheritance_tree) nss = object.inheritance_tree(true) if object.respond_to?(:superclass) nss |= [P('Object')] if object.superclass != P('BasicObject') nss |= [P('BasicObject')] end nss end
[ "def", "collect_namespaces", "(", "object", ")", "return", "[", "]", "unless", "object", ".", "respond_to?", "(", ":inheritance_tree", ")", "nss", "=", "object", ".", "inheritance_tree", "(", "true", ")", "if", "object", ".", "respond_to?", "(", ":superclass", ")", "nss", "|=", "[", "P", "(", "'Object'", ")", "]", "if", "object", ".", "superclass", "!=", "P", "(", "'BasicObject'", ")", "nss", "|=", "[", "P", "(", "'BasicObject'", ")", "]", "end", "nss", "end" ]
Collects and returns all inherited namespaces for a given object
[ "Collects", "and", "returns", "all", "inherited", "namespaces", "for", "a", "given", "object" ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/registry_resolver.rb#L177-L187
train
lsegal/yard
lib/yard/options.rb
YARD.Options.update
def update(opts) opts = opts.to_hash if Options === opts opts.each do |key, value| self[key] = value end self end
ruby
def update(opts) opts = opts.to_hash if Options === opts opts.each do |key, value| self[key] = value end self end
[ "def", "update", "(", "opts", ")", "opts", "=", "opts", ".", "to_hash", "if", "Options", "===", "opts", "opts", ".", "each", "do", "|", "key", ",", "value", "|", "self", "[", "key", "]", "=", "value", "end", "self", "end" ]
Updates values from an options hash or options object on this object. All keys passed should be key names defined by attributes on the class. @example Updating a set of options on an Options object opts.update(:template => :guide, :type => :fulldoc) @param [Hash, Options] opts @return [self]
[ "Updates", "values", "from", "an", "options", "hash", "or", "options", "object", "on", "this", "object", ".", "All", "keys", "passed", "should", "be", "key", "names", "defined", "by", "attributes", "on", "the", "class", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/options.rb#L109-L115
train
lsegal/yard
lib/yard/options.rb
YARD.Options.each
def each instance_variables.each do |ivar| name = ivar.to_s.sub(/^@/, '') yield(name.to_sym, send(name)) end end
ruby
def each instance_variables.each do |ivar| name = ivar.to_s.sub(/^@/, '') yield(name.to_sym, send(name)) end end
[ "def", "each", "instance_variables", ".", "each", "do", "|", "ivar", "|", "name", "=", "ivar", ".", "to_s", ".", "sub", "(", "/", "/", ",", "''", ")", "yield", "(", "name", ".", "to_sym", ",", "send", "(", "name", ")", ")", "end", "end" ]
Yields over every option key and value @yield [key, value] every option key and value @yieldparam [Symbol] key the option key @yieldparam [Object] value the option value @return [void]
[ "Yields", "over", "every", "option", "key", "and", "value" ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/options.rb#L143-L148
train
lsegal/yard
lib/yard/options.rb
YARD.Options.reset_defaults
def reset_defaults names_set = {} self.class.ancestors.each do |klass| # look at all ancestors defaults = klass.instance_variable_defined?("@defaults") && klass.instance_variable_get("@defaults") next unless defaults defaults.each do |key, value| next if names_set[key] names_set[key] = true self[key] = Proc === value ? value.call : value end end end
ruby
def reset_defaults names_set = {} self.class.ancestors.each do |klass| # look at all ancestors defaults = klass.instance_variable_defined?("@defaults") && klass.instance_variable_get("@defaults") next unless defaults defaults.each do |key, value| next if names_set[key] names_set[key] = true self[key] = Proc === value ? value.call : value end end end
[ "def", "reset_defaults", "names_set", "=", "{", "}", "self", ".", "class", ".", "ancestors", ".", "each", "do", "|", "klass", "|", "# look at all ancestors", "defaults", "=", "klass", ".", "instance_variable_defined?", "(", "\"@defaults\"", ")", "&&", "klass", ".", "instance_variable_get", "(", "\"@defaults\"", ")", "next", "unless", "defaults", "defaults", ".", "each", "do", "|", "key", ",", "value", "|", "next", "if", "names_set", "[", "key", "]", "names_set", "[", "key", "]", "=", "true", "self", "[", "key", "]", "=", "Proc", "===", "value", "?", "value", ".", "call", ":", "value", "end", "end", "end" ]
Resets all values to their defaults. @abstract Subclasses should override this method to perform custom value initialization if not using {default_attr}. Be sure to call +super+ so that default initialization can take place. @return [void]
[ "Resets", "all", "values", "to", "their", "defaults", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/options.rb#L188-L201
train
lsegal/yard
lib/yard/templates/helpers/base_helper.rb
YARD::Templates::Helpers.BaseHelper.link_object
def link_object(obj, title = nil) return title if title case obj when YARD::CodeObjects::Base, YARD::CodeObjects::Proxy obj.title when String, Symbol P(obj).title else obj end end
ruby
def link_object(obj, title = nil) return title if title case obj when YARD::CodeObjects::Base, YARD::CodeObjects::Proxy obj.title when String, Symbol P(obj).title else obj end end
[ "def", "link_object", "(", "obj", ",", "title", "=", "nil", ")", "return", "title", "if", "title", "case", "obj", "when", "YARD", "::", "CodeObjects", "::", "Base", ",", "YARD", "::", "CodeObjects", "::", "Proxy", "obj", ".", "title", "when", "String", ",", "Symbol", "P", "(", "obj", ")", ".", "title", "else", "obj", "end", "end" ]
Links to an object with an optional title @param [CodeObjects::Base] obj the object to link to @param [String] title the title to use for the link @return [String] the linked object
[ "Links", "to", "an", "object", "with", "an", "optional", "title" ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/templates/helpers/base_helper.rb#L122-L133
train
lsegal/yard
lib/yard/templates/helpers/base_helper.rb
YARD::Templates::Helpers.BaseHelper.link_file
def link_file(filename, title = nil, anchor = nil) # rubocop:disable Lint/UnusedMethodArgument return filename.filename if CodeObjects::ExtraFileObject === filename filename end
ruby
def link_file(filename, title = nil, anchor = nil) # rubocop:disable Lint/UnusedMethodArgument return filename.filename if CodeObjects::ExtraFileObject === filename filename end
[ "def", "link_file", "(", "filename", ",", "title", "=", "nil", ",", "anchor", "=", "nil", ")", "# rubocop:disable Lint/UnusedMethodArgument", "return", "filename", ".", "filename", "if", "CodeObjects", "::", "ExtraFileObject", "===", "filename", "filename", "end" ]
Links to an extra file @param [String] filename the filename to link to @param [String] title the title of the link @param [String] anchor optional anchor @return [String] the link to the file @since 0.5.5
[ "Links", "to", "an", "extra", "file" ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/templates/helpers/base_helper.rb#L152-L155
train
lsegal/yard
lib/yard/rubygems/hook.rb
YARD.RubygemsHook.setup
def setup self.class.load_yard if File.exist?(@doc_dir) raise Gem::FilePermissionError, @doc_dir unless File.writable?(@doc_dir) else FileUtils.mkdir_p @doc_dir end end
ruby
def setup self.class.load_yard if File.exist?(@doc_dir) raise Gem::FilePermissionError, @doc_dir unless File.writable?(@doc_dir) else FileUtils.mkdir_p @doc_dir end end
[ "def", "setup", "self", ".", "class", ".", "load_yard", "if", "File", ".", "exist?", "(", "@doc_dir", ")", "raise", "Gem", "::", "FilePermissionError", ",", "@doc_dir", "unless", "File", ".", "writable?", "(", "@doc_dir", ")", "else", "FileUtils", ".", "mkdir_p", "@doc_dir", "end", "end" ]
Prepares the spec for documentation generation
[ "Prepares", "the", "spec", "for", "documentation", "generation" ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/rubygems/hook.rb#L162-L170
train
lsegal/yard
lib/yard/code_objects/method_object.rb
YARD::CodeObjects.MethodObject.scope=
def scope=(v) reregister = @scope ? true : false # handle module function if v == :module other = self.class.new(namespace, name) other.visibility = :private @visibility = :public @module_function = true @path = nil end YARD::Registry.delete(self) @path = nil @scope = v.to_sym @scope = :class if @scope == :module YARD::Registry.register(self) if reregister end
ruby
def scope=(v) reregister = @scope ? true : false # handle module function if v == :module other = self.class.new(namespace, name) other.visibility = :private @visibility = :public @module_function = true @path = nil end YARD::Registry.delete(self) @path = nil @scope = v.to_sym @scope = :class if @scope == :module YARD::Registry.register(self) if reregister end
[ "def", "scope", "=", "(", "v", ")", "reregister", "=", "@scope", "?", "true", ":", "false", "# handle module function", "if", "v", "==", ":module", "other", "=", "self", ".", "class", ".", "new", "(", "namespace", ",", "name", ")", "other", ".", "visibility", "=", ":private", "@visibility", "=", ":public", "@module_function", "=", "true", "@path", "=", "nil", "end", "YARD", "::", "Registry", ".", "delete", "(", "self", ")", "@path", "=", "nil", "@scope", "=", "v", ".", "to_sym", "@scope", "=", ":class", "if", "@scope", "==", ":module", "YARD", "::", "Registry", ".", "register", "(", "self", ")", "if", "reregister", "end" ]
Creates a new method object in +namespace+ with +name+ and an instance or class +scope+ If scope is +:module+, this object is instantiated as a public method in +:class+ scope, but also creates a new (empty) method as a private +:instance+ method on the same class or module. @param [NamespaceObject] namespace the namespace @param [String, Symbol] name the method name @param [Symbol] scope +:instance+, +:class+, or +:module+ Changes the scope of an object from :instance or :class @param [Symbol] v the new scope
[ "Creates", "a", "new", "method", "object", "in", "+", "namespace", "+", "with", "+", "name", "+", "and", "an", "instance", "or", "class", "+", "scope", "+" ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/method_object.rb#L58-L75
train
lsegal/yard
lib/yard/code_objects/method_object.rb
YARD::CodeObjects.MethodObject.is_attribute?
def is_attribute? info = attr_info if info read_or_write = name.to_s =~ /=$/ ? :write : :read info[read_or_write] ? true : false else false end end
ruby
def is_attribute? info = attr_info if info read_or_write = name.to_s =~ /=$/ ? :write : :read info[read_or_write] ? true : false else false end end
[ "def", "is_attribute?", "info", "=", "attr_info", "if", "info", "read_or_write", "=", "name", ".", "to_s", "=~", "/", "/", "?", ":write", ":", ":read", "info", "[", "read_or_write", "]", "?", "true", ":", "false", "else", "false", "end", "end" ]
Tests if the object is defined as an attribute in the namespace @return [Boolean] whether the object is an attribute
[ "Tests", "if", "the", "object", "is", "defined", "as", "an", "attribute", "in", "the", "namespace" ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/method_object.rb#L114-L122
train
lsegal/yard
lib/yard/code_objects/method_object.rb
YARD::CodeObjects.MethodObject.sep
def sep if scope == :class namespace && namespace != YARD::Registry.root ? CSEP : NSEP else ISEP end end
ruby
def sep if scope == :class namespace && namespace != YARD::Registry.root ? CSEP : NSEP else ISEP end end
[ "def", "sep", "if", "scope", "==", ":class", "namespace", "&&", "namespace", "!=", "YARD", "::", "Registry", ".", "root", "?", "CSEP", ":", "NSEP", "else", "ISEP", "end", "end" ]
Override separator to differentiate between class and instance methods. @return [String] "#" for an instance method, "." for class
[ "Override", "separator", "to", "differentiate", "between", "class", "and", "instance", "methods", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/method_object.rb#L182-L188
train
lsegal/yard
lib/yard/registry_store.rb
YARD.RegistryStore.put
def put(key, value) if key == '' @object_types[:root] = [:root] @store[:root] = value else @notfound.delete(key.to_sym) (@object_types[value.type] ||= []) << key.to_s if @store[key.to_sym] @object_types[@store[key.to_sym].type].delete(key.to_s) end @store[key.to_sym] = value end end
ruby
def put(key, value) if key == '' @object_types[:root] = [:root] @store[:root] = value else @notfound.delete(key.to_sym) (@object_types[value.type] ||= []) << key.to_s if @store[key.to_sym] @object_types[@store[key.to_sym].type].delete(key.to_s) end @store[key.to_sym] = value end end
[ "def", "put", "(", "key", ",", "value", ")", "if", "key", "==", "''", "@object_types", "[", ":root", "]", "=", "[", ":root", "]", "@store", "[", ":root", "]", "=", "value", "else", "@notfound", ".", "delete", "(", "key", ".", "to_sym", ")", "(", "@object_types", "[", "value", ".", "type", "]", "||=", "[", "]", ")", "<<", "key", ".", "to_s", "if", "@store", "[", "key", ".", "to_sym", "]", "@object_types", "[", "@store", "[", "key", ".", "to_sym", "]", ".", "type", "]", ".", "delete", "(", "key", ".", "to_s", ")", "end", "@store", "[", "key", ".", "to_sym", "]", "=", "value", "end", "end" ]
Associates an object with a path @param [String, Symbol] key the path name (:root or '' for root object) @param [CodeObjects::Base] value the object to store @return [CodeObjects::Base] returns +value+
[ "Associates", "an", "object", "with", "a", "path" ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/registry_store.rb#L55-L67
train
lsegal/yard
lib/yard/registry_store.rb
YARD.RegistryStore.load_all
def load_all return unless @file return if @loaded_objects >= @available_objects log.debug "Loading entire database: #{@file} ..." objects = [] all_disk_objects.sort_by(&:size).each do |path| obj = @serializer.deserialize(path, true) objects << obj if obj end objects.each do |obj| put(obj.path, obj) end @loaded_objects += objects.size log.debug "Loaded database (file='#{@file}' count=#{objects.size} total=#{@available_objects})" end
ruby
def load_all return unless @file return if @loaded_objects >= @available_objects log.debug "Loading entire database: #{@file} ..." objects = [] all_disk_objects.sort_by(&:size).each do |path| obj = @serializer.deserialize(path, true) objects << obj if obj end objects.each do |obj| put(obj.path, obj) end @loaded_objects += objects.size log.debug "Loaded database (file='#{@file}' count=#{objects.size} total=#{@available_objects})" end
[ "def", "load_all", "return", "unless", "@file", "return", "if", "@loaded_objects", ">=", "@available_objects", "log", ".", "debug", "\"Loading entire database: #{@file} ...\"", "objects", "=", "[", "]", "all_disk_objects", ".", "sort_by", "(", ":size", ")", ".", "each", "do", "|", "path", "|", "obj", "=", "@serializer", ".", "deserialize", "(", "path", ",", "true", ")", "objects", "<<", "obj", "if", "obj", "end", "objects", ".", "each", "do", "|", "obj", "|", "put", "(", "obj", ".", "path", ",", "obj", ")", "end", "@loaded_objects", "+=", "objects", ".", "size", "log", ".", "debug", "\"Loaded database (file='#{@file}' count=#{objects.size} total=#{@available_objects})\"", "end" ]
Loads all cached objects into memory @return [void]
[ "Loads", "all", "cached", "objects", "into", "memory" ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/registry_store.rb#L148-L165
train
lsegal/yard
lib/yard/registry_store.rb
YARD.RegistryStore.save
def save(merge = true, file = nil) if file && file != @file @file = file @serializer = Serializers::YardocSerializer.new(@file) end destroy unless merge sdb = Registry.single_object_db if sdb == true || sdb.nil? @serializer.serialize(@store) else values(false).each do |object| @serializer.serialize(object) end end write_proxy_types write_object_types write_checksums write_complete_lock true end
ruby
def save(merge = true, file = nil) if file && file != @file @file = file @serializer = Serializers::YardocSerializer.new(@file) end destroy unless merge sdb = Registry.single_object_db if sdb == true || sdb.nil? @serializer.serialize(@store) else values(false).each do |object| @serializer.serialize(object) end end write_proxy_types write_object_types write_checksums write_complete_lock true end
[ "def", "save", "(", "merge", "=", "true", ",", "file", "=", "nil", ")", "if", "file", "&&", "file", "!=", "@file", "@file", "=", "file", "@serializer", "=", "Serializers", "::", "YardocSerializer", ".", "new", "(", "@file", ")", "end", "destroy", "unless", "merge", "sdb", "=", "Registry", ".", "single_object_db", "if", "sdb", "==", "true", "||", "sdb", ".", "nil?", "@serializer", ".", "serialize", "(", "@store", ")", "else", "values", "(", "false", ")", ".", "each", "do", "|", "object", "|", "@serializer", ".", "serialize", "(", "object", ")", "end", "end", "write_proxy_types", "write_object_types", "write_checksums", "write_complete_lock", "true", "end" ]
Saves the database to disk @param [Boolean] merge if true, merges the data in memory with the data on disk, otherwise the data on disk is deleted. @param [String, nil] file if supplied, the name of the file to save to @return [Boolean] whether the database was saved
[ "Saves", "the", "database", "to", "disk" ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/registry_store.rb#L172-L192
train
lsegal/yard
lib/yard/registry_store.rb
YARD.RegistryStore.destroy
def destroy(force = false) if (!force && file =~ /\.yardoc$/) || force if File.file?(@file) # Handle silent upgrade of old .yardoc format File.unlink(@file) elsif File.directory?(@file) FileUtils.rm_rf(@file) end true else false end end
ruby
def destroy(force = false) if (!force && file =~ /\.yardoc$/) || force if File.file?(@file) # Handle silent upgrade of old .yardoc format File.unlink(@file) elsif File.directory?(@file) FileUtils.rm_rf(@file) end true else false end end
[ "def", "destroy", "(", "force", "=", "false", ")", "if", "(", "!", "force", "&&", "file", "=~", "/", "\\.", "/", ")", "||", "force", "if", "File", ".", "file?", "(", "@file", ")", "# Handle silent upgrade of old .yardoc format", "File", ".", "unlink", "(", "@file", ")", "elsif", "File", ".", "directory?", "(", "@file", ")", "FileUtils", ".", "rm_rf", "(", "@file", ")", "end", "true", "else", "false", "end", "end" ]
Deletes the .yardoc database on disk @param [Boolean] force if force is not set to true, the file/directory will only be removed if it ends with .yardoc. This helps with cases where the directory might have been named incorrectly. @return [Boolean] true if the .yardoc database was deleted, false otherwise.
[ "Deletes", "the", ".", "yardoc", "database", "on", "disk" ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/registry_store.rb#L213-L225
train
lsegal/yard
lib/yard/docstring.rb
YARD.Docstring.summary
def summary resolve_reference return @summary if defined?(@summary) && @summary stripped = gsub(/[\r\n](?![\r\n])/, ' ').strip num_parens = 0 idx = length.times do |index| case stripped[index, 1] when "." next_char = stripped[index + 1, 1].to_s break index - 1 if num_parens <= 0 && next_char =~ /^\s*$/ when "\r", "\n" next_char = stripped[index + 1, 1].to_s if next_char =~ /^\s*$/ break stripped[index - 1, 1] == '.' ? index - 2 : index - 1 end when "{", "(", "[" num_parens += 1 when "}", ")", "]" num_parens -= 1 end end @summary = stripped[0..idx] if [email protected]? && @summary !~ /\A\s*\{include:.+\}\s*\Z/ @summary += '.' end @summary end
ruby
def summary resolve_reference return @summary if defined?(@summary) && @summary stripped = gsub(/[\r\n](?![\r\n])/, ' ').strip num_parens = 0 idx = length.times do |index| case stripped[index, 1] when "." next_char = stripped[index + 1, 1].to_s break index - 1 if num_parens <= 0 && next_char =~ /^\s*$/ when "\r", "\n" next_char = stripped[index + 1, 1].to_s if next_char =~ /^\s*$/ break stripped[index - 1, 1] == '.' ? index - 2 : index - 1 end when "{", "(", "[" num_parens += 1 when "}", ")", "]" num_parens -= 1 end end @summary = stripped[0..idx] if [email protected]? && @summary !~ /\A\s*\{include:.+\}\s*\Z/ @summary += '.' end @summary end
[ "def", "summary", "resolve_reference", "return", "@summary", "if", "defined?", "(", "@summary", ")", "&&", "@summary", "stripped", "=", "gsub", "(", "/", "\\r", "\\n", "\\r", "\\n", "/", ",", "' '", ")", ".", "strip", "num_parens", "=", "0", "idx", "=", "length", ".", "times", "do", "|", "index", "|", "case", "stripped", "[", "index", ",", "1", "]", "when", "\".\"", "next_char", "=", "stripped", "[", "index", "+", "1", ",", "1", "]", ".", "to_s", "break", "index", "-", "1", "if", "num_parens", "<=", "0", "&&", "next_char", "=~", "/", "\\s", "/", "when", "\"\\r\"", ",", "\"\\n\"", "next_char", "=", "stripped", "[", "index", "+", "1", ",", "1", "]", ".", "to_s", "if", "next_char", "=~", "/", "\\s", "/", "break", "stripped", "[", "index", "-", "1", ",", "1", "]", "==", "'.'", "?", "index", "-", "2", ":", "index", "-", "1", "end", "when", "\"{\"", ",", "\"(\"", ",", "\"[\"", "num_parens", "+=", "1", "when", "\"}\"", ",", "\")\"", ",", "\"]\"", "num_parens", "-=", "1", "end", "end", "@summary", "=", "stripped", "[", "0", "..", "idx", "]", "if", "!", "@summary", ".", "empty?", "&&", "@summary", "!~", "/", "\\A", "\\s", "\\{", "\\}", "\\s", "\\Z", "/", "@summary", "+=", "'.'", "end", "@summary", "end" ]
Gets the first line of a docstring to the period or the first paragraph. @return [String] The first line or paragraph of the docstring; always ends with a period.
[ "Gets", "the", "first", "line", "of", "a", "docstring", "to", "the", "period", "or", "the", "first", "paragraph", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/docstring.rb#L173-L199
train
lsegal/yard
lib/yard/docstring.rb
YARD.Docstring.to_raw
def to_raw tag_data = tags.map do |tag| case tag when Tags::OverloadTag tag_text = "@#{tag.tag_name} #{tag.signature}\n" unless tag.docstring.blank? tag_text += "\n " + tag.docstring.all.gsub(/\r?\n/, "\n ") end when Tags::OptionTag tag_text = "@#{tag.tag_name} #{tag.name}" tag_text += ' [' + tag.pair.types.join(', ') + ']' if tag.pair.types tag_text += ' ' + tag.pair.name.to_s if tag.pair.name tag_text += "\n " if tag.name && tag.text tag_text += ' (' + tag.pair.defaults.join(', ') + ')' if tag.pair.defaults tag_text += " " + tag.pair.text.strip.gsub(/\n/, "\n ") if tag.pair.text else tag_text = '@' + tag.tag_name tag_text += ' [' + tag.types.join(', ') + ']' if tag.types tag_text += ' ' + tag.name.to_s if tag.name tag_text += "\n " if tag.name && tag.text tag_text += ' ' + tag.text.strip.gsub(/\n/, "\n ") if tag.text end tag_text end [strip, tag_data.join("\n")].reject(&:empty?).compact.join("\n") end
ruby
def to_raw tag_data = tags.map do |tag| case tag when Tags::OverloadTag tag_text = "@#{tag.tag_name} #{tag.signature}\n" unless tag.docstring.blank? tag_text += "\n " + tag.docstring.all.gsub(/\r?\n/, "\n ") end when Tags::OptionTag tag_text = "@#{tag.tag_name} #{tag.name}" tag_text += ' [' + tag.pair.types.join(', ') + ']' if tag.pair.types tag_text += ' ' + tag.pair.name.to_s if tag.pair.name tag_text += "\n " if tag.name && tag.text tag_text += ' (' + tag.pair.defaults.join(', ') + ')' if tag.pair.defaults tag_text += " " + tag.pair.text.strip.gsub(/\n/, "\n ") if tag.pair.text else tag_text = '@' + tag.tag_name tag_text += ' [' + tag.types.join(', ') + ']' if tag.types tag_text += ' ' + tag.name.to_s if tag.name tag_text += "\n " if tag.name && tag.text tag_text += ' ' + tag.text.strip.gsub(/\n/, "\n ") if tag.text end tag_text end [strip, tag_data.join("\n")].reject(&:empty?).compact.join("\n") end
[ "def", "to_raw", "tag_data", "=", "tags", ".", "map", "do", "|", "tag", "|", "case", "tag", "when", "Tags", "::", "OverloadTag", "tag_text", "=", "\"@#{tag.tag_name} #{tag.signature}\\n\"", "unless", "tag", ".", "docstring", ".", "blank?", "tag_text", "+=", "\"\\n \"", "+", "tag", ".", "docstring", ".", "all", ".", "gsub", "(", "/", "\\r", "\\n", "/", ",", "\"\\n \"", ")", "end", "when", "Tags", "::", "OptionTag", "tag_text", "=", "\"@#{tag.tag_name} #{tag.name}\"", "tag_text", "+=", "' ['", "+", "tag", ".", "pair", ".", "types", ".", "join", "(", "', '", ")", "+", "']'", "if", "tag", ".", "pair", ".", "types", "tag_text", "+=", "' '", "+", "tag", ".", "pair", ".", "name", ".", "to_s", "if", "tag", ".", "pair", ".", "name", "tag_text", "+=", "\"\\n \"", "if", "tag", ".", "name", "&&", "tag", ".", "text", "tag_text", "+=", "' ('", "+", "tag", ".", "pair", ".", "defaults", ".", "join", "(", "', '", ")", "+", "')'", "if", "tag", ".", "pair", ".", "defaults", "tag_text", "+=", "\" \"", "+", "tag", ".", "pair", ".", "text", ".", "strip", ".", "gsub", "(", "/", "\\n", "/", ",", "\"\\n \"", ")", "if", "tag", ".", "pair", ".", "text", "else", "tag_text", "=", "'@'", "+", "tag", ".", "tag_name", "tag_text", "+=", "' ['", "+", "tag", ".", "types", ".", "join", "(", "', '", ")", "+", "']'", "if", "tag", ".", "types", "tag_text", "+=", "' '", "+", "tag", ".", "name", ".", "to_s", "if", "tag", ".", "name", "tag_text", "+=", "\"\\n \"", "if", "tag", ".", "name", "&&", "tag", ".", "text", "tag_text", "+=", "' '", "+", "tag", ".", "text", ".", "strip", ".", "gsub", "(", "/", "\\n", "/", ",", "\"\\n \"", ")", "if", "tag", ".", "text", "end", "tag_text", "end", "[", "strip", ",", "tag_data", ".", "join", "(", "\"\\n\"", ")", "]", ".", "reject", "(", ":empty?", ")", ".", "compact", ".", "join", "(", "\"\\n\"", ")", "end" ]
Reformats and returns a raw representation of the tag data using the current tag and docstring data, not the original text. @return [String] the updated raw formatted docstring data @since 0.7.0 @todo Add Tags::Tag#to_raw and refactor
[ "Reformats", "and", "returns", "a", "raw", "representation", "of", "the", "tag", "data", "using", "the", "current", "tag", "and", "docstring", "data", "not", "the", "original", "text", "." ]
12f56cf7d58e7025085f00b9f9f2f62c24b13d93
https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/docstring.rb#L207-L232
train