id int32 0 24.9k | repo stringlengths 5 58 | path stringlengths 9 168 | func_name stringlengths 9 130 | original_string stringlengths 66 10.5k | language stringclasses 1 value | code stringlengths 66 10.5k | code_tokens list | docstring stringlengths 8 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 94 266 |
|---|---|---|---|---|---|---|---|---|---|---|---|
14,800 | 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",
"]"... | 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 |
14,801 | 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",
"=... | 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 |
14,802 | 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",... | 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 |
14,803 | 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",
... | 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 |
14,804 | 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",
"=",... | 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 |
14,805 | 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_posit... | 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 |
14,806 | 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",
"=",
"@i... | 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 |
14,807 | 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... | 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 |
14,808 | 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"... | 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 |
14,809 | 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",
"r... | 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 |
14,810 | 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",
"-",... | Delete a row | [
"Delete",
"a",
"row"
] | d17887e279c27e2b2ec7a252627c04b4b03c0a7a | https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L1091-L1101 |
14,811 | 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... | 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 |
14,812 | 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 |
14,813 | 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 |
14,814 | 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 |
14,815 | 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 |
14,816 | 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",
"numbe... | 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 |
14,817 | 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",
"|"... | 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",
... | d17887e279c27e2b2ec7a252627c04b4b03c0a7a | https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L1275-L1291 |
14,818 | 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",
... | 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 |
14,819 | 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",
".",
... | 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 |
14,820 | 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",
"=",
"SetSingleIndexStr... | 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 |
14,821 | 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",
"=",
"vecto... | 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 |
14,822 | 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"... | 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 |
14,823 | 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",
... | 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 |
14,824 | 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",
"]"... | 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 |
14,825 | 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",
"+",
"' '... | 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 |
14,826 | 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... | Convert to html for IRuby. | [
"Convert",
"to",
"html",
"for",
"IRuby",
"."
] | d17887e279c27e2b2ec7a252627c04b4b03c0a7a | https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/dataframe.rb#L2094-L2103 |
14,827 | 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",
")",
"... | 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 |
14,828 | 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",
",... | 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 |
14,829 | 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 |
14,830 | 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",
".... | 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 |
14,831 | 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 |
14,832 | 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",
"]",
"s... | 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 |
14,833 | 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",
",",
... | 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 |
14,834 | 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",
")",
"e... | 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 |
14,835 | 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 |
14,836 | 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 |
14,837 | 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",
".",
"d... | 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 |
14,838 | 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",
"(",... | 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 |
14,839 | 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}\"... | 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 |
14,840 | 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?... | 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 |
14,841 | 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 |
14,842 | 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_att... | 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 |
14,843 | 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",
"cat... | 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 |
14,844 | 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"... | 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 |
14,845 | 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",
".",... | 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 |
14,846 | 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 |
14,847 | 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 |
14,848 | 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",
"=",
"PR... | 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 |
14,849 | 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",
".",
"... | 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 |
14,850 | 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 |
14,851 | 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 |
14,852 | 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",
".",
... | 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 |
14,853 | 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",
")",
".",
"reje... | 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 |
14,854 | 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",... | 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 |
14,855 | 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",
":... | 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 |
14,856 | 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",
"+=",
"superclas... | 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 |
14,857 | 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",
")",
"... | 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 |
14,858 | 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",... | 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 |
14,859 | 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 |
14,860 | 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 |
14,861 | 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",
... | 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 |
14,862 | 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",
... | 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 |
14,863 | 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 |
14,864 | 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",
".",
"mk... | 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 |
14,865 | 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",
".",
"visib... | 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 |
14,866 | 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 |
14,867 | 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 |
14,868 | 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",
")",
"(",
... | 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 |
14,869 | 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",
")",
".",
"ea... | 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 |
14,870 | 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",
"unle... | 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 |
14,871 | 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",
"(... | 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 |
14,872 | 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",
"=",
... | 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 |
14,873 | 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",
"+=",
"\... | 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 |
14,874 | lsegal/yard | lib/yard/docstring.rb | YARD.Docstring.tag | def tag(name)
tags.find {|tag| tag.tag_name.to_s == name.to_s }
end | ruby | def tag(name)
tags.find {|tag| tag.tag_name.to_s == name.to_s }
end | [
"def",
"tag",
"(",
"name",
")",
"tags",
".",
"find",
"{",
"|",
"tag",
"|",
"tag",
".",
"tag_name",
".",
"to_s",
"==",
"name",
".",
"to_s",
"}",
"end"
] | Convenience method to return the first tag
object in the list of tag objects of that name
@example
doc = Docstring.new("@return zero when nil")
doc.tag(:return).text # => "zero when nil"
@param [#to_s] name the tag name to return data for
@return [Tags::Tag] the first tag in the list of {#tags} | [
"Convenience",
"method",
"to",
"return",
"the",
"first",
"tag",
"object",
"in",
"the",
"list",
"of",
"tag",
"objects",
"of",
"that",
"name"
] | 12f56cf7d58e7025085f00b9f9f2f62c24b13d93 | https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/docstring.rb#L265-L267 |
14,875 | lsegal/yard | lib/yard/docstring.rb | YARD.Docstring.tags | def tags(name = nil)
list = stable_sort_by(@tags + convert_ref_tags, &:tag_name)
return list unless name
list.select {|tag| tag.tag_name.to_s == name.to_s }
end | ruby | def tags(name = nil)
list = stable_sort_by(@tags + convert_ref_tags, &:tag_name)
return list unless name
list.select {|tag| tag.tag_name.to_s == name.to_s }
end | [
"def",
"tags",
"(",
"name",
"=",
"nil",
")",
"list",
"=",
"stable_sort_by",
"(",
"@tags",
"+",
"convert_ref_tags",
",",
":tag_name",
")",
"return",
"list",
"unless",
"name",
"list",
".",
"select",
"{",
"|",
"tag",
"|",
"tag",
".",
"tag_name",
".",
"to_... | Returns a list of tags specified by +name+ or all tags if +name+ is not specified.
@param [#to_s] name the tag name to return data for, or nil for all tags
@return [Array<Tags::Tag>] the list of tags by the specified tag name | [
"Returns",
"a",
"list",
"of",
"tags",
"specified",
"by",
"+",
"name",
"+",
"or",
"all",
"tags",
"if",
"+",
"name",
"+",
"is",
"not",
"specified",
"."
] | 12f56cf7d58e7025085f00b9f9f2f62c24b13d93 | https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/docstring.rb#L273-L277 |
14,876 | lsegal/yard | lib/yard/docstring.rb | YARD.Docstring.has_tag? | def has_tag?(name)
tags.any? {|tag| tag.tag_name.to_s == name.to_s }
end | ruby | def has_tag?(name)
tags.any? {|tag| tag.tag_name.to_s == name.to_s }
end | [
"def",
"has_tag?",
"(",
"name",
")",
"tags",
".",
"any?",
"{",
"|",
"tag",
"|",
"tag",
".",
"tag_name",
".",
"to_s",
"==",
"name",
".",
"to_s",
"}",
"end"
] | Returns true if at least one tag by the name +name+ was declared
@param [String] name the tag name to search for
@return [Boolean] whether or not the tag +name+ was declared | [
"Returns",
"true",
"if",
"at",
"least",
"one",
"tag",
"by",
"the",
"name",
"+",
"name",
"+",
"was",
"declared"
] | 12f56cf7d58e7025085f00b9f9f2f62c24b13d93 | https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/docstring.rb#L283-L285 |
14,877 | lsegal/yard | lib/yard/docstring.rb | YARD.Docstring.blank? | def blank?(only_visible_tags = true)
if only_visible_tags
empty? && !tags.any? {|tag| Tags::Library.visible_tags.include?(tag.tag_name.to_sym) }
else
empty? && @tags.empty? && @ref_tags.empty?
end
end | ruby | def blank?(only_visible_tags = true)
if only_visible_tags
empty? && !tags.any? {|tag| Tags::Library.visible_tags.include?(tag.tag_name.to_sym) }
else
empty? && @tags.empty? && @ref_tags.empty?
end
end | [
"def",
"blank?",
"(",
"only_visible_tags",
"=",
"true",
")",
"if",
"only_visible_tags",
"empty?",
"&&",
"!",
"tags",
".",
"any?",
"{",
"|",
"tag",
"|",
"Tags",
"::",
"Library",
".",
"visible_tags",
".",
"include?",
"(",
"tag",
".",
"tag_name",
".",
"to_s... | Returns true if the docstring has no content that is visible to a template.
@param [Boolean] only_visible_tags whether only {Tags::Library.visible_tags}
should be checked, or if all tags should be considered.
@return [Boolean] whether or not the docstring has content | [
"Returns",
"true",
"if",
"the",
"docstring",
"has",
"no",
"content",
"that",
"is",
"visible",
"to",
"a",
"template",
"."
] | 12f56cf7d58e7025085f00b9f9f2f62c24b13d93 | https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/docstring.rb#L310-L316 |
14,878 | lsegal/yard | lib/yard/docstring.rb | YARD.Docstring.convert_ref_tags | def convert_ref_tags
list = @ref_tags.reject {|t| CodeObjects::Proxy === t.owner }
@ref_tag_recurse_count ||= 0
@ref_tag_recurse_count += 1
if @ref_tag_recurse_count > 2
log.error "#{@object.file}:#{@object.line}: Detected circular reference tag in " \
"`#{@object}', ignoring all reference tags for this object " \
"(#{@ref_tags.map {|t| "@#{t.tag_name}" }.join(", ")})."
@ref_tags = []
return @ref_tags
end
list = list.map(&:tags).flatten
@ref_tag_recurse_count -= 1
list
end | ruby | def convert_ref_tags
list = @ref_tags.reject {|t| CodeObjects::Proxy === t.owner }
@ref_tag_recurse_count ||= 0
@ref_tag_recurse_count += 1
if @ref_tag_recurse_count > 2
log.error "#{@object.file}:#{@object.line}: Detected circular reference tag in " \
"`#{@object}', ignoring all reference tags for this object " \
"(#{@ref_tags.map {|t| "@#{t.tag_name}" }.join(", ")})."
@ref_tags = []
return @ref_tags
end
list = list.map(&:tags).flatten
@ref_tag_recurse_count -= 1
list
end | [
"def",
"convert_ref_tags",
"list",
"=",
"@ref_tags",
".",
"reject",
"{",
"|",
"t",
"|",
"CodeObjects",
"::",
"Proxy",
"===",
"t",
".",
"owner",
"}",
"@ref_tag_recurse_count",
"||=",
"0",
"@ref_tag_recurse_count",
"+=",
"1",
"if",
"@ref_tag_recurse_count",
">",
... | Maps valid reference tags
@return [Array<Tags::RefTag>] the list of valid reference tags | [
"Maps",
"valid",
"reference",
"tags"
] | 12f56cf7d58e7025085f00b9f9f2f62c24b13d93 | https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/docstring.rb#L344-L359 |
14,879 | lsegal/yard | lib/yard/docstring.rb | YARD.Docstring.parse_comments | def parse_comments(comments)
parser = self.class.parser
parser.parse(comments, object)
@all = parser.raw_text
@unresolved_reference = parser.reference
add_tag(*parser.tags)
parser.text
end | ruby | def parse_comments(comments)
parser = self.class.parser
parser.parse(comments, object)
@all = parser.raw_text
@unresolved_reference = parser.reference
add_tag(*parser.tags)
parser.text
end | [
"def",
"parse_comments",
"(",
"comments",
")",
"parser",
"=",
"self",
".",
"class",
".",
"parser",
"parser",
".",
"parse",
"(",
"comments",
",",
"object",
")",
"@all",
"=",
"parser",
".",
"raw_text",
"@unresolved_reference",
"=",
"parser",
".",
"reference",
... | Parses out comments split by newlines into a new code object
@param [String] comments
the newline delimited array of comments. If the comments
are passed as a String, they will be split by newlines.
@return [String] the non-metadata portion of the comments to
be used as a docstring | [
"Parses",
"out",
"comments",
"split",
"by",
"newlines",
"into",
"a",
"new",
"code",
"object"
] | 12f56cf7d58e7025085f00b9f9f2f62c24b13d93 | https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/docstring.rb#L369-L376 |
14,880 | lsegal/yard | lib/yard/docstring.rb | YARD.Docstring.stable_sort_by | def stable_sort_by(list)
list.each_with_index.sort_by {|tag, i| [yield(tag), i] }.map(&:first)
end | ruby | def stable_sort_by(list)
list.each_with_index.sort_by {|tag, i| [yield(tag), i] }.map(&:first)
end | [
"def",
"stable_sort_by",
"(",
"list",
")",
"list",
".",
"each_with_index",
".",
"sort_by",
"{",
"|",
"tag",
",",
"i",
"|",
"[",
"yield",
"(",
"tag",
")",
",",
"i",
"]",
"}",
".",
"map",
"(",
":first",
")",
"end"
] | A stable sort_by method.
@param list [Enumerable] the list to sort.
@return [Array] a stable sorted list. | [
"A",
"stable",
"sort_by",
"method",
"."
] | 12f56cf7d58e7025085f00b9f9f2f62c24b13d93 | https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/docstring.rb#L382-L384 |
14,881 | lsegal/yard | lib/yard/code_objects/module_object.rb | YARD::CodeObjects.ModuleObject.inheritance_tree | def inheritance_tree(include_mods = false)
return [self] unless include_mods
[self] + mixins(:instance, :class).map do |m|
next if m == self
next m unless m.respond_to?(:inheritance_tree)
m.inheritance_tree(true)
end.compact.flatten.uniq
end | ruby | def inheritance_tree(include_mods = false)
return [self] unless include_mods
[self] + mixins(:instance, :class).map do |m|
next if m == self
next m unless m.respond_to?(:inheritance_tree)
m.inheritance_tree(true)
end.compact.flatten.uniq
end | [
"def",
"inheritance_tree",
"(",
"include_mods",
"=",
"false",
")",
"return",
"[",
"self",
"]",
"unless",
"include_mods",
"[",
"self",
"]",
"+",
"mixins",
"(",
":instance",
",",
":class",
")",
".",
"map",
"do",
"|",
"m",
"|",
"next",
"if",
"m",
"==",
... | Returns the inheritance tree of mixins.
@param [Boolean] include_mods if true, will include mixed in
modules (which is likely what is wanted).
@return [Array<NamespaceObject>] a list of namespace objects | [
"Returns",
"the",
"inheritance",
"tree",
"of",
"mixins",
"."
] | 12f56cf7d58e7025085f00b9f9f2f62c24b13d93 | https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/module_object.rb#L12-L19 |
14,882 | lsegal/yard | lib/yard/code_objects/namespace_object.rb | YARD::CodeObjects.NamespaceObject.child | def child(opts = {})
if !opts.is_a?(Hash)
children.find {|o| o.name == opts.to_sym }
else
opts = SymbolHash[opts]
children.find do |obj|
opts.each do |meth, value|
break false unless value.is_a?(Array) ? value.include?(obj[meth]) : obj[meth] == value
end
end
end
end | ruby | def child(opts = {})
if !opts.is_a?(Hash)
children.find {|o| o.name == opts.to_sym }
else
opts = SymbolHash[opts]
children.find do |obj|
opts.each do |meth, value|
break false unless value.is_a?(Array) ? value.include?(obj[meth]) : obj[meth] == value
end
end
end
end | [
"def",
"child",
"(",
"opts",
"=",
"{",
"}",
")",
"if",
"!",
"opts",
".",
"is_a?",
"(",
"Hash",
")",
"children",
".",
"find",
"{",
"|",
"o",
"|",
"o",
".",
"name",
"==",
"opts",
".",
"to_sym",
"}",
"else",
"opts",
"=",
"SymbolHash",
"[",
"opts",... | Looks for a child that matches the attributes specified by +opts+.
@example Finds a child by name and scope
namespace.child(:name => :to_s, :scope => :instance)
# => #<yardoc method MyClass#to_s>
@return [Base, nil] the first matched child object, or nil | [
"Looks",
"for",
"a",
"child",
"that",
"matches",
"the",
"attributes",
"specified",
"by",
"+",
"opts",
"+",
"."
] | 12f56cf7d58e7025085f00b9f9f2f62c24b13d93 | https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/namespace_object.rb#L86-L97 |
14,883 | lsegal/yard | lib/yard/code_objects/namespace_object.rb | YARD::CodeObjects.NamespaceObject.meths | def meths(opts = {})
opts = SymbolHash[
:visibility => [:public, :private, :protected],
:scope => [:class, :instance],
:included => true
].update(opts)
opts[:visibility] = [opts[:visibility]].flatten
opts[:scope] = [opts[:scope]].flatten
ourmeths = children.select do |o|
o.is_a?(MethodObject) &&
opts[:visibility].include?(o.visibility) &&
opts[:scope].include?(o.scope)
end
ourmeths + (opts[:included] ? included_meths(opts) : [])
end | ruby | def meths(opts = {})
opts = SymbolHash[
:visibility => [:public, :private, :protected],
:scope => [:class, :instance],
:included => true
].update(opts)
opts[:visibility] = [opts[:visibility]].flatten
opts[:scope] = [opts[:scope]].flatten
ourmeths = children.select do |o|
o.is_a?(MethodObject) &&
opts[:visibility].include?(o.visibility) &&
opts[:scope].include?(o.scope)
end
ourmeths + (opts[:included] ? included_meths(opts) : [])
end | [
"def",
"meths",
"(",
"opts",
"=",
"{",
"}",
")",
"opts",
"=",
"SymbolHash",
"[",
":visibility",
"=>",
"[",
":public",
",",
":private",
",",
":protected",
"]",
",",
":scope",
"=>",
"[",
":class",
",",
":instance",
"]",
",",
":included",
"=>",
"true",
... | Returns all methods that match the attributes specified by +opts+. If
no options are provided, returns all methods.
@example Finds all private and protected class methods
namespace.meths(:visibility => [:private, :protected], :scope => :class)
# => [#<yardoc method MyClass.privmeth>, #<yardoc method MyClass.protmeth>]
@option opts [Array<Symbol>, Symbol] :visibility ([:public, :private,
:protected]) the visibility of the methods to list. Can be an array or
single value.
@option opts [Array<Symbol>, Symbol] :scope ([:class, :instance]) the
scope of the methods to list. Can be an array or single value.
@option opts [Boolean] :included (true) whether to include mixed in
methods in the list.
@return [Array<MethodObject>] a list of method objects | [
"Returns",
"all",
"methods",
"that",
"match",
"the",
"attributes",
"specified",
"by",
"+",
"opts",
"+",
".",
"If",
"no",
"options",
"are",
"provided",
"returns",
"all",
"methods",
"."
] | 12f56cf7d58e7025085f00b9f9f2f62c24b13d93 | https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/namespace_object.rb#L113-L130 |
14,884 | lsegal/yard | lib/yard/code_objects/namespace_object.rb | YARD::CodeObjects.NamespaceObject.included_meths | def included_meths(opts = {})
opts = SymbolHash[:scope => [:instance, :class]].update(opts)
[opts[:scope]].flatten.map do |scope|
mixins(scope).inject([]) do |list, mixin|
next list if mixin.is_a?(Proxy)
arr = mixin.meths(opts.merge(:scope => :instance)).reject do |o|
next false if opts[:all]
child(:name => o.name, :scope => scope) || list.find {|o2| o2.name == o.name }
end
arr.map! {|o| ExtendedMethodObject.new(o) } if scope == :class
list + arr
end
end.flatten
end | ruby | def included_meths(opts = {})
opts = SymbolHash[:scope => [:instance, :class]].update(opts)
[opts[:scope]].flatten.map do |scope|
mixins(scope).inject([]) do |list, mixin|
next list if mixin.is_a?(Proxy)
arr = mixin.meths(opts.merge(:scope => :instance)).reject do |o|
next false if opts[:all]
child(:name => o.name, :scope => scope) || list.find {|o2| o2.name == o.name }
end
arr.map! {|o| ExtendedMethodObject.new(o) } if scope == :class
list + arr
end
end.flatten
end | [
"def",
"included_meths",
"(",
"opts",
"=",
"{",
"}",
")",
"opts",
"=",
"SymbolHash",
"[",
":scope",
"=>",
"[",
":instance",
",",
":class",
"]",
"]",
".",
"update",
"(",
"opts",
")",
"[",
"opts",
"[",
":scope",
"]",
"]",
".",
"flatten",
".",
"map",
... | Returns methods included from any mixins that match the attributes
specified by +opts+. If no options are specified, returns all included
methods.
@option opts [Array<Symbol>, Symbol] :visibility ([:public, :private,
:protected]) the visibility of the methods to list. Can be an array or
single value.
@option opts [Array<Symbol>, Symbol] :scope ([:class, :instance]) the
scope of the methods to list. Can be an array or single value.
@option opts [Boolean] :included (true) whether to include mixed in
methods in the list.
@see #meths | [
"Returns",
"methods",
"included",
"from",
"any",
"mixins",
"that",
"match",
"the",
"attributes",
"specified",
"by",
"+",
"opts",
"+",
".",
"If",
"no",
"options",
"are",
"specified",
"returns",
"all",
"included",
"methods",
"."
] | 12f56cf7d58e7025085f00b9f9f2f62c24b13d93 | https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/namespace_object.rb#L144-L157 |
14,885 | lsegal/yard | lib/yard/code_objects/namespace_object.rb | YARD::CodeObjects.NamespaceObject.constants | def constants(opts = {})
opts = SymbolHash[:included => true].update(opts)
consts = children.select {|o| o.is_a? ConstantObject }
consts + (opts[:included] ? included_constants : [])
end | ruby | def constants(opts = {})
opts = SymbolHash[:included => true].update(opts)
consts = children.select {|o| o.is_a? ConstantObject }
consts + (opts[:included] ? included_constants : [])
end | [
"def",
"constants",
"(",
"opts",
"=",
"{",
"}",
")",
"opts",
"=",
"SymbolHash",
"[",
":included",
"=>",
"true",
"]",
".",
"update",
"(",
"opts",
")",
"consts",
"=",
"children",
".",
"select",
"{",
"|",
"o",
"|",
"o",
".",
"is_a?",
"ConstantObject",
... | Returns all constants in the namespace
@option opts [Boolean] :included (true) whether or not to include
mixed in constants in list
@return [Array<ConstantObject>] a list of constant objects | [
"Returns",
"all",
"constants",
"in",
"the",
"namespace"
] | 12f56cf7d58e7025085f00b9f9f2f62c24b13d93 | https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/namespace_object.rb#L164-L168 |
14,886 | lsegal/yard | lib/yard/code_objects/namespace_object.rb | YARD::CodeObjects.NamespaceObject.included_constants | def included_constants
instance_mixins.inject([]) do |list, mixin|
if mixin.respond_to? :constants
list += mixin.constants.reject do |o|
child(:name => o.name) || list.find {|o2| o2.name == o.name }
end
else
list
end
end
end | ruby | def included_constants
instance_mixins.inject([]) do |list, mixin|
if mixin.respond_to? :constants
list += mixin.constants.reject do |o|
child(:name => o.name) || list.find {|o2| o2.name == o.name }
end
else
list
end
end
end | [
"def",
"included_constants",
"instance_mixins",
".",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"list",
",",
"mixin",
"|",
"if",
"mixin",
".",
"respond_to?",
":constants",
"list",
"+=",
"mixin",
".",
"constants",
".",
"reject",
"do",
"|",
"o",
"|",
"child"... | Returns constants included from any mixins
@return [Array<ConstantObject>] a list of constant objects | [
"Returns",
"constants",
"included",
"from",
"any",
"mixins"
] | 12f56cf7d58e7025085f00b9f9f2f62c24b13d93 | https://github.com/lsegal/yard/blob/12f56cf7d58e7025085f00b9f9f2f62c24b13d93/lib/yard/code_objects/namespace_object.rb#L172-L182 |
14,887 | dmayer/idb | lib/lib/ca_interface.rb | Idb.CAInterface.remove_cert | def remove_cert(cert)
der = cert.to_der
query = %(DELETE FROM "tsettings" WHERE sha1 = #{blobify(sha1_from_der(der))};)
begin
db = SQLite3::Database.new(@db_path)
db.execute(query)
db.close
rescue StandardError => e
raise "[*] Error writing to SQLite database at #{@db_path}: #{e.message}"
end
end | ruby | def remove_cert(cert)
der = cert.to_der
query = %(DELETE FROM "tsettings" WHERE sha1 = #{blobify(sha1_from_der(der))};)
begin
db = SQLite3::Database.new(@db_path)
db.execute(query)
db.close
rescue StandardError => e
raise "[*] Error writing to SQLite database at #{@db_path}: #{e.message}"
end
end | [
"def",
"remove_cert",
"(",
"cert",
")",
"der",
"=",
"cert",
".",
"to_der",
"query",
"=",
"%(DELETE FROM \"tsettings\" WHERE sha1 = #{blobify(sha1_from_der(der))};)",
"begin",
"db",
"=",
"SQLite3",
"::",
"Database",
".",
"new",
"(",
"@db_path",
")",
"db",
".",
"exe... | performs uninstall based on sha1 hash provided in certfile | [
"performs",
"uninstall",
"based",
"on",
"sha1",
"hash",
"provided",
"in",
"certfile"
] | 038355497091b24c53596817b8818d2b2bc18e4b | https://github.com/dmayer/idb/blob/038355497091b24c53596817b8818d2b2bc18e4b/lib/lib/ca_interface.rb#L9-L20 |
14,888 | charlotte-ruby/impressionist | app/models/impressionist/impressionable.rb | Impressionist.Impressionable.impressionist_count | def impressionist_count(options={})
# Uses these options as defaults unless overridden in options hash
options.reverse_merge!(:filter => :request_hash, :start_date => nil, :end_date => Time.now)
# If a start_date is provided, finds impressions between then and the end_date. Otherwise returns all impressions
imps = options[:start_date].blank? ? impressions : impressions.where("created_at >= ? and created_at <= ?", options[:start_date], options[:end_date])
if options[:message]
imps = imps.where("impressions.message = ?", options[:message])
end
# Count all distinct impressions unless the :all filter is provided.
distinct = options[:filter] != :all
if Rails::VERSION::MAJOR >= 4
distinct ? imps.select(options[:filter]).distinct.count : imps.count
else
distinct ? imps.count(options[:filter], :distinct => true) : imps.count
end
end | ruby | def impressionist_count(options={})
# Uses these options as defaults unless overridden in options hash
options.reverse_merge!(:filter => :request_hash, :start_date => nil, :end_date => Time.now)
# If a start_date is provided, finds impressions between then and the end_date. Otherwise returns all impressions
imps = options[:start_date].blank? ? impressions : impressions.where("created_at >= ? and created_at <= ?", options[:start_date], options[:end_date])
if options[:message]
imps = imps.where("impressions.message = ?", options[:message])
end
# Count all distinct impressions unless the :all filter is provided.
distinct = options[:filter] != :all
if Rails::VERSION::MAJOR >= 4
distinct ? imps.select(options[:filter]).distinct.count : imps.count
else
distinct ? imps.count(options[:filter], :distinct => true) : imps.count
end
end | [
"def",
"impressionist_count",
"(",
"options",
"=",
"{",
"}",
")",
"# Uses these options as defaults unless overridden in options hash",
"options",
".",
"reverse_merge!",
"(",
":filter",
"=>",
":request_hash",
",",
":start_date",
"=>",
"nil",
",",
":end_date",
"=>",
"Tim... | end of ClassMethods | [
"end",
"of",
"ClassMethods"
] | 79c8dc02864e9b998009396d7c80dcbe78bed104 | https://github.com/charlotte-ruby/impressionist/blob/79c8dc02864e9b998009396d7c80dcbe78bed104/app/models/impressionist/impressionable.rb#L31-L49 |
14,889 | charlotte-ruby/impressionist | lib/impressionist/models/mongoid/impressionist/impressionable.rb | Impressionist.Impressionable.impressionist_count | def impressionist_count(options={})
# Uses these options as defaults unless overridden in options hash
options.reverse_merge!(:filter => :request_hash, :start_date => nil, :end_date => Time.now)
# If a start_date is provided, finds impressions between then and the end_date.
# Otherwise returns all impressions
imps = options[:start_date].blank? ? impressions :
impressions.between(created_at: options[:start_date]..options[:end_date])
# Count all distinct impressions unless the :all filter is provided
distinct = options[:filter] != :all
distinct ? imps.where(options[:filter].ne => nil).distinct(options[:filter]).count : imps.count
end | ruby | def impressionist_count(options={})
# Uses these options as defaults unless overridden in options hash
options.reverse_merge!(:filter => :request_hash, :start_date => nil, :end_date => Time.now)
# If a start_date is provided, finds impressions between then and the end_date.
# Otherwise returns all impressions
imps = options[:start_date].blank? ? impressions :
impressions.between(created_at: options[:start_date]..options[:end_date])
# Count all distinct impressions unless the :all filter is provided
distinct = options[:filter] != :all
distinct ? imps.where(options[:filter].ne => nil).distinct(options[:filter]).count : imps.count
end | [
"def",
"impressionist_count",
"(",
"options",
"=",
"{",
"}",
")",
"# Uses these options as defaults unless overridden in options hash",
"options",
".",
"reverse_merge!",
"(",
":filter",
"=>",
":request_hash",
",",
":start_date",
"=>",
"nil",
",",
":end_date",
"=>",
"Tim... | Overides impressionist_count in order to provide mongoid compability | [
"Overides",
"impressionist_count",
"in",
"order",
"to",
"provide",
"mongoid",
"compability"
] | 79c8dc02864e9b998009396d7c80dcbe78bed104 | https://github.com/charlotte-ruby/impressionist/blob/79c8dc02864e9b998009396d7c80dcbe78bed104/lib/impressionist/models/mongoid/impressionist/impressionable.rb#L8-L22 |
14,890 | charlotte-ruby/impressionist | app/controllers/impressionist_controller.rb | ImpressionistController.InstanceMethods.associative_create_statement | def associative_create_statement(query_params={})
filter = ActionDispatch::Http::ParameterFilter.new(Rails.application.config.filter_parameters)
query_params.reverse_merge!(
:controller_name => controller_name,
:action_name => action_name,
:user_id => user_id,
:request_hash => @impressionist_hash,
:session_hash => session_hash,
:ip_address => request.remote_ip,
:referrer => request.referer,
:params => filter.filter(params_hash)
)
end | ruby | def associative_create_statement(query_params={})
filter = ActionDispatch::Http::ParameterFilter.new(Rails.application.config.filter_parameters)
query_params.reverse_merge!(
:controller_name => controller_name,
:action_name => action_name,
:user_id => user_id,
:request_hash => @impressionist_hash,
:session_hash => session_hash,
:ip_address => request.remote_ip,
:referrer => request.referer,
:params => filter.filter(params_hash)
)
end | [
"def",
"associative_create_statement",
"(",
"query_params",
"=",
"{",
"}",
")",
"filter",
"=",
"ActionDispatch",
"::",
"Http",
"::",
"ParameterFilter",
".",
"new",
"(",
"Rails",
".",
"application",
".",
"config",
".",
"filter_parameters",
")",
"query_params",
".... | creates a statment hash that contains default values for creating an impression via an AR relation. | [
"creates",
"a",
"statment",
"hash",
"that",
"contains",
"default",
"values",
"for",
"creating",
"an",
"impression",
"via",
"an",
"AR",
"relation",
"."
] | 79c8dc02864e9b998009396d7c80dcbe78bed104 | https://github.com/charlotte-ruby/impressionist/blob/79c8dc02864e9b998009396d7c80dcbe78bed104/app/controllers/impressionist_controller.rb#L53-L65 |
14,891 | charlotte-ruby/impressionist | app/controllers/impressionist_controller.rb | ImpressionistController.InstanceMethods.unique_query | def unique_query(unique_opts,impressionable=nil)
full_statement = direct_create_statement({},impressionable)
# reduce the full statement to the params we need for the specified unique options
unique_opts.reduce({}) do |query, param|
query[param] = full_statement[param]
query
end
end | ruby | def unique_query(unique_opts,impressionable=nil)
full_statement = direct_create_statement({},impressionable)
# reduce the full statement to the params we need for the specified unique options
unique_opts.reduce({}) do |query, param|
query[param] = full_statement[param]
query
end
end | [
"def",
"unique_query",
"(",
"unique_opts",
",",
"impressionable",
"=",
"nil",
")",
"full_statement",
"=",
"direct_create_statement",
"(",
"{",
"}",
",",
"impressionable",
")",
"# reduce the full statement to the params we need for the specified unique options",
"unique_opts",
... | creates the query to check for uniqueness | [
"creates",
"the",
"query",
"to",
"check",
"for",
"uniqueness"
] | 79c8dc02864e9b998009396d7c80dcbe78bed104 | https://github.com/charlotte-ruby/impressionist/blob/79c8dc02864e9b998009396d7c80dcbe78bed104/app/controllers/impressionist_controller.rb#L117-L124 |
14,892 | charlotte-ruby/impressionist | app/controllers/impressionist_controller.rb | ImpressionistController.InstanceMethods.direct_create_statement | def direct_create_statement(query_params={},impressionable=nil)
query_params.reverse_merge!(
:impressionable_type => controller_name.singularize.camelize,
:impressionable_id => impressionable.present? ? impressionable.id : params[:id]
)
associative_create_statement(query_params)
end | ruby | def direct_create_statement(query_params={},impressionable=nil)
query_params.reverse_merge!(
:impressionable_type => controller_name.singularize.camelize,
:impressionable_id => impressionable.present? ? impressionable.id : params[:id]
)
associative_create_statement(query_params)
end | [
"def",
"direct_create_statement",
"(",
"query_params",
"=",
"{",
"}",
",",
"impressionable",
"=",
"nil",
")",
"query_params",
".",
"reverse_merge!",
"(",
":impressionable_type",
"=>",
"controller_name",
".",
"singularize",
".",
"camelize",
",",
":impressionable_id",
... | creates a statment hash that contains default values for creating an impression. | [
"creates",
"a",
"statment",
"hash",
"that",
"contains",
"default",
"values",
"for",
"creating",
"an",
"impression",
"."
] | 79c8dc02864e9b998009396d7c80dcbe78bed104 | https://github.com/charlotte-ruby/impressionist/blob/79c8dc02864e9b998009396d7c80dcbe78bed104/app/controllers/impressionist_controller.rb#L127-L133 |
14,893 | mgomes/api_auth | lib/api_auth/helpers.rb | ApiAuth.Helpers.capitalize_keys | def capitalize_keys(hsh)
capitalized_hash = {}
hsh.each_pair { |k, v| capitalized_hash[k.to_s.upcase] = v }
capitalized_hash
end | ruby | def capitalize_keys(hsh)
capitalized_hash = {}
hsh.each_pair { |k, v| capitalized_hash[k.to_s.upcase] = v }
capitalized_hash
end | [
"def",
"capitalize_keys",
"(",
"hsh",
")",
"capitalized_hash",
"=",
"{",
"}",
"hsh",
".",
"each_pair",
"{",
"|",
"k",
",",
"v",
"|",
"capitalized_hash",
"[",
"k",
".",
"to_s",
".",
"upcase",
"]",
"=",
"v",
"}",
"capitalized_hash",
"end"
] | Capitalizes the keys of a hash | [
"Capitalizes",
"the",
"keys",
"of",
"a",
"hash"
] | 05270e24a8189958da5b6f2247320540a6c570bc | https://github.com/mgomes/api_auth/blob/05270e24a8189958da5b6f2247320540a6c570bc/lib/api_auth/helpers.rb#L12-L16 |
14,894 | bigcommerce/gruf | lib/gruf/client.rb | Gruf.Client.execute | def execute(call_sig, req, metadata, opts = {}, &block)
operation = nil
result = Gruf::Timer.time do
opts[:return_op] = true
opts[:metadata] = metadata
operation = send(call_sig, req, opts, &block)
operation.execute
end
[result, operation]
end | ruby | def execute(call_sig, req, metadata, opts = {}, &block)
operation = nil
result = Gruf::Timer.time do
opts[:return_op] = true
opts[:metadata] = metadata
operation = send(call_sig, req, opts, &block)
operation.execute
end
[result, operation]
end | [
"def",
"execute",
"(",
"call_sig",
",",
"req",
",",
"metadata",
",",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"operation",
"=",
"nil",
"result",
"=",
"Gruf",
"::",
"Timer",
".",
"time",
"do",
"opts",
"[",
":return_op",
"]",
"=",
"true",
"opts... | Execute the given request to the service
@param [Symbol] call_sig The call signature being executed
@param [Object] req (Optional) The protobuf request message to send
@param [Hash] metadata (Optional) A hash of metadata key/values that are transported with the client request
@param [Hash] opts (Optional) A hash of options to send to the gRPC request_response method
@return [Array<Gruf::Timer::Result, GRPC::ActiveCall::Operation>] | [
"Execute",
"the",
"given",
"request",
"to",
"the",
"service"
] | 9e438b174df81845c8100302da671721d5a112c5 | https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/client.rb#L127-L136 |
14,895 | bigcommerce/gruf | lib/gruf/client.rb | Gruf.Client.request_object | def request_object(request_method, params = {})
desc = rpc_desc(request_method)
desc&.input ? desc.input.new(params) : nil
end | ruby | def request_object(request_method, params = {})
desc = rpc_desc(request_method)
desc&.input ? desc.input.new(params) : nil
end | [
"def",
"request_object",
"(",
"request_method",
",",
"params",
"=",
"{",
"}",
")",
"desc",
"=",
"rpc_desc",
"(",
"request_method",
")",
"desc",
"&.",
"input",
"?",
"desc",
".",
"input",
".",
"new",
"(",
"params",
")",
":",
"nil",
"end"
] | Get the appropriate protobuf request message for the given request method on the service being called
@param [Symbol] request_method The method name being called on the remote service
@param [Hash] params (Optional) A hash of parameters that will populate the request object
@return [Class] The request object that corresponds to the method being called | [
"Get",
"the",
"appropriate",
"protobuf",
"request",
"message",
"for",
"the",
"given",
"request",
"method",
"on",
"the",
"service",
"being",
"called"
] | 9e438b174df81845c8100302da671721d5a112c5 | https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/client.rb#L155-L158 |
14,896 | bigcommerce/gruf | lib/gruf/client.rb | Gruf.Client.build_metadata | def build_metadata(metadata = {})
unless opts[:password].empty?
username = opts.fetch(:username, 'grpc').to_s
username = username.empty? ? '' : "#{username}:"
auth_string = Base64.encode64("#{username}#{opts[:password]}")
metadata[:authorization] = "Basic #{auth_string}".tr("\n", '')
end
metadata
end | ruby | def build_metadata(metadata = {})
unless opts[:password].empty?
username = opts.fetch(:username, 'grpc').to_s
username = username.empty? ? '' : "#{username}:"
auth_string = Base64.encode64("#{username}#{opts[:password]}")
metadata[:authorization] = "Basic #{auth_string}".tr("\n", '')
end
metadata
end | [
"def",
"build_metadata",
"(",
"metadata",
"=",
"{",
"}",
")",
"unless",
"opts",
"[",
":password",
"]",
".",
"empty?",
"username",
"=",
"opts",
".",
"fetch",
"(",
":username",
",",
"'grpc'",
")",
".",
"to_s",
"username",
"=",
"username",
".",
"empty?",
... | Build a sanitized, authenticated metadata hash for the given request
@param [Hash] metadata A base metadata hash to build from
@return [Hash] The compiled metadata hash that is ready to be transported over the wire | [
"Build",
"a",
"sanitized",
"authenticated",
"metadata",
"hash",
"for",
"the",
"given",
"request"
] | 9e438b174df81845c8100302da671721d5a112c5 | https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/client.rb#L176-L184 |
14,897 | bigcommerce/gruf | spec/support/helpers.rb | Gruf.Helpers.build_operation | def build_operation(options = {})
double(:operation, {
execute: true,
metadata: {},
trailing_metadata: {},
deadline: Time.now.to_i + 600,
cancelled?: false,
execution_time: rand(1_000..10_000)
}.merge(options))
end | ruby | def build_operation(options = {})
double(:operation, {
execute: true,
metadata: {},
trailing_metadata: {},
deadline: Time.now.to_i + 600,
cancelled?: false,
execution_time: rand(1_000..10_000)
}.merge(options))
end | [
"def",
"build_operation",
"(",
"options",
"=",
"{",
"}",
")",
"double",
"(",
":operation",
",",
"{",
"execute",
":",
"true",
",",
"metadata",
":",
"{",
"}",
",",
"trailing_metadata",
":",
"{",
"}",
",",
"deadline",
":",
"Time",
".",
"now",
".",
"to_i... | Build a gRPC operation stub for testing | [
"Build",
"a",
"gRPC",
"operation",
"stub",
"for",
"testing"
] | 9e438b174df81845c8100302da671721d5a112c5 | https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/spec/support/helpers.rb#L27-L36 |
14,898 | bigcommerce/gruf | spec/support/helpers.rb | Gruf.Helpers.run_server | def run_server(server)
grpc_server = server.server
t = Thread.new { grpc_server.run }
grpc_server.wait_till_running
begin
yield
ensure
grpc_server.stop
sleep(0.1) until grpc_server.stopped?
t.join
end
end | ruby | def run_server(server)
grpc_server = server.server
t = Thread.new { grpc_server.run }
grpc_server.wait_till_running
begin
yield
ensure
grpc_server.stop
sleep(0.1) until grpc_server.stopped?
t.join
end
end | [
"def",
"run_server",
"(",
"server",
")",
"grpc_server",
"=",
"server",
".",
"server",
"t",
"=",
"Thread",
".",
"new",
"{",
"grpc_server",
".",
"run",
"}",
"grpc_server",
".",
"wait_till_running",
"begin",
"yield",
"ensure",
"grpc_server",
".",
"stop",
"sleep... | Runs a server
@param [Gruf::Server] server | [
"Runs",
"a",
"server"
] | 9e438b174df81845c8100302da671721d5a112c5 | https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/spec/support/helpers.rb#L65-L78 |
14,899 | bigcommerce/gruf | lib/gruf/error.rb | Gruf.Error.add_field_error | def add_field_error(field_name, error_code, message = '')
@field_errors << Errors::Field.new(field_name, error_code, message)
end | ruby | def add_field_error(field_name, error_code, message = '')
@field_errors << Errors::Field.new(field_name, error_code, message)
end | [
"def",
"add_field_error",
"(",
"field_name",
",",
"error_code",
",",
"message",
"=",
"''",
")",
"@field_errors",
"<<",
"Errors",
"::",
"Field",
".",
"new",
"(",
"field_name",
",",
"error_code",
",",
"message",
")",
"end"
] | Initialize the error, setting default values
@param [Hash] args (Optional) An optional hash of arguments that will set fields on the error object
Add a field error to this error package
@param [Symbol] field_name The field name for the error
@param [Symbol] error_code The application error code for the error; e.g. :job_not_found
@param [String] message The application error message for the error; e.g. "Job not found with ID 123" | [
"Initialize",
"the",
"error",
"setting",
"default",
"values"
] | 9e438b174df81845c8100302da671721d5a112c5 | https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/error.rb#L98-L100 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.