repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
pkubicki/yamled_acl | lib/yamled_acl/controller_extension.rb | YamledAcl.ControllerExtension.authorize_action | def authorize_action
YamledAcl.init(current_user_group_name, params[:controller])
allowed_to?(params[:action]) or raise(YamledAcl::AccessDenied)
end | ruby | def authorize_action
YamledAcl.init(current_user_group_name, params[:controller])
allowed_to?(params[:action]) or raise(YamledAcl::AccessDenied)
end | [
"def",
"authorize_action",
"YamledAcl",
".",
"init",
"(",
"current_user_group_name",
",",
"params",
"[",
":controller",
"]",
")",
"allowed_to?",
"(",
"params",
"[",
":action",
"]",
")",
"or",
"raise",
"(",
"YamledAcl",
"::",
"AccessDenied",
")",
"end"
] | This method should be be called by +before_filter+.
before_filter :authorize_action | [
"This",
"method",
"should",
"be",
"be",
"called",
"by",
"+",
"before_filter",
"+",
"."
] | cd4a02e3b70977112830c5c1f2487e06d43b5a34 | https://github.com/pkubicki/yamled_acl/blob/cd4a02e3b70977112830c5c1f2487e06d43b5a34/lib/yamled_acl/controller_extension.rb#L56-L59 | train |
gluons/mysticonfig | lib/mysticonfig.rb | Mysticonfig.Loader.load | def load
config_file = find_file @filenames
config = Utils.load_auto config_file
config.empty? ? @default_config : @default_config.merge(config)
end | ruby | def load
config_file = find_file @filenames
config = Utils.load_auto config_file
config.empty? ? @default_config : @default_config.merge(config)
end | [
"def",
"load",
"config_file",
"=",
"find_file",
"@filenames",
"config",
"=",
"Utils",
".",
"load_auto",
"config_file",
"config",
".",
"empty?",
"?",
"@default_config",
":",
"@default_config",
".",
"merge",
"(",
"config",
")",
"end"
] | Find and load config file. | [
"Find",
"and",
"load",
"config",
"file",
"."
] | 4bc6354a3f1f77e76f1f1211e9f26acc044ff539 | https://github.com/gluons/mysticonfig/blob/4bc6354a3f1f77e76f1f1211e9f26acc044ff539/lib/mysticonfig.rb#L16-L21 | train |
gluons/mysticonfig | lib/mysticonfig.rb | Mysticonfig.Loader.load_json | def load_json
json_config_file = Utils.lookup_file @filenames[:json]
config = Utils.load_json json_config_file
config.empty? ? @default_config : @default_config.merge(config)
end | ruby | def load_json
json_config_file = Utils.lookup_file @filenames[:json]
config = Utils.load_json json_config_file
config.empty? ? @default_config : @default_config.merge(config)
end | [
"def",
"load_json",
"json_config_file",
"=",
"Utils",
".",
"lookup_file",
"@filenames",
"[",
":json",
"]",
"config",
"=",
"Utils",
".",
"load_json",
"json_config_file",
"config",
".",
"empty?",
"?",
"@default_config",
":",
"@default_config",
".",
"merge",
"(",
"config",
")",
"end"
] | Find and load JSON config file. | [
"Find",
"and",
"load",
"JSON",
"config",
"file",
"."
] | 4bc6354a3f1f77e76f1f1211e9f26acc044ff539 | https://github.com/gluons/mysticonfig/blob/4bc6354a3f1f77e76f1f1211e9f26acc044ff539/lib/mysticonfig.rb#L25-L30 | train |
gluons/mysticonfig | lib/mysticonfig.rb | Mysticonfig.Loader.load_yaml | def load_yaml
yaml_config_files = @filenames[:yaml]
yaml_config_file = nil
yaml_config_files.each do |file|
yaml_config_file = Utils.lookup_file file
unless yaml_config_file.nil?
config = Utils.load_yaml(yaml_config_file)
return config.empty? ? @default_config : @default_config.merge(config)
end
end
@default_config # Return default config when can't load config file
end | ruby | def load_yaml
yaml_config_files = @filenames[:yaml]
yaml_config_file = nil
yaml_config_files.each do |file|
yaml_config_file = Utils.lookup_file file
unless yaml_config_file.nil?
config = Utils.load_yaml(yaml_config_file)
return config.empty? ? @default_config : @default_config.merge(config)
end
end
@default_config # Return default config when can't load config file
end | [
"def",
"load_yaml",
"yaml_config_files",
"=",
"@filenames",
"[",
":yaml",
"]",
"yaml_config_file",
"=",
"nil",
"yaml_config_files",
".",
"each",
"do",
"|",
"file",
"|",
"yaml_config_file",
"=",
"Utils",
".",
"lookup_file",
"file",
"unless",
"yaml_config_file",
".",
"nil?",
"config",
"=",
"Utils",
".",
"load_yaml",
"(",
"yaml_config_file",
")",
"return",
"config",
".",
"empty?",
"?",
"@default_config",
":",
"@default_config",
".",
"merge",
"(",
"config",
")",
"end",
"end",
"@default_config",
"end"
] | Find and load YAML config file. | [
"Find",
"and",
"load",
"YAML",
"config",
"file",
"."
] | 4bc6354a3f1f77e76f1f1211e9f26acc044ff539 | https://github.com/gluons/mysticonfig/blob/4bc6354a3f1f77e76f1f1211e9f26acc044ff539/lib/mysticonfig.rb#L34-L47 | train |
georgyangelov/vcs-toolkit | lib/vcs_toolkit/diff.rb | VCSToolkit.Diff.new_content | def new_content(conflict_start='<<<', conflict_switch='>>>', conflict_end='===')
flat_map do |change|
if change.conflict?
version_one = change.diff_one.new_content(conflict_start, conflict_switch, conflict_end)
version_two = change.diff_two.new_content(conflict_start, conflict_switch, conflict_end)
[conflict_start] + version_one + [conflict_switch] + version_two + [conflict_end]
elsif change.deleting?
[]
else
[change.new_element]
end
end
end | ruby | def new_content(conflict_start='<<<', conflict_switch='>>>', conflict_end='===')
flat_map do |change|
if change.conflict?
version_one = change.diff_one.new_content(conflict_start, conflict_switch, conflict_end)
version_two = change.diff_two.new_content(conflict_start, conflict_switch, conflict_end)
[conflict_start] + version_one + [conflict_switch] + version_two + [conflict_end]
elsif change.deleting?
[]
else
[change.new_element]
end
end
end | [
"def",
"new_content",
"(",
"conflict_start",
"=",
"'<<<'",
",",
"conflict_switch",
"=",
"'>>>'",
",",
"conflict_end",
"=",
"'==='",
")",
"flat_map",
"do",
"|",
"change",
"|",
"if",
"change",
".",
"conflict?",
"version_one",
"=",
"change",
".",
"diff_one",
".",
"new_content",
"(",
"conflict_start",
",",
"conflict_switch",
",",
"conflict_end",
")",
"version_two",
"=",
"change",
".",
"diff_two",
".",
"new_content",
"(",
"conflict_start",
",",
"conflict_switch",
",",
"conflict_end",
")",
"[",
"conflict_start",
"]",
"+",
"version_one",
"+",
"[",
"conflict_switch",
"]",
"+",
"version_two",
"+",
"[",
"conflict_end",
"]",
"elsif",
"change",
".",
"deleting?",
"[",
"]",
"else",
"[",
"change",
".",
"new_element",
"]",
"end",
"end",
"end"
] | Reconstruct the new sequence from the diff | [
"Reconstruct",
"the",
"new",
"sequence",
"from",
"the",
"diff"
] | 9d73735da090a5e0f612aee04f423306fa512f38 | https://github.com/georgyangelov/vcs-toolkit/blob/9d73735da090a5e0f612aee04f423306fa512f38/lib/vcs_toolkit/diff.rb#L42-L55 | train |
finn-francis/ruby-edit | lib/ruby_edit/source_file.rb | RubyEdit.SourceFile.populate | def populate(content, **options)
generator.create_file(RubyEdit::SOURCE_FILE_LOCATION,
content,
force: true,
verbose: false,
**options)
end | ruby | def populate(content, **options)
generator.create_file(RubyEdit::SOURCE_FILE_LOCATION,
content,
force: true,
verbose: false,
**options)
end | [
"def",
"populate",
"(",
"content",
",",
"**",
"options",
")",
"generator",
".",
"create_file",
"(",
"RubyEdit",
"::",
"SOURCE_FILE_LOCATION",
",",
"content",
",",
"force",
":",
"true",
",",
"verbose",
":",
"false",
",",
"**",
"options",
")",
"end"
] | Populates the sourcefile with the given content
@param content [String] - Usually the output of a bash command
@param **options [key value pairs] -
See https://github.com/piotrmurach/tty-file for TTY::File docs | [
"Populates",
"the",
"sourcefile",
"with",
"the",
"given",
"content"
] | 90022f4de01b420f5321f12c490566d0a1e19a29 | https://github.com/finn-francis/ruby-edit/blob/90022f4de01b420f5321f12c490566d0a1e19a29/lib/ruby_edit/source_file.rb#L16-L22 | train |
cjfuller/rimageanalysistools | lib/rimageanalysistools/skeletonizer.rb | RImageAnalysisTools.Skeletonizer.compute_n | def compute_n(ic)
temp_ic = ImageCoordinate.cloneCoord(ic)
n = -1 # compensate for 0,0 case
x_off = [-1,0,1]
y_off = [-1,0,1]
x_off.each do |x|
y_off.each do |y|
temp_ic[:x] = ic[:x] + x
temp_ic[:y] = ic[:y] + y
if @im.inBounds(temp_ic) and @im[temp_ic] == @im[ic] then
n += 1
end
end
end
temp_ic.recycle
n
end | ruby | def compute_n(ic)
temp_ic = ImageCoordinate.cloneCoord(ic)
n = -1 # compensate for 0,0 case
x_off = [-1,0,1]
y_off = [-1,0,1]
x_off.each do |x|
y_off.each do |y|
temp_ic[:x] = ic[:x] + x
temp_ic[:y] = ic[:y] + y
if @im.inBounds(temp_ic) and @im[temp_ic] == @im[ic] then
n += 1
end
end
end
temp_ic.recycle
n
end | [
"def",
"compute_n",
"(",
"ic",
")",
"temp_ic",
"=",
"ImageCoordinate",
".",
"cloneCoord",
"(",
"ic",
")",
"n",
"=",
"-",
"1",
"x_off",
"=",
"[",
"-",
"1",
",",
"0",
",",
"1",
"]",
"y_off",
"=",
"[",
"-",
"1",
",",
"0",
",",
"1",
"]",
"x_off",
".",
"each",
"do",
"|",
"x",
"|",
"y_off",
".",
"each",
"do",
"|",
"y",
"|",
"temp_ic",
"[",
":x",
"]",
"=",
"ic",
"[",
":x",
"]",
"+",
"x",
"temp_ic",
"[",
":y",
"]",
"=",
"ic",
"[",
":y",
"]",
"+",
"y",
"if",
"@im",
".",
"inBounds",
"(",
"temp_ic",
")",
"and",
"@im",
"[",
"temp_ic",
"]",
"==",
"@im",
"[",
"ic",
"]",
"then",
"n",
"+=",
"1",
"end",
"end",
"end",
"temp_ic",
".",
"recycle",
"n",
"end"
] | implementation of skeletonization algorithm presented in Gonzalez & Woods, p 651-652 | [
"implementation",
"of",
"skeletonization",
"algorithm",
"presented",
"in",
"Gonzalez",
"&",
"Woods",
"p",
"651",
"-",
"652"
] | 991aa7a61a8ad7bd902a31d99a19ce135e3cc485 | https://github.com/cjfuller/rimageanalysistools/blob/991aa7a61a8ad7bd902a31d99a19ce135e3cc485/lib/rimageanalysistools/skeletonizer.rb#L44-L71 | train |
mrlhumphreys/board_game_grid | lib/board_game_grid/square_set.rb | BoardGameGrid.SquareSet.where | def where(hash)
res = hash.inject(squares) do |memo, (attribute, value)|
memo.select { |square| square.attribute_match?(attribute, value) }
end
self.class.new(squares: res)
end | ruby | def where(hash)
res = hash.inject(squares) do |memo, (attribute, value)|
memo.select { |square| square.attribute_match?(attribute, value) }
end
self.class.new(squares: res)
end | [
"def",
"where",
"(",
"hash",
")",
"res",
"=",
"hash",
".",
"inject",
"(",
"squares",
")",
"do",
"|",
"memo",
",",
"(",
"attribute",
",",
"value",
")",
"|",
"memo",
".",
"select",
"{",
"|",
"square",
"|",
"square",
".",
"attribute_match?",
"(",
"attribute",
",",
"value",
")",
"}",
"end",
"self",
".",
"class",
".",
"new",
"(",
"squares",
":",
"res",
")",
"end"
] | Filter the squares with a hash of attribute and matching values.
@param [Hash] hash
attributes to query for.
@return [SquareSet]
==== Example:
# Find all squares where piece is nil
square_set.where(piece: nil) | [
"Filter",
"the",
"squares",
"with",
"a",
"hash",
"of",
"attribute",
"and",
"matching",
"values",
"."
] | df07a84c7f7db076d055c6063f1e418f0c8ed288 | https://github.com/mrlhumphreys/board_game_grid/blob/df07a84c7f7db076d055c6063f1e418f0c8ed288/lib/board_game_grid/square_set.rb#L128-L133 | train |
mrlhumphreys/board_game_grid | lib/board_game_grid/square_set.rb | BoardGameGrid.SquareSet.find_by_x_and_y | def find_by_x_and_y(x, y)
select { |square| square.x == x && square.y == y }.first
end | ruby | def find_by_x_and_y(x, y)
select { |square| square.x == x && square.y == y }.first
end | [
"def",
"find_by_x_and_y",
"(",
"x",
",",
"y",
")",
"select",
"{",
"|",
"square",
"|",
"square",
".",
"x",
"==",
"x",
"&&",
"square",
".",
"y",
"==",
"y",
"}",
".",
"first",
"end"
] | Find the square with the matching x and y co-ordinates
@param [Fixnum] x
the x co-ordinate.
@param [Fixnum] y
the y co-ordinate.
@return [Square]
==== Example:
# Find the square at 4,2
square_set.find_by_x_and_y(4, 2) | [
"Find",
"the",
"square",
"with",
"the",
"matching",
"x",
"and",
"y",
"co",
"-",
"ordinates"
] | df07a84c7f7db076d055c6063f1e418f0c8ed288 | https://github.com/mrlhumphreys/board_game_grid/blob/df07a84c7f7db076d055c6063f1e418f0c8ed288/lib/board_game_grid/square_set.rb#L160-L162 | train |
mrlhumphreys/board_game_grid | lib/board_game_grid/square_set.rb | BoardGameGrid.SquareSet.in_range | def in_range(origin, distance)
select { |square| Vector.new(origin, square).magnitude <= distance }
end | ruby | def in_range(origin, distance)
select { |square| Vector.new(origin, square).magnitude <= distance }
end | [
"def",
"in_range",
"(",
"origin",
",",
"distance",
")",
"select",
"{",
"|",
"square",
"|",
"Vector",
".",
"new",
"(",
"origin",
",",
"square",
")",
".",
"magnitude",
"<=",
"distance",
"}",
"end"
] | Find all squares within distance of square
@param [Square] square
the originating square
@param [Fixnum] distance
the specified distance from the square
@return [SquareSet]
==== Example:
# Get all squares within 2 squares of square_a
square_set.in_range(square_a, 2) | [
"Find",
"all",
"squares",
"within",
"distance",
"of",
"square"
] | df07a84c7f7db076d055c6063f1e418f0c8ed288 | https://github.com/mrlhumphreys/board_game_grid/blob/df07a84c7f7db076d055c6063f1e418f0c8ed288/lib/board_game_grid/square_set.rb#L176-L178 | train |
mrlhumphreys/board_game_grid | lib/board_game_grid/square_set.rb | BoardGameGrid.SquareSet.at_range | def at_range(origin, distance)
select { |square| Vector.new(origin, square).magnitude == distance }
end | ruby | def at_range(origin, distance)
select { |square| Vector.new(origin, square).magnitude == distance }
end | [
"def",
"at_range",
"(",
"origin",
",",
"distance",
")",
"select",
"{",
"|",
"square",
"|",
"Vector",
".",
"new",
"(",
"origin",
",",
"square",
")",
".",
"magnitude",
"==",
"distance",
"}",
"end"
] | Find all squares at distance of square
@param [Square] square
the originating square
@param [Fixnum] distance
the specified distance from the square
@return [SquareSet]
==== Example:
# Get all squares at 2 squares from square_a
square_set.at_range(square_a, 2) | [
"Find",
"all",
"squares",
"at",
"distance",
"of",
"square"
] | df07a84c7f7db076d055c6063f1e418f0c8ed288 | https://github.com/mrlhumphreys/board_game_grid/blob/df07a84c7f7db076d055c6063f1e418f0c8ed288/lib/board_game_grid/square_set.rb#L192-L194 | train |
mrlhumphreys/board_game_grid | lib/board_game_grid/square_set.rb | BoardGameGrid.SquareSet.unblocked | def unblocked(origin, square_set)
select { |destination| square_set.between(origin, destination).all?(&:unoccupied?) }
end | ruby | def unblocked(origin, square_set)
select { |destination| square_set.between(origin, destination).all?(&:unoccupied?) }
end | [
"def",
"unblocked",
"(",
"origin",
",",
"square_set",
")",
"select",
"{",
"|",
"destination",
"|",
"square_set",
".",
"between",
"(",
"origin",
",",
"destination",
")",
".",
"all?",
"(",
"&",
":unoccupied?",
")",
"}",
"end"
] | Returns destination from the origin that have a clear path
@param [Square] origin
the originating square.
@param [SquareSet] square_set
the board position.
@return [SquareSet] | [
"Returns",
"destination",
"from",
"the",
"origin",
"that",
"have",
"a",
"clear",
"path"
] | df07a84c7f7db076d055c6063f1e418f0c8ed288 | https://github.com/mrlhumphreys/board_game_grid/blob/df07a84c7f7db076d055c6063f1e418f0c8ed288/lib/board_game_grid/square_set.rb#L264-L266 | train |
mrlhumphreys/board_game_grid | lib/board_game_grid/square_set.rb | BoardGameGrid.SquareSet.between | def between(origin, destination)
vector = Vector.new(origin, destination)
if vector.diagonal? || vector.orthogonal?
point_counter = origin.point
direction = vector.direction
_squares = []
while point_counter != destination.point
point_counter = point_counter + direction
square = find_by_x_and_y(point_counter.x, point_counter.y)
if square && square.point != destination.point
_squares.push(square)
end
end
else
_squares = []
end
self.class.new(squares: _squares)
end | ruby | def between(origin, destination)
vector = Vector.new(origin, destination)
if vector.diagonal? || vector.orthogonal?
point_counter = origin.point
direction = vector.direction
_squares = []
while point_counter != destination.point
point_counter = point_counter + direction
square = find_by_x_and_y(point_counter.x, point_counter.y)
if square && square.point != destination.point
_squares.push(square)
end
end
else
_squares = []
end
self.class.new(squares: _squares)
end | [
"def",
"between",
"(",
"origin",
",",
"destination",
")",
"vector",
"=",
"Vector",
".",
"new",
"(",
"origin",
",",
"destination",
")",
"if",
"vector",
".",
"diagonal?",
"||",
"vector",
".",
"orthogonal?",
"point_counter",
"=",
"origin",
".",
"point",
"direction",
"=",
"vector",
".",
"direction",
"_squares",
"=",
"[",
"]",
"while",
"point_counter",
"!=",
"destination",
".",
"point",
"point_counter",
"=",
"point_counter",
"+",
"direction",
"square",
"=",
"find_by_x_and_y",
"(",
"point_counter",
".",
"x",
",",
"point_counter",
".",
"y",
")",
"if",
"square",
"&&",
"square",
".",
"point",
"!=",
"destination",
".",
"point",
"_squares",
".",
"push",
"(",
"square",
")",
"end",
"end",
"else",
"_squares",
"=",
"[",
"]",
"end",
"self",
".",
"class",
".",
"new",
"(",
"squares",
":",
"_squares",
")",
"end"
] | Returns squares between a and b.
Only squares that are in the same diagonal will return squares.
@param [Square] a
a square.
@param [Square] b
another square.
@return [SquareSet]
==== Example:
# Get all squares between square_a and square_b
square_set.between(square_a, square_b) | [
"Returns",
"squares",
"between",
"a",
"and",
"b",
".",
"Only",
"squares",
"that",
"are",
"in",
"the",
"same",
"diagonal",
"will",
"return",
"squares",
"."
] | df07a84c7f7db076d055c6063f1e418f0c8ed288 | https://github.com/mrlhumphreys/board_game_grid/blob/df07a84c7f7db076d055c6063f1e418f0c8ed288/lib/board_game_grid/square_set.rb#L282-L302 | train |
bradfeehan/derelict | lib/derelict/parser/version.rb | Derelict.Parser::Version.version | def version
logger.debug "Parsing version from output using #{description}"
matches = output.match PARSE_VERSION_FROM_OUTPUT
raise InvalidFormat.new output if matches.nil?
matches.captures[0]
end | ruby | def version
logger.debug "Parsing version from output using #{description}"
matches = output.match PARSE_VERSION_FROM_OUTPUT
raise InvalidFormat.new output if matches.nil?
matches.captures[0]
end | [
"def",
"version",
"logger",
".",
"debug",
"\"Parsing version from output using #{description}\"",
"matches",
"=",
"output",
".",
"match",
"PARSE_VERSION_FROM_OUTPUT",
"raise",
"InvalidFormat",
".",
"new",
"output",
"if",
"matches",
".",
"nil?",
"matches",
".",
"captures",
"[",
"0",
"]",
"end"
] | Determines the version of Vagrant based on the output | [
"Determines",
"the",
"version",
"of",
"Vagrant",
"based",
"on",
"the",
"output"
] | c9d70f04562280a34083dd060b0e4099e6f32d8d | https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/parser/version.rb#L13-L18 | train |
eunomie/valr | lib/valr/repo.rb | Valr.Repo.full_changelog | def full_changelog(first_parent: false, range: nil, branch: nil, from_ancestor_with: nil)
changelog_list = changelog first_parent: first_parent, range: range, branch: branch, from_ancestor_with: from_ancestor_with
if !range.nil?
header = full_changelog_header_range range
elsif !branch.nil?
header = full_changelog_header_branch branch, from_ancestor_with
else
header = full_changelog_header_no_range
end
[header, changelog_list].join "\n"
end | ruby | def full_changelog(first_parent: false, range: nil, branch: nil, from_ancestor_with: nil)
changelog_list = changelog first_parent: first_parent, range: range, branch: branch, from_ancestor_with: from_ancestor_with
if !range.nil?
header = full_changelog_header_range range
elsif !branch.nil?
header = full_changelog_header_branch branch, from_ancestor_with
else
header = full_changelog_header_no_range
end
[header, changelog_list].join "\n"
end | [
"def",
"full_changelog",
"(",
"first_parent",
":",
"false",
",",
"range",
":",
"nil",
",",
"branch",
":",
"nil",
",",
"from_ancestor_with",
":",
"nil",
")",
"changelog_list",
"=",
"changelog",
"first_parent",
":",
"first_parent",
",",
"range",
":",
"range",
",",
"branch",
":",
"branch",
",",
"from_ancestor_with",
":",
"from_ancestor_with",
"if",
"!",
"range",
".",
"nil?",
"header",
"=",
"full_changelog_header_range",
"range",
"elsif",
"!",
"branch",
".",
"nil?",
"header",
"=",
"full_changelog_header_branch",
"branch",
",",
"from_ancestor_with",
"else",
"header",
"=",
"full_changelog_header_no_range",
"end",
"[",
"header",
",",
"changelog_list",
"]",
".",
"join",
"\"\\n\"",
"end"
] | Get the full changelog including metadata.
@param [Boolean] first_parent Optional, if true limits to first parent commits
@param [String] range Optional, define a specific range of commits
@param [String] branch Optional, show commits in a branch
@param [String] from_ancestor_with Optional, from common ancestor with this branch
@return [String] changelog | [
"Get",
"the",
"full",
"changelog",
"including",
"metadata",
"."
] | f6a79ab33dbed0be21b1609405a667139524a251 | https://github.com/eunomie/valr/blob/f6a79ab33dbed0be21b1609405a667139524a251/lib/valr/repo.rb#L38-L48 | train |
eunomie/valr | lib/valr/repo.rb | Valr.Repo.log_messages | def log_messages(first_parent = false, range = nil, branch = nil, from_ancestor_with = nil)
walker = Rugged::Walker.new @repo
if !range.nil?
begin
walker.push_range range
rescue Rugged::ReferenceError
raise Valr::NotValidRangeError.new range
end
elsif !branch.nil?
b = @repo.references["refs/heads/#{branch}"]
raise Valr::NotValidBranchError.new branch if b.nil?
if !from_ancestor_with.nil?
a = @repo.references["refs/heads/#{from_ancestor_with}"]
raise Valr::NotValidBranchError.new from_ancestor_with if a.nil?
base = @repo.merge_base b.target_id, a.target_id
walker.push_range "#{base}..#{b.target_id}"
else
walker.push b.target_id
end
else
walker.push @repo.head.target_id
end
walker.simplify_first_parent if first_parent
message_list = walker.inject([]) { |messages, c| messages << c.message }
walker.reset
message_list
end | ruby | def log_messages(first_parent = false, range = nil, branch = nil, from_ancestor_with = nil)
walker = Rugged::Walker.new @repo
if !range.nil?
begin
walker.push_range range
rescue Rugged::ReferenceError
raise Valr::NotValidRangeError.new range
end
elsif !branch.nil?
b = @repo.references["refs/heads/#{branch}"]
raise Valr::NotValidBranchError.new branch if b.nil?
if !from_ancestor_with.nil?
a = @repo.references["refs/heads/#{from_ancestor_with}"]
raise Valr::NotValidBranchError.new from_ancestor_with if a.nil?
base = @repo.merge_base b.target_id, a.target_id
walker.push_range "#{base}..#{b.target_id}"
else
walker.push b.target_id
end
else
walker.push @repo.head.target_id
end
walker.simplify_first_parent if first_parent
message_list = walker.inject([]) { |messages, c| messages << c.message }
walker.reset
message_list
end | [
"def",
"log_messages",
"(",
"first_parent",
"=",
"false",
",",
"range",
"=",
"nil",
",",
"branch",
"=",
"nil",
",",
"from_ancestor_with",
"=",
"nil",
")",
"walker",
"=",
"Rugged",
"::",
"Walker",
".",
"new",
"@repo",
"if",
"!",
"range",
".",
"nil?",
"begin",
"walker",
".",
"push_range",
"range",
"rescue",
"Rugged",
"::",
"ReferenceError",
"raise",
"Valr",
"::",
"NotValidRangeError",
".",
"new",
"range",
"end",
"elsif",
"!",
"branch",
".",
"nil?",
"b",
"=",
"@repo",
".",
"references",
"[",
"\"refs/heads/#{branch}\"",
"]",
"raise",
"Valr",
"::",
"NotValidBranchError",
".",
"new",
"branch",
"if",
"b",
".",
"nil?",
"if",
"!",
"from_ancestor_with",
".",
"nil?",
"a",
"=",
"@repo",
".",
"references",
"[",
"\"refs/heads/#{from_ancestor_with}\"",
"]",
"raise",
"Valr",
"::",
"NotValidBranchError",
".",
"new",
"from_ancestor_with",
"if",
"a",
".",
"nil?",
"base",
"=",
"@repo",
".",
"merge_base",
"b",
".",
"target_id",
",",
"a",
".",
"target_id",
"walker",
".",
"push_range",
"\"#{base}..#{b.target_id}\"",
"else",
"walker",
".",
"push",
"b",
".",
"target_id",
"end",
"else",
"walker",
".",
"push",
"@repo",
".",
"head",
".",
"target_id",
"end",
"walker",
".",
"simplify_first_parent",
"if",
"first_parent",
"message_list",
"=",
"walker",
".",
"inject",
"(",
"[",
"]",
")",
"{",
"|",
"messages",
",",
"c",
"|",
"messages",
"<<",
"c",
".",
"message",
"}",
"walker",
".",
"reset",
"message_list",
"end"
] | Get log messages for a repository
@param [Boolean] first_parent Optional, if true limit to first parent commits
@param [String] range Optional, define a specific range of commits
@param [String] branch Optional, show commits in a branch
@param [String] from_ancestor_with Optional, from common ancestor with this branch
@return [Array<String>] log messages | [
"Get",
"log",
"messages",
"for",
"a",
"repository"
] | f6a79ab33dbed0be21b1609405a667139524a251 | https://github.com/eunomie/valr/blob/f6a79ab33dbed0be21b1609405a667139524a251/lib/valr/repo.rb#L76-L102 | train |
eunomie/valr | lib/valr/repo.rb | Valr.Repo.full_changelog_header_range | def full_changelog_header_range(range)
from, to = range.split '..'
from_commit, to_commit = [from, to].map { |ref| rev_parse ref }
Koios::Doc.write {
[pre(["from: #{from} <#{from_commit.oid}>",
"to: #{to} <#{to_commit.oid}>"])]
}
end | ruby | def full_changelog_header_range(range)
from, to = range.split '..'
from_commit, to_commit = [from, to].map { |ref| rev_parse ref }
Koios::Doc.write {
[pre(["from: #{from} <#{from_commit.oid}>",
"to: #{to} <#{to_commit.oid}>"])]
}
end | [
"def",
"full_changelog_header_range",
"(",
"range",
")",
"from",
",",
"to",
"=",
"range",
".",
"split",
"'..'",
"from_commit",
",",
"to_commit",
"=",
"[",
"from",
",",
"to",
"]",
".",
"map",
"{",
"|",
"ref",
"|",
"rev_parse",
"ref",
"}",
"Koios",
"::",
"Doc",
".",
"write",
"{",
"[",
"pre",
"(",
"[",
"\"from: #{from} <#{from_commit.oid}>\"",
",",
"\"to: #{to} <#{to_commit.oid}>\"",
"]",
")",
"]",
"}",
"end"
] | Get the header when a range is defined
@param [String] range Define a specific range of commits
@return [String] header with a range | [
"Get",
"the",
"header",
"when",
"a",
"range",
"is",
"defined"
] | f6a79ab33dbed0be21b1609405a667139524a251 | https://github.com/eunomie/valr/blob/f6a79ab33dbed0be21b1609405a667139524a251/lib/valr/repo.rb#L114-L121 | train |
eunomie/valr | lib/valr/repo.rb | Valr.Repo.full_changelog_header_branch | def full_changelog_header_branch(branch, ancestor)
h = ["branch: #{branch} <#{@repo.references["refs/heads/#{branch}"].target_id}>"]
h << "from ancestor with: #{ancestor} <#{@repo.references["refs/heads/#{ancestor}"].target_id}>" unless ancestor.nil?
Koios::Doc.write {[pre(h)]}
end | ruby | def full_changelog_header_branch(branch, ancestor)
h = ["branch: #{branch} <#{@repo.references["refs/heads/#{branch}"].target_id}>"]
h << "from ancestor with: #{ancestor} <#{@repo.references["refs/heads/#{ancestor}"].target_id}>" unless ancestor.nil?
Koios::Doc.write {[pre(h)]}
end | [
"def",
"full_changelog_header_branch",
"(",
"branch",
",",
"ancestor",
")",
"h",
"=",
"[",
"\"branch: #{branch} <#{@repo.references[\"refs/heads/#{branch}\"].target_id}>\"",
"]",
"h",
"<<",
"\"from ancestor with: #{ancestor} <#{@repo.references[\"refs/heads/#{ancestor}\"].target_id}>\"",
"unless",
"ancestor",
".",
"nil?",
"Koios",
"::",
"Doc",
".",
"write",
"{",
"[",
"pre",
"(",
"h",
")",
"]",
"}",
"end"
] | Get the header when a branch is defined
@param [String] branch Show commits for a branch
@param [String] ancestor Ancestor or nil
@return [String] header with a branch | [
"Get",
"the",
"header",
"when",
"a",
"branch",
"is",
"defined"
] | f6a79ab33dbed0be21b1609405a667139524a251 | https://github.com/eunomie/valr/blob/f6a79ab33dbed0be21b1609405a667139524a251/lib/valr/repo.rb#L127-L131 | train |
OiNutter/grayskull | lib/grayskull/validator.rb | Grayskull.Validator.match_node | def match_node(node,expected,label)
#check type
if !check_type(node,expected['type'],label,expected['ok_empty'])
@errors.push('Error: node ' + label + ' is not of an accepted type. Should be one of ' + expected['accepts'].join(', '))
return false
end
if (node.kind_of?(Hash) || node.kind_of?(Array))
if node.empty? && !expected['ok_empty']
@errors.push('Error: node ' + label + ' cannot be empty')
return false
elsif !node.empty? && expected.has_key?('accepts')
valid_content = false
if node.kind_of?(Hash)
matched = []
unmatched = []
node.each_pair{
|key,value|
expected['accepts'].each{
|accepts|
result = check_type(value,accepts,key)
if result
matched.push(key)
if !unmatched.find_index(key).nil?
unmatched.slice(unmatched.find_index(key))
end
break
else
unmatched.push(key)
end
}
}
if(matched.count==node.count)
valid_content = true
else
unmatched.each{
|node|
@errors.push('Error: node ' + node + ' is not of an accepted type. Should be one of ' + expected['accepts'].join(', '))
}
end
elsif node.kind_of?(Array)
matched = []
unmatched = []
node.each_index{
|n|
expected['accepts'].each{
|accepts|
key = label + '[' + n.to_s + ']'
result = check_type(node[n],accepts,key)
if result
matched.push(key)
if !unmatched.find_index(key).nil?
unmatched.slice(unmatched.find_index(key))
end
break
else
unmatched.push(key)
end
}
}
if(matched.count==node.count)
valid_content = true
else
unmatched.each{
|node|
@errors.push('Error: node ' + node + ' is not of an accepted type. Should be one of ' + expected['accepts'].join(', '))
}
end
end
if !valid_content
@errors.push('Error: node ' + label + ' contains an unaccepted type.')
return false
end
end
end
return true
end | ruby | def match_node(node,expected,label)
#check type
if !check_type(node,expected['type'],label,expected['ok_empty'])
@errors.push('Error: node ' + label + ' is not of an accepted type. Should be one of ' + expected['accepts'].join(', '))
return false
end
if (node.kind_of?(Hash) || node.kind_of?(Array))
if node.empty? && !expected['ok_empty']
@errors.push('Error: node ' + label + ' cannot be empty')
return false
elsif !node.empty? && expected.has_key?('accepts')
valid_content = false
if node.kind_of?(Hash)
matched = []
unmatched = []
node.each_pair{
|key,value|
expected['accepts'].each{
|accepts|
result = check_type(value,accepts,key)
if result
matched.push(key)
if !unmatched.find_index(key).nil?
unmatched.slice(unmatched.find_index(key))
end
break
else
unmatched.push(key)
end
}
}
if(matched.count==node.count)
valid_content = true
else
unmatched.each{
|node|
@errors.push('Error: node ' + node + ' is not of an accepted type. Should be one of ' + expected['accepts'].join(', '))
}
end
elsif node.kind_of?(Array)
matched = []
unmatched = []
node.each_index{
|n|
expected['accepts'].each{
|accepts|
key = label + '[' + n.to_s + ']'
result = check_type(node[n],accepts,key)
if result
matched.push(key)
if !unmatched.find_index(key).nil?
unmatched.slice(unmatched.find_index(key))
end
break
else
unmatched.push(key)
end
}
}
if(matched.count==node.count)
valid_content = true
else
unmatched.each{
|node|
@errors.push('Error: node ' + node + ' is not of an accepted type. Should be one of ' + expected['accepts'].join(', '))
}
end
end
if !valid_content
@errors.push('Error: node ' + label + ' contains an unaccepted type.')
return false
end
end
end
return true
end | [
"def",
"match_node",
"(",
"node",
",",
"expected",
",",
"label",
")",
"if",
"!",
"check_type",
"(",
"node",
",",
"expected",
"[",
"'type'",
"]",
",",
"label",
",",
"expected",
"[",
"'ok_empty'",
"]",
")",
"@errors",
".",
"push",
"(",
"'Error: node '",
"+",
"label",
"+",
"' is not of an accepted type. Should be one of '",
"+",
"expected",
"[",
"'accepts'",
"]",
".",
"join",
"(",
"', '",
")",
")",
"return",
"false",
"end",
"if",
"(",
"node",
".",
"kind_of?",
"(",
"Hash",
")",
"||",
"node",
".",
"kind_of?",
"(",
"Array",
")",
")",
"if",
"node",
".",
"empty?",
"&&",
"!",
"expected",
"[",
"'ok_empty'",
"]",
"@errors",
".",
"push",
"(",
"'Error: node '",
"+",
"label",
"+",
"' cannot be empty'",
")",
"return",
"false",
"elsif",
"!",
"node",
".",
"empty?",
"&&",
"expected",
".",
"has_key?",
"(",
"'accepts'",
")",
"valid_content",
"=",
"false",
"if",
"node",
".",
"kind_of?",
"(",
"Hash",
")",
"matched",
"=",
"[",
"]",
"unmatched",
"=",
"[",
"]",
"node",
".",
"each_pair",
"{",
"|",
"key",
",",
"value",
"|",
"expected",
"[",
"'accepts'",
"]",
".",
"each",
"{",
"|",
"accepts",
"|",
"result",
"=",
"check_type",
"(",
"value",
",",
"accepts",
",",
"key",
")",
"if",
"result",
"matched",
".",
"push",
"(",
"key",
")",
"if",
"!",
"unmatched",
".",
"find_index",
"(",
"key",
")",
".",
"nil?",
"unmatched",
".",
"slice",
"(",
"unmatched",
".",
"find_index",
"(",
"key",
")",
")",
"end",
"break",
"else",
"unmatched",
".",
"push",
"(",
"key",
")",
"end",
"}",
"}",
"if",
"(",
"matched",
".",
"count",
"==",
"node",
".",
"count",
")",
"valid_content",
"=",
"true",
"else",
"unmatched",
".",
"each",
"{",
"|",
"node",
"|",
"@errors",
".",
"push",
"(",
"'Error: node '",
"+",
"node",
"+",
"' is not of an accepted type. Should be one of '",
"+",
"expected",
"[",
"'accepts'",
"]",
".",
"join",
"(",
"', '",
")",
")",
"}",
"end",
"elsif",
"node",
".",
"kind_of?",
"(",
"Array",
")",
"matched",
"=",
"[",
"]",
"unmatched",
"=",
"[",
"]",
"node",
".",
"each_index",
"{",
"|",
"n",
"|",
"expected",
"[",
"'accepts'",
"]",
".",
"each",
"{",
"|",
"accepts",
"|",
"key",
"=",
"label",
"+",
"'['",
"+",
"n",
".",
"to_s",
"+",
"']'",
"result",
"=",
"check_type",
"(",
"node",
"[",
"n",
"]",
",",
"accepts",
",",
"key",
")",
"if",
"result",
"matched",
".",
"push",
"(",
"key",
")",
"if",
"!",
"unmatched",
".",
"find_index",
"(",
"key",
")",
".",
"nil?",
"unmatched",
".",
"slice",
"(",
"unmatched",
".",
"find_index",
"(",
"key",
")",
")",
"end",
"break",
"else",
"unmatched",
".",
"push",
"(",
"key",
")",
"end",
"}",
"}",
"if",
"(",
"matched",
".",
"count",
"==",
"node",
".",
"count",
")",
"valid_content",
"=",
"true",
"else",
"unmatched",
".",
"each",
"{",
"|",
"node",
"|",
"@errors",
".",
"push",
"(",
"'Error: node '",
"+",
"node",
"+",
"' is not of an accepted type. Should be one of '",
"+",
"expected",
"[",
"'accepts'",
"]",
".",
"join",
"(",
"', '",
")",
")",
"}",
"end",
"end",
"if",
"!",
"valid_content",
"@errors",
".",
"push",
"(",
"'Error: node '",
"+",
"label",
"+",
"' contains an unaccepted type.'",
")",
"return",
"false",
"end",
"end",
"end",
"return",
"true",
"end"
] | Checks file node matches the schema.
Checks type of node against expected type and
checks any children are of the accepted types. | [
"Checks",
"file",
"node",
"matches",
"the",
"schema",
"."
] | c0bcdebcd1ef8220c61953e75c941edf0ae5df16 | https://github.com/OiNutter/grayskull/blob/c0bcdebcd1ef8220c61953e75c941edf0ae5df16/lib/grayskull/validator.rb#L65-L164 | train |
OiNutter/grayskull | lib/grayskull/validator.rb | Grayskull.Validator.check_type | def check_type(node,expected_type,label,accept_nil = false)
valid_type = true;
if(@types.has_key?(expected_type))
valid_type = match_node(node,@types[expected_type],label)
elsif node.class.to_s != expected_type && !(node.kind_of?(NilClass) && (expected_type=='empty' || accept_nil))
valid_type = false
end
return valid_type
end | ruby | def check_type(node,expected_type,label,accept_nil = false)
valid_type = true;
if(@types.has_key?(expected_type))
valid_type = match_node(node,@types[expected_type],label)
elsif node.class.to_s != expected_type && !(node.kind_of?(NilClass) && (expected_type=='empty' || accept_nil))
valid_type = false
end
return valid_type
end | [
"def",
"check_type",
"(",
"node",
",",
"expected_type",
",",
"label",
",",
"accept_nil",
"=",
"false",
")",
"valid_type",
"=",
"true",
";",
"if",
"(",
"@types",
".",
"has_key?",
"(",
"expected_type",
")",
")",
"valid_type",
"=",
"match_node",
"(",
"node",
",",
"@types",
"[",
"expected_type",
"]",
",",
"label",
")",
"elsif",
"node",
".",
"class",
".",
"to_s",
"!=",
"expected_type",
"&&",
"!",
"(",
"node",
".",
"kind_of?",
"(",
"NilClass",
")",
"&&",
"(",
"expected_type",
"==",
"'empty'",
"||",
"accept_nil",
")",
")",
"valid_type",
"=",
"false",
"end",
"return",
"valid_type",
"end"
] | Checks that the node is of the correct type
If the expected node is a custom node type as defined in the schema
It will run `match_node` to check that the node schema matches the
custom type. | [
"Checks",
"that",
"the",
"node",
"is",
"of",
"the",
"correct",
"type"
] | c0bcdebcd1ef8220c61953e75c941edf0ae5df16 | https://github.com/OiNutter/grayskull/blob/c0bcdebcd1ef8220c61953e75c941edf0ae5df16/lib/grayskull/validator.rb#L171-L182 | train |
barnabyalter/microservice_precompiler | lib/microservice_precompiler/builder.rb | MicroservicePrecompiler.Builder.cleanup | def cleanup(sprocket_assets = [:javascripts, :stylesheets])
# Remove previous dist path
FileUtils.rm_r build_path if File.exists?(build_path)
# Clean compass project
Compass::Exec::SubCommandUI.new(["clean", project_root]).run!
# Don't initialize Compass assets, the config will take care of it
sprocket_assets.each do |asset|
FileUtils.mkdir_p File.join(build_path, asset.to_s)
end
if mustaches_config_file_exists?
mustaches_yaml.each_key do |dir|
FileUtils.mkdir_p File.join(build_path, dir.to_s)
end
end
end | ruby | def cleanup(sprocket_assets = [:javascripts, :stylesheets])
# Remove previous dist path
FileUtils.rm_r build_path if File.exists?(build_path)
# Clean compass project
Compass::Exec::SubCommandUI.new(["clean", project_root]).run!
# Don't initialize Compass assets, the config will take care of it
sprocket_assets.each do |asset|
FileUtils.mkdir_p File.join(build_path, asset.to_s)
end
if mustaches_config_file_exists?
mustaches_yaml.each_key do |dir|
FileUtils.mkdir_p File.join(build_path, dir.to_s)
end
end
end | [
"def",
"cleanup",
"(",
"sprocket_assets",
"=",
"[",
":javascripts",
",",
":stylesheets",
"]",
")",
"FileUtils",
".",
"rm_r",
"build_path",
"if",
"File",
".",
"exists?",
"(",
"build_path",
")",
"Compass",
"::",
"Exec",
"::",
"SubCommandUI",
".",
"new",
"(",
"[",
"\"clean\"",
",",
"project_root",
"]",
")",
".",
"run!",
"sprocket_assets",
".",
"each",
"do",
"|",
"asset",
"|",
"FileUtils",
".",
"mkdir_p",
"File",
".",
"join",
"(",
"build_path",
",",
"asset",
".",
"to_s",
")",
"end",
"if",
"mustaches_config_file_exists?",
"mustaches_yaml",
".",
"each_key",
"do",
"|",
"dir",
"|",
"FileUtils",
".",
"mkdir_p",
"File",
".",
"join",
"(",
"build_path",
",",
"dir",
".",
"to_s",
")",
"end",
"end",
"end"
] | Public function for running cleanup of previous build | [
"Public",
"function",
"for",
"running",
"cleanup",
"of",
"previous",
"build"
] | c485955eaf27ab70970426b4aeecd20740ac482c | https://github.com/barnabyalter/microservice_precompiler/blob/c485955eaf27ab70970426b4aeecd20740ac482c/lib/microservice_precompiler/builder.rb#L32-L46 | train |
barnabyalter/microservice_precompiler | lib/microservice_precompiler/builder.rb | MicroservicePrecompiler.Builder.sprockets_build | def sprockets_build(sprocket_assets = [:javascripts, :stylesheets])
sprocket_assets.each do |asset_type|
load_path = File.join(@project_root, asset_type.to_s)
next unless File.exists?(load_path)
sprockets_env.append_path load_path
Dir.new(load_path).each do |filename|
file = File.join(load_path, filename)
if File.file?(file)
asset = sprockets_env[filename]
attributes = sprockets_env.find_asset(asset.pathname)
# logical_path is the filename
build_file = File.join(build_path, asset_type.to_s, attributes.logical_path)
File.open(build_file, 'w') do |f|
extension = attributes.logical_path.split(".").last
f.write(minify(asset, extension))
end
end
end
end
end | ruby | def sprockets_build(sprocket_assets = [:javascripts, :stylesheets])
sprocket_assets.each do |asset_type|
load_path = File.join(@project_root, asset_type.to_s)
next unless File.exists?(load_path)
sprockets_env.append_path load_path
Dir.new(load_path).each do |filename|
file = File.join(load_path, filename)
if File.file?(file)
asset = sprockets_env[filename]
attributes = sprockets_env.find_asset(asset.pathname)
# logical_path is the filename
build_file = File.join(build_path, asset_type.to_s, attributes.logical_path)
File.open(build_file, 'w') do |f|
extension = attributes.logical_path.split(".").last
f.write(minify(asset, extension))
end
end
end
end
end | [
"def",
"sprockets_build",
"(",
"sprocket_assets",
"=",
"[",
":javascripts",
",",
":stylesheets",
"]",
")",
"sprocket_assets",
".",
"each",
"do",
"|",
"asset_type",
"|",
"load_path",
"=",
"File",
".",
"join",
"(",
"@project_root",
",",
"asset_type",
".",
"to_s",
")",
"next",
"unless",
"File",
".",
"exists?",
"(",
"load_path",
")",
"sprockets_env",
".",
"append_path",
"load_path",
"Dir",
".",
"new",
"(",
"load_path",
")",
".",
"each",
"do",
"|",
"filename",
"|",
"file",
"=",
"File",
".",
"join",
"(",
"load_path",
",",
"filename",
")",
"if",
"File",
".",
"file?",
"(",
"file",
")",
"asset",
"=",
"sprockets_env",
"[",
"filename",
"]",
"attributes",
"=",
"sprockets_env",
".",
"find_asset",
"(",
"asset",
".",
"pathname",
")",
"build_file",
"=",
"File",
".",
"join",
"(",
"build_path",
",",
"asset_type",
".",
"to_s",
",",
"attributes",
".",
"logical_path",
")",
"File",
".",
"open",
"(",
"build_file",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"extension",
"=",
"attributes",
".",
"logical_path",
".",
"split",
"(",
"\".\"",
")",
".",
"last",
"f",
".",
"write",
"(",
"minify",
"(",
"asset",
",",
"extension",
")",
")",
"end",
"end",
"end",
"end",
"end"
] | Public function for building sprockets assets and minifying | [
"Public",
"function",
"for",
"building",
"sprockets",
"assets",
"and",
"minifying"
] | c485955eaf27ab70970426b4aeecd20740ac482c | https://github.com/barnabyalter/microservice_precompiler/blob/c485955eaf27ab70970426b4aeecd20740ac482c/lib/microservice_precompiler/builder.rb#L55-L74 | train |
barnabyalter/microservice_precompiler | lib/microservice_precompiler/builder.rb | MicroservicePrecompiler.Builder.mustache_template_build | def mustache_template_build(dir, template_file, logic_file)
# Get the class name from an underscore-named file
logic_class_name = underscore_to_camelcase(logic_file)
# Output file should match the syntax of the mustaches config
output_file = logic_file
# Now we can name the logic_file to underscored version
logic_file = camelcase_to_underscore(logic_file)
# Require logic file, used to generate content from template
require File.join(project_root, camelcase_to_underscore(dir), logic_file)
# Create relevant directory path
FileUtils.mkdir_p File.join(build_path, dir.to_s)
# Instantiate class from required file
mustache = Kernel.const_get(logic_class_name).new
# Set the template file
mustache.template_file = File.join(project_root, camelcase_to_underscore(dir), template_file) + ".html.mustache"
# Get the name of the file we will write to after it's template is processed
build_file = File.join(build_path, dir, "#{output_file}.html")
File.open(build_file, 'w') do |f|
f.write(mustache.render)
end
end | ruby | def mustache_template_build(dir, template_file, logic_file)
# Get the class name from an underscore-named file
logic_class_name = underscore_to_camelcase(logic_file)
# Output file should match the syntax of the mustaches config
output_file = logic_file
# Now we can name the logic_file to underscored version
logic_file = camelcase_to_underscore(logic_file)
# Require logic file, used to generate content from template
require File.join(project_root, camelcase_to_underscore(dir), logic_file)
# Create relevant directory path
FileUtils.mkdir_p File.join(build_path, dir.to_s)
# Instantiate class from required file
mustache = Kernel.const_get(logic_class_name).new
# Set the template file
mustache.template_file = File.join(project_root, camelcase_to_underscore(dir), template_file) + ".html.mustache"
# Get the name of the file we will write to after it's template is processed
build_file = File.join(build_path, dir, "#{output_file}.html")
File.open(build_file, 'w') do |f|
f.write(mustache.render)
end
end | [
"def",
"mustache_template_build",
"(",
"dir",
",",
"template_file",
",",
"logic_file",
")",
"logic_class_name",
"=",
"underscore_to_camelcase",
"(",
"logic_file",
")",
"output_file",
"=",
"logic_file",
"logic_file",
"=",
"camelcase_to_underscore",
"(",
"logic_file",
")",
"require",
"File",
".",
"join",
"(",
"project_root",
",",
"camelcase_to_underscore",
"(",
"dir",
")",
",",
"logic_file",
")",
"FileUtils",
".",
"mkdir_p",
"File",
".",
"join",
"(",
"build_path",
",",
"dir",
".",
"to_s",
")",
"mustache",
"=",
"Kernel",
".",
"const_get",
"(",
"logic_class_name",
")",
".",
"new",
"mustache",
".",
"template_file",
"=",
"File",
".",
"join",
"(",
"project_root",
",",
"camelcase_to_underscore",
"(",
"dir",
")",
",",
"template_file",
")",
"+",
"\".html.mustache\"",
"build_file",
"=",
"File",
".",
"join",
"(",
"build_path",
",",
"dir",
",",
"\"#{output_file}.html\"",
")",
"File",
".",
"open",
"(",
"build_file",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"mustache",
".",
"render",
")",
"end",
"end"
] | Render html from a mustache template | [
"Render",
"html",
"from",
"a",
"mustache",
"template"
] | c485955eaf27ab70970426b4aeecd20740ac482c | https://github.com/barnabyalter/microservice_precompiler/blob/c485955eaf27ab70970426b4aeecd20740ac482c/lib/microservice_precompiler/builder.rb#L128-L148 | train |
barnabyalter/microservice_precompiler | lib/microservice_precompiler/builder.rb | MicroservicePrecompiler.Builder.underscore_to_camelcase | def underscore_to_camelcase(underscore_string)
underscore_string = underscore_string.gsub(/(_)/,' ').split(' ').each { |word| word.capitalize! }.join("") unless underscore_string.match(/_/).nil?
underscore_string = underscore_string if underscore_string.match(/_/).nil?
return underscore_string
end | ruby | def underscore_to_camelcase(underscore_string)
underscore_string = underscore_string.gsub(/(_)/,' ').split(' ').each { |word| word.capitalize! }.join("") unless underscore_string.match(/_/).nil?
underscore_string = underscore_string if underscore_string.match(/_/).nil?
return underscore_string
end | [
"def",
"underscore_to_camelcase",
"(",
"underscore_string",
")",
"underscore_string",
"=",
"underscore_string",
".",
"gsub",
"(",
"/",
"/",
",",
"' '",
")",
".",
"split",
"(",
"' '",
")",
".",
"each",
"{",
"|",
"word",
"|",
"word",
".",
"capitalize!",
"}",
".",
"join",
"(",
"\"\"",
")",
"unless",
"underscore_string",
".",
"match",
"(",
"/",
"/",
")",
".",
"nil?",
"underscore_string",
"=",
"underscore_string",
"if",
"underscore_string",
".",
"match",
"(",
"/",
"/",
")",
".",
"nil?",
"return",
"underscore_string",
"end"
] | Conver underscore to camelcase | [
"Conver",
"underscore",
"to",
"camelcase"
] | c485955eaf27ab70970426b4aeecd20740ac482c | https://github.com/barnabyalter/microservice_precompiler/blob/c485955eaf27ab70970426b4aeecd20740ac482c/lib/microservice_precompiler/builder.rb#L156-L160 | train |
barnabyalter/microservice_precompiler | lib/microservice_precompiler/builder.rb | MicroservicePrecompiler.Builder.sprockets_env | def sprockets_env
@sprockets_env ||= Sprockets::Environment.new(project_root) { |env| env.logger = Logger.new(STDOUT) }
end | ruby | def sprockets_env
@sprockets_env ||= Sprockets::Environment.new(project_root) { |env| env.logger = Logger.new(STDOUT) }
end | [
"def",
"sprockets_env",
"@sprockets_env",
"||=",
"Sprockets",
"::",
"Environment",
".",
"new",
"(",
"project_root",
")",
"{",
"|",
"env",
"|",
"env",
".",
"logger",
"=",
"Logger",
".",
"new",
"(",
"STDOUT",
")",
"}",
"end"
] | Initialize sprockets environment | [
"Initialize",
"sprockets",
"environment"
] | c485955eaf27ab70970426b4aeecd20740ac482c | https://github.com/barnabyalter/microservice_precompiler/blob/c485955eaf27ab70970426b4aeecd20740ac482c/lib/microservice_precompiler/builder.rb#L163-L165 | train |
barnabyalter/microservice_precompiler | lib/microservice_precompiler/builder.rb | MicroservicePrecompiler.Builder.minify | def minify(asset, format)
asset = asset.to_s
# Minify JS
return Uglifier.compile(asset) if format.eql?("js")
# Minify CSS
return YUI::CssCompressor.new.compress(asset) if format.eql?("css")
# Return string representation if not minimizing
return asset
end | ruby | def minify(asset, format)
asset = asset.to_s
# Minify JS
return Uglifier.compile(asset) if format.eql?("js")
# Minify CSS
return YUI::CssCompressor.new.compress(asset) if format.eql?("css")
# Return string representation if not minimizing
return asset
end | [
"def",
"minify",
"(",
"asset",
",",
"format",
")",
"asset",
"=",
"asset",
".",
"to_s",
"return",
"Uglifier",
".",
"compile",
"(",
"asset",
")",
"if",
"format",
".",
"eql?",
"(",
"\"js\"",
")",
"return",
"YUI",
"::",
"CssCompressor",
".",
"new",
".",
"compress",
"(",
"asset",
")",
"if",
"format",
".",
"eql?",
"(",
"\"css\"",
")",
"return",
"asset",
"end"
] | Minify assets in format | [
"Minify",
"assets",
"in",
"format"
] | c485955eaf27ab70970426b4aeecd20740ac482c | https://github.com/barnabyalter/microservice_precompiler/blob/c485955eaf27ab70970426b4aeecd20740ac482c/lib/microservice_precompiler/builder.rb#L168-L176 | train |
jeremyd/virtualmonkey | lib/virtualmonkey/deployment_runner.rb | VirtualMonkey.DeploymentRunner.launch_all | def launch_all
@servers.each { |s|
begin
object_behavior(s, :start)
rescue Exception => e
raise e unless e.message =~ /AlreadyLaunchedError/
end
}
end | ruby | def launch_all
@servers.each { |s|
begin
object_behavior(s, :start)
rescue Exception => e
raise e unless e.message =~ /AlreadyLaunchedError/
end
}
end | [
"def",
"launch_all",
"@servers",
".",
"each",
"{",
"|",
"s",
"|",
"begin",
"object_behavior",
"(",
"s",
",",
":start",
")",
"rescue",
"Exception",
"=>",
"e",
"raise",
"e",
"unless",
"e",
".",
"message",
"=~",
"/",
"/",
"end",
"}",
"end"
] | Launch all servers in the deployment. | [
"Launch",
"all",
"servers",
"in",
"the",
"deployment",
"."
] | b2c7255f20ac5ec881eb90afbb5e712160db0dcb | https://github.com/jeremyd/virtualmonkey/blob/b2c7255f20ac5ec881eb90afbb5e712160db0dcb/lib/virtualmonkey/deployment_runner.rb#L57-L65 | train |
jeremyd/virtualmonkey | lib/virtualmonkey/deployment_runner.rb | VirtualMonkey.DeploymentRunner.check_monitoring | def check_monitoring
@servers.each do |server|
server.settings
response = nil
count = 0
until response || count > 20 do
begin
response = server.monitoring
rescue
response = nil
count += 1
sleep 10
end
end
raise "Fatal: Failed to verify that monitoring is operational" unless response
#TODO: pass in some list of plugin info to check multiple values. For now just
# hardcoding the cpu check
sleep 60 # This is to allow monitoring data to accumulate
monitor=server.get_sketchy_data({'start'=>-60,'end'=>-20,'plugin_name'=>"cpu-0",'plugin_type'=>"cpu-idle"})
idle_values = monitor['data']['value']
raise "No cpu idle data" unless idle_values.length > 0
raise "No idle time" unless idle_values[0] > 0
puts "Monitoring is OK for #{server.nickname}"
end
end | ruby | def check_monitoring
@servers.each do |server|
server.settings
response = nil
count = 0
until response || count > 20 do
begin
response = server.monitoring
rescue
response = nil
count += 1
sleep 10
end
end
raise "Fatal: Failed to verify that monitoring is operational" unless response
#TODO: pass in some list of plugin info to check multiple values. For now just
# hardcoding the cpu check
sleep 60 # This is to allow monitoring data to accumulate
monitor=server.get_sketchy_data({'start'=>-60,'end'=>-20,'plugin_name'=>"cpu-0",'plugin_type'=>"cpu-idle"})
idle_values = monitor['data']['value']
raise "No cpu idle data" unless idle_values.length > 0
raise "No idle time" unless idle_values[0] > 0
puts "Monitoring is OK for #{server.nickname}"
end
end | [
"def",
"check_monitoring",
"@servers",
".",
"each",
"do",
"|",
"server",
"|",
"server",
".",
"settings",
"response",
"=",
"nil",
"count",
"=",
"0",
"until",
"response",
"||",
"count",
">",
"20",
"do",
"begin",
"response",
"=",
"server",
".",
"monitoring",
"rescue",
"response",
"=",
"nil",
"count",
"+=",
"1",
"sleep",
"10",
"end",
"end",
"raise",
"\"Fatal: Failed to verify that monitoring is operational\"",
"unless",
"response",
"sleep",
"60",
"monitor",
"=",
"server",
".",
"get_sketchy_data",
"(",
"{",
"'start'",
"=>",
"-",
"60",
",",
"'end'",
"=>",
"-",
"20",
",",
"'plugin_name'",
"=>",
"\"cpu-0\"",
",",
"'plugin_type'",
"=>",
"\"cpu-idle\"",
"}",
")",
"idle_values",
"=",
"monitor",
"[",
"'data'",
"]",
"[",
"'value'",
"]",
"raise",
"\"No cpu idle data\"",
"unless",
"idle_values",
".",
"length",
">",
"0",
"raise",
"\"No idle time\"",
"unless",
"idle_values",
"[",
"0",
"]",
">",
"0",
"puts",
"\"Monitoring is OK for #{server.nickname}\"",
"end",
"end"
] | Checks that monitoring is enabled on all servers in the deployment. Will raise an error if monitoring is not enabled. | [
"Checks",
"that",
"monitoring",
"is",
"enabled",
"on",
"all",
"servers",
"in",
"the",
"deployment",
".",
"Will",
"raise",
"an",
"error",
"if",
"monitoring",
"is",
"not",
"enabled",
"."
] | b2c7255f20ac5ec881eb90afbb5e712160db0dcb | https://github.com/jeremyd/virtualmonkey/blob/b2c7255f20ac5ec881eb90afbb5e712160db0dcb/lib/virtualmonkey/deployment_runner.rb#L248-L272 | train |
malditogeek/redisrecord | lib/redisrecord.rb | RedisRecord.Model.add_attributes | def add_attributes(hash)
hash.each_pair do |k,v|
k = k.to_sym
#raise DuplicateAttribute.new("#{k}") unless (k == :id or !self.respond_to?(k))
if k == :id or !self.respond_to?(k)
@cached_attrs[k] = v
meta = class << self; self; end
meta.send(:define_method, k) { @cached_attrs[k] }
meta.send(:define_method, "#{k}=") do |new_value|
@cached_attrs[k] = new_value.is_a?(RedisRecord::Model) ? new_value.id : new_value
@stored_attrs.delete(k)
end
end
end
hash
end | ruby | def add_attributes(hash)
hash.each_pair do |k,v|
k = k.to_sym
#raise DuplicateAttribute.new("#{k}") unless (k == :id or !self.respond_to?(k))
if k == :id or !self.respond_to?(k)
@cached_attrs[k] = v
meta = class << self; self; end
meta.send(:define_method, k) { @cached_attrs[k] }
meta.send(:define_method, "#{k}=") do |new_value|
@cached_attrs[k] = new_value.is_a?(RedisRecord::Model) ? new_value.id : new_value
@stored_attrs.delete(k)
end
end
end
hash
end | [
"def",
"add_attributes",
"(",
"hash",
")",
"hash",
".",
"each_pair",
"do",
"|",
"k",
",",
"v",
"|",
"k",
"=",
"k",
".",
"to_sym",
"if",
"k",
"==",
":id",
"or",
"!",
"self",
".",
"respond_to?",
"(",
"k",
")",
"@cached_attrs",
"[",
"k",
"]",
"=",
"v",
"meta",
"=",
"class",
"<<",
"self",
";",
"self",
";",
"end",
"meta",
".",
"send",
"(",
":define_method",
",",
"k",
")",
"{",
"@cached_attrs",
"[",
"k",
"]",
"}",
"meta",
".",
"send",
"(",
":define_method",
",",
"\"#{k}=\"",
")",
"do",
"|",
"new_value",
"|",
"@cached_attrs",
"[",
"k",
"]",
"=",
"new_value",
".",
"is_a?",
"(",
"RedisRecord",
"::",
"Model",
")",
"?",
"new_value",
".",
"id",
":",
"new_value",
"@stored_attrs",
".",
"delete",
"(",
"k",
")",
"end",
"end",
"end",
"hash",
"end"
] | Add attributes to the instance cache and define the accessor methods | [
"Add",
"attributes",
"to",
"the",
"instance",
"cache",
"and",
"define",
"the",
"accessor",
"methods"
] | ae2d9904c622559904b9b6b02f00f9e9635525d1 | https://github.com/malditogeek/redisrecord/blob/ae2d9904c622559904b9b6b02f00f9e9635525d1/lib/redisrecord.rb#L343-L358 | train |
malditogeek/redisrecord | lib/redisrecord.rb | RedisRecord.Model.add_foreign_keys_as_attributes | def add_foreign_keys_as_attributes
@@reflections[self.class.name.to_sym][:belongs_to].each do |klass|
add_attribute klass.to_s.foreign_key.to_sym
end
end | ruby | def add_foreign_keys_as_attributes
@@reflections[self.class.name.to_sym][:belongs_to].each do |klass|
add_attribute klass.to_s.foreign_key.to_sym
end
end | [
"def",
"add_foreign_keys_as_attributes",
"@@reflections",
"[",
"self",
".",
"class",
".",
"name",
".",
"to_sym",
"]",
"[",
":belongs_to",
"]",
".",
"each",
"do",
"|",
"klass",
"|",
"add_attribute",
"klass",
".",
"to_s",
".",
"foreign_key",
".",
"to_sym",
"end",
"end"
] | Add the foreign key for the belongs_to relationships | [
"Add",
"the",
"foreign",
"key",
"for",
"the",
"belongs_to",
"relationships"
] | ae2d9904c622559904b9b6b02f00f9e9635525d1 | https://github.com/malditogeek/redisrecord/blob/ae2d9904c622559904b9b6b02f00f9e9635525d1/lib/redisrecord.rb#L366-L370 | train |
jutonz/dctl_rb | lib/dctl/main.rb | Dctl.Main.image_tag | def image_tag(image, version: current_version_for_image(image))
org = settings.org
project = settings.project
tag = "#{org}/#{project}-#{env}-#{image}"
if !version.nil?
version = version.to_i
tag +=
if version.negative?
current_version = current_version_for_image(image)
":#{current_version.to_i + version}"
else
":#{version}"
end
end
tag
end | ruby | def image_tag(image, version: current_version_for_image(image))
org = settings.org
project = settings.project
tag = "#{org}/#{project}-#{env}-#{image}"
if !version.nil?
version = version.to_i
tag +=
if version.negative?
current_version = current_version_for_image(image)
":#{current_version.to_i + version}"
else
":#{version}"
end
end
tag
end | [
"def",
"image_tag",
"(",
"image",
",",
"version",
":",
"current_version_for_image",
"(",
"image",
")",
")",
"org",
"=",
"settings",
".",
"org",
"project",
"=",
"settings",
".",
"project",
"tag",
"=",
"\"#{org}/#{project}-#{env}-#{image}\"",
"if",
"!",
"version",
".",
"nil?",
"version",
"=",
"version",
".",
"to_i",
"tag",
"+=",
"if",
"version",
".",
"negative?",
"current_version",
"=",
"current_version_for_image",
"(",
"image",
")",
"\":#{current_version.to_i + version}\"",
"else",
"\":#{version}\"",
"end",
"end",
"tag",
"end"
] | Generate the full tag for the given image, concatenating the org,
project, env, image name, and version.
Pass `version: nil` to exclude the version portion.
@example
image_tag("app") # => jutonz/dctl-dev-app:1 | [
"Generate",
"the",
"full",
"tag",
"for",
"the",
"given",
"image",
"concatenating",
"the",
"org",
"project",
"env",
"image",
"name",
"and",
"version",
"."
] | 55bae93a0ae642841231abe862a578344b732c5f | https://github.com/jutonz/dctl_rb/blob/55bae93a0ae642841231abe862a578344b732c5f/lib/dctl/main.rb#L18-L35 | train |
jutonz/dctl_rb | lib/dctl/main.rb | Dctl.Main.config_path | def config_path
path = File.expand_path ".dctl.yml", Dir.pwd
unless File.exist? path
error = "Could not find config file at #{path}"
puts Rainbow(error).red
exit 1
end
path
end | ruby | def config_path
path = File.expand_path ".dctl.yml", Dir.pwd
unless File.exist? path
error = "Could not find config file at #{path}"
puts Rainbow(error).red
exit 1
end
path
end | [
"def",
"config_path",
"path",
"=",
"File",
".",
"expand_path",
"\".dctl.yml\"",
",",
"Dir",
".",
"pwd",
"unless",
"File",
".",
"exist?",
"path",
"error",
"=",
"\"Could not find config file at #{path}\"",
"puts",
"Rainbow",
"(",
"error",
")",
".",
"red",
"exit",
"1",
"end",
"path",
"end"
] | Returns the path to the .dctl.yml file for the current project | [
"Returns",
"the",
"path",
"to",
"the",
".",
"dctl",
".",
"yml",
"file",
"for",
"the",
"current",
"project"
] | 55bae93a0ae642841231abe862a578344b732c5f | https://github.com/jutonz/dctl_rb/blob/55bae93a0ae642841231abe862a578344b732c5f/lib/dctl/main.rb#L90-L100 | train |
jutonz/dctl_rb | lib/dctl/main.rb | Dctl.Main.define_custom_commands | def define_custom_commands(klass)
Array(settings.custom_commands).each do |command, args|
klass.send(:desc, command, "[Custom Command] #{command}")
# Concat with string so we can use exec rather than executing multiple
# subshells. Exec allows us to reuse the shell in which dctl is being
# executed, so we get to do things like reuse sudo authorizations
# rather than always having to prmopt.
concatenated = Array(args).join(" && ").strip
klass.send(:define_method, command, -> do
stream_output(concatenated, exec: true)
end)
end
end | ruby | def define_custom_commands(klass)
Array(settings.custom_commands).each do |command, args|
klass.send(:desc, command, "[Custom Command] #{command}")
# Concat with string so we can use exec rather than executing multiple
# subshells. Exec allows us to reuse the shell in which dctl is being
# executed, so we get to do things like reuse sudo authorizations
# rather than always having to prmopt.
concatenated = Array(args).join(" && ").strip
klass.send(:define_method, command, -> do
stream_output(concatenated, exec: true)
end)
end
end | [
"def",
"define_custom_commands",
"(",
"klass",
")",
"Array",
"(",
"settings",
".",
"custom_commands",
")",
".",
"each",
"do",
"|",
"command",
",",
"args",
"|",
"klass",
".",
"send",
"(",
":desc",
",",
"command",
",",
"\"[Custom Command] #{command}\"",
")",
"concatenated",
"=",
"Array",
"(",
"args",
")",
".",
"join",
"(",
"\" && \"",
")",
".",
"strip",
"klass",
".",
"send",
"(",
":define_method",
",",
"command",
",",
"->",
"do",
"stream_output",
"(",
"concatenated",
",",
"exec",
":",
"true",
")",
"end",
")",
"end",
"end"
] | If there are user defined commands in .dctl.yml, dynamically add them to
the passed thor CLI so they may be executed. | [
"If",
"there",
"are",
"user",
"defined",
"commands",
"in",
".",
"dctl",
".",
"yml",
"dynamically",
"add",
"them",
"to",
"the",
"passed",
"thor",
"CLI",
"so",
"they",
"may",
"be",
"executed",
"."
] | 55bae93a0ae642841231abe862a578344b732c5f | https://github.com/jutonz/dctl_rb/blob/55bae93a0ae642841231abe862a578344b732c5f/lib/dctl/main.rb#L164-L177 | train |
jutonz/dctl_rb | lib/dctl/main.rb | Dctl.Main.check_settings! | def check_settings!
required_keys = %w(
org
project
)
required_keys.each do |key|
unless Settings.send key
error = "Config is missing required key '#{key}'. Please add it " \
"to #{config_path} and try again."
error += "\n\nFor more info, see https://github.com/jutonz/dctl_rb#required-keys"
puts Rainbow(error).red
exit 1
end
end
end | ruby | def check_settings!
required_keys = %w(
org
project
)
required_keys.each do |key|
unless Settings.send key
error = "Config is missing required key '#{key}'. Please add it " \
"to #{config_path} and try again."
error += "\n\nFor more info, see https://github.com/jutonz/dctl_rb#required-keys"
puts Rainbow(error).red
exit 1
end
end
end | [
"def",
"check_settings!",
"required_keys",
"=",
"%w(",
"org",
"project",
")",
"required_keys",
".",
"each",
"do",
"|",
"key",
"|",
"unless",
"Settings",
".",
"send",
"key",
"error",
"=",
"\"Config is missing required key '#{key}'. Please add it \"",
"\"to #{config_path} and try again.\"",
"error",
"+=",
"\"\\n\\nFor more info, see https://github.com/jutonz/dctl_rb#required-keys\"",
"puts",
"Rainbow",
"(",
"error",
")",
".",
"red",
"exit",
"1",
"end",
"end",
"end"
] | Ensure the current project's .dctl.yml contains all the requisite keys. | [
"Ensure",
"the",
"current",
"project",
"s",
".",
"dctl",
".",
"yml",
"contains",
"all",
"the",
"requisite",
"keys",
"."
] | 55bae93a0ae642841231abe862a578344b732c5f | https://github.com/jutonz/dctl_rb/blob/55bae93a0ae642841231abe862a578344b732c5f/lib/dctl/main.rb#L181-L196 | train |
sinefunc/sinatra-helpers | lib/sinatra/helpers.rb | Sinatra.Helpers.select_options | def select_options(pairs, current = nil, prompt = nil)
pairs.unshift([prompt, '']) if prompt
pairs.map { |label, value|
tag(:option, label, :value => value, :selected => (current == value))
}.join("\n")
end | ruby | def select_options(pairs, current = nil, prompt = nil)
pairs.unshift([prompt, '']) if prompt
pairs.map { |label, value|
tag(:option, label, :value => value, :selected => (current == value))
}.join("\n")
end | [
"def",
"select_options",
"(",
"pairs",
",",
"current",
"=",
"nil",
",",
"prompt",
"=",
"nil",
")",
"pairs",
".",
"unshift",
"(",
"[",
"prompt",
",",
"''",
"]",
")",
"if",
"prompt",
"pairs",
".",
"map",
"{",
"|",
"label",
",",
"value",
"|",
"tag",
"(",
":option",
",",
"label",
",",
":value",
"=>",
"value",
",",
":selected",
"=>",
"(",
"current",
"==",
"value",
")",
")",
"}",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] | Accepts a list of pairs and produces option tags.
@example
select_options([['One', 1], ['Two', 2]])
select_options([['One', 1], ['Two', 2]], 1)
select_options([['One', 1], ['Two', 2]], 1, '- Choose -')
# using it with the provided date helpers...
select_options year_choices, 2010 # select 2010 as default
select_options month_choices, 5 # select May as default
select_options day_choices, 25 # select the 25th as default
@param [Array] pairs a collection of label, value tuples.
@param [Object] current the current value of this select.
@param [#to_s] prompt a default prompt to place at the beginning
of the list. | [
"Accepts",
"a",
"list",
"of",
"pairs",
"and",
"produces",
"option",
"tags",
"."
] | d13b3caf83fdc0ba73a8d1a3fab80f562fbbcdb4 | https://github.com/sinefunc/sinatra-helpers/blob/d13b3caf83fdc0ba73a8d1a3fab80f562fbbcdb4/lib/sinatra/helpers.rb#L122-L128 | train |
sinefunc/sinatra-helpers | lib/sinatra/helpers.rb | Sinatra.Helpers.errors_on | def errors_on(object, options = { :class => 'errors' }, &block)
return if object.errors.empty?
lines = if object.errors.respond_to?(:full_messages)
object.errors.full_messages
else
HamlErrorPresenter.new(object.errors).present(self, &block)
end
haml_tag(:div, options) do
haml_tag(:ul) do
lines.each do |error|
haml_tag(:li, error)
end
end
end
end | ruby | def errors_on(object, options = { :class => 'errors' }, &block)
return if object.errors.empty?
lines = if object.errors.respond_to?(:full_messages)
object.errors.full_messages
else
HamlErrorPresenter.new(object.errors).present(self, &block)
end
haml_tag(:div, options) do
haml_tag(:ul) do
lines.each do |error|
haml_tag(:li, error)
end
end
end
end | [
"def",
"errors_on",
"(",
"object",
",",
"options",
"=",
"{",
":class",
"=>",
"'errors'",
"}",
",",
"&",
"block",
")",
"return",
"if",
"object",
".",
"errors",
".",
"empty?",
"lines",
"=",
"if",
"object",
".",
"errors",
".",
"respond_to?",
"(",
":full_messages",
")",
"object",
".",
"errors",
".",
"full_messages",
"else",
"HamlErrorPresenter",
".",
"new",
"(",
"object",
".",
"errors",
")",
".",
"present",
"(",
"self",
",",
"&",
"block",
")",
"end",
"haml_tag",
"(",
":div",
",",
"options",
")",
"do",
"haml_tag",
"(",
":ul",
")",
"do",
"lines",
".",
"each",
"do",
"|",
"error",
"|",
"haml_tag",
"(",
":li",
",",
"error",
")",
"end",
"end",
"end",
"end"
] | Presents errors on your form. Takes the explicit approach and assumes
that for every form you have, the copy for the errors are important,
instead of producing canned responses.
Allows you to do the following in your haml view:
@example
- errors_on @user do |e|
- e.on [:email, :not_present], "We need your email address."
- e.on [:password, :not_present], "You must specify a password."
# produces the following:
# <div class="errors">
# <ul>
# <li>We need your email address</li>
# <li>You must specify a password.</li>
# </ul>
# </div>
@param [#errors] object An object responding to #errors. This validation
also checks for the presence of a #full_messages method
in the errors object for compatibility with ActiveRecord
style objects.
@param [Hash] options a hash of HTML attributes to place on the
containing div.
@option options [#to_s] :class (defaults to errors) The css class to put
in the div.
@yield [Sinatra::Helpers::HamlErrorPresenter] an object responding to #on.
@see Sinatra::Helpers::HamlErrorPresenter#on | [
"Presents",
"errors",
"on",
"your",
"form",
".",
"Takes",
"the",
"explicit",
"approach",
"and",
"assumes",
"that",
"for",
"every",
"form",
"you",
"have",
"the",
"copy",
"for",
"the",
"errors",
"are",
"important",
"instead",
"of",
"producing",
"canned",
"responses",
"."
] | d13b3caf83fdc0ba73a8d1a3fab80f562fbbcdb4 | https://github.com/sinefunc/sinatra-helpers/blob/d13b3caf83fdc0ba73a8d1a3fab80f562fbbcdb4/lib/sinatra/helpers.rb#L161-L177 | train |
sinefunc/sinatra-helpers | lib/sinatra/helpers.rb | Sinatra.Helpers.percentage | def percentage(number, precision = 2)
return if number.to_s.empty?
ret = "%02.#{ precision }f%" % number
ret.gsub(/\.0*%$/, '%')
end | ruby | def percentage(number, precision = 2)
return if number.to_s.empty?
ret = "%02.#{ precision }f%" % number
ret.gsub(/\.0*%$/, '%')
end | [
"def",
"percentage",
"(",
"number",
",",
"precision",
"=",
"2",
")",
"return",
"if",
"number",
".",
"to_s",
".",
"empty?",
"ret",
"=",
"\"%02.#{ precision }f%\"",
"%",
"number",
"ret",
".",
"gsub",
"(",
"/",
"\\.",
"/",
",",
"'%'",
")",
"end"
] | Show the percentage representation of a numeric value.
@example
percentage(100) == "100.00%"
percentage(100, 0) == "100%"
@param [Numeric] number A numeric value
@param [Fixnum] precision (defaults to 2) Number of decimals to show.
@return [String] the number displayed as a percentage
@return [nil] given a nil value or an empty string. | [
"Show",
"the",
"percentage",
"representation",
"of",
"a",
"numeric",
"value",
"."
] | d13b3caf83fdc0ba73a8d1a3fab80f562fbbcdb4 | https://github.com/sinefunc/sinatra-helpers/blob/d13b3caf83fdc0ba73a8d1a3fab80f562fbbcdb4/lib/sinatra/helpers.rb#L234-L239 | train |
minch/buoy_data | lib/buoy_data/noaa_buoy_observation.rb | BuoyData.NoaaBuoyObservation.google_chart_url | def google_chart_url
max = 120
response = get_all
return unless response
historical_data = []
response.each_with_index do |row, index|
break if index >= max
next if row.match(/^#/)
row = row.split(/ ?/)
historical_data << row[5]
end
return if historical_data.blank?
historical_data = historical_data.join(',')
[ self.class.google_chart_base(@buoy_id), '&chd=t:', historical_data ].join
end | ruby | def google_chart_url
max = 120
response = get_all
return unless response
historical_data = []
response.each_with_index do |row, index|
break if index >= max
next if row.match(/^#/)
row = row.split(/ ?/)
historical_data << row[5]
end
return if historical_data.blank?
historical_data = historical_data.join(',')
[ self.class.google_chart_base(@buoy_id), '&chd=t:', historical_data ].join
end | [
"def",
"google_chart_url",
"max",
"=",
"120",
"response",
"=",
"get_all",
"return",
"unless",
"response",
"historical_data",
"=",
"[",
"]",
"response",
".",
"each_with_index",
"do",
"|",
"row",
",",
"index",
"|",
"break",
"if",
"index",
">=",
"max",
"next",
"if",
"row",
".",
"match",
"(",
"/",
"/",
")",
"row",
"=",
"row",
".",
"split",
"(",
"/",
"/",
")",
"historical_data",
"<<",
"row",
"[",
"5",
"]",
"end",
"return",
"if",
"historical_data",
".",
"blank?",
"historical_data",
"=",
"historical_data",
".",
"join",
"(",
"','",
")",
"[",
"self",
".",
"class",
".",
"google_chart_base",
"(",
"@buoy_id",
")",
",",
"'&chd=t:'",
",",
"historical_data",
"]",
".",
"join",
"end"
] | Get a graph of the historical data for the given buoy.
Inspired by:
https://github.com/thepug/nbdc_graph/blob/master/generate_graphs.py | [
"Get",
"a",
"graph",
"of",
"the",
"historical",
"data",
"for",
"the",
"given",
"buoy",
"."
] | 6f1e36828ed6df1cb2610d09cc046118291dbe55 | https://github.com/minch/buoy_data/blob/6f1e36828ed6df1cb2610d09cc046118291dbe55/lib/buoy_data/noaa_buoy_observation.rb#L49-L66 | train |
octoai/gem-octocore-cassandra | lib/octocore-cassandra/models/contactus.rb | Octo.ContactUs.send_email | def send_email
# Send thankyou mail
subject = 'Thanks for contacting us - Octo.ai'
opts = {
text: 'Hey we will get in touch with you shortly. Thanks :)',
name: self.firstname + ' ' + self.lastname
}
Octo::Email.send(self.email, subject, opts)
# Send mail to aron and param
Octo.get_config(:email_to).each { |x|
opts1 = {
text: self.email + ' \n\r ' + self.typeofrequest + '\n\r' + self.message,
name: x.fetch('name')
}
Octo::Email.send(x.fetch('email'), subject, opts1)
}
end | ruby | def send_email
# Send thankyou mail
subject = 'Thanks for contacting us - Octo.ai'
opts = {
text: 'Hey we will get in touch with you shortly. Thanks :)',
name: self.firstname + ' ' + self.lastname
}
Octo::Email.send(self.email, subject, opts)
# Send mail to aron and param
Octo.get_config(:email_to).each { |x|
opts1 = {
text: self.email + ' \n\r ' + self.typeofrequest + '\n\r' + self.message,
name: x.fetch('name')
}
Octo::Email.send(x.fetch('email'), subject, opts1)
}
end | [
"def",
"send_email",
"subject",
"=",
"'Thanks for contacting us - Octo.ai'",
"opts",
"=",
"{",
"text",
":",
"'Hey we will get in touch with you shortly. Thanks :)'",
",",
"name",
":",
"self",
".",
"firstname",
"+",
"' '",
"+",
"self",
".",
"lastname",
"}",
"Octo",
"::",
"Email",
".",
"send",
"(",
"self",
".",
"email",
",",
"subject",
",",
"opts",
")",
"Octo",
".",
"get_config",
"(",
":email_to",
")",
".",
"each",
"{",
"|",
"x",
"|",
"opts1",
"=",
"{",
"text",
":",
"self",
".",
"email",
"+",
"' \\n\\r '",
"+",
"self",
".",
"typeofrequest",
"+",
"'\\n\\r'",
"+",
"self",
".",
"message",
",",
"name",
":",
"x",
".",
"fetch",
"(",
"'name'",
")",
"}",
"Octo",
"::",
"Email",
".",
"send",
"(",
"x",
".",
"fetch",
"(",
"'email'",
")",
",",
"subject",
",",
"opts1",
")",
"}",
"end"
] | Send Email after model save | [
"Send",
"Email",
"after",
"model",
"save"
] | c0977dce5ba0eb174ff810f161aba151069935df | https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/models/contactus.rb#L19-L39 | train |
conversation/raca | lib/raca/servers.rb | Raca.Servers.create | def create(server_name, flavor_name, image_name, files = {})
request = {
"server" => {
"name" => server_name,
"imageRef" => image_name_to_id(image_name),
"flavorRef" => flavor_name_to_id(flavor_name),
}
}
files.each do |path, blob|
request['server']['personality'] ||= []
request['server']['personality'] << {
'path' => path,
'contents' => Base64.encode64(blob)
}
end
response = servers_client.post(servers_path, JSON.dump(request), json_headers)
data = JSON.parse(response.body)['server']
Raca::Server.new(@account, @region, data['id'])
end | ruby | def create(server_name, flavor_name, image_name, files = {})
request = {
"server" => {
"name" => server_name,
"imageRef" => image_name_to_id(image_name),
"flavorRef" => flavor_name_to_id(flavor_name),
}
}
files.each do |path, blob|
request['server']['personality'] ||= []
request['server']['personality'] << {
'path' => path,
'contents' => Base64.encode64(blob)
}
end
response = servers_client.post(servers_path, JSON.dump(request), json_headers)
data = JSON.parse(response.body)['server']
Raca::Server.new(@account, @region, data['id'])
end | [
"def",
"create",
"(",
"server_name",
",",
"flavor_name",
",",
"image_name",
",",
"files",
"=",
"{",
"}",
")",
"request",
"=",
"{",
"\"server\"",
"=>",
"{",
"\"name\"",
"=>",
"server_name",
",",
"\"imageRef\"",
"=>",
"image_name_to_id",
"(",
"image_name",
")",
",",
"\"flavorRef\"",
"=>",
"flavor_name_to_id",
"(",
"flavor_name",
")",
",",
"}",
"}",
"files",
".",
"each",
"do",
"|",
"path",
",",
"blob",
"|",
"request",
"[",
"'server'",
"]",
"[",
"'personality'",
"]",
"||=",
"[",
"]",
"request",
"[",
"'server'",
"]",
"[",
"'personality'",
"]",
"<<",
"{",
"'path'",
"=>",
"path",
",",
"'contents'",
"=>",
"Base64",
".",
"encode64",
"(",
"blob",
")",
"}",
"end",
"response",
"=",
"servers_client",
".",
"post",
"(",
"servers_path",
",",
"JSON",
".",
"dump",
"(",
"request",
")",
",",
"json_headers",
")",
"data",
"=",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
"[",
"'server'",
"]",
"Raca",
"::",
"Server",
".",
"new",
"(",
"@account",
",",
"@region",
",",
"data",
"[",
"'id'",
"]",
")",
"end"
] | create a new server on Rackspace.
server_name is a free text name you want to assign the server.
flavor_name is a string that describes the amount of RAM. If you enter
an invalid option a list of valid options will be raised.
image_name is a string that describes the OS image to use. If you enter
an invalid option a list of valid options will be raised. I suggest
starting with 'Ubuntu 10.04 LTS'
files is an optional Hash of path to blobs. Use it to place a file on the
disk of the new server.
Use it like this:
server.create("my-server", 512, "Ubuntu 10.04 LTS", "/root/.ssh/authorised_keys" => File.read("/foo")) | [
"create",
"a",
"new",
"server",
"on",
"Rackspace",
"."
] | fa69dfde22359cc0e06f655055be4eadcc7019c0 | https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/servers.rb#L43-L62 | train |
jeremyruppel/codependency | lib/codependency/graph.rb | Codependency.Graph.require | def require( file )
return if key?( file )
self[ file ] = deps( file )
self[ file ].each do |dependency|
self.require dependency
end
end | ruby | def require( file )
return if key?( file )
self[ file ] = deps( file )
self[ file ].each do |dependency|
self.require dependency
end
end | [
"def",
"require",
"(",
"file",
")",
"return",
"if",
"key?",
"(",
"file",
")",
"self",
"[",
"file",
"]",
"=",
"deps",
"(",
"file",
")",
"self",
"[",
"file",
"]",
".",
"each",
"do",
"|",
"dependency",
"|",
"self",
".",
"require",
"dependency",
"end",
"end"
] | Add the given file to this graph. Creates a new entry in the
graph, the key of which is the relative path to this file and
the value is the array of relative paths to its dependencies.
Any dependent files will also be recursively added to this
graph. | [
"Add",
"the",
"given",
"file",
"to",
"this",
"graph",
".",
"Creates",
"a",
"new",
"entry",
"in",
"the",
"graph",
"the",
"key",
"of",
"which",
"is",
"the",
"relative",
"path",
"to",
"this",
"file",
"and",
"the",
"value",
"is",
"the",
"array",
"of",
"relative",
"paths",
"to",
"its",
"dependencies",
".",
"Any",
"dependent",
"files",
"will",
"also",
"be",
"recursively",
"added",
"to",
"this",
"graph",
"."
] | 635eddcc0149211e71f89bcaddaa6603aacf942f | https://github.com/jeremyruppel/codependency/blob/635eddcc0149211e71f89bcaddaa6603aacf942f/lib/codependency/graph.rb#L12-L19 | train |
jeremyruppel/codependency | lib/codependency/graph.rb | Codependency.Graph.scan | def scan( glob )
Dir[ glob ].flat_map { |f| deps( f ) }.uniq.each do |dependency|
self.require dependency
end
end | ruby | def scan( glob )
Dir[ glob ].flat_map { |f| deps( f ) }.uniq.each do |dependency|
self.require dependency
end
end | [
"def",
"scan",
"(",
"glob",
")",
"Dir",
"[",
"glob",
"]",
".",
"flat_map",
"{",
"|",
"f",
"|",
"deps",
"(",
"f",
")",
"}",
".",
"uniq",
".",
"each",
"do",
"|",
"dependency",
"|",
"self",
".",
"require",
"dependency",
"end",
"end"
] | Parses all of the files in the given glob and adds their
dependencies to the graph. A file in this glob is not added
to the graph unless another file in the glob depends on it. | [
"Parses",
"all",
"of",
"the",
"files",
"in",
"the",
"given",
"glob",
"and",
"adds",
"their",
"dependencies",
"to",
"the",
"graph",
".",
"A",
"file",
"in",
"this",
"glob",
"is",
"not",
"added",
"to",
"the",
"graph",
"unless",
"another",
"file",
"in",
"the",
"glob",
"depends",
"on",
"it",
"."
] | 635eddcc0149211e71f89bcaddaa6603aacf942f | https://github.com/jeremyruppel/codependency/blob/635eddcc0149211e71f89bcaddaa6603aacf942f/lib/codependency/graph.rb#L26-L30 | train |
jeremyruppel/codependency | lib/codependency/graph.rb | Codependency.Graph.deps | def deps( file )
parser.parse( file ).map { |f| path_to path[ f ] }
end | ruby | def deps( file )
parser.parse( file ).map { |f| path_to path[ f ] }
end | [
"def",
"deps",
"(",
"file",
")",
"parser",
".",
"parse",
"(",
"file",
")",
".",
"map",
"{",
"|",
"f",
"|",
"path_to",
"path",
"[",
"f",
"]",
"}",
"end"
] | Parses the file and returns the relative paths to its dependencies. | [
"Parses",
"the",
"file",
"and",
"returns",
"the",
"relative",
"paths",
"to",
"its",
"dependencies",
"."
] | 635eddcc0149211e71f89bcaddaa6603aacf942f | https://github.com/jeremyruppel/codependency/blob/635eddcc0149211e71f89bcaddaa6603aacf942f/lib/codependency/graph.rb#L85-L87 | train |
Deradon/Ruby-Rescuetime | lib/rescuetime/loop.rb | Rescuetime.Loop.run | def run
running!
@current_app = Application.create(:debug => debug?)
while true
sleep 1 # TODO: move to config
focus_changed if @current_app.finished? || backup?
end
end | ruby | def run
running!
@current_app = Application.create(:debug => debug?)
while true
sleep 1 # TODO: move to config
focus_changed if @current_app.finished? || backup?
end
end | [
"def",
"run",
"running!",
"@current_app",
"=",
"Application",
".",
"create",
"(",
":debug",
"=>",
"debug?",
")",
"while",
"true",
"sleep",
"1",
"focus_changed",
"if",
"@current_app",
".",
"finished?",
"||",
"backup?",
"end",
"end"
] | Run the loop | [
"Run",
"the",
"loop"
] | 0a81fb2e889bd225e0a0714d23c61fb9b1e36ffd | https://github.com/Deradon/Ruby-Rescuetime/blob/0a81fb2e889bd225e0a0714d23c61fb9b1e36ffd/lib/rescuetime/loop.rb#L77-L85 | train |
mochnatiy/flexible_accessibility | lib/flexible_accessibility/controller_methods.rb | FlexibleAccessibility.ControllerMethods.has_access? | def has_access?(permission, user)
raise UnknownUserException if user.nil?
AccessProvider.action_permitted_for_user?(permission, user)
end | ruby | def has_access?(permission, user)
raise UnknownUserException if user.nil?
AccessProvider.action_permitted_for_user?(permission, user)
end | [
"def",
"has_access?",
"(",
"permission",
",",
"user",
")",
"raise",
"UnknownUserException",
"if",
"user",
".",
"nil?",
"AccessProvider",
".",
"action_permitted_for_user?",
"(",
"permission",
",",
"user",
")",
"end"
] | Check the url for each link in view to show it | [
"Check",
"the",
"url",
"for",
"each",
"link",
"in",
"view",
"to",
"show",
"it"
] | ffd7f76e0765aa28909625b3bfa282264b8a5195 | https://github.com/mochnatiy/flexible_accessibility/blob/ffd7f76e0765aa28909625b3bfa282264b8a5195/lib/flexible_accessibility/controller_methods.rb#L79-L83 | train |
GeoffWilliams/puppetbox | lib/puppetbox/puppetbox.rb | PuppetBox.PuppetBox.run_puppet | def run_puppet(driver_instance, puppet_tests, logger:nil, reset_after_run:true)
# use supplied logger in preference to the default puppetbox logger instance
logger = logger || @logger
logger.debug("#{driver_instance.node_name} running #{puppet_tests.size} tests")
if driver_instance.open
logger.debug("#{driver_instance.node_name} started")
if driver_instance.self_test
logger.debug("#{driver_instance.node_name} self_test OK, running puppet")
puppet_tests.each { |test_name, puppet_code|
if @result_set.class_size(driver_instance.node_name) > 0 and reset_after_run
# purge and reboot the vm - this will save approximately 1 second
# per class on the self-test which we now know will succeed
driver_instance.reset
end
setup_test(driver_instance, test_name)
logger.info("running test #{driver_instance.node_name} - #{test_name}")
# write out the local test file
relative_puppet_file = commit_testcase(
puppet_tests, driver_instance.node_name, test_name
)
driver_instance.sync_testcase(driver_instance.node_name, test_name)
puppet_file_remote = File.join(PUPPET_TESTCASE_DIR, relative_puppet_file)
driver_instance.run_puppet_x2(puppet_file_remote)
@logger.debug("Saved result #{driver_instance.node_name} #{test_name} #{driver_instance.result.passed?}")
@result_set.save(driver_instance.node_name, test_name, driver_instance.result)
Report::log_test_result_or_errors(
@logger,
driver_instance.node_name,
test_name,
driver_instance.result,
)
}
logger.debug("#{driver_instance.node_name} test completed, closing instance")
else
raise "#{driver_instance.node_name} self test failed, unable to continue"
end
else
raise "#{driver_instance.node_name} failed to start, unable to continue"
end
driver_instance.close
end | ruby | def run_puppet(driver_instance, puppet_tests, logger:nil, reset_after_run:true)
# use supplied logger in preference to the default puppetbox logger instance
logger = logger || @logger
logger.debug("#{driver_instance.node_name} running #{puppet_tests.size} tests")
if driver_instance.open
logger.debug("#{driver_instance.node_name} started")
if driver_instance.self_test
logger.debug("#{driver_instance.node_name} self_test OK, running puppet")
puppet_tests.each { |test_name, puppet_code|
if @result_set.class_size(driver_instance.node_name) > 0 and reset_after_run
# purge and reboot the vm - this will save approximately 1 second
# per class on the self-test which we now know will succeed
driver_instance.reset
end
setup_test(driver_instance, test_name)
logger.info("running test #{driver_instance.node_name} - #{test_name}")
# write out the local test file
relative_puppet_file = commit_testcase(
puppet_tests, driver_instance.node_name, test_name
)
driver_instance.sync_testcase(driver_instance.node_name, test_name)
puppet_file_remote = File.join(PUPPET_TESTCASE_DIR, relative_puppet_file)
driver_instance.run_puppet_x2(puppet_file_remote)
@logger.debug("Saved result #{driver_instance.node_name} #{test_name} #{driver_instance.result.passed?}")
@result_set.save(driver_instance.node_name, test_name, driver_instance.result)
Report::log_test_result_or_errors(
@logger,
driver_instance.node_name,
test_name,
driver_instance.result,
)
}
logger.debug("#{driver_instance.node_name} test completed, closing instance")
else
raise "#{driver_instance.node_name} self test failed, unable to continue"
end
else
raise "#{driver_instance.node_name} failed to start, unable to continue"
end
driver_instance.close
end | [
"def",
"run_puppet",
"(",
"driver_instance",
",",
"puppet_tests",
",",
"logger",
":",
"nil",
",",
"reset_after_run",
":",
"true",
")",
"logger",
"=",
"logger",
"||",
"@logger",
"logger",
".",
"debug",
"(",
"\"#{driver_instance.node_name} running #{puppet_tests.size} tests\"",
")",
"if",
"driver_instance",
".",
"open",
"logger",
".",
"debug",
"(",
"\"#{driver_instance.node_name} started\"",
")",
"if",
"driver_instance",
".",
"self_test",
"logger",
".",
"debug",
"(",
"\"#{driver_instance.node_name} self_test OK, running puppet\"",
")",
"puppet_tests",
".",
"each",
"{",
"|",
"test_name",
",",
"puppet_code",
"|",
"if",
"@result_set",
".",
"class_size",
"(",
"driver_instance",
".",
"node_name",
")",
">",
"0",
"and",
"reset_after_run",
"driver_instance",
".",
"reset",
"end",
"setup_test",
"(",
"driver_instance",
",",
"test_name",
")",
"logger",
".",
"info",
"(",
"\"running test #{driver_instance.node_name} - #{test_name}\"",
")",
"relative_puppet_file",
"=",
"commit_testcase",
"(",
"puppet_tests",
",",
"driver_instance",
".",
"node_name",
",",
"test_name",
")",
"driver_instance",
".",
"sync_testcase",
"(",
"driver_instance",
".",
"node_name",
",",
"test_name",
")",
"puppet_file_remote",
"=",
"File",
".",
"join",
"(",
"PUPPET_TESTCASE_DIR",
",",
"relative_puppet_file",
")",
"driver_instance",
".",
"run_puppet_x2",
"(",
"puppet_file_remote",
")",
"@logger",
".",
"debug",
"(",
"\"Saved result #{driver_instance.node_name} #{test_name} #{driver_instance.result.passed?}\"",
")",
"@result_set",
".",
"save",
"(",
"driver_instance",
".",
"node_name",
",",
"test_name",
",",
"driver_instance",
".",
"result",
")",
"Report",
"::",
"log_test_result_or_errors",
"(",
"@logger",
",",
"driver_instance",
".",
"node_name",
",",
"test_name",
",",
"driver_instance",
".",
"result",
",",
")",
"}",
"logger",
".",
"debug",
"(",
"\"#{driver_instance.node_name} test completed, closing instance\"",
")",
"else",
"raise",
"\"#{driver_instance.node_name} self test failed, unable to continue\"",
"end",
"else",
"raise",
"\"#{driver_instance.node_name} failed to start, unable to continue\"",
"end",
"driver_instance",
".",
"close",
"end"
] | Run puppet using `driver_instance` to execute `puppet_codes`
@param puppet_test Hash of test names <-> puppet code, eg {"apache"=>"include apache","nginx"=>"include nginx"}} | [
"Run",
"puppet",
"using",
"driver_instance",
"to",
"execute",
"puppet_codes"
] | 8ace050aa46e8908c1b266b9307f01929e222e53 | https://github.com/GeoffWilliams/puppetbox/blob/8ace050aa46e8908c1b266b9307f01929e222e53/lib/puppetbox/puppetbox.rb#L180-L225 | train |
elementar/shapewear | lib/shapewear/request.rb | Shapewear::Request.RequestHandler.extract_parameters | def extract_parameters(op_options, node)
logger.debug "Operation node: #{node.inspect}"
r = []
op_options[:parameters].each do |p|
logger.debug " Looking for: tns:#{p.first.camelize_if_symbol(:lower)}"
v = node.xpath("tns:#{p.first.camelize_if_symbol(:lower)}", namespaces).first
if v.nil?
# does nothing
elsif p.last == Fixnum
v = v.text.to_i
elsif p.last == DateTime
v = DateTime.parse(v.text) # TODO: add tests
else
v = v.text
end
logger.debug " Found: #{v.inspect}"
r << v
end
r
end | ruby | def extract_parameters(op_options, node)
logger.debug "Operation node: #{node.inspect}"
r = []
op_options[:parameters].each do |p|
logger.debug " Looking for: tns:#{p.first.camelize_if_symbol(:lower)}"
v = node.xpath("tns:#{p.first.camelize_if_symbol(:lower)}", namespaces).first
if v.nil?
# does nothing
elsif p.last == Fixnum
v = v.text.to_i
elsif p.last == DateTime
v = DateTime.parse(v.text) # TODO: add tests
else
v = v.text
end
logger.debug " Found: #{v.inspect}"
r << v
end
r
end | [
"def",
"extract_parameters",
"(",
"op_options",
",",
"node",
")",
"logger",
".",
"debug",
"\"Operation node: #{node.inspect}\"",
"r",
"=",
"[",
"]",
"op_options",
"[",
":parameters",
"]",
".",
"each",
"do",
"|",
"p",
"|",
"logger",
".",
"debug",
"\" Looking for: tns:#{p.first.camelize_if_symbol(:lower)}\"",
"v",
"=",
"node",
".",
"xpath",
"(",
"\"tns:#{p.first.camelize_if_symbol(:lower)}\"",
",",
"namespaces",
")",
".",
"first",
"if",
"v",
".",
"nil?",
"elsif",
"p",
".",
"last",
"==",
"Fixnum",
"v",
"=",
"v",
".",
"text",
".",
"to_i",
"elsif",
"p",
".",
"last",
"==",
"DateTime",
"v",
"=",
"DateTime",
".",
"parse",
"(",
"v",
".",
"text",
")",
"else",
"v",
"=",
"v",
".",
"text",
"end",
"logger",
".",
"debug",
"\" Found: #{v.inspect}\"",
"r",
"<<",
"v",
"end",
"r",
"end"
] | Extracts all parameters from the operation node, and return as an array.
@param op_options [Hash] The operation options.
@param node [Nokogiri::XML] The operation node.
@return [Array] The parsed parameters. | [
"Extracts",
"all",
"parameters",
"from",
"the",
"operation",
"node",
"and",
"return",
"as",
"an",
"array",
"."
] | 18cef0227930dbe26a2c821e8e636fda5d2bc6e2 | https://github.com/elementar/shapewear/blob/18cef0227930dbe26a2c821e8e636fda5d2bc6e2/lib/shapewear/request.rb#L75-L94 | train |
elementar/shapewear | lib/shapewear/request.rb | Shapewear::Request.RequestHandler.serialize_soap_result | def serialize_soap_result(op_options, r)
xb = Builder::XmlMarkup.new
xb.instruct!
xb.Envelope :xmlns => soap_env_ns, 'xmlns:xsi' => namespaces['xsi'] do |xenv|
xenv.Body do |xbody|
xbody.tag! "#{op_options[:public_name]}Response", :xmlns => namespaces['tns'] do |xresp|
if r.nil?
xresp.tag! "#{op_options[:public_name]}Result", 'xsi:nil' => 'true'
else
ret = op_options[:returns] rescue nil
case ret
when NilClass, Class
xresp.tag! "#{op_options[:public_name]}Result", r
when Hash
xresp.tag! "#{op_options[:public_name]}Result" do |xres|
ret.each do |k, v|
extract_and_serialize_value(xres, r, k, v)
end
end
else
raise "Unsupported return type: #{ret.inspect}"
end
end
end
end
end
end | ruby | def serialize_soap_result(op_options, r)
xb = Builder::XmlMarkup.new
xb.instruct!
xb.Envelope :xmlns => soap_env_ns, 'xmlns:xsi' => namespaces['xsi'] do |xenv|
xenv.Body do |xbody|
xbody.tag! "#{op_options[:public_name]}Response", :xmlns => namespaces['tns'] do |xresp|
if r.nil?
xresp.tag! "#{op_options[:public_name]}Result", 'xsi:nil' => 'true'
else
ret = op_options[:returns] rescue nil
case ret
when NilClass, Class
xresp.tag! "#{op_options[:public_name]}Result", r
when Hash
xresp.tag! "#{op_options[:public_name]}Result" do |xres|
ret.each do |k, v|
extract_and_serialize_value(xres, r, k, v)
end
end
else
raise "Unsupported return type: #{ret.inspect}"
end
end
end
end
end
end | [
"def",
"serialize_soap_result",
"(",
"op_options",
",",
"r",
")",
"xb",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"xb",
".",
"instruct!",
"xb",
".",
"Envelope",
":xmlns",
"=>",
"soap_env_ns",
",",
"'xmlns:xsi'",
"=>",
"namespaces",
"[",
"'xsi'",
"]",
"do",
"|",
"xenv",
"|",
"xenv",
".",
"Body",
"do",
"|",
"xbody",
"|",
"xbody",
".",
"tag!",
"\"#{op_options[:public_name]}Response\"",
",",
":xmlns",
"=>",
"namespaces",
"[",
"'tns'",
"]",
"do",
"|",
"xresp",
"|",
"if",
"r",
".",
"nil?",
"xresp",
".",
"tag!",
"\"#{op_options[:public_name]}Result\"",
",",
"'xsi:nil'",
"=>",
"'true'",
"else",
"ret",
"=",
"op_options",
"[",
":returns",
"]",
"rescue",
"nil",
"case",
"ret",
"when",
"NilClass",
",",
"Class",
"xresp",
".",
"tag!",
"\"#{op_options[:public_name]}Result\"",
",",
"r",
"when",
"Hash",
"xresp",
".",
"tag!",
"\"#{op_options[:public_name]}Result\"",
"do",
"|",
"xres",
"|",
"ret",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"extract_and_serialize_value",
"(",
"xres",
",",
"r",
",",
"k",
",",
"v",
")",
"end",
"end",
"else",
"raise",
"\"Unsupported return type: #{ret.inspect}\"",
"end",
"end",
"end",
"end",
"end",
"end"
] | Serializes the result of an operation as a SOAP Envelope.
@param op_options [Hash] The operation options.
@param r [Hash,Object] The operation result.
noinspection RubyArgCount | [
"Serializes",
"the",
"result",
"of",
"an",
"operation",
"as",
"a",
"SOAP",
"Envelope",
"."
] | 18cef0227930dbe26a2c821e8e636fda5d2bc6e2 | https://github.com/elementar/shapewear/blob/18cef0227930dbe26a2c821e8e636fda5d2bc6e2/lib/shapewear/request.rb#L101-L128 | train |
elementar/shapewear | lib/shapewear/request.rb | Shapewear::Request.RequestHandler.extract_and_serialize_value | def extract_and_serialize_value(builder, obj, field, type)
v = if obj.is_a?(Hash)
obj[field] or obj[field.to_sym] or obj[field.to_s.underscore] or obj[field.to_s.underscore.to_sym]
elsif obj.respond_to?(field)
obj.send(field)
elsif obj.respond_to?(field.underscore)
obj.send(field.underscore)
else
raise "Could not extract #{field.inspect} from object: #{obj.inspect}"
end
if v.nil?
builder.tag! field.camelize_if_symbol, 'xsi:nil' => 'true'
else
builder.tag! field.camelize_if_symbol, v
end
end | ruby | def extract_and_serialize_value(builder, obj, field, type)
v = if obj.is_a?(Hash)
obj[field] or obj[field.to_sym] or obj[field.to_s.underscore] or obj[field.to_s.underscore.to_sym]
elsif obj.respond_to?(field)
obj.send(field)
elsif obj.respond_to?(field.underscore)
obj.send(field.underscore)
else
raise "Could not extract #{field.inspect} from object: #{obj.inspect}"
end
if v.nil?
builder.tag! field.camelize_if_symbol, 'xsi:nil' => 'true'
else
builder.tag! field.camelize_if_symbol, v
end
end | [
"def",
"extract_and_serialize_value",
"(",
"builder",
",",
"obj",
",",
"field",
",",
"type",
")",
"v",
"=",
"if",
"obj",
".",
"is_a?",
"(",
"Hash",
")",
"obj",
"[",
"field",
"]",
"or",
"obj",
"[",
"field",
".",
"to_sym",
"]",
"or",
"obj",
"[",
"field",
".",
"to_s",
".",
"underscore",
"]",
"or",
"obj",
"[",
"field",
".",
"to_s",
".",
"underscore",
".",
"to_sym",
"]",
"elsif",
"obj",
".",
"respond_to?",
"(",
"field",
")",
"obj",
".",
"send",
"(",
"field",
")",
"elsif",
"obj",
".",
"respond_to?",
"(",
"field",
".",
"underscore",
")",
"obj",
".",
"send",
"(",
"field",
".",
"underscore",
")",
"else",
"raise",
"\"Could not extract #{field.inspect} from object: #{obj.inspect}\"",
"end",
"if",
"v",
".",
"nil?",
"builder",
".",
"tag!",
"field",
".",
"camelize_if_symbol",
",",
"'xsi:nil'",
"=>",
"'true'",
"else",
"builder",
".",
"tag!",
"field",
".",
"camelize_if_symbol",
",",
"v",
"end",
"end"
] | Extracts a field from an object, casts it to the appropriate type, and serializes as XML.
@param builder [Builder::XmlMarkup] The XML builder.
@param obj [Hash,Object] The resulting object.
@param field [Symbol,String] The field to extract.
@param type [Class] The type to convert. | [
"Extracts",
"a",
"field",
"from",
"an",
"object",
"casts",
"it",
"to",
"the",
"appropriate",
"type",
"and",
"serializes",
"as",
"XML",
"."
] | 18cef0227930dbe26a2c821e8e636fda5d2bc6e2 | https://github.com/elementar/shapewear/blob/18cef0227930dbe26a2c821e8e636fda5d2bc6e2/lib/shapewear/request.rb#L136-L152 | train |
elementar/shapewear | lib/shapewear/request.rb | Shapewear::Request.RequestHandler.serialize_soap_fault | def serialize_soap_fault(ex)
logger.debug "Serializing SOAP Fault: #{ex.inspect}"
xb = Builder::XmlMarkup.new
xb.instruct!
xb.tag! 'e:Envelope', 'xmlns:e' => soap_env_ns do |xenv|
xenv.tag! 'e:Body' do |xbody|
xbody.tag! 'e:Fault' do |xf|
case soap_version
when :soap11
xf.faultcode "e:Server.#{ex.class.name}"
xf.faultstring ex.message
when :soap12
xf.tag! 'e:Code' do |xcode|
xcode.tag! 'e:Value', 'e:Receiver'
xcode.tag! 'e:Subcode' do |xsubcode|
xsubcode.tag! 'e:Value', ex.class.name
end
end
xf.tag! 'e:Reason', ex.message
else
raise "Unsupported SOAP version: #{soap_version}"
end
end
end
end
end | ruby | def serialize_soap_fault(ex)
logger.debug "Serializing SOAP Fault: #{ex.inspect}"
xb = Builder::XmlMarkup.new
xb.instruct!
xb.tag! 'e:Envelope', 'xmlns:e' => soap_env_ns do |xenv|
xenv.tag! 'e:Body' do |xbody|
xbody.tag! 'e:Fault' do |xf|
case soap_version
when :soap11
xf.faultcode "e:Server.#{ex.class.name}"
xf.faultstring ex.message
when :soap12
xf.tag! 'e:Code' do |xcode|
xcode.tag! 'e:Value', 'e:Receiver'
xcode.tag! 'e:Subcode' do |xsubcode|
xsubcode.tag! 'e:Value', ex.class.name
end
end
xf.tag! 'e:Reason', ex.message
else
raise "Unsupported SOAP version: #{soap_version}"
end
end
end
end
end | [
"def",
"serialize_soap_fault",
"(",
"ex",
")",
"logger",
".",
"debug",
"\"Serializing SOAP Fault: #{ex.inspect}\"",
"xb",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"xb",
".",
"instruct!",
"xb",
".",
"tag!",
"'e:Envelope'",
",",
"'xmlns:e'",
"=>",
"soap_env_ns",
"do",
"|",
"xenv",
"|",
"xenv",
".",
"tag!",
"'e:Body'",
"do",
"|",
"xbody",
"|",
"xbody",
".",
"tag!",
"'e:Fault'",
"do",
"|",
"xf",
"|",
"case",
"soap_version",
"when",
":soap11",
"xf",
".",
"faultcode",
"\"e:Server.#{ex.class.name}\"",
"xf",
".",
"faultstring",
"ex",
".",
"message",
"when",
":soap12",
"xf",
".",
"tag!",
"'e:Code'",
"do",
"|",
"xcode",
"|",
"xcode",
".",
"tag!",
"'e:Value'",
",",
"'e:Receiver'",
"xcode",
".",
"tag!",
"'e:Subcode'",
"do",
"|",
"xsubcode",
"|",
"xsubcode",
".",
"tag!",
"'e:Value'",
",",
"ex",
".",
"class",
".",
"name",
"end",
"end",
"xf",
".",
"tag!",
"'e:Reason'",
",",
"ex",
".",
"message",
"else",
"raise",
"\"Unsupported SOAP version: #{soap_version}\"",
"end",
"end",
"end",
"end",
"end"
] | Serializes an exception as a SOAP Envelope containing a SOAP Fault.
@param ex [Exception] The Exception to serialize.
@return [String] The SOAP Envelope containing the Fault.
noinspection RubyArgCount | [
"Serializes",
"an",
"exception",
"as",
"a",
"SOAP",
"Envelope",
"containing",
"a",
"SOAP",
"Fault",
"."
] | 18cef0227930dbe26a2c821e8e636fda5d2bc6e2 | https://github.com/elementar/shapewear/blob/18cef0227930dbe26a2c821e8e636fda5d2bc6e2/lib/shapewear/request.rb#L159-L186 | train |
nerboda/easy_breadcrumbs | lib/easy_breadcrumbs/sinatra_config.rb | Sinatra.EasyBreadcrumbs.view_variables | def view_variables
instance_variables
.select { |var| additional_var?(var) }
.map { |var| fetch_ivar_value(var) }
end | ruby | def view_variables
instance_variables
.select { |var| additional_var?(var) }
.map { |var| fetch_ivar_value(var) }
end | [
"def",
"view_variables",
"instance_variables",
".",
"select",
"{",
"|",
"var",
"|",
"additional_var?",
"(",
"var",
")",
"}",
".",
"map",
"{",
"|",
"var",
"|",
"fetch_ivar_value",
"(",
"var",
")",
"}",
"end"
] | All user defined instance variables for current request. | [
"All",
"user",
"defined",
"instance",
"variables",
"for",
"current",
"request",
"."
] | 53af89b4ba1329a4963ff6bc253f4714ac9030f8 | https://github.com/nerboda/easy_breadcrumbs/blob/53af89b4ba1329a4963ff6bc253f4714ac9030f8/lib/easy_breadcrumbs/sinatra_config.rb#L31-L35 | train |
starpeak/gricer | app/controllers/gricer/capture_controller.rb | Gricer.CaptureController.index | def index
gricer_request = ::Gricer.config.request_model.first_by_id(params[:id])
gricer_session = ::Gricer.config.session_model.first_by_id(session[:gricer_session])
if gricer_session
gricer_session.javascript = true
gricer_session.java = params[:j]
gricer_session.flash_version = params[:f] unless params[:f] == 'false'
gricer_session.silverlight_version = params[:sl] unless params[:sl] == 'false'
gricer_session.screen_width = params[:sx]
gricer_session.screen_height = params[:sy]
gricer_session.screen_size = "#{params[:sx]}x#{params[:sy]}" unless params[:sx].blank? or params[:sy].blank?
gricer_session.screen_depth = params[:sd]
gricer_session.save
if gricer_request and gricer_request.session == gricer_session
gricer_request.javascript = true
gricer_request.window_width = params[:wx]
gricer_request.window_height = params[:wy]
if gricer_request.save
render text: 'ok'
else
render text: 'session only', status: 500
end
return
else
render text: 'session only'
return
end
end
render text: 'failed', status: 500
end | ruby | def index
gricer_request = ::Gricer.config.request_model.first_by_id(params[:id])
gricer_session = ::Gricer.config.session_model.first_by_id(session[:gricer_session])
if gricer_session
gricer_session.javascript = true
gricer_session.java = params[:j]
gricer_session.flash_version = params[:f] unless params[:f] == 'false'
gricer_session.silverlight_version = params[:sl] unless params[:sl] == 'false'
gricer_session.screen_width = params[:sx]
gricer_session.screen_height = params[:sy]
gricer_session.screen_size = "#{params[:sx]}x#{params[:sy]}" unless params[:sx].blank? or params[:sy].blank?
gricer_session.screen_depth = params[:sd]
gricer_session.save
if gricer_request and gricer_request.session == gricer_session
gricer_request.javascript = true
gricer_request.window_width = params[:wx]
gricer_request.window_height = params[:wy]
if gricer_request.save
render text: 'ok'
else
render text: 'session only', status: 500
end
return
else
render text: 'session only'
return
end
end
render text: 'failed', status: 500
end | [
"def",
"index",
"gricer_request",
"=",
"::",
"Gricer",
".",
"config",
".",
"request_model",
".",
"first_by_id",
"(",
"params",
"[",
":id",
"]",
")",
"gricer_session",
"=",
"::",
"Gricer",
".",
"config",
".",
"session_model",
".",
"first_by_id",
"(",
"session",
"[",
":gricer_session",
"]",
")",
"if",
"gricer_session",
"gricer_session",
".",
"javascript",
"=",
"true",
"gricer_session",
".",
"java",
"=",
"params",
"[",
":j",
"]",
"gricer_session",
".",
"flash_version",
"=",
"params",
"[",
":f",
"]",
"unless",
"params",
"[",
":f",
"]",
"==",
"'false'",
"gricer_session",
".",
"silverlight_version",
"=",
"params",
"[",
":sl",
"]",
"unless",
"params",
"[",
":sl",
"]",
"==",
"'false'",
"gricer_session",
".",
"screen_width",
"=",
"params",
"[",
":sx",
"]",
"gricer_session",
".",
"screen_height",
"=",
"params",
"[",
":sy",
"]",
"gricer_session",
".",
"screen_size",
"=",
"\"#{params[:sx]}x#{params[:sy]}\"",
"unless",
"params",
"[",
":sx",
"]",
".",
"blank?",
"or",
"params",
"[",
":sy",
"]",
".",
"blank?",
"gricer_session",
".",
"screen_depth",
"=",
"params",
"[",
":sd",
"]",
"gricer_session",
".",
"save",
"if",
"gricer_request",
"and",
"gricer_request",
".",
"session",
"==",
"gricer_session",
"gricer_request",
".",
"javascript",
"=",
"true",
"gricer_request",
".",
"window_width",
"=",
"params",
"[",
":wx",
"]",
"gricer_request",
".",
"window_height",
"=",
"params",
"[",
":wy",
"]",
"if",
"gricer_request",
".",
"save",
"render",
"text",
":",
"'ok'",
"else",
"render",
"text",
":",
"'session only'",
",",
"status",
":",
"500",
"end",
"return",
"else",
"render",
"text",
":",
"'session only'",
"return",
"end",
"end",
"render",
"text",
":",
"'failed'",
",",
"status",
":",
"500",
"end"
] | This action stores the data submitted by the Javascript. | [
"This",
"action",
"stores",
"the",
"data",
"submitted",
"by",
"the",
"Javascript",
"."
] | 46bb77bd4fc7074ce294d0310ad459fef068f507 | https://github.com/starpeak/gricer/blob/46bb77bd4fc7074ce294d0310ad459fef068f507/app/controllers/gricer/capture_controller.rb#L7-L40 | train |
byu/optser | lib/optser/opt_set.rb | Optser.OptSet.get | def get(key, default=nil, &block)
value = options[key]
value = default if value.nil?
value = block.call if value.nil? && block
return value
end | ruby | def get(key, default=nil, &block)
value = options[key]
value = default if value.nil?
value = block.call if value.nil? && block
return value
end | [
"def",
"get",
"(",
"key",
",",
"default",
"=",
"nil",
",",
"&",
"block",
")",
"value",
"=",
"options",
"[",
"key",
"]",
"value",
"=",
"default",
"if",
"value",
".",
"nil?",
"value",
"=",
"block",
".",
"call",
"if",
"value",
".",
"nil?",
"&&",
"block",
"return",
"value",
"end"
] | Lookup an option from our options set.
Examples:
# Optional parameter whose default value is nil.
do_extra = opt_set.get :do_extra
# Optional params that defaults to [1,2,3]
start_array = opt_set.get :start_array, [1,2,3]
Returns default value when:
* Key is non-existent in Options Hash.
* OR when the value of the key in the Options Hash is nil.
Returns nil when:
* Default is nil and the Options Hash lookup returns a nil.
Options Hash returns a nil because of either a
non-existent key or a nil value in said hash for said key. | [
"Lookup",
"an",
"option",
"from",
"our",
"options",
"set",
"."
] | c88c19f15ca31874ad46fb6f15b20485635a5ffb | https://github.com/byu/optser/blob/c88c19f15ca31874ad46fb6f15b20485635a5ffb/lib/optser/opt_set.rb#L32-L37 | train |
byu/optser | lib/optser/opt_set.rb | Optser.OptSet.get! | def get!(key, default=nil, &block)
value = get key, default, &block
raise "Nil value found for option: #{key}, #{default}" if value.nil?
return value
end | ruby | def get!(key, default=nil, &block)
value = get key, default, &block
raise "Nil value found for option: #{key}, #{default}" if value.nil?
return value
end | [
"def",
"get!",
"(",
"key",
",",
"default",
"=",
"nil",
",",
"&",
"block",
")",
"value",
"=",
"get",
"key",
",",
"default",
",",
"&",
"block",
"raise",
"\"Nil value found for option: #{key}, #{default}\"",
"if",
"value",
".",
"nil?",
"return",
"value",
"end"
] | Use this the option is mandatory.
There are cases where an option may have a default value for a feature,
but the caller may just want to disable said feature. To do so,
users of this module should allow for the caller to pass in 'false'
as an option value instead of nil to disable said feature. The
implementer will have to do a boolean check of the returned option value
and disable accordingly.
Examples:
# Has a default logger, but we can disable logging by passing false.
# If caller had passed in nil for :logger, it would have
# defaulted to ::Log4r['my_logger'].
logger = opt_set.get! :logger, ::Log4r['my_logger']
# Here we force the end user to pass in a Non-nil option as a
# mandatory parameter.
max_threads = opt_set.get! :max_threads
Raises error when `get` returns a nil. | [
"Use",
"this",
"the",
"option",
"is",
"mandatory",
"."
] | c88c19f15ca31874ad46fb6f15b20485635a5ffb | https://github.com/byu/optser/blob/c88c19f15ca31874ad46fb6f15b20485635a5ffb/lib/optser/opt_set.rb#L62-L66 | train |
samvera-deprecated/solrizer-fedora | lib/solrizer/fedora/indexer.rb | Solrizer::Fedora.Indexer.connect | def connect
if defined?(Blacklight)
solr_config = Blacklight.solr_config
elsif defined?(Rails.root.to_s)
solr_config = load_rails_config
else
solr_config = load_fallback_config
end
if index_full_text == true && solr_config.has_key?(:fulltext) && solr_config[:fulltext].has_key?('url')
solr_config[:url] = solr_config[:fulltext]['url']
elsif solr_config.has_key?(:default) && solr_config[:default].has_key?('url')
solr_config[:url] = solr_config[:default]['url']
elsif !solr_config.has_key?(:url)
raise "Unable to find a solr url in the config file"
end
@solr = RSolr.connect solr_config
rescue RuntimeError => e
logger.debug "Unable to establish SOLR Connection with #{solr_config.inspect}. Failed with #{e.message}"
raise URI::InvalidURIError
end | ruby | def connect
if defined?(Blacklight)
solr_config = Blacklight.solr_config
elsif defined?(Rails.root.to_s)
solr_config = load_rails_config
else
solr_config = load_fallback_config
end
if index_full_text == true && solr_config.has_key?(:fulltext) && solr_config[:fulltext].has_key?('url')
solr_config[:url] = solr_config[:fulltext]['url']
elsif solr_config.has_key?(:default) && solr_config[:default].has_key?('url')
solr_config[:url] = solr_config[:default]['url']
elsif !solr_config.has_key?(:url)
raise "Unable to find a solr url in the config file"
end
@solr = RSolr.connect solr_config
rescue RuntimeError => e
logger.debug "Unable to establish SOLR Connection with #{solr_config.inspect}. Failed with #{e.message}"
raise URI::InvalidURIError
end | [
"def",
"connect",
"if",
"defined?",
"(",
"Blacklight",
")",
"solr_config",
"=",
"Blacklight",
".",
"solr_config",
"elsif",
"defined?",
"(",
"Rails",
".",
"root",
".",
"to_s",
")",
"solr_config",
"=",
"load_rails_config",
"else",
"solr_config",
"=",
"load_fallback_config",
"end",
"if",
"index_full_text",
"==",
"true",
"&&",
"solr_config",
".",
"has_key?",
"(",
":fulltext",
")",
"&&",
"solr_config",
"[",
":fulltext",
"]",
".",
"has_key?",
"(",
"'url'",
")",
"solr_config",
"[",
":url",
"]",
"=",
"solr_config",
"[",
":fulltext",
"]",
"[",
"'url'",
"]",
"elsif",
"solr_config",
".",
"has_key?",
"(",
":default",
")",
"&&",
"solr_config",
"[",
":default",
"]",
".",
"has_key?",
"(",
"'url'",
")",
"solr_config",
"[",
":url",
"]",
"=",
"solr_config",
"[",
":default",
"]",
"[",
"'url'",
"]",
"elsif",
"!",
"solr_config",
".",
"has_key?",
"(",
":url",
")",
"raise",
"\"Unable to find a solr url in the config file\"",
"end",
"@solr",
"=",
"RSolr",
".",
"connect",
"solr_config",
"rescue",
"RuntimeError",
"=>",
"e",
"logger",
".",
"debug",
"\"Unable to establish SOLR Connection with #{solr_config.inspect}. Failed with #{e.message}\"",
"raise",
"URI",
"::",
"InvalidURIError",
"end"
] | This method performs initialization tasks
This method connects to the Solr instance. It looks to see if Blacklight is loaded first for the
Blacklight.solr_config. If not loaded, it then looks for the Rails.root.to_s/config/solr.yaml file and loads
it to get the solr url. The configuration strucuture can take both the
{ "development" => {"default" => { "url" => "http://localhost"}, "fulltext" => { "url" => "http://localhost"} }}
or { "development"=>{"url"=>"http://localhost" }}
Can also take Blacklight.solr_config["url"] and Blacklight.solr_config[:url]
If you want to specify a timeout for solr, provide these keys:
:read_timeout=>120, :open_timeout => 120 | [
"This",
"method",
"performs",
"initialization",
"tasks"
] | 277fab50a93a761fbccd07e2cfa01b22736d5cff | https://github.com/samvera-deprecated/solrizer-fedora/blob/277fab50a93a761fbccd07e2cfa01b22736d5cff/lib/solrizer/fedora/indexer.rb#L44-L66 | train |
samvera-deprecated/solrizer-fedora | lib/solrizer/fedora/indexer.rb | Solrizer::Fedora.Indexer.generate_dates | def generate_dates(solr_doc)
# This will check for valid dates, but it seems most of the dates are currently invalid....
#date_check = /^(19|20)\d\d([- \/.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])/
#if there is not date_t, add on with easy-to-find value
if solr_doc[:date_t].nil?
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :date_t, "9999-99-99")
end #if
# Grab the date value from date_t regardless of wheter it is inside of an array
# then convert it to a Date object
date_value = solr_doc[:date_t]
if date_value.kind_of? Array
date_value = date_value.first
end
date_obj = Date._parse(date_value)
if date_obj[:mon].nil?
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :month_facet, "99")
elsif 0 < date_obj[:mon] && date_obj[:mon] < 13
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :month_facet, date_obj[:mon].to_s.rjust(2, '0'))
else
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :month_facet, "99")
end
if date_obj[:mday].nil?
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :day_facet, "99")
elsif 0 < date_obj[:mday] && date_obj[:mday] < 32
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :day_facet, date_obj[:mday].to_s.rjust(2, '0'))
else
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :day_facet, "99")
end
return solr_doc
end | ruby | def generate_dates(solr_doc)
# This will check for valid dates, but it seems most of the dates are currently invalid....
#date_check = /^(19|20)\d\d([- \/.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])/
#if there is not date_t, add on with easy-to-find value
if solr_doc[:date_t].nil?
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :date_t, "9999-99-99")
end #if
# Grab the date value from date_t regardless of wheter it is inside of an array
# then convert it to a Date object
date_value = solr_doc[:date_t]
if date_value.kind_of? Array
date_value = date_value.first
end
date_obj = Date._parse(date_value)
if date_obj[:mon].nil?
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :month_facet, "99")
elsif 0 < date_obj[:mon] && date_obj[:mon] < 13
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :month_facet, date_obj[:mon].to_s.rjust(2, '0'))
else
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :month_facet, "99")
end
if date_obj[:mday].nil?
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :day_facet, "99")
elsif 0 < date_obj[:mday] && date_obj[:mday] < 32
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :day_facet, date_obj[:mday].to_s.rjust(2, '0'))
else
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :day_facet, "99")
end
return solr_doc
end | [
"def",
"generate_dates",
"(",
"solr_doc",
")",
"if",
"solr_doc",
"[",
":date_t",
"]",
".",
"nil?",
"::",
"Solrizer",
"::",
"Extractor",
".",
"insert_solr_field_value",
"(",
"solr_doc",
",",
":date_t",
",",
"\"9999-99-99\"",
")",
"end",
"date_value",
"=",
"solr_doc",
"[",
":date_t",
"]",
"if",
"date_value",
".",
"kind_of?",
"Array",
"date_value",
"=",
"date_value",
".",
"first",
"end",
"date_obj",
"=",
"Date",
".",
"_parse",
"(",
"date_value",
")",
"if",
"date_obj",
"[",
":mon",
"]",
".",
"nil?",
"::",
"Solrizer",
"::",
"Extractor",
".",
"insert_solr_field_value",
"(",
"solr_doc",
",",
":month_facet",
",",
"\"99\"",
")",
"elsif",
"0",
"<",
"date_obj",
"[",
":mon",
"]",
"&&",
"date_obj",
"[",
":mon",
"]",
"<",
"13",
"::",
"Solrizer",
"::",
"Extractor",
".",
"insert_solr_field_value",
"(",
"solr_doc",
",",
":month_facet",
",",
"date_obj",
"[",
":mon",
"]",
".",
"to_s",
".",
"rjust",
"(",
"2",
",",
"'0'",
")",
")",
"else",
"::",
"Solrizer",
"::",
"Extractor",
".",
"insert_solr_field_value",
"(",
"solr_doc",
",",
":month_facet",
",",
"\"99\"",
")",
"end",
"if",
"date_obj",
"[",
":mday",
"]",
".",
"nil?",
"::",
"Solrizer",
"::",
"Extractor",
".",
"insert_solr_field_value",
"(",
"solr_doc",
",",
":day_facet",
",",
"\"99\"",
")",
"elsif",
"0",
"<",
"date_obj",
"[",
":mday",
"]",
"&&",
"date_obj",
"[",
":mday",
"]",
"<",
"32",
"::",
"Solrizer",
"::",
"Extractor",
".",
"insert_solr_field_value",
"(",
"solr_doc",
",",
":day_facet",
",",
"date_obj",
"[",
":mday",
"]",
".",
"to_s",
".",
"rjust",
"(",
"2",
",",
"'0'",
")",
")",
"else",
"::",
"Solrizer",
"::",
"Extractor",
".",
"insert_solr_field_value",
"(",
"solr_doc",
",",
":day_facet",
",",
"\"99\"",
")",
"end",
"return",
"solr_doc",
"end"
] | This method generates the month and day facets from the date_t in solr_doc | [
"This",
"method",
"generates",
"the",
"month",
"and",
"day",
"facets",
"from",
"the",
"date_t",
"in",
"solr_doc"
] | 277fab50a93a761fbccd07e2cfa01b22736d5cff | https://github.com/samvera-deprecated/solrizer-fedora/blob/277fab50a93a761fbccd07e2cfa01b22736d5cff/lib/solrizer/fedora/indexer.rb#L100-L136 | train |
samvera-deprecated/solrizer-fedora | lib/solrizer/fedora/indexer.rb | Solrizer::Fedora.Indexer.create_document | def create_document( obj )
solr_doc = Hash.new
model_klazz_array = ActiveFedora::ContentModel.known_models_for( obj )
model_klazz_array.delete(ActiveFedora::Base)
# If the object was passed in as an ActiveFedora::Base, call to_solr in order to get the base field entries from ActiveFedora::Base
# Otherwise, the object was passed in as a model instance other than ActiveFedora::Base,so call its to_solr method & allow it to insert the fields from ActiveFedora::Base
if obj.class == ActiveFedora::Base
solr_doc = obj.to_solr(solr_doc)
logger.debug " added base fields from #{obj.class.to_s}"
else
solr_doc = obj.to_solr(solr_doc)
model_klazz_array.delete(obj.class)
logger.debug " added base fields from #{obj.class.to_s} and model fields from #{obj.class.to_s}"
end
# Load the object as an instance of each of its other models and get the corresponding solr fields
# Include :model_only=>true in the options in order to avoid adding the metadata from ActiveFedora::Base every time.
model_klazz_array.each do |klazz|
instance = obj.adapt_to(klazz)
solr_doc = instance.to_solr(solr_doc, :model_only=>true)
logger.debug " added solr fields from #{klazz.to_s}"
end
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :id_t, "#{obj.pid}" )
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :id, "#{obj.pid}" ) unless solr_doc[:id]
return solr_doc
end | ruby | def create_document( obj )
solr_doc = Hash.new
model_klazz_array = ActiveFedora::ContentModel.known_models_for( obj )
model_klazz_array.delete(ActiveFedora::Base)
# If the object was passed in as an ActiveFedora::Base, call to_solr in order to get the base field entries from ActiveFedora::Base
# Otherwise, the object was passed in as a model instance other than ActiveFedora::Base,so call its to_solr method & allow it to insert the fields from ActiveFedora::Base
if obj.class == ActiveFedora::Base
solr_doc = obj.to_solr(solr_doc)
logger.debug " added base fields from #{obj.class.to_s}"
else
solr_doc = obj.to_solr(solr_doc)
model_klazz_array.delete(obj.class)
logger.debug " added base fields from #{obj.class.to_s} and model fields from #{obj.class.to_s}"
end
# Load the object as an instance of each of its other models and get the corresponding solr fields
# Include :model_only=>true in the options in order to avoid adding the metadata from ActiveFedora::Base every time.
model_klazz_array.each do |klazz|
instance = obj.adapt_to(klazz)
solr_doc = instance.to_solr(solr_doc, :model_only=>true)
logger.debug " added solr fields from #{klazz.to_s}"
end
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :id_t, "#{obj.pid}" )
::Solrizer::Extractor.insert_solr_field_value(solr_doc, :id, "#{obj.pid}" ) unless solr_doc[:id]
return solr_doc
end | [
"def",
"create_document",
"(",
"obj",
")",
"solr_doc",
"=",
"Hash",
".",
"new",
"model_klazz_array",
"=",
"ActiveFedora",
"::",
"ContentModel",
".",
"known_models_for",
"(",
"obj",
")",
"model_klazz_array",
".",
"delete",
"(",
"ActiveFedora",
"::",
"Base",
")",
"if",
"obj",
".",
"class",
"==",
"ActiveFedora",
"::",
"Base",
"solr_doc",
"=",
"obj",
".",
"to_solr",
"(",
"solr_doc",
")",
"logger",
".",
"debug",
"\" added base fields from #{obj.class.to_s}\"",
"else",
"solr_doc",
"=",
"obj",
".",
"to_solr",
"(",
"solr_doc",
")",
"model_klazz_array",
".",
"delete",
"(",
"obj",
".",
"class",
")",
"logger",
".",
"debug",
"\" added base fields from #{obj.class.to_s} and model fields from #{obj.class.to_s}\"",
"end",
"model_klazz_array",
".",
"each",
"do",
"|",
"klazz",
"|",
"instance",
"=",
"obj",
".",
"adapt_to",
"(",
"klazz",
")",
"solr_doc",
"=",
"instance",
".",
"to_solr",
"(",
"solr_doc",
",",
":model_only",
"=>",
"true",
")",
"logger",
".",
"debug",
"\" added solr fields from #{klazz.to_s}\"",
"end",
"::",
"Solrizer",
"::",
"Extractor",
".",
"insert_solr_field_value",
"(",
"solr_doc",
",",
":id_t",
",",
"\"#{obj.pid}\"",
")",
"::",
"Solrizer",
"::",
"Extractor",
".",
"insert_solr_field_value",
"(",
"solr_doc",
",",
":id",
",",
"\"#{obj.pid}\"",
")",
"unless",
"solr_doc",
"[",
":id",
"]",
"return",
"solr_doc",
"end"
] | This method creates a Solr-formatted XML document | [
"This",
"method",
"creates",
"a",
"Solr",
"-",
"formatted",
"XML",
"document"
] | 277fab50a93a761fbccd07e2cfa01b22736d5cff | https://github.com/samvera-deprecated/solrizer-fedora/blob/277fab50a93a761fbccd07e2cfa01b22736d5cff/lib/solrizer/fedora/indexer.rb#L141-L171 | train |
megamsys/megam_api | lib/megam/api/accounts.rb | Megam.API.post_accounts | def post_accounts(new_account)
@options = {path: '/accounts/content',
body: Megam::JSONCompat.to_json(new_account)}.merge(@options)
request(
:expects => 201,
:method => :post,
:body => @options[:body]
)
end | ruby | def post_accounts(new_account)
@options = {path: '/accounts/content',
body: Megam::JSONCompat.to_json(new_account)}.merge(@options)
request(
:expects => 201,
:method => :post,
:body => @options[:body]
)
end | [
"def",
"post_accounts",
"(",
"new_account",
")",
"@options",
"=",
"{",
"path",
":",
"'/accounts/content'",
",",
"body",
":",
"Megam",
"::",
"JSONCompat",
".",
"to_json",
"(",
"new_account",
")",
"}",
".",
"merge",
"(",
"@options",
")",
"request",
"(",
":expects",
"=>",
"201",
",",
":method",
"=>",
":post",
",",
":body",
"=>",
"@options",
"[",
":body",
"]",
")",
"end"
] | The body content needs to be a json. | [
"The",
"body",
"content",
"needs",
"to",
"be",
"a",
"json",
"."
] | c28e743311706dfef9c7745ae64058a468f5b1a4 | https://github.com/megamsys/megam_api/blob/c28e743311706dfef9c7745ae64058a468f5b1a4/lib/megam/api/accounts.rb#L28-L37 | train |
michaelmior/mipper | lib/mipper/lp_solve/model.rb | MIPPeR.LPSolveModel.store_constraint_matrix | def store_constraint_matrix(constr, type)
# Initialize arrays used to hold the coefficients for each variable
row = []
colno = []
constr.expression.terms.each do |var, coeff|
row << coeff * 1.0
colno << var.index
end
row_buffer = build_pointer_array row, :double
colno_buffer = build_pointer_array colno, :int
ret = LPSolve.add_constraintex(@ptr, constr.expression.terms.length,
row_buffer, colno_buffer,
type, constr.rhs)
fail if ret != 1
end | ruby | def store_constraint_matrix(constr, type)
# Initialize arrays used to hold the coefficients for each variable
row = []
colno = []
constr.expression.terms.each do |var, coeff|
row << coeff * 1.0
colno << var.index
end
row_buffer = build_pointer_array row, :double
colno_buffer = build_pointer_array colno, :int
ret = LPSolve.add_constraintex(@ptr, constr.expression.terms.length,
row_buffer, colno_buffer,
type, constr.rhs)
fail if ret != 1
end | [
"def",
"store_constraint_matrix",
"(",
"constr",
",",
"type",
")",
"row",
"=",
"[",
"]",
"colno",
"=",
"[",
"]",
"constr",
".",
"expression",
".",
"terms",
".",
"each",
"do",
"|",
"var",
",",
"coeff",
"|",
"row",
"<<",
"coeff",
"*",
"1.0",
"colno",
"<<",
"var",
".",
"index",
"end",
"row_buffer",
"=",
"build_pointer_array",
"row",
",",
":double",
"colno_buffer",
"=",
"build_pointer_array",
"colno",
",",
":int",
"ret",
"=",
"LPSolve",
".",
"add_constraintex",
"(",
"@ptr",
",",
"constr",
".",
"expression",
".",
"terms",
".",
"length",
",",
"row_buffer",
",",
"colno_buffer",
",",
"type",
",",
"constr",
".",
"rhs",
")",
"fail",
"if",
"ret",
"!=",
"1",
"end"
] | Build the constraint matrix and add it to the model | [
"Build",
"the",
"constraint",
"matrix",
"and",
"add",
"it",
"to",
"the",
"model"
] | 4ab7f8b32c27f33fc5121756554a0a28d2077e06 | https://github.com/michaelmior/mipper/blob/4ab7f8b32c27f33fc5121756554a0a28d2077e06/lib/mipper/lp_solve/model.rb#L70-L86 | train |
oniram88/imdb-scan | lib/imdb/person.rb | IMDB.Person.birthdate | def birthdate
month_data_element = bio_document.at("td.label[text()*='Date of Birth']").
next_element.first_element_child
date_month = month_data_element.inner_text.strip rescue ""
year = month_data_element.next_element.inner_text.strip rescue ""
Date.parse("#{date_month} #{year}") rescue nil
end | ruby | def birthdate
month_data_element = bio_document.at("td.label[text()*='Date of Birth']").
next_element.first_element_child
date_month = month_data_element.inner_text.strip rescue ""
year = month_data_element.next_element.inner_text.strip rescue ""
Date.parse("#{date_month} #{year}") rescue nil
end | [
"def",
"birthdate",
"month_data_element",
"=",
"bio_document",
".",
"at",
"(",
"\"td.label[text()*='Date of Birth']\"",
")",
".",
"next_element",
".",
"first_element_child",
"date_month",
"=",
"month_data_element",
".",
"inner_text",
".",
"strip",
"rescue",
"\"\"",
"year",
"=",
"month_data_element",
".",
"next_element",
".",
"inner_text",
".",
"strip",
"rescue",
"\"\"",
"Date",
".",
"parse",
"(",
"\"#{date_month} #{year}\"",
")",
"rescue",
"nil",
"end"
] | Get The Birth Date
@return [Date] | [
"Get",
"The",
"Birth",
"Date"
] | e358adaba3db178df42c711c79c894f14d83c742 | https://github.com/oniram88/imdb-scan/blob/e358adaba3db178df42c711c79c894f14d83c742/lib/imdb/person.rb#L50-L56 | train |
oniram88/imdb-scan | lib/imdb/person.rb | IMDB.Person.deathdate | def deathdate
date_month = bio_document.at("h5[text()*='Date of Death']").next_element.inner_text.strip rescue ""
year = bio_document.at("a[@href*='death_date']").inner_text.strip rescue ""
Date.parse("#{date_month} #{year}") rescue nil
end | ruby | def deathdate
date_month = bio_document.at("h5[text()*='Date of Death']").next_element.inner_text.strip rescue ""
year = bio_document.at("a[@href*='death_date']").inner_text.strip rescue ""
Date.parse("#{date_month} #{year}") rescue nil
end | [
"def",
"deathdate",
"date_month",
"=",
"bio_document",
".",
"at",
"(",
"\"h5[text()*='Date of Death']\"",
")",
".",
"next_element",
".",
"inner_text",
".",
"strip",
"rescue",
"\"\"",
"year",
"=",
"bio_document",
".",
"at",
"(",
"\"a[@href*='death_date']\"",
")",
".",
"inner_text",
".",
"strip",
"rescue",
"\"\"",
"Date",
".",
"parse",
"(",
"\"#{date_month} #{year}\"",
")",
"rescue",
"nil",
"end"
] | Get The death date else nil
@return [Date] | [
"Get",
"The",
"death",
"date",
"else",
"nil"
] | e358adaba3db178df42c711c79c894f14d83c742 | https://github.com/oniram88/imdb-scan/blob/e358adaba3db178df42c711c79c894f14d83c742/lib/imdb/person.rb#L60-L64 | train |
oniram88/imdb-scan | lib/imdb/person.rb | IMDB.Person.filmography | def filmography
#@return [Hash]
# writer: [Movie]
# actor: [Movie]
# director: [Movie]
# composer: [Movie]
#as_writer = main_document.at("#filmo-head-Writer").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
#as_actor = main_document.at("#filmo-head-Actor").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
#as_director = main_document.at("#filmo-head-Director").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
#as_composer = main_document.at("#filmo-head-Composer").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
#{ writer: as_writer.map { |m| Movie.new(m) }, actor: as_actor.map { |m| Movie.new(m) }, director: as_director.map { |m| Movie.new(m) }, composer: as_composer.map { |m| Movie.new(m) } }
films=main_document.css(".filmo-row b a").map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
films.map { |f| Movie.new(f.to_i) }
end | ruby | def filmography
#@return [Hash]
# writer: [Movie]
# actor: [Movie]
# director: [Movie]
# composer: [Movie]
#as_writer = main_document.at("#filmo-head-Writer").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
#as_actor = main_document.at("#filmo-head-Actor").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
#as_director = main_document.at("#filmo-head-Director").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
#as_composer = main_document.at("#filmo-head-Composer").next_element.search('b a').map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
#{ writer: as_writer.map { |m| Movie.new(m) }, actor: as_actor.map { |m| Movie.new(m) }, director: as_director.map { |m| Movie.new(m) }, composer: as_composer.map { |m| Movie.new(m) } }
films=main_document.css(".filmo-row b a").map { |e| e.get_attribute('href')[/tt(\d+)/, 1] } rescue []
films.map { |f| Movie.new(f.to_i) }
end | [
"def",
"filmography",
"films",
"=",
"main_document",
".",
"css",
"(",
"\".filmo-row b a\"",
")",
".",
"map",
"{",
"|",
"e",
"|",
"e",
".",
"get_attribute",
"(",
"'href'",
")",
"[",
"/",
"\\d",
"/",
",",
"1",
"]",
"}",
"rescue",
"[",
"]",
"films",
".",
"map",
"{",
"|",
"f",
"|",
"Movie",
".",
"new",
"(",
"f",
".",
"to_i",
")",
"}",
"end"
] | Return the Filmography
for the moment I can't make subdivision of this, then i take all in an array
@return [Movie] | [
"Return",
"the",
"Filmography",
"for",
"the",
"moment",
"I",
"can",
"t",
"make",
"subdivision",
"of",
"this",
"then",
"i",
"take",
"all",
"in",
"an",
"array"
] | e358adaba3db178df42c711c79c894f14d83c742 | https://github.com/oniram88/imdb-scan/blob/e358adaba3db178df42c711c79c894f14d83c742/lib/imdb/person.rb#L93-L106 | train |
rixth/tay | lib/tay/specification.rb | Tay.Specification.all_javascript_paths | def all_javascript_paths
all_paths = []
all_paths += @javascripts
all_paths += @background_scripts
all_paths += @content_scripts.map { |cs| cs.javascripts }.compact
all_paths.flatten.uniq
end | ruby | def all_javascript_paths
all_paths = []
all_paths += @javascripts
all_paths += @background_scripts
all_paths += @content_scripts.map { |cs| cs.javascripts }.compact
all_paths.flatten.uniq
end | [
"def",
"all_javascript_paths",
"all_paths",
"=",
"[",
"]",
"all_paths",
"+=",
"@javascripts",
"all_paths",
"+=",
"@background_scripts",
"all_paths",
"+=",
"@content_scripts",
".",
"map",
"{",
"|",
"cs",
"|",
"cs",
".",
"javascripts",
"}",
".",
"compact",
"all_paths",
".",
"flatten",
".",
"uniq",
"end"
] | Return all the javascript paths in the spec, included those nested
inside other objects | [
"Return",
"all",
"the",
"javascript",
"paths",
"in",
"the",
"spec",
"included",
"those",
"nested",
"inside",
"other",
"objects"
] | 60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5 | https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/specification.rb#L261-L267 | train |
rixth/tay | lib/tay/specification.rb | Tay.Specification.all_stylesheet_paths | def all_stylesheet_paths
all_paths = []
all_paths += @stylesheets
all_paths += @content_scripts.map { |cs| cs.stylesheets }.compact
all_paths.flatten.uniq
end | ruby | def all_stylesheet_paths
all_paths = []
all_paths += @stylesheets
all_paths += @content_scripts.map { |cs| cs.stylesheets }.compact
all_paths.flatten.uniq
end | [
"def",
"all_stylesheet_paths",
"all_paths",
"=",
"[",
"]",
"all_paths",
"+=",
"@stylesheets",
"all_paths",
"+=",
"@content_scripts",
".",
"map",
"{",
"|",
"cs",
"|",
"cs",
".",
"stylesheets",
"}",
".",
"compact",
"all_paths",
".",
"flatten",
".",
"uniq",
"end"
] | Return all the stylesheet paths in the spec, included those nested
inside other objects | [
"Return",
"all",
"the",
"stylesheet",
"paths",
"in",
"the",
"spec",
"included",
"those",
"nested",
"inside",
"other",
"objects"
] | 60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5 | https://github.com/rixth/tay/blob/60a5d64aa54e7ef13d10d9c8fb7825e2febea8e5/lib/tay/specification.rb#L272-L277 | train |
ideonetwork/lato-blog | app/models/lato_blog/category/serializer_helpers.rb | LatoBlog.Category::SerializerHelpers.serialize | def serialize
serialized = {}
# set basic info
serialized[:id] = id
serialized[:title] = title
serialized[:meta_language] = meta_language
serialized[:meta_permalink] = meta_permalink
# add category father informations
serialized[:category_father] = category_father ? category_father.serialize_base : nil
# add category children informations
serialized[:category_children] = serialize_category_children
# add category parent informations
serialized[:other_informations] = serialize_other_informations
# return serialized post
serialized
end | ruby | def serialize
serialized = {}
# set basic info
serialized[:id] = id
serialized[:title] = title
serialized[:meta_language] = meta_language
serialized[:meta_permalink] = meta_permalink
# add category father informations
serialized[:category_father] = category_father ? category_father.serialize_base : nil
# add category children informations
serialized[:category_children] = serialize_category_children
# add category parent informations
serialized[:other_informations] = serialize_other_informations
# return serialized post
serialized
end | [
"def",
"serialize",
"serialized",
"=",
"{",
"}",
"serialized",
"[",
":id",
"]",
"=",
"id",
"serialized",
"[",
":title",
"]",
"=",
"title",
"serialized",
"[",
":meta_language",
"]",
"=",
"meta_language",
"serialized",
"[",
":meta_permalink",
"]",
"=",
"meta_permalink",
"serialized",
"[",
":category_father",
"]",
"=",
"category_father",
"?",
"category_father",
".",
"serialize_base",
":",
"nil",
"serialized",
"[",
":category_children",
"]",
"=",
"serialize_category_children",
"serialized",
"[",
":other_informations",
"]",
"=",
"serialize_other_informations",
"serialized",
"end"
] | This function serializes a complete version of the category. | [
"This",
"function",
"serializes",
"a",
"complete",
"version",
"of",
"the",
"category",
"."
] | a0d92de299a0e285851743b9d4a902f611187cba | https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/category/serializer_helpers.rb#L5-L25 | train |
ideonetwork/lato-blog | app/models/lato_blog/category/serializer_helpers.rb | LatoBlog.Category::SerializerHelpers.serialize_base | def serialize_base
serialized = {}
# set basic info
serialized[:id] = id
serialized[:title] = title
serialized[:meta_language] = meta_language
serialized[:meta_permalink] = meta_permalink
# return serialized category
serialized
end | ruby | def serialize_base
serialized = {}
# set basic info
serialized[:id] = id
serialized[:title] = title
serialized[:meta_language] = meta_language
serialized[:meta_permalink] = meta_permalink
# return serialized category
serialized
end | [
"def",
"serialize_base",
"serialized",
"=",
"{",
"}",
"serialized",
"[",
":id",
"]",
"=",
"id",
"serialized",
"[",
":title",
"]",
"=",
"title",
"serialized",
"[",
":meta_language",
"]",
"=",
"meta_language",
"serialized",
"[",
":meta_permalink",
"]",
"=",
"meta_permalink",
"serialized",
"end"
] | This function serializes a basic version of the category. | [
"This",
"function",
"serializes",
"a",
"basic",
"version",
"of",
"the",
"category",
"."
] | a0d92de299a0e285851743b9d4a902f611187cba | https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/category/serializer_helpers.rb#L28-L39 | train |
paxtonhare/marklogic-ruby-driver | lib/marklogic/collection.rb | MarkLogic.Collection.from_criteria | def from_criteria(criteria)
queries = []
criteria.each do |k, v|
name, operator, index_type, value = nil
query_options = {}
if (v.is_a?(Hash))
name = k.to_s
query_options.merge!(v.delete(:options) || {})
sub_queries = []
v.each do |kk, vv|
operator = kk.to_s.gsub('$', '').upcase || "EQ"
if @operators.include?(operator)
value = vv
value = value.to_s if value.is_a?(MarkLogic::ObjectId)
sub_queries << build_query(name, operator, value, query_options)
elsif value.is_a?(Hash)
child_queries = value.map do |kk, vv|
build_query(kk, vv, query_options)
end
sub_queries << Queries::ContainerQuery.new(name, Queries::AndQuery.new(child_queries))
end
end
if sub_queries.length > 1
queries << Queries::AndQuery.new(sub_queries)
elsif sub_queries.length == 1
queries << sub_queries[0]
end
else
name = k.to_s
value = v
operator = "EQ"
queries << build_query(name, operator, value, query_options)
end
end
if queries.length > 1
MarkLogic::Queries::AndQuery.new(*queries)
elsif queries.length == 1
queries[0]
end
end | ruby | def from_criteria(criteria)
queries = []
criteria.each do |k, v|
name, operator, index_type, value = nil
query_options = {}
if (v.is_a?(Hash))
name = k.to_s
query_options.merge!(v.delete(:options) || {})
sub_queries = []
v.each do |kk, vv|
operator = kk.to_s.gsub('$', '').upcase || "EQ"
if @operators.include?(operator)
value = vv
value = value.to_s if value.is_a?(MarkLogic::ObjectId)
sub_queries << build_query(name, operator, value, query_options)
elsif value.is_a?(Hash)
child_queries = value.map do |kk, vv|
build_query(kk, vv, query_options)
end
sub_queries << Queries::ContainerQuery.new(name, Queries::AndQuery.new(child_queries))
end
end
if sub_queries.length > 1
queries << Queries::AndQuery.new(sub_queries)
elsif sub_queries.length == 1
queries << sub_queries[0]
end
else
name = k.to_s
value = v
operator = "EQ"
queries << build_query(name, operator, value, query_options)
end
end
if queries.length > 1
MarkLogic::Queries::AndQuery.new(*queries)
elsif queries.length == 1
queries[0]
end
end | [
"def",
"from_criteria",
"(",
"criteria",
")",
"queries",
"=",
"[",
"]",
"criteria",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"name",
",",
"operator",
",",
"index_type",
",",
"value",
"=",
"nil",
"query_options",
"=",
"{",
"}",
"if",
"(",
"v",
".",
"is_a?",
"(",
"Hash",
")",
")",
"name",
"=",
"k",
".",
"to_s",
"query_options",
".",
"merge!",
"(",
"v",
".",
"delete",
"(",
":options",
")",
"||",
"{",
"}",
")",
"sub_queries",
"=",
"[",
"]",
"v",
".",
"each",
"do",
"|",
"kk",
",",
"vv",
"|",
"operator",
"=",
"kk",
".",
"to_s",
".",
"gsub",
"(",
"'$'",
",",
"''",
")",
".",
"upcase",
"||",
"\"EQ\"",
"if",
"@operators",
".",
"include?",
"(",
"operator",
")",
"value",
"=",
"vv",
"value",
"=",
"value",
".",
"to_s",
"if",
"value",
".",
"is_a?",
"(",
"MarkLogic",
"::",
"ObjectId",
")",
"sub_queries",
"<<",
"build_query",
"(",
"name",
",",
"operator",
",",
"value",
",",
"query_options",
")",
"elsif",
"value",
".",
"is_a?",
"(",
"Hash",
")",
"child_queries",
"=",
"value",
".",
"map",
"do",
"|",
"kk",
",",
"vv",
"|",
"build_query",
"(",
"kk",
",",
"vv",
",",
"query_options",
")",
"end",
"sub_queries",
"<<",
"Queries",
"::",
"ContainerQuery",
".",
"new",
"(",
"name",
",",
"Queries",
"::",
"AndQuery",
".",
"new",
"(",
"child_queries",
")",
")",
"end",
"end",
"if",
"sub_queries",
".",
"length",
">",
"1",
"queries",
"<<",
"Queries",
"::",
"AndQuery",
".",
"new",
"(",
"sub_queries",
")",
"elsif",
"sub_queries",
".",
"length",
"==",
"1",
"queries",
"<<",
"sub_queries",
"[",
"0",
"]",
"end",
"else",
"name",
"=",
"k",
".",
"to_s",
"value",
"=",
"v",
"operator",
"=",
"\"EQ\"",
"queries",
"<<",
"build_query",
"(",
"name",
",",
"operator",
",",
"value",
",",
"query_options",
")",
"end",
"end",
"if",
"queries",
".",
"length",
">",
"1",
"MarkLogic",
"::",
"Queries",
"::",
"AndQuery",
".",
"new",
"(",
"*",
"queries",
")",
"elsif",
"queries",
".",
"length",
"==",
"1",
"queries",
"[",
"0",
"]",
"end",
"end"
] | Builds a MarkLogic Query from Mongo Style Criteria
@param [Hash] criteria The Criteria to use when searching
@example Build a query from criteria
# Query on age == 3
collection.from_criteria({ 'age' => { '$eq' => 3 } })
# Query on age < 3
collection.from_criteria({ 'age' => { '$lt' => 3 } })
# Query on age <= 3
collection.from_criteria({ 'age' => { '$le' => 3 } })
# Query on age > 3
collection.from_criteria({ 'age' => { '$gt' => 3 } })
# Query on age >= 3
collection.from_criteria({ 'age' => { '$ge' => 3 } })
# Query on age != 3
collection.from_criteria({ 'age' => { '$ne' => 3 } })
@since 0.0.1 | [
"Builds",
"a",
"MarkLogic",
"Query",
"from",
"Mongo",
"Style",
"Criteria"
] | 76c3f2c2da7b8266cdbe786b7f3e910e0983eb9b | https://github.com/paxtonhare/marklogic-ruby-driver/blob/76c3f2c2da7b8266cdbe786b7f3e910e0983eb9b/lib/marklogic/collection.rb#L174-L218 | train |
cjfuller/rimageanalysistools | lib/rimageanalysistools/drawing.rb | RImageAnalysisTools.Drawing.draw | def draw(im, draw_value = 255.0)
im.each do |ic|
if (yield ic) then
im.setValue(ic, draw_value)
end
end
end | ruby | def draw(im, draw_value = 255.0)
im.each do |ic|
if (yield ic) then
im.setValue(ic, draw_value)
end
end
end | [
"def",
"draw",
"(",
"im",
",",
"draw_value",
"=",
"255.0",
")",
"im",
".",
"each",
"do",
"|",
"ic",
"|",
"if",
"(",
"yield",
"ic",
")",
"then",
"im",
".",
"setValue",
"(",
"ic",
",",
"draw_value",
")",
"end",
"end",
"end"
] | A basic drawing method that iterates through an entire image. At each coordinate,
an attached block is evaluated for a boolean response that determines whether that
coordinate is overwritten with a specified value. The attached block will be given
a single parameter, which is the current ImageCoordinate.
@param [WritableImage] im the image being drawn on
@param [Numeric] draw_value the value to which a pixel will be set if the block
evaluates to a true value at that coordinate
@return [void] | [
"A",
"basic",
"drawing",
"method",
"that",
"iterates",
"through",
"an",
"entire",
"image",
".",
"At",
"each",
"coordinate",
"an",
"attached",
"block",
"is",
"evaluated",
"for",
"a",
"boolean",
"response",
"that",
"determines",
"whether",
"that",
"coordinate",
"is",
"overwritten",
"with",
"a",
"specified",
"value",
".",
"The",
"attached",
"block",
"will",
"be",
"given",
"a",
"single",
"parameter",
"which",
"is",
"the",
"current",
"ImageCoordinate",
"."
] | 991aa7a61a8ad7bd902a31d99a19ce135e3cc485 | https://github.com/cjfuller/rimageanalysistools/blob/991aa7a61a8ad7bd902a31d99a19ce135e3cc485/lib/rimageanalysistools/drawing.rb#L96-L108 | train |
cjfuller/rimageanalysistools | lib/rimageanalysistools/drawing.rb | RImageAnalysisTools.Drawing.draw_shape | def draw_shape(im, location, shape_name=:circle, shape_parameters= 10)
if self.respond_to?(shape_name) then
self.send(shape_name, im, location, shape_parameters)
end
end | ruby | def draw_shape(im, location, shape_name=:circle, shape_parameters= 10)
if self.respond_to?(shape_name) then
self.send(shape_name, im, location, shape_parameters)
end
end | [
"def",
"draw_shape",
"(",
"im",
",",
"location",
",",
"shape_name",
"=",
":circle",
",",
"shape_parameters",
"=",
"10",
")",
"if",
"self",
".",
"respond_to?",
"(",
"shape_name",
")",
"then",
"self",
".",
"send",
"(",
"shape_name",
",",
"im",
",",
"location",
",",
"shape_parameters",
")",
"end",
"end"
] | Draws a specified shape into an image.
@param [WritableImage] im the image into which to draw
@param [Array] location an array containing the coordinates of the shape to draw.
The exact meaning of this parameter depends on which shape is being drawn.
@param [Symbol] shape_name the name of the shape to draw. This should correspond
to one of the methods of this class.
@param shape_parameters the parameters for drawing the specified shape;
the meaning of this parameter depends on the shape.
@return [void] | [
"Draws",
"a",
"specified",
"shape",
"into",
"an",
"image",
"."
] | 991aa7a61a8ad7bd902a31d99a19ce135e3cc485 | https://github.com/cjfuller/rimageanalysistools/blob/991aa7a61a8ad7bd902a31d99a19ce135e3cc485/lib/rimageanalysistools/drawing.rb#L123-L131 | train |
cjfuller/rimageanalysistools | lib/rimageanalysistools/drawing.rb | RImageAnalysisTools.Drawing.circle | def circle(im, center, radius)
lower = ImageCoordinate[center[0]-radius-1, center[1]-radius-1, 0,0,0]
upper = ImageCoordinate[center[0]+radius+1, center[1]+radius+1, 0,0,0]
im.box_conservative(lower, upper, [:x, :y])
draw(im) do |ic|
xdiff = ic[:x] - center[0]
ydiff = ic[:y] - center[1]
if (Math.hypot(xdiff, ydiff) - radius).abs <= Math.sqrt(2) then
true
else
false
end
end
lower.recycle
upper.recycle
end | ruby | def circle(im, center, radius)
lower = ImageCoordinate[center[0]-radius-1, center[1]-radius-1, 0,0,0]
upper = ImageCoordinate[center[0]+radius+1, center[1]+radius+1, 0,0,0]
im.box_conservative(lower, upper, [:x, :y])
draw(im) do |ic|
xdiff = ic[:x] - center[0]
ydiff = ic[:y] - center[1]
if (Math.hypot(xdiff, ydiff) - radius).abs <= Math.sqrt(2) then
true
else
false
end
end
lower.recycle
upper.recycle
end | [
"def",
"circle",
"(",
"im",
",",
"center",
",",
"radius",
")",
"lower",
"=",
"ImageCoordinate",
"[",
"center",
"[",
"0",
"]",
"-",
"radius",
"-",
"1",
",",
"center",
"[",
"1",
"]",
"-",
"radius",
"-",
"1",
",",
"0",
",",
"0",
",",
"0",
"]",
"upper",
"=",
"ImageCoordinate",
"[",
"center",
"[",
"0",
"]",
"+",
"radius",
"+",
"1",
",",
"center",
"[",
"1",
"]",
"+",
"radius",
"+",
"1",
",",
"0",
",",
"0",
",",
"0",
"]",
"im",
".",
"box_conservative",
"(",
"lower",
",",
"upper",
",",
"[",
":x",
",",
":y",
"]",
")",
"draw",
"(",
"im",
")",
"do",
"|",
"ic",
"|",
"xdiff",
"=",
"ic",
"[",
":x",
"]",
"-",
"center",
"[",
"0",
"]",
"ydiff",
"=",
"ic",
"[",
":y",
"]",
"-",
"center",
"[",
"1",
"]",
"if",
"(",
"Math",
".",
"hypot",
"(",
"xdiff",
",",
"ydiff",
")",
"-",
"radius",
")",
".",
"abs",
"<=",
"Math",
".",
"sqrt",
"(",
"2",
")",
"then",
"true",
"else",
"false",
"end",
"end",
"lower",
".",
"recycle",
"upper",
".",
"recycle",
"end"
] | Draws a circle into an image.
@param [WritableImage] im the image into which to draw
@param [Array] center an array containing the x,y coordinates of the circle's center
@param [Numeric] radius the radius of the circle in pixels
@return [void] | [
"Draws",
"a",
"circle",
"into",
"an",
"image",
"."
] | 991aa7a61a8ad7bd902a31d99a19ce135e3cc485 | https://github.com/cjfuller/rimageanalysistools/blob/991aa7a61a8ad7bd902a31d99a19ce135e3cc485/lib/rimageanalysistools/drawing.rb#L142-L165 | train |
cjfuller/rimageanalysistools | lib/rimageanalysistools/drawing.rb | RImageAnalysisTools.Drawing.ellipse | def ellipse(im, foci, radius_inc)
min_x = foci[0][0]
max_x = foci[1][0]
min_y = foci[0][1]
max_y = foci[1][1]
if foci[1][0] < min_x then
min_x = foci[1][0]
max_x = foci[0][0]
end
if foci[1][1] < min_y then
min_y = foci[1][1]
max_y = foci[0][1]
end
radius = radius_inc + Math.hypot(max_x-min_x, max_y-min_y)
lower = ImageCoordinate[min_x-radius-1, min_y-radius-1, 0,0,0]
upper = ImageCoordinate[max_x+radius+1, max_y+radius+1, 0,0,0]
im.box_conservative(lower, upper, [:x, :y])
draw(im) do |ic|
xdiff0 = ic[:x] - foci[0][0]
ydiff0 = ic[:y] - foci[0][1]
xdiff1 = ic[:x] - foci[1][0]
ydiff1 = ic[:y] - foci[1][1]
if (Math.hypot(xdiff0, ydiff0) + Math.hypot(xdiff1, ydiff1) - radius).abs <= Math.sqrt(2) then
true
else
false
end
end
end | ruby | def ellipse(im, foci, radius_inc)
min_x = foci[0][0]
max_x = foci[1][0]
min_y = foci[0][1]
max_y = foci[1][1]
if foci[1][0] < min_x then
min_x = foci[1][0]
max_x = foci[0][0]
end
if foci[1][1] < min_y then
min_y = foci[1][1]
max_y = foci[0][1]
end
radius = radius_inc + Math.hypot(max_x-min_x, max_y-min_y)
lower = ImageCoordinate[min_x-radius-1, min_y-radius-1, 0,0,0]
upper = ImageCoordinate[max_x+radius+1, max_y+radius+1, 0,0,0]
im.box_conservative(lower, upper, [:x, :y])
draw(im) do |ic|
xdiff0 = ic[:x] - foci[0][0]
ydiff0 = ic[:y] - foci[0][1]
xdiff1 = ic[:x] - foci[1][0]
ydiff1 = ic[:y] - foci[1][1]
if (Math.hypot(xdiff0, ydiff0) + Math.hypot(xdiff1, ydiff1) - radius).abs <= Math.sqrt(2) then
true
else
false
end
end
end | [
"def",
"ellipse",
"(",
"im",
",",
"foci",
",",
"radius_inc",
")",
"min_x",
"=",
"foci",
"[",
"0",
"]",
"[",
"0",
"]",
"max_x",
"=",
"foci",
"[",
"1",
"]",
"[",
"0",
"]",
"min_y",
"=",
"foci",
"[",
"0",
"]",
"[",
"1",
"]",
"max_y",
"=",
"foci",
"[",
"1",
"]",
"[",
"1",
"]",
"if",
"foci",
"[",
"1",
"]",
"[",
"0",
"]",
"<",
"min_x",
"then",
"min_x",
"=",
"foci",
"[",
"1",
"]",
"[",
"0",
"]",
"max_x",
"=",
"foci",
"[",
"0",
"]",
"[",
"0",
"]",
"end",
"if",
"foci",
"[",
"1",
"]",
"[",
"1",
"]",
"<",
"min_y",
"then",
"min_y",
"=",
"foci",
"[",
"1",
"]",
"[",
"1",
"]",
"max_y",
"=",
"foci",
"[",
"0",
"]",
"[",
"1",
"]",
"end",
"radius",
"=",
"radius_inc",
"+",
"Math",
".",
"hypot",
"(",
"max_x",
"-",
"min_x",
",",
"max_y",
"-",
"min_y",
")",
"lower",
"=",
"ImageCoordinate",
"[",
"min_x",
"-",
"radius",
"-",
"1",
",",
"min_y",
"-",
"radius",
"-",
"1",
",",
"0",
",",
"0",
",",
"0",
"]",
"upper",
"=",
"ImageCoordinate",
"[",
"max_x",
"+",
"radius",
"+",
"1",
",",
"max_y",
"+",
"radius",
"+",
"1",
",",
"0",
",",
"0",
",",
"0",
"]",
"im",
".",
"box_conservative",
"(",
"lower",
",",
"upper",
",",
"[",
":x",
",",
":y",
"]",
")",
"draw",
"(",
"im",
")",
"do",
"|",
"ic",
"|",
"xdiff0",
"=",
"ic",
"[",
":x",
"]",
"-",
"foci",
"[",
"0",
"]",
"[",
"0",
"]",
"ydiff0",
"=",
"ic",
"[",
":y",
"]",
"-",
"foci",
"[",
"0",
"]",
"[",
"1",
"]",
"xdiff1",
"=",
"ic",
"[",
":x",
"]",
"-",
"foci",
"[",
"1",
"]",
"[",
"0",
"]",
"ydiff1",
"=",
"ic",
"[",
":y",
"]",
"-",
"foci",
"[",
"1",
"]",
"[",
"1",
"]",
"if",
"(",
"Math",
".",
"hypot",
"(",
"xdiff0",
",",
"ydiff0",
")",
"+",
"Math",
".",
"hypot",
"(",
"xdiff1",
",",
"ydiff1",
")",
"-",
"radius",
")",
".",
"abs",
"<=",
"Math",
".",
"sqrt",
"(",
"2",
")",
"then",
"true",
"else",
"false",
"end",
"end",
"end"
] | Draws an ellipse into an image.
@param [WritableImage] im the image into which to draw
@param [Array] foci an array containing two arrays, each of which contains the x,y
coordinates of one focus of the ellipse
@param [Numeric] radius_inc the extra amount of distance (in pixels) beyond the
distance between the foci that the ellipse should be drawn. (2*radius_inc + dist
between foci = major axis length)
@return [void] | [
"Draws",
"an",
"ellipse",
"into",
"an",
"image",
"."
] | 991aa7a61a8ad7bd902a31d99a19ce135e3cc485 | https://github.com/cjfuller/rimageanalysistools/blob/991aa7a61a8ad7bd902a31d99a19ce135e3cc485/lib/rimageanalysistools/drawing.rb#L179-L219 | train |
assaf/css-annotate | lib/css/annotate.rb | CSS.Annotate.annotate | def annotate(filename)
engine = Sass::Engine.new(IO.read(filename), options.merge(:syntax=>guess_syntax(filename)))
tree = engine.to_tree
tree.perform!(Sass::Environment.new)
resolve_rules tree
@rows = to_rows(tree)
end | ruby | def annotate(filename)
engine = Sass::Engine.new(IO.read(filename), options.merge(:syntax=>guess_syntax(filename)))
tree = engine.to_tree
tree.perform!(Sass::Environment.new)
resolve_rules tree
@rows = to_rows(tree)
end | [
"def",
"annotate",
"(",
"filename",
")",
"engine",
"=",
"Sass",
"::",
"Engine",
".",
"new",
"(",
"IO",
".",
"read",
"(",
"filename",
")",
",",
"options",
".",
"merge",
"(",
":syntax",
"=>",
"guess_syntax",
"(",
"filename",
")",
")",
")",
"tree",
"=",
"engine",
".",
"to_tree",
"tree",
".",
"perform!",
"(",
"Sass",
"::",
"Environment",
".",
"new",
")",
"resolve_rules",
"tree",
"@rows",
"=",
"to_rows",
"(",
"tree",
")",
"end"
] | Annotate the named file. Sets and returns rows. | [
"Annotate",
"the",
"named",
"file",
".",
"Sets",
"and",
"returns",
"rows",
"."
] | 5368d8f15e70b2f3cc6b38872a4685383b119d02 | https://github.com/assaf/css-annotate/blob/5368d8f15e70b2f3cc6b38872a4685383b119d02/lib/css/annotate.rb#L29-L35 | train |
assaf/css-annotate | lib/css/annotate.rb | CSS.Annotate.to_html | def to_html(filename)
rows = annotate(filename)
ERB.new(IO.read(File.dirname(__FILE__) + "/annotate/template.erb")).result(binding)
rescue Sass::SyntaxError=>error
error = Sass::SyntaxError.exception_to_css error, @options.merge(:full_exception=>true)
ERB.new(IO.read(File.dirname(__FILE__) + "/annotate/template.erb")).result(binding)
end | ruby | def to_html(filename)
rows = annotate(filename)
ERB.new(IO.read(File.dirname(__FILE__) + "/annotate/template.erb")).result(binding)
rescue Sass::SyntaxError=>error
error = Sass::SyntaxError.exception_to_css error, @options.merge(:full_exception=>true)
ERB.new(IO.read(File.dirname(__FILE__) + "/annotate/template.erb")).result(binding)
end | [
"def",
"to_html",
"(",
"filename",
")",
"rows",
"=",
"annotate",
"(",
"filename",
")",
"ERB",
".",
"new",
"(",
"IO",
".",
"read",
"(",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
"+",
"\"/annotate/template.erb\"",
")",
")",
".",
"result",
"(",
"binding",
")",
"rescue",
"Sass",
"::",
"SyntaxError",
"=>",
"error",
"error",
"=",
"Sass",
"::",
"SyntaxError",
".",
"exception_to_css",
"error",
",",
"@options",
".",
"merge",
"(",
":full_exception",
"=>",
"true",
")",
"ERB",
".",
"new",
"(",
"IO",
".",
"read",
"(",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
"+",
"\"/annotate/template.erb\"",
")",
")",
".",
"result",
"(",
"binding",
")",
"end"
] | Annotate the named file, returns HTML document. | [
"Annotate",
"the",
"named",
"file",
"returns",
"HTML",
"document",
"."
] | 5368d8f15e70b2f3cc6b38872a4685383b119d02 | https://github.com/assaf/css-annotate/blob/5368d8f15e70b2f3cc6b38872a4685383b119d02/lib/css/annotate.rb#L38-L44 | train |
assaf/css-annotate | lib/css/annotate.rb | CSS.Annotate.styles | def styles
Sass::Engine.new(IO.read(File.dirname(__FILE__) + "/annotate/style.scss"), :syntax=>:scss).render
end | ruby | def styles
Sass::Engine.new(IO.read(File.dirname(__FILE__) + "/annotate/style.scss"), :syntax=>:scss).render
end | [
"def",
"styles",
"Sass",
"::",
"Engine",
".",
"new",
"(",
"IO",
".",
"read",
"(",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
"+",
"\"/annotate/style.scss\"",
")",
",",
":syntax",
"=>",
":scss",
")",
".",
"render",
"end"
] | ERB template uses this to obtain our own stylesheet. | [
"ERB",
"template",
"uses",
"this",
"to",
"obtain",
"our",
"own",
"stylesheet",
"."
] | 5368d8f15e70b2f3cc6b38872a4685383b119d02 | https://github.com/assaf/css-annotate/blob/5368d8f15e70b2f3cc6b38872a4685383b119d02/lib/css/annotate.rb#L52-L54 | train |
wapcaplet/kelp | lib/kelp/visibility.rb | Kelp.Visibility.page_contains? | def page_contains?(text_or_regexp)
if text_or_regexp.class == String
return page.has_content?(text_or_regexp)
elsif text_or_regexp.class == Regexp
return page.has_xpath?('.//*', :text => text_or_regexp)
else
raise ArgumentError, "Expected String or Regexp, got #{text_or_regexp.class}"
end
end | ruby | def page_contains?(text_or_regexp)
if text_or_regexp.class == String
return page.has_content?(text_or_regexp)
elsif text_or_regexp.class == Regexp
return page.has_xpath?('.//*', :text => text_or_regexp)
else
raise ArgumentError, "Expected String or Regexp, got #{text_or_regexp.class}"
end
end | [
"def",
"page_contains?",
"(",
"text_or_regexp",
")",
"if",
"text_or_regexp",
".",
"class",
"==",
"String",
"return",
"page",
".",
"has_content?",
"(",
"text_or_regexp",
")",
"elsif",
"text_or_regexp",
".",
"class",
"==",
"Regexp",
"return",
"page",
".",
"has_xpath?",
"(",
"'.//*'",
",",
":text",
"=>",
"text_or_regexp",
")",
"else",
"raise",
"ArgumentError",
",",
"\"Expected String or Regexp, got #{text_or_regexp.class}\"",
"end",
"end"
] | Return `true` if the current page contains the given text or regular expression,
or `false` if it does not.
@param [String, Regexp] text_or_regexp
Text or regular expression to look for
@raise [ArgumentError]
If the given argument isn't a String or Regexp
@since 0.2.0 | [
"Return",
"true",
"if",
"the",
"current",
"page",
"contains",
"the",
"given",
"text",
"or",
"regular",
"expression",
"or",
"false",
"if",
"it",
"does",
"not",
"."
] | 592fe188db5a3d05e6120ed2157ad8d781601b7a | https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/visibility.rb#L26-L34 | train |
wapcaplet/kelp | lib/kelp/visibility.rb | Kelp.Visibility.should_see | def should_see(texts, scope={})
in_scope(scope) do
texts = [texts] if (texts.class == String || texts.class == Regexp)
# Select all expected values that don't appear on the page
unexpected = texts.select do |text|
!page_contains?(text)
end
if !unexpected.empty?
raise Kelp::Unexpected,
"Expected to see: #{texts.inspect}\nDid not see: #{unexpected.inspect}"
end
end
end | ruby | def should_see(texts, scope={})
in_scope(scope) do
texts = [texts] if (texts.class == String || texts.class == Regexp)
# Select all expected values that don't appear on the page
unexpected = texts.select do |text|
!page_contains?(text)
end
if !unexpected.empty?
raise Kelp::Unexpected,
"Expected to see: #{texts.inspect}\nDid not see: #{unexpected.inspect}"
end
end
end | [
"def",
"should_see",
"(",
"texts",
",",
"scope",
"=",
"{",
"}",
")",
"in_scope",
"(",
"scope",
")",
"do",
"texts",
"=",
"[",
"texts",
"]",
"if",
"(",
"texts",
".",
"class",
"==",
"String",
"||",
"texts",
".",
"class",
"==",
"Regexp",
")",
"unexpected",
"=",
"texts",
".",
"select",
"do",
"|",
"text",
"|",
"!",
"page_contains?",
"(",
"text",
")",
"end",
"if",
"!",
"unexpected",
".",
"empty?",
"raise",
"Kelp",
"::",
"Unexpected",
",",
"\"Expected to see: #{texts.inspect}\\nDid not see: #{unexpected.inspect}\"",
"end",
"end",
"end"
] | Verify the presence of content on the page. Passes when all the given items
are found on the page, and fails if any of them are not found.
@example
should_see "Animaniacs"
should_see ["Yakko", "Wakko", "Dot"]
should_see "Baloney", :within => "#slacks"
should_see /(Animaney|Totally Insaney|Pinky and the Brainy)/
@param [String, Regexp, Array] texts
Text(s) or regexp(s) to look for
@param [Hash] scope
Scoping keywords as understood by {#in_scope}
@raise [Kelp::Unexpected]
If any of the expected text strings are not seen in the given scope | [
"Verify",
"the",
"presence",
"of",
"content",
"on",
"the",
"page",
".",
"Passes",
"when",
"all",
"the",
"given",
"items",
"are",
"found",
"on",
"the",
"page",
"and",
"fails",
"if",
"any",
"of",
"them",
"are",
"not",
"found",
"."
] | 592fe188db5a3d05e6120ed2157ad8d781601b7a | https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/visibility.rb#L54-L66 | train |
wapcaplet/kelp | lib/kelp/visibility.rb | Kelp.Visibility.should_see_in_same_row | def should_see_in_same_row(texts, scope={})
in_scope(scope) do
if !page.has_xpath?(xpath_row_containing(texts))
raise Kelp::Unexpected, "Expected, but did not see: #{texts.inspect} in the same row"
end
end
end | ruby | def should_see_in_same_row(texts, scope={})
in_scope(scope) do
if !page.has_xpath?(xpath_row_containing(texts))
raise Kelp::Unexpected, "Expected, but did not see: #{texts.inspect} in the same row"
end
end
end | [
"def",
"should_see_in_same_row",
"(",
"texts",
",",
"scope",
"=",
"{",
"}",
")",
"in_scope",
"(",
"scope",
")",
"do",
"if",
"!",
"page",
".",
"has_xpath?",
"(",
"xpath_row_containing",
"(",
"texts",
")",
")",
"raise",
"Kelp",
"::",
"Unexpected",
",",
"\"Expected, but did not see: #{texts.inspect} in the same row\"",
"end",
"end",
"end"
] | Verify that all items appear in the same table row. Passes if a `tr`
element exists containing all the given `texts`, and fails if no such
`tr` exists. The texts may be in any order in the row.
@example
should_see_in_same_row ["Yakko", "Rob Paulsen"]
should_see_in_same_row ["Wakko", "Jess Harnell"]
should_see_in_same_row ["Dot", "Tress MacNeille"]
@param [Array] texts
Array of Strings that should appear in the same row
@param [Hash] scope
Scoping keywords as understood by {#in_scope}
@raise [Kelp::Unexpected]
If no row is found containing all strings in `texts` | [
"Verify",
"that",
"all",
"items",
"appear",
"in",
"the",
"same",
"table",
"row",
".",
"Passes",
"if",
"a",
"tr",
"element",
"exists",
"containing",
"all",
"the",
"given",
"texts",
"and",
"fails",
"if",
"no",
"such",
"tr",
"exists",
".",
"The",
"texts",
"may",
"be",
"in",
"any",
"order",
"in",
"the",
"row",
"."
] | 592fe188db5a3d05e6120ed2157ad8d781601b7a | https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/visibility.rb#L112-L118 | train |
jeremyd/virtualmonkey | lib/virtualmonkey/ebs.rb | VirtualMonkey.EBS.wait_for_snapshots | def wait_for_snapshots
timeout=1500
step=10
while timeout > 0
puts "Checking for snapshot completed"
snapshots = behavior(:find_snapshots)
status= snapshots.map { |x| x.aws_status }
break unless status.include?("pending")
sleep step
timeout -= step
end
raise "FATAL: timed out waiting for all snapshots in lineage #{@lineage} to complete" if timeout == 0
end | ruby | def wait_for_snapshots
timeout=1500
step=10
while timeout > 0
puts "Checking for snapshot completed"
snapshots = behavior(:find_snapshots)
status= snapshots.map { |x| x.aws_status }
break unless status.include?("pending")
sleep step
timeout -= step
end
raise "FATAL: timed out waiting for all snapshots in lineage #{@lineage} to complete" if timeout == 0
end | [
"def",
"wait_for_snapshots",
"timeout",
"=",
"1500",
"step",
"=",
"10",
"while",
"timeout",
">",
"0",
"puts",
"\"Checking for snapshot completed\"",
"snapshots",
"=",
"behavior",
"(",
":find_snapshots",
")",
"status",
"=",
"snapshots",
".",
"map",
"{",
"|",
"x",
"|",
"x",
".",
"aws_status",
"}",
"break",
"unless",
"status",
".",
"include?",
"(",
"\"pending\"",
")",
"sleep",
"step",
"timeout",
"-=",
"step",
"end",
"raise",
"\"FATAL: timed out waiting for all snapshots in lineage #{@lineage} to complete\"",
"if",
"timeout",
"==",
"0",
"end"
] | take the lineage name, find all snapshots and sleep until none are in the pending state. | [
"take",
"the",
"lineage",
"name",
"find",
"all",
"snapshots",
"and",
"sleep",
"until",
"none",
"are",
"in",
"the",
"pending",
"state",
"."
] | b2c7255f20ac5ec881eb90afbb5e712160db0dcb | https://github.com/jeremyd/virtualmonkey/blob/b2c7255f20ac5ec881eb90afbb5e712160db0dcb/lib/virtualmonkey/ebs.rb#L45-L57 | train |
jeremyd/virtualmonkey | lib/virtualmonkey/ebs.rb | VirtualMonkey.EBS.find_snapshot_timestamp | def find_snapshot_timestamp
last_snap = behavior(:find_snapshots).last
last_snap.tags.detect { |t| t["name"] =~ /timestamp=(\d+)$/ }
timestamp = $1
end | ruby | def find_snapshot_timestamp
last_snap = behavior(:find_snapshots).last
last_snap.tags.detect { |t| t["name"] =~ /timestamp=(\d+)$/ }
timestamp = $1
end | [
"def",
"find_snapshot_timestamp",
"last_snap",
"=",
"behavior",
"(",
":find_snapshots",
")",
".",
"last",
"last_snap",
".",
"tags",
".",
"detect",
"{",
"|",
"t",
"|",
"t",
"[",
"\"name\"",
"]",
"=~",
"/",
"\\d",
"/",
"}",
"timestamp",
"=",
"$1",
"end"
] | Returns the timestamp of the latest snapshot for testing OPT_DB_RESTORE_TIMESTAMP_OVERRIDE | [
"Returns",
"the",
"timestamp",
"of",
"the",
"latest",
"snapshot",
"for",
"testing",
"OPT_DB_RESTORE_TIMESTAMP_OVERRIDE"
] | b2c7255f20ac5ec881eb90afbb5e712160db0dcb | https://github.com/jeremyd/virtualmonkey/blob/b2c7255f20ac5ec881eb90afbb5e712160db0dcb/lib/virtualmonkey/ebs.rb#L70-L74 | train |
postmodern/open_namespace | lib/open_namespace/class_methods.rb | OpenNamespace.ClassMethods.require_file | def require_file(name)
name = name.to_s
path = File.join(namespace_root,File.expand_path(File.join('',name)))
begin
require path
rescue Gem::LoadError => e
raise(e)
rescue ::LoadError
return nil
end
return true
end | ruby | def require_file(name)
name = name.to_s
path = File.join(namespace_root,File.expand_path(File.join('',name)))
begin
require path
rescue Gem::LoadError => e
raise(e)
rescue ::LoadError
return nil
end
return true
end | [
"def",
"require_file",
"(",
"name",
")",
"name",
"=",
"name",
".",
"to_s",
"path",
"=",
"File",
".",
"join",
"(",
"namespace_root",
",",
"File",
".",
"expand_path",
"(",
"File",
".",
"join",
"(",
"''",
",",
"name",
")",
")",
")",
"begin",
"require",
"path",
"rescue",
"Gem",
"::",
"LoadError",
"=>",
"e",
"raise",
"(",
"e",
")",
"rescue",
"::",
"LoadError",
"return",
"nil",
"end",
"return",
"true",
"end"
] | Requires the file with the given name, within the namespace root
directory.
@param [Symbol, String] name
The name of the file to require.
@return [true, nil]
Returns `true` if the file was successfully loaded, returns `nil`
on a `LoadError` exception.
@raise [Gem::LoadError]
A dependency needed by the file could not be satisfied by RubyGems.
@since 0.3.0 | [
"Requires",
"the",
"file",
"with",
"the",
"given",
"name",
"within",
"the",
"namespace",
"root",
"directory",
"."
] | 305e3a794fda6a290faa935098fe528048ffed77 | https://github.com/postmodern/open_namespace/blob/305e3a794fda6a290faa935098fe528048ffed77/lib/open_namespace/class_methods.rb#L67-L80 | train |
postmodern/open_namespace | lib/open_namespace/class_methods.rb | OpenNamespace.ClassMethods.const_defined? | def const_defined?(name,*inherit)
if super(name,*inherit)
true
else
# attempt to load the file that might have the constant
require_file(OpenNamespace.const_path(name))
# check for the constant again
return super(name,*inherit)
end
end | ruby | def const_defined?(name,*inherit)
if super(name,*inherit)
true
else
# attempt to load the file that might have the constant
require_file(OpenNamespace.const_path(name))
# check for the constant again
return super(name,*inherit)
end
end | [
"def",
"const_defined?",
"(",
"name",
",",
"*",
"inherit",
")",
"if",
"super",
"(",
"name",
",",
"*",
"inherit",
")",
"true",
"else",
"require_file",
"(",
"OpenNamespace",
".",
"const_path",
"(",
"name",
")",
")",
"return",
"super",
"(",
"name",
",",
"*",
"inherit",
")",
"end",
"end"
] | Checks if a constant is defined or attempts loading the constant.
@param [String] name
The name of the constant.
@param [Boolean] inherit
Specifies whether to search the ancestors for the constant.
@return [Boolean]
Specifies whether the constant is defined. | [
"Checks",
"if",
"a",
"constant",
"is",
"defined",
"or",
"attempts",
"loading",
"the",
"constant",
"."
] | 305e3a794fda6a290faa935098fe528048ffed77 | https://github.com/postmodern/open_namespace/blob/305e3a794fda6a290faa935098fe528048ffed77/lib/open_namespace/class_methods.rb#L94-L104 | train |
maxjacobson/todo_lint | lib/todo_lint/todo.rb | TodoLint.Todo.relative_path | def relative_path
current_dir = Pathname.new(File.expand_path("./"))
Pathname.new(path).relative_path_from(current_dir).to_s
end | ruby | def relative_path
current_dir = Pathname.new(File.expand_path("./"))
Pathname.new(path).relative_path_from(current_dir).to_s
end | [
"def",
"relative_path",
"current_dir",
"=",
"Pathname",
".",
"new",
"(",
"File",
".",
"expand_path",
"(",
"\"./\"",
")",
")",
"Pathname",
".",
"new",
"(",
"path",
")",
".",
"relative_path_from",
"(",
"current_dir",
")",
".",
"to_s",
"end"
] | Which todo is due sooner?
@example
[todo_one, todo_two].sort # this implicitly calls <=>
@return [Fixnum]
@api public
The relative path to the file where this todo was found
@example
todo.relative #=> "spec/spec_helper.rb"
@return [String]
@api public | [
"Which",
"todo",
"is",
"due",
"sooner?"
] | 0d1061383ea205ef4c74edc64568e308ac1af990 | https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/todo.rb#L179-L182 | train |
maxjacobson/todo_lint | lib/todo_lint/todo.rb | TodoLint.Todo.lookup_tag_due_date | def lookup_tag_due_date
config.fetch(:tags).fetch(match[:tag])
rescue KeyError
msg = "#{match[:tag]} tag not defined in config file"
raise KeyError, msg
end | ruby | def lookup_tag_due_date
config.fetch(:tags).fetch(match[:tag])
rescue KeyError
msg = "#{match[:tag]} tag not defined in config file"
raise KeyError, msg
end | [
"def",
"lookup_tag_due_date",
"config",
".",
"fetch",
"(",
":tags",
")",
".",
"fetch",
"(",
"match",
"[",
":tag",
"]",
")",
"rescue",
"KeyError",
"msg",
"=",
"\"#{match[:tag]} tag not defined in config file\"",
"raise",
"KeyError",
",",
"msg",
"end"
] | A tag was referenced, so let's see when that's due
@return [DueDate]
@raise [KeyError] if the tag does not reference a due date in the config
@api private | [
"A",
"tag",
"was",
"referenced",
"so",
"let",
"s",
"see",
"when",
"that",
"s",
"due"
] | 0d1061383ea205ef4c74edc64568e308ac1af990 | https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/todo.rb#L224-L229 | train |
Deradon/Rdcpu16 | lib/dcpu16/support/debug.rb | DCPU16.Debug.debug | def debug(msg = nil, &block)
return unless debug?
puts "\n[DEBUG] - #{caller.first}"
msg.each { |m| puts(m) } if msg.is_a?(Array)
if msg.is_a?(Hash)
msg.each do |k, v|
puts "[#{k.to_s}]"
if v.is_a?(Array)
v.each {|m| puts(m) }
else
puts v
end
end
elsif (msg.is_a?(String) || msg.is_a?(Symbol))
puts msg.to_s
end
yield if block_given?
puts "\n"
end | ruby | def debug(msg = nil, &block)
return unless debug?
puts "\n[DEBUG] - #{caller.first}"
msg.each { |m| puts(m) } if msg.is_a?(Array)
if msg.is_a?(Hash)
msg.each do |k, v|
puts "[#{k.to_s}]"
if v.is_a?(Array)
v.each {|m| puts(m) }
else
puts v
end
end
elsif (msg.is_a?(String) || msg.is_a?(Symbol))
puts msg.to_s
end
yield if block_given?
puts "\n"
end | [
"def",
"debug",
"(",
"msg",
"=",
"nil",
",",
"&",
"block",
")",
"return",
"unless",
"debug?",
"puts",
"\"\\n[DEBUG] - #{caller.first}\"",
"msg",
".",
"each",
"{",
"|",
"m",
"|",
"puts",
"(",
"m",
")",
"}",
"if",
"msg",
".",
"is_a?",
"(",
"Array",
")",
"if",
"msg",
".",
"is_a?",
"(",
"Hash",
")",
"msg",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"puts",
"\"[#{k.to_s}]\"",
"if",
"v",
".",
"is_a?",
"(",
"Array",
")",
"v",
".",
"each",
"{",
"|",
"m",
"|",
"puts",
"(",
"m",
")",
"}",
"else",
"puts",
"v",
"end",
"end",
"elsif",
"(",
"msg",
".",
"is_a?",
"(",
"String",
")",
"||",
"msg",
".",
"is_a?",
"(",
"Symbol",
")",
")",
"puts",
"msg",
".",
"to_s",
"end",
"yield",
"if",
"block_given?",
"puts",
"\"\\n\"",
"end"
] | Debug-Wrapper | [
"Debug",
"-",
"Wrapper"
] | a4460927aa64c2a514c57993e8ea13f5b48377e9 | https://github.com/Deradon/Rdcpu16/blob/a4460927aa64c2a514c57993e8ea13f5b48377e9/lib/dcpu16/support/debug.rb#L11-L33 | train |
sanichi/icu_tournament | lib/icu_tournament/result.rb | ICU.Result.rateable= | def rateable=(rateable)
if opponent.nil?
@rateable = false
return
end
@rateable = case rateable
when nil then true # default is true
when false then false # this is the only way to turn it off
else true
end
end | ruby | def rateable=(rateable)
if opponent.nil?
@rateable = false
return
end
@rateable = case rateable
when nil then true # default is true
when false then false # this is the only way to turn it off
else true
end
end | [
"def",
"rateable",
"=",
"(",
"rateable",
")",
"if",
"opponent",
".",
"nil?",
"@rateable",
"=",
"false",
"return",
"end",
"@rateable",
"=",
"case",
"rateable",
"when",
"nil",
"then",
"true",
"when",
"false",
"then",
"false",
"else",
"true",
"end",
"end"
] | Rateable flag. If false, result is not rateable. Can only be true if there is an opponent. | [
"Rateable",
"flag",
".",
"If",
"false",
"result",
"is",
"not",
"rateable",
".",
"Can",
"only",
"be",
"true",
"if",
"there",
"is",
"an",
"opponent",
"."
] | badd2940189feaeb9f0edb4b4e07ff6b2548bd3d | https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/result.rb#L142-L152 | train |
groupdocs-storage-cloud/groupdocs-storage-cloud-ruby | lib/GroupDocs/Storage/configuration.rb | GroupDocsStorageCloud.Configuration.auth_settings | def auth_settings
{
'appsid' =>
{
type: 'api_key',
in: 'query',
key: 'appsid',
value: api_key_with_prefix('appsid')
},
'oauth' =>
{
type: 'oauth2',
in: 'header',
key: 'Authorization',
value: "Bearer #{access_token}"
},
'signature' =>
{
type: 'api_key',
in: 'query',
key: 'signature',
value: api_key_with_prefix('signature')
},
}
end | ruby | def auth_settings
{
'appsid' =>
{
type: 'api_key',
in: 'query',
key: 'appsid',
value: api_key_with_prefix('appsid')
},
'oauth' =>
{
type: 'oauth2',
in: 'header',
key: 'Authorization',
value: "Bearer #{access_token}"
},
'signature' =>
{
type: 'api_key',
in: 'query',
key: 'signature',
value: api_key_with_prefix('signature')
},
}
end | [
"def",
"auth_settings",
"{",
"'appsid'",
"=>",
"{",
"type",
":",
"'api_key'",
",",
"in",
":",
"'query'",
",",
"key",
":",
"'appsid'",
",",
"value",
":",
"api_key_with_prefix",
"(",
"'appsid'",
")",
"}",
",",
"'oauth'",
"=>",
"{",
"type",
":",
"'oauth2'",
",",
"in",
":",
"'header'",
",",
"key",
":",
"'Authorization'",
",",
"value",
":",
"\"Bearer #{access_token}\"",
"}",
",",
"'signature'",
"=>",
"{",
"type",
":",
"'api_key'",
",",
"in",
":",
"'query'",
",",
"key",
":",
"'signature'",
",",
"value",
":",
"api_key_with_prefix",
"(",
"'signature'",
")",
"}",
",",
"}",
"end"
] | Returns Auth Settings hash for api client. | [
"Returns",
"Auth",
"Settings",
"hash",
"for",
"api",
"client",
"."
] | 0820b8b5582ea2a6bc0f5e7f694eb80aad5e67ce | https://github.com/groupdocs-storage-cloud/groupdocs-storage-cloud-ruby/blob/0820b8b5582ea2a6bc0f5e7f694eb80aad5e67ce/lib/GroupDocs/Storage/configuration.rb#L177-L201 | train |
chetan/bixby-common | lib/bixby-common/api/http_channel.rb | Bixby.HttpChannel.execute_internal | def execute_internal(json_request, &block)
if json_request.respond_to?(:headers) then
# always required for posting to API
json_request.headers["Content-Type"] = "application/json"
end
req = HTTPI::Request.new(:url => @uri, :body => json_request.to_wire)
# add in extra headers if we have a SignedJsonRequest (or anything which has additional headers)
if json_request.respond_to? :headers then
req.headers.merge!(json_request.headers)
end
if block then
# execute request with block
req.on_body(&block)
HTTPI.post(req)
return JsonResponse.new("success")
else
# execute normal req, and return parsed response
res = HTTPI.post(req).body
return JsonResponse.from_json(res)
end
end | ruby | def execute_internal(json_request, &block)
if json_request.respond_to?(:headers) then
# always required for posting to API
json_request.headers["Content-Type"] = "application/json"
end
req = HTTPI::Request.new(:url => @uri, :body => json_request.to_wire)
# add in extra headers if we have a SignedJsonRequest (or anything which has additional headers)
if json_request.respond_to? :headers then
req.headers.merge!(json_request.headers)
end
if block then
# execute request with block
req.on_body(&block)
HTTPI.post(req)
return JsonResponse.new("success")
else
# execute normal req, and return parsed response
res = HTTPI.post(req).body
return JsonResponse.from_json(res)
end
end | [
"def",
"execute_internal",
"(",
"json_request",
",",
"&",
"block",
")",
"if",
"json_request",
".",
"respond_to?",
"(",
":headers",
")",
"then",
"json_request",
".",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"\"application/json\"",
"end",
"req",
"=",
"HTTPI",
"::",
"Request",
".",
"new",
"(",
":url",
"=>",
"@uri",
",",
":body",
"=>",
"json_request",
".",
"to_wire",
")",
"if",
"json_request",
".",
"respond_to?",
":headers",
"then",
"req",
".",
"headers",
".",
"merge!",
"(",
"json_request",
".",
"headers",
")",
"end",
"if",
"block",
"then",
"req",
".",
"on_body",
"(",
"&",
"block",
")",
"HTTPI",
".",
"post",
"(",
"req",
")",
"return",
"JsonResponse",
".",
"new",
"(",
"\"success\"",
")",
"else",
"res",
"=",
"HTTPI",
".",
"post",
"(",
"req",
")",
".",
"body",
"return",
"JsonResponse",
".",
"from_json",
"(",
"res",
")",
"end",
"end"
] | Execute the request, optionally passing a block to handle the response
@param [JsonRequest] json_request
@param [Block] block
@return [JsonResponse] response | [
"Execute",
"the",
"request",
"optionally",
"passing",
"a",
"block",
"to",
"handle",
"the",
"response"
] | 3fb8829987b115fc53ec820d97a20b4a8c49b4a2 | https://github.com/chetan/bixby-common/blob/3fb8829987b115fc53ec820d97a20b4a8c49b4a2/lib/bixby-common/api/http_channel.rb#L40-L67 | train |
ajeychronus/chronuscop_client | lib/chronuscop_client/synchronizer.rb | ChronuscopClient.Synchronizer.write_last_update | def write_last_update(last_update_at)
# Check for the presence of the tmp directory.
if(! File::directory?("tmp")) then
Dir.mkdir("tmp")
end
f = File.new("tmp/chronuscop.tmp","w")
f.printf("%d",last_update_at.to_i)
f.close()
end | ruby | def write_last_update(last_update_at)
# Check for the presence of the tmp directory.
if(! File::directory?("tmp")) then
Dir.mkdir("tmp")
end
f = File.new("tmp/chronuscop.tmp","w")
f.printf("%d",last_update_at.to_i)
f.close()
end | [
"def",
"write_last_update",
"(",
"last_update_at",
")",
"if",
"(",
"!",
"File",
"::",
"directory?",
"(",
"\"tmp\"",
")",
")",
"then",
"Dir",
".",
"mkdir",
"(",
"\"tmp\"",
")",
"end",
"f",
"=",
"File",
".",
"new",
"(",
"\"tmp/chronuscop.tmp\"",
",",
"\"w\"",
")",
"f",
".",
"printf",
"(",
"\"%d\"",
",",
"last_update_at",
".",
"to_i",
")",
"f",
".",
"close",
"(",
")",
"end"
] | Function to write the last update time to a temporary file. | [
"Function",
"to",
"write",
"the",
"last",
"update",
"time",
"to",
"a",
"temporary",
"file",
"."
] | 17834beba5215b122b399f145f8710da03ff7a0a | https://github.com/ajeychronus/chronuscop_client/blob/17834beba5215b122b399f145f8710da03ff7a0a/lib/chronuscop_client/synchronizer.rb#L19-L28 | train |
ajeychronus/chronuscop_client | lib/chronuscop_client/synchronizer.rb | ChronuscopClient.Synchronizer.xml_time_to_integer | def xml_time_to_integer(str)
arr = str.gsub(/T|Z|:/,"-").split(/-/)
year = arr[0]
month = arr[1]
day = arr[2]
hour = arr[3]
min = arr[4]
sec = arr[5]
Time.utc(year,month,day,hour,min,sec).to_i
end | ruby | def xml_time_to_integer(str)
arr = str.gsub(/T|Z|:/,"-").split(/-/)
year = arr[0]
month = arr[1]
day = arr[2]
hour = arr[3]
min = arr[4]
sec = arr[5]
Time.utc(year,month,day,hour,min,sec).to_i
end | [
"def",
"xml_time_to_integer",
"(",
"str",
")",
"arr",
"=",
"str",
".",
"gsub",
"(",
"/",
"/",
",",
"\"-\"",
")",
".",
"split",
"(",
"/",
"/",
")",
"year",
"=",
"arr",
"[",
"0",
"]",
"month",
"=",
"arr",
"[",
"1",
"]",
"day",
"=",
"arr",
"[",
"2",
"]",
"hour",
"=",
"arr",
"[",
"3",
"]",
"min",
"=",
"arr",
"[",
"4",
"]",
"sec",
"=",
"arr",
"[",
"5",
"]",
"Time",
".",
"utc",
"(",
"year",
",",
"month",
",",
"day",
",",
"hour",
",",
"min",
",",
"sec",
")",
".",
"to_i",
"end"
] | To convert xml_time received from the server to integer. | [
"To",
"convert",
"xml_time",
"received",
"from",
"the",
"server",
"to",
"integer",
"."
] | 17834beba5215b122b399f145f8710da03ff7a0a | https://github.com/ajeychronus/chronuscop_client/blob/17834beba5215b122b399f145f8710da03ff7a0a/lib/chronuscop_client/synchronizer.rb#L58-L67 | train |
ajeychronus/chronuscop_client | lib/chronuscop_client/synchronizer.rb | ChronuscopClient.Synchronizer.sync_it_now | def sync_it_now
puts "Attempt Sync"
# Getting the last sync value.
last_update_at = get_last_update_at
# querying the page.
page = @mechanize_agent.get("#{ChronuscopClient.configuration_object.chronuscop_server_address}/projects/#{ChronuscopClient.configuration_object.project_number}/translations.xml/?auth_token=#{ChronuscopClient.configuration_object.api_token}&last_update_at=#{last_update_at}")
# converting the returned xml page into a hash.
words_hash = XmlSimple.xml_in(page.body)
# catching the case when no-translations are returned.
if(!words_hash) then
puts "Nothing new added."
return
end
# collecting the translations array.
all_translations = words_hash["translation"]
# catching the case when no-translations are returned.
if(!all_translations) then
puts "Nothing new added."
return
end
all_translations.each do |t|
# Inserting into the redis store.
@redis_agent.set "#{t["key"]}","#{t["value"]}"
# Bad hack used here. Should fix this.
str = t["updated-at"][0]["content"]
key_updated_at = xml_time_to_integer(str)
# Updating the value last_update_at
if(key_updated_at > last_update_at) then
last_update_at = key_updated_at
end
end
# Writing the value of last_update_at to the file.
write_last_update(last_update_at.to_i)
puts "Finished synchronizing !!!"
end | ruby | def sync_it_now
puts "Attempt Sync"
# Getting the last sync value.
last_update_at = get_last_update_at
# querying the page.
page = @mechanize_agent.get("#{ChronuscopClient.configuration_object.chronuscop_server_address}/projects/#{ChronuscopClient.configuration_object.project_number}/translations.xml/?auth_token=#{ChronuscopClient.configuration_object.api_token}&last_update_at=#{last_update_at}")
# converting the returned xml page into a hash.
words_hash = XmlSimple.xml_in(page.body)
# catching the case when no-translations are returned.
if(!words_hash) then
puts "Nothing new added."
return
end
# collecting the translations array.
all_translations = words_hash["translation"]
# catching the case when no-translations are returned.
if(!all_translations) then
puts "Nothing new added."
return
end
all_translations.each do |t|
# Inserting into the redis store.
@redis_agent.set "#{t["key"]}","#{t["value"]}"
# Bad hack used here. Should fix this.
str = t["updated-at"][0]["content"]
key_updated_at = xml_time_to_integer(str)
# Updating the value last_update_at
if(key_updated_at > last_update_at) then
last_update_at = key_updated_at
end
end
# Writing the value of last_update_at to the file.
write_last_update(last_update_at.to_i)
puts "Finished synchronizing !!!"
end | [
"def",
"sync_it_now",
"puts",
"\"Attempt Sync\"",
"last_update_at",
"=",
"get_last_update_at",
"page",
"=",
"@mechanize_agent",
".",
"get",
"(",
"\"#{ChronuscopClient.configuration_object.chronuscop_server_address}/projects/#{ChronuscopClient.configuration_object.project_number}/translations.xml/?auth_token=#{ChronuscopClient.configuration_object.api_token}&last_update_at=#{last_update_at}\"",
")",
"words_hash",
"=",
"XmlSimple",
".",
"xml_in",
"(",
"page",
".",
"body",
")",
"if",
"(",
"!",
"words_hash",
")",
"then",
"puts",
"\"Nothing new added.\"",
"return",
"end",
"all_translations",
"=",
"words_hash",
"[",
"\"translation\"",
"]",
"if",
"(",
"!",
"all_translations",
")",
"then",
"puts",
"\"Nothing new added.\"",
"return",
"end",
"all_translations",
".",
"each",
"do",
"|",
"t",
"|",
"@redis_agent",
".",
"set",
"\"#{t[\"key\"]}\"",
",",
"\"#{t[\"value\"]}\"",
"str",
"=",
"t",
"[",
"\"updated-at\"",
"]",
"[",
"0",
"]",
"[",
"\"content\"",
"]",
"key_updated_at",
"=",
"xml_time_to_integer",
"(",
"str",
")",
"if",
"(",
"key_updated_at",
">",
"last_update_at",
")",
"then",
"last_update_at",
"=",
"key_updated_at",
"end",
"end",
"write_last_update",
"(",
"last_update_at",
".",
"to_i",
")",
"puts",
"\"Finished synchronizing !!!\"",
"end"
] | This method keeps the remote-keys and the local-keys synchronized.
This method should be called only after initializing the configuration
object as it uses those configuration values. | [
"This",
"method",
"keeps",
"the",
"remote",
"-",
"keys",
"and",
"the",
"local",
"-",
"keys",
"synchronized",
".",
"This",
"method",
"should",
"be",
"called",
"only",
"after",
"initializing",
"the",
"configuration",
"object",
"as",
"it",
"uses",
"those",
"configuration",
"values",
"."
] | 17834beba5215b122b399f145f8710da03ff7a0a | https://github.com/ajeychronus/chronuscop_client/blob/17834beba5215b122b399f145f8710da03ff7a0a/lib/chronuscop_client/synchronizer.rb#L74-L120 | train |
agilecreativity/vim_printer | lib/vim_printer/cli.rb | VimPrinter.CLI.get_input_files | def get_input_files(args = {})
command = args.fetch(:command, nil)
if command.nil?
CodeLister.files(args)
else
# Note: base_dir must be the the same the directory where the command is executed from
CodeLister.files_from_shell(command, args.fetch(:base_dir, "."))
end
end | ruby | def get_input_files(args = {})
command = args.fetch(:command, nil)
if command.nil?
CodeLister.files(args)
else
# Note: base_dir must be the the same the directory where the command is executed from
CodeLister.files_from_shell(command, args.fetch(:base_dir, "."))
end
end | [
"def",
"get_input_files",
"(",
"args",
"=",
"{",
"}",
")",
"command",
"=",
"args",
".",
"fetch",
"(",
":command",
",",
"nil",
")",
"if",
"command",
".",
"nil?",
"CodeLister",
".",
"files",
"(",
"args",
")",
"else",
"CodeLister",
".",
"files_from_shell",
"(",
"command",
",",
"args",
".",
"fetch",
"(",
":base_dir",
",",
"\".\"",
")",
")",
"end",
"end"
] | Get the list of input file
@param [Hash<Symbol, Object>] args the input options
@option args [String] :command the shell command to be used to get list of files
@return [Array<String>] list of files in the format
["./Gemfile", "./lib/vim_printer/cli.rb", ..] | [
"Get",
"the",
"list",
"of",
"input",
"file"
] | 4ac22ca6034da299ffd2f6f8fb6c1b6efbc59206 | https://github.com/agilecreativity/vim_printer/blob/4ac22ca6034da299ffd2f6f8fb6c1b6efbc59206/lib/vim_printer/cli.rb#L84-L92 | train |
agilecreativity/vim_printer | lib/vim_printer/cli.rb | VimPrinter.CLI.execute | def execute(options = {})
input_files = get_input_files(options)
# we want to avoid printing the binary file
input_files.delete_if do |file|
File.binary?(file.gsub(/^\./, options[:base_dir]))
end
if input_files.empty?
puts "No file found for your option: #{options}"
return
end
to_htmls(input_files, options)
generated_files = input_files.map { |f| "#{f}.xhtml" }
index_file = "./index.html"
IndexHtml.htmlify generated_files, base_dir: options[:base_dir],
output: index_file,
drop_ext: true
generated_files << index_file if options[:index]
output_file = "vim_printer_#{File.basename(File.expand_path(options[:base_dir]))}.tar.gz"
AgileUtils::FileUtil.tar_gzip_files(generated_files, output_file)
AgileUtils::FileUtil.delete(generated_files)
FileUtils.rm_rf(index_file) if options[:index]
puts "Your output file is '#{File.absolute_path(output_file)}'"
end | ruby | def execute(options = {})
input_files = get_input_files(options)
# we want to avoid printing the binary file
input_files.delete_if do |file|
File.binary?(file.gsub(/^\./, options[:base_dir]))
end
if input_files.empty?
puts "No file found for your option: #{options}"
return
end
to_htmls(input_files, options)
generated_files = input_files.map { |f| "#{f}.xhtml" }
index_file = "./index.html"
IndexHtml.htmlify generated_files, base_dir: options[:base_dir],
output: index_file,
drop_ext: true
generated_files << index_file if options[:index]
output_file = "vim_printer_#{File.basename(File.expand_path(options[:base_dir]))}.tar.gz"
AgileUtils::FileUtil.tar_gzip_files(generated_files, output_file)
AgileUtils::FileUtil.delete(generated_files)
FileUtils.rm_rf(index_file) if options[:index]
puts "Your output file is '#{File.absolute_path(output_file)}'"
end | [
"def",
"execute",
"(",
"options",
"=",
"{",
"}",
")",
"input_files",
"=",
"get_input_files",
"(",
"options",
")",
"input_files",
".",
"delete_if",
"do",
"|",
"file",
"|",
"File",
".",
"binary?",
"(",
"file",
".",
"gsub",
"(",
"/",
"\\.",
"/",
",",
"options",
"[",
":base_dir",
"]",
")",
")",
"end",
"if",
"input_files",
".",
"empty?",
"puts",
"\"No file found for your option: #{options}\"",
"return",
"end",
"to_htmls",
"(",
"input_files",
",",
"options",
")",
"generated_files",
"=",
"input_files",
".",
"map",
"{",
"|",
"f",
"|",
"\"#{f}.xhtml\"",
"}",
"index_file",
"=",
"\"./index.html\"",
"IndexHtml",
".",
"htmlify",
"generated_files",
",",
"base_dir",
":",
"options",
"[",
":base_dir",
"]",
",",
"output",
":",
"index_file",
",",
"drop_ext",
":",
"true",
"generated_files",
"<<",
"index_file",
"if",
"options",
"[",
":index",
"]",
"output_file",
"=",
"\"vim_printer_#{File.basename(File.expand_path(options[:base_dir]))}.tar.gz\"",
"AgileUtils",
"::",
"FileUtil",
".",
"tar_gzip_files",
"(",
"generated_files",
",",
"output_file",
")",
"AgileUtils",
"::",
"FileUtil",
".",
"delete",
"(",
"generated_files",
")",
"FileUtils",
".",
"rm_rf",
"(",
"index_file",
")",
"if",
"options",
"[",
":index",
"]",
"puts",
"\"Your output file is '#{File.absolute_path(output_file)}'\"",
"end"
] | Main entry point to export the code
@param [Hash<Symbol, Object>] options the options argument | [
"Main",
"entry",
"point",
"to",
"export",
"the",
"code"
] | 4ac22ca6034da299ffd2f6f8fb6c1b6efbc59206 | https://github.com/agilecreativity/vim_printer/blob/4ac22ca6034da299ffd2f6f8fb6c1b6efbc59206/lib/vim_printer/cli.rb#L97-L121 | train |
agilecreativity/vim_printer | lib/vim_printer/cli.rb | VimPrinter.CLI.to_htmls | def to_htmls(files, options = {})
FileUtils.chdir(File.expand_path(options[:base_dir]))
files.each_with_index do |file, index|
puts "FYI: process file #{index + 1} of #{files.size} : #{file}"
to_html(file, options)
end
end | ruby | def to_htmls(files, options = {})
FileUtils.chdir(File.expand_path(options[:base_dir]))
files.each_with_index do |file, index|
puts "FYI: process file #{index + 1} of #{files.size} : #{file}"
to_html(file, options)
end
end | [
"def",
"to_htmls",
"(",
"files",
",",
"options",
"=",
"{",
"}",
")",
"FileUtils",
".",
"chdir",
"(",
"File",
".",
"expand_path",
"(",
"options",
"[",
":base_dir",
"]",
")",
")",
"files",
".",
"each_with_index",
"do",
"|",
"file",
",",
"index",
"|",
"puts",
"\"FYI: process file #{index + 1} of #{files.size} : #{file}\"",
"to_html",
"(",
"file",
",",
"options",
")",
"end",
"end"
] | convert multiple files to html | [
"convert",
"multiple",
"files",
"to",
"html"
] | 4ac22ca6034da299ffd2f6f8fb6c1b6efbc59206 | https://github.com/agilecreativity/vim_printer/blob/4ac22ca6034da299ffd2f6f8fb6c1b6efbc59206/lib/vim_printer/cli.rb#L124-L130 | train |
kylegrantlucas/takeout | lib/takeout/client.rb | Takeout.Client.substitute_template_values | def substitute_template_values(endpoint, request_type, options={})
# Gets the proper template for the give CUSTOM_SCHEMA string for this endpoint and substitutes value for it based on give options
endpoint_templates = @schemas.fetch(request_type.to_sym, nil)
template = endpoint_templates.fetch(endpoint.to_sym, nil) if endpoint_templates
if template
extracted_options, options = extract_template_options(options.merge({endpoint: endpoint}), template)
# Render out the template
rendered_template = Liquid::Template.parse(template).render(extracted_options)
end
return rendered_template, options
end | ruby | def substitute_template_values(endpoint, request_type, options={})
# Gets the proper template for the give CUSTOM_SCHEMA string for this endpoint and substitutes value for it based on give options
endpoint_templates = @schemas.fetch(request_type.to_sym, nil)
template = endpoint_templates.fetch(endpoint.to_sym, nil) if endpoint_templates
if template
extracted_options, options = extract_template_options(options.merge({endpoint: endpoint}), template)
# Render out the template
rendered_template = Liquid::Template.parse(template).render(extracted_options)
end
return rendered_template, options
end | [
"def",
"substitute_template_values",
"(",
"endpoint",
",",
"request_type",
",",
"options",
"=",
"{",
"}",
")",
"endpoint_templates",
"=",
"@schemas",
".",
"fetch",
"(",
"request_type",
".",
"to_sym",
",",
"nil",
")",
"template",
"=",
"endpoint_templates",
".",
"fetch",
"(",
"endpoint",
".",
"to_sym",
",",
"nil",
")",
"if",
"endpoint_templates",
"if",
"template",
"extracted_options",
",",
"options",
"=",
"extract_template_options",
"(",
"options",
".",
"merge",
"(",
"{",
"endpoint",
":",
"endpoint",
"}",
")",
",",
"template",
")",
"rendered_template",
"=",
"Liquid",
"::",
"Template",
".",
"parse",
"(",
"template",
")",
".",
"render",
"(",
"extracted_options",
")",
"end",
"return",
"rendered_template",
",",
"options",
"end"
] | Render out the template values and return the updated options hash
@param [String] endpoint
@param [String] request_type
@param [Hash] options
@return [String] rendered_template
@return [Hash] options | [
"Render",
"out",
"the",
"template",
"values",
"and",
"return",
"the",
"updated",
"options",
"hash"
] | c6ac62e5c0bcd2a33be6a2657dfc2ae1c1e712df | https://github.com/kylegrantlucas/takeout/blob/c6ac62e5c0bcd2a33be6a2657dfc2ae1c1e712df/lib/takeout/client.rb#L90-L102 | train |
pdorrell/regenerate | lib/regenerate/site-regenerator.rb | Regenerate.SiteRegenerator.copySrcToOutputFile | def copySrcToOutputFile(srcFile, outFile, makeBackup)
if makeBackup
makeBackupFile(outFile)
end
FileUtils.cp(srcFile, outFile, :verbose => true)
end | ruby | def copySrcToOutputFile(srcFile, outFile, makeBackup)
if makeBackup
makeBackupFile(outFile)
end
FileUtils.cp(srcFile, outFile, :verbose => true)
end | [
"def",
"copySrcToOutputFile",
"(",
"srcFile",
",",
"outFile",
",",
"makeBackup",
")",
"if",
"makeBackup",
"makeBackupFile",
"(",
"outFile",
")",
"end",
"FileUtils",
".",
"cp",
"(",
"srcFile",
",",
"outFile",
",",
":verbose",
"=>",
"true",
")",
"end"
] | Copy a source file directly to an output file | [
"Copy",
"a",
"source",
"file",
"directly",
"to",
"an",
"output",
"file"
] | 31f3beb3ff9b45384a90f20fed61be20f39da0d4 | https://github.com/pdorrell/regenerate/blob/31f3beb3ff9b45384a90f20fed61be20f39da0d4/lib/regenerate/site-regenerator.rb#L87-L92 | train |
niyireth/brownpapertickets | lib/brownpapertickets/httpost.rb | BrownPaperTickets.Httpost.handle_deflation | def handle_deflation
case last_response["content-encoding"]
when "gzip"
body_io = StringIO.new(last_response.body)
last_response.body.replace Zlib::GzipReader.new(body_io).read
when "deflate"
last_response.body.replace Zlib::Inflate.inflate(last_response.body)
end
end | ruby | def handle_deflation
case last_response["content-encoding"]
when "gzip"
body_io = StringIO.new(last_response.body)
last_response.body.replace Zlib::GzipReader.new(body_io).read
when "deflate"
last_response.body.replace Zlib::Inflate.inflate(last_response.body)
end
end | [
"def",
"handle_deflation",
"case",
"last_response",
"[",
"\"content-encoding\"",
"]",
"when",
"\"gzip\"",
"body_io",
"=",
"StringIO",
".",
"new",
"(",
"last_response",
".",
"body",
")",
"last_response",
".",
"body",
".",
"replace",
"Zlib",
"::",
"GzipReader",
".",
"new",
"(",
"body_io",
")",
".",
"read",
"when",
"\"deflate\"",
"last_response",
".",
"body",
".",
"replace",
"Zlib",
"::",
"Inflate",
".",
"inflate",
"(",
"last_response",
".",
"body",
")",
"end",
"end"
] | Inspired by Ruby 1.9 | [
"Inspired",
"by",
"Ruby",
"1",
".",
"9"
] | 1eae1dc6f02b183c55090b79a62023e0f572fb57 | https://github.com/niyireth/brownpapertickets/blob/1eae1dc6f02b183c55090b79a62023e0f572fb57/lib/brownpapertickets/httpost.rb#L169-L177 | train |
nragaz/timely | lib/timely/cell.rb | Timely.Cell.value_from_redis | def value_from_redis
if val = Timely.redis.hget(redis_hash_key, redis_value_key)
val = val.include?(".") ? val.to_f : val.to_i
else
val = value_without_caching
Timely.redis.hset(redis_hash_key, redis_value_key, val)
end
val
end | ruby | def value_from_redis
if val = Timely.redis.hget(redis_hash_key, redis_value_key)
val = val.include?(".") ? val.to_f : val.to_i
else
val = value_without_caching
Timely.redis.hset(redis_hash_key, redis_value_key, val)
end
val
end | [
"def",
"value_from_redis",
"if",
"val",
"=",
"Timely",
".",
"redis",
".",
"hget",
"(",
"redis_hash_key",
",",
"redis_value_key",
")",
"val",
"=",
"val",
".",
"include?",
"(",
"\".\"",
")",
"?",
"val",
".",
"to_f",
":",
"val",
".",
"to_i",
"else",
"val",
"=",
"value_without_caching",
"Timely",
".",
"redis",
".",
"hset",
"(",
"redis_hash_key",
",",
"redis_value_key",
",",
"val",
")",
"end",
"val",
"end"
] | retrieve a cached value from a redis hash.
hashes are accessed using the report title and row title. values within
the hash are keyed using the column's start/end timestamps | [
"retrieve",
"a",
"cached",
"value",
"from",
"a",
"redis",
"hash",
"."
] | 768c15630b2d4b28a96d3f89307175f058b32374 | https://github.com/nragaz/timely/blob/768c15630b2d4b28a96d3f89307175f058b32374/lib/timely/cell.rb#L59-L68 | train |
marcbowes/UsingYAML | lib/using_yaml.rb | UsingYAML.ClassMethods.using_yaml | def using_yaml(*args)
# Include the instance methods which provide accessors and
# mutators for reading/writing from/to the YAML objects.
include InstanceMethods
# Each argument is either a filename or a :path option
args.each do |arg|
case arg
when Symbol, String
# Define accessors for this file
using_yaml_file(arg.to_s)
when Hash
# Currently only accepts { :path => ... }
next unless arg.size == 1 && arg.keys.first == :path
# Take note of the path
UsingYAML.path = [self.inspect, arg.values.first]
end
end
end | ruby | def using_yaml(*args)
# Include the instance methods which provide accessors and
# mutators for reading/writing from/to the YAML objects.
include InstanceMethods
# Each argument is either a filename or a :path option
args.each do |arg|
case arg
when Symbol, String
# Define accessors for this file
using_yaml_file(arg.to_s)
when Hash
# Currently only accepts { :path => ... }
next unless arg.size == 1 && arg.keys.first == :path
# Take note of the path
UsingYAML.path = [self.inspect, arg.values.first]
end
end
end | [
"def",
"using_yaml",
"(",
"*",
"args",
")",
"include",
"InstanceMethods",
"args",
".",
"each",
"do",
"|",
"arg",
"|",
"case",
"arg",
"when",
"Symbol",
",",
"String",
"using_yaml_file",
"(",
"arg",
".",
"to_s",
")",
"when",
"Hash",
"next",
"unless",
"arg",
".",
"size",
"==",
"1",
"&&",
"arg",
".",
"keys",
".",
"first",
"==",
":path",
"UsingYAML",
".",
"path",
"=",
"[",
"self",
".",
"inspect",
",",
"arg",
".",
"values",
".",
"first",
"]",
"end",
"end",
"end"
] | Used to configure UsingYAML for a class by defining what files
should be loaded and from where.
include UsingYAML
using_yaml :foo, :bar, :path => "/some/where"
+args+ can contain either filenames or a hash which specifices a
path which contains the corresponding files.
The value of :path must either be a string or Proc (see
+using_yaml_path+ for more information on overriding paths). | [
"Used",
"to",
"configure",
"UsingYAML",
"for",
"a",
"class",
"by",
"defining",
"what",
"files",
"should",
"be",
"loaded",
"and",
"from",
"where",
"."
] | 4485476ad0ad14850d41c8ed61673f7b08b9f007 | https://github.com/marcbowes/UsingYAML/blob/4485476ad0ad14850d41c8ed61673f7b08b9f007/lib/using_yaml.rb#L100-L119 | train |
device-independent/restless_router | lib/restless_router/route.rb | RestlessRouter.Route.url_for | def url_for(options={})
if templated?
template = Addressable::Template.new(base_path)
template = template.expand(options)
template.to_s
else
base_path
end
end | ruby | def url_for(options={})
if templated?
template = Addressable::Template.new(base_path)
template = template.expand(options)
template.to_s
else
base_path
end
end | [
"def",
"url_for",
"(",
"options",
"=",
"{",
"}",
")",
"if",
"templated?",
"template",
"=",
"Addressable",
"::",
"Template",
".",
"new",
"(",
"base_path",
")",
"template",
"=",
"template",
".",
"expand",
"(",
"options",
")",
"template",
".",
"to_s",
"else",
"base_path",
"end",
"end"
] | Returns the URL for the route. If it's templated,
then we utilize the provided options hash to expand
the route. Otherwise we return the `path`
@return [String] The templated or base URI | [
"Returns",
"the",
"URL",
"for",
"the",
"route",
".",
"If",
"it",
"s",
"templated",
"then",
"we",
"utilize",
"the",
"provided",
"options",
"hash",
"to",
"expand",
"the",
"route",
".",
"Otherwise",
"we",
"return",
"the",
"path"
] | c20ea03ec53b889d192393c7ab18bcacb0b5e46f | https://github.com/device-independent/restless_router/blob/c20ea03ec53b889d192393c7ab18bcacb0b5e46f/lib/restless_router/route.rb#L63-L71 | train |
mnipper/serket | lib/serket/field_decrypter.rb | Serket.FieldDecrypter.decrypt | def decrypt(field)
return if field !~ /\S/
iv, encrypted_aes_key, encrypted_text = parse(field)
private_key = OpenSSL::PKey::RSA.new(File.read(private_key_filepath))
decrypted_aes_key = private_key.private_decrypt(Base64.decode64(encrypted_aes_key))
decrypted_field = decrypt_data(iv, decrypted_aes_key, encrypted_text)
decrypted_field.force_encoding(encoding)
end | ruby | def decrypt(field)
return if field !~ /\S/
iv, encrypted_aes_key, encrypted_text = parse(field)
private_key = OpenSSL::PKey::RSA.new(File.read(private_key_filepath))
decrypted_aes_key = private_key.private_decrypt(Base64.decode64(encrypted_aes_key))
decrypted_field = decrypt_data(iv, decrypted_aes_key, encrypted_text)
decrypted_field.force_encoding(encoding)
end | [
"def",
"decrypt",
"(",
"field",
")",
"return",
"if",
"field",
"!~",
"/",
"\\S",
"/",
"iv",
",",
"encrypted_aes_key",
",",
"encrypted_text",
"=",
"parse",
"(",
"field",
")",
"private_key",
"=",
"OpenSSL",
"::",
"PKey",
"::",
"RSA",
".",
"new",
"(",
"File",
".",
"read",
"(",
"private_key_filepath",
")",
")",
"decrypted_aes_key",
"=",
"private_key",
".",
"private_decrypt",
"(",
"Base64",
".",
"decode64",
"(",
"encrypted_aes_key",
")",
")",
"decrypted_field",
"=",
"decrypt_data",
"(",
"iv",
",",
"decrypted_aes_key",
",",
"encrypted_text",
")",
"decrypted_field",
".",
"force_encoding",
"(",
"encoding",
")",
"end"
] | Decrypt the provided cipher text, and return the plaintext
Return nil if whitespace | [
"Decrypt",
"the",
"provided",
"cipher",
"text",
"and",
"return",
"the",
"plaintext",
"Return",
"nil",
"if",
"whitespace"
] | a4606071fde8982d794ff1f8fc09c399ac92ba17 | https://github.com/mnipper/serket/blob/a4606071fde8982d794ff1f8fc09c399ac92ba17/lib/serket/field_decrypter.rb#L22-L29 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.