repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
noprompt/vic | lib/vic/highlight.rb | Vic.Highlight.bg= | def bg=(color)
color = Color.new(color)
@ctermbg, @guibg = color.to_cterm, color.to_gui
self
end | ruby | def bg=(color)
color = Color.new(color)
@ctermbg, @guibg = color.to_cterm, color.to_gui
self
end | [
"def",
"bg",
"=",
"(",
"color",
")",
"color",
"=",
"Color",
".",
"new",
"(",
"color",
")",
"@ctermbg",
",",
"@guibg",
"=",
"color",
".",
"to_cterm",
",",
"color",
".",
"to_gui",
"self",
"end"
]
| Set both ctermbg and guibg simultaneously
@param [String] color
the color to use
@return [Vic::Highlight]
the updated highlight
@api public | [
"Set",
"both",
"ctermbg",
"and",
"guibg",
"simultaneously"
]
| 276e18fc5d81727023d3abfdf95829648818a9c4 | https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/highlight.rb#L88-L92 | train |
noprompt/vic | lib/vic/highlight.rb | Vic.Highlight.fg= | def fg=(color)
color = Color.new(color)
@ctermfg, @guifg = color.to_cterm, color.to_gui
self
end | ruby | def fg=(color)
color = Color.new(color)
@ctermfg, @guifg = color.to_cterm, color.to_gui
self
end | [
"def",
"fg",
"=",
"(",
"color",
")",
"color",
"=",
"Color",
".",
"new",
"(",
"color",
")",
"@ctermfg",
",",
"@guifg",
"=",
"color",
".",
"to_cterm",
",",
"color",
".",
"to_gui",
"self",
"end"
]
| Set both ctermfg and guifg simultaneously
@param [String] color
the color to use
@return [Vic::Highlight]
the updated highlight
@api public | [
"Set",
"both",
"ctermfg",
"and",
"guifg",
"simultaneously"
]
| 276e18fc5d81727023d3abfdf95829648818a9c4 | https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/highlight.rb#L103-L107 | train |
noprompt/vic | lib/vic/highlight.rb | Vic.Highlight.select_styles | def select_styles(*styles)
styles.tap(&:compact).flatten!
if styles.empty? or styles.length == 1 && /\Anone\z/io.match(styles[0])
return :NONE
end
styles.select { |s| FONT_STYLE.match(s) }
end | ruby | def select_styles(*styles)
styles.tap(&:compact).flatten!
if styles.empty? or styles.length == 1 && /\Anone\z/io.match(styles[0])
return :NONE
end
styles.select { |s| FONT_STYLE.match(s) }
end | [
"def",
"select_styles",
"(",
"*",
"styles",
")",
"styles",
".",
"tap",
"(",
"&",
":compact",
")",
".",
"flatten!",
"if",
"styles",
".",
"empty?",
"or",
"styles",
".",
"length",
"==",
"1",
"&&",
"/",
"\\A",
"\\z",
"/io",
".",
"match",
"(",
"styles",
"[",
"0",
"]",
")",
"return",
":NONE",
"end",
"styles",
".",
"select",
"{",
"|",
"s",
"|",
"FONT_STYLE",
".",
"match",
"(",
"s",
")",
"}",
"end"
]
| Selcect valid styles from a list
@param [Mixed] styles
the list of styles
@return [Array,Symbol]
the list of valid styles or "NONE"
@api private | [
"Selcect",
"valid",
"styles",
"from",
"a",
"list"
]
| 276e18fc5d81727023d3abfdf95829648818a9c4 | https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/highlight.rb#L222-L228 | train |
aidistan/ruby-biotcm | lib/biotcm/databases/hgnc/parser.rb | BioTCM::Databases::HGNC.Parser.parse | def parse(fin)
# Headline
names = fin.gets.chomp.split("\t")
index2identifier = {}
index_hgncid = nil
BioTCM::Databases::HGNC::IDENTIFIERS.each do |identifer, name|
if identifer == :hgncid
index_hgncid = names.index(name)
elsif name.is_a?(String)
index2identifier[names.index(name)] = identifer if names.index(name)
else
name.each_with_index do |n, i|
next unless names.index(n)
index2identifier[names.index(n)] = (i == 0 ? identifer : identifer.to_s)
end
end
end
# Dynamically bulid a line processor
process_one_line = index2identifier.collect do |index, identifer|
# Symbol will be mapped to single item
if identifer.is_a?(Symbol)
%(
unless column[#{index}] == nil || column[#{index}] == "" || column[#{index}] == "-"
@#{identifer}2hgncid[column[#{index}]] = column[#{index_hgncid}]
@hgncid2#{identifer}[column[#{index_hgncid}]] = column[#{index}]
end
)
# Others will be mapped to list item
else
%{
unless column[#{index}] == nil
column[#{index}].split(", ").each do |id|
} +
if identifer == 'symbol'
%(
if @ambiguous_symbol[id]
@ambiguous_symbol[id] << @hgncid2symbol[column[#{index_hgncid}]]
elsif @symbol2hgncid[id].nil?
@symbol2hgncid[id] = column[#{index_hgncid}]
else
@ambiguous_symbol[id] = [@hgncid2symbol[column[#{index_hgncid}]]]
unless @hgncid2symbol[@symbol2hgncid[id]] == id
@ambiguous_symbol[id] << @hgncid2symbol[@symbol2hgncid[id]]
@symbol2hgncid.delete(id)
end
end
)
else
%(
@#{identifer}2hgncid[id] = column[#{index_hgncid}] if @#{identifer}2hgncid[id].nil?
)
end +
%(
end
end
)
end
end.join
# Process the content
eval %{fin.each do |line|\n column = line.chomp.split("\\t", -1)} + process_one_line + 'end' # rubocop:disable Lint/Eval
end | ruby | def parse(fin)
# Headline
names = fin.gets.chomp.split("\t")
index2identifier = {}
index_hgncid = nil
BioTCM::Databases::HGNC::IDENTIFIERS.each do |identifer, name|
if identifer == :hgncid
index_hgncid = names.index(name)
elsif name.is_a?(String)
index2identifier[names.index(name)] = identifer if names.index(name)
else
name.each_with_index do |n, i|
next unless names.index(n)
index2identifier[names.index(n)] = (i == 0 ? identifer : identifer.to_s)
end
end
end
# Dynamically bulid a line processor
process_one_line = index2identifier.collect do |index, identifer|
# Symbol will be mapped to single item
if identifer.is_a?(Symbol)
%(
unless column[#{index}] == nil || column[#{index}] == "" || column[#{index}] == "-"
@#{identifer}2hgncid[column[#{index}]] = column[#{index_hgncid}]
@hgncid2#{identifer}[column[#{index_hgncid}]] = column[#{index}]
end
)
# Others will be mapped to list item
else
%{
unless column[#{index}] == nil
column[#{index}].split(", ").each do |id|
} +
if identifer == 'symbol'
%(
if @ambiguous_symbol[id]
@ambiguous_symbol[id] << @hgncid2symbol[column[#{index_hgncid}]]
elsif @symbol2hgncid[id].nil?
@symbol2hgncid[id] = column[#{index_hgncid}]
else
@ambiguous_symbol[id] = [@hgncid2symbol[column[#{index_hgncid}]]]
unless @hgncid2symbol[@symbol2hgncid[id]] == id
@ambiguous_symbol[id] << @hgncid2symbol[@symbol2hgncid[id]]
@symbol2hgncid.delete(id)
end
end
)
else
%(
@#{identifer}2hgncid[id] = column[#{index_hgncid}] if @#{identifer}2hgncid[id].nil?
)
end +
%(
end
end
)
end
end.join
# Process the content
eval %{fin.each do |line|\n column = line.chomp.split("\\t", -1)} + process_one_line + 'end' # rubocop:disable Lint/Eval
end | [
"def",
"parse",
"(",
"fin",
")",
"names",
"=",
"fin",
".",
"gets",
".",
"chomp",
".",
"split",
"(",
"\"\\t\"",
")",
"index2identifier",
"=",
"{",
"}",
"index_hgncid",
"=",
"nil",
"BioTCM",
"::",
"Databases",
"::",
"HGNC",
"::",
"IDENTIFIERS",
".",
"each",
"do",
"|",
"identifer",
",",
"name",
"|",
"if",
"identifer",
"==",
":hgncid",
"index_hgncid",
"=",
"names",
".",
"index",
"(",
"name",
")",
"elsif",
"name",
".",
"is_a?",
"(",
"String",
")",
"index2identifier",
"[",
"names",
".",
"index",
"(",
"name",
")",
"]",
"=",
"identifer",
"if",
"names",
".",
"index",
"(",
"name",
")",
"else",
"name",
".",
"each_with_index",
"do",
"|",
"n",
",",
"i",
"|",
"next",
"unless",
"names",
".",
"index",
"(",
"n",
")",
"index2identifier",
"[",
"names",
".",
"index",
"(",
"n",
")",
"]",
"=",
"(",
"i",
"==",
"0",
"?",
"identifer",
":",
"identifer",
".",
"to_s",
")",
"end",
"end",
"end",
"process_one_line",
"=",
"index2identifier",
".",
"collect",
"do",
"|",
"index",
",",
"identifer",
"|",
"if",
"identifer",
".",
"is_a?",
"(",
"Symbol",
")",
"%( unless column[#{index}] == nil || column[#{index}] == \"\" || column[#{index}] == \"-\" @#{identifer}2hgncid[column[#{index}]] = column[#{index_hgncid}] @hgncid2#{identifer}[column[#{index_hgncid}]] = column[#{index}] end )",
"else",
"%{ unless column[#{index}] == nil column[#{index}].split(\", \").each do |id| }",
"+",
"if",
"identifer",
"==",
"'symbol'",
"%( if @ambiguous_symbol[id] @ambiguous_symbol[id] << @hgncid2symbol[column[#{index_hgncid}]] elsif @symbol2hgncid[id].nil? @symbol2hgncid[id] = column[#{index_hgncid}] else @ambiguous_symbol[id] = [@hgncid2symbol[column[#{index_hgncid}]]] unless @hgncid2symbol[@symbol2hgncid[id]] == id @ambiguous_symbol[id] << @hgncid2symbol[@symbol2hgncid[id]] @symbol2hgncid.delete(id) end end )",
"else",
"%( @#{identifer}2hgncid[id] = column[#{index_hgncid}] if @#{identifer}2hgncid[id].nil? )",
"end",
"+",
"%( end end )",
"end",
"end",
".",
"join",
"eval",
"%{fin.each do |line|\\n column = line.chomp.split(\"\\\\t\", -1)}",
"+",
"process_one_line",
"+",
"'end'",
"end"
]
| Load an HGNC table from IO
@param fin [#gets, #each] Typically a File or IO
@private | [
"Load",
"an",
"HGNC",
"table",
"from",
"IO"
]
| 89b798acc1773087d9e8b754187c884d57fd06d7 | https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/databases/hgnc/parser.rb#L17-L79 | train |
rightscale/right_scraper | lib/right_scraper/retrievers/git.rb | RightScraper::Retrievers.Git.retrieve | def retrieve
raise RetrieverError.new("git retriever is unavailable") unless available?
private_key = @repository.first_credential
private_key = nil if private_key && private_key.empty?
if is_windows?
if private_key
with_private_key_windows(private_key) { super }
else
super
end
else
# always start the ssh agent in Linux so we can disable strict host name
# checking, regardless of credentials.
::RightScraper::Processes::SSHAgent.with do |agent|
agent.add_key(private_key) if private_key
super
end
end
true
end | ruby | def retrieve
raise RetrieverError.new("git retriever is unavailable") unless available?
private_key = @repository.first_credential
private_key = nil if private_key && private_key.empty?
if is_windows?
if private_key
with_private_key_windows(private_key) { super }
else
super
end
else
# always start the ssh agent in Linux so we can disable strict host name
# checking, regardless of credentials.
::RightScraper::Processes::SSHAgent.with do |agent|
agent.add_key(private_key) if private_key
super
end
end
true
end | [
"def",
"retrieve",
"raise",
"RetrieverError",
".",
"new",
"(",
"\"git retriever is unavailable\"",
")",
"unless",
"available?",
"private_key",
"=",
"@repository",
".",
"first_credential",
"private_key",
"=",
"nil",
"if",
"private_key",
"&&",
"private_key",
".",
"empty?",
"if",
"is_windows?",
"if",
"private_key",
"with_private_key_windows",
"(",
"private_key",
")",
"{",
"super",
"}",
"else",
"super",
"end",
"else",
"::",
"RightScraper",
"::",
"Processes",
"::",
"SSHAgent",
".",
"with",
"do",
"|",
"agent",
"|",
"agent",
".",
"add_key",
"(",
"private_key",
")",
"if",
"private_key",
"super",
"end",
"end",
"true",
"end"
]
| In addition to normal retriever initialization, if the
underlying repository has a credential we need to initialize a
fresh SSHAgent and add the credential to it. | [
"In",
"addition",
"to",
"normal",
"retriever",
"initialization",
"if",
"the",
"underlying",
"repository",
"has",
"a",
"credential",
"we",
"need",
"to",
"initialize",
"a",
"fresh",
"SSHAgent",
"and",
"add",
"the",
"credential",
"to",
"it",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/git.rb#L66-L85 | train |
rightscale/right_scraper | lib/right_scraper/retrievers/git.rb | RightScraper::Retrievers.Git.do_clean_all | def do_clean_all(git_repo)
old_initial_directory = git_repo.repo_dir
clean_all_options = {
:directories => true,
:gitignored => true,
:submodules => true
}
relative_paths = [
'.',
git_repo.submodule_paths(:recursive => true)
].flatten
relative_paths.each do |relative_path|
subdir_path = ::File.expand_path(::File.join(@repo_dir, relative_path))
if ::File.directory?(subdir_path)
# reuse shell with any watch parameters already set but vary the
# initial directory for each submodule.
git_repo.shell.initial_directory = subdir_path
git_repo.clean_all(clean_all_options)
end
end
true
rescue ::RightGit::RightGitError => e
@logger.note_warning(e.message)
false
ensure
git_repo.shell.initial_directory = old_initial_directory
end | ruby | def do_clean_all(git_repo)
old_initial_directory = git_repo.repo_dir
clean_all_options = {
:directories => true,
:gitignored => true,
:submodules => true
}
relative_paths = [
'.',
git_repo.submodule_paths(:recursive => true)
].flatten
relative_paths.each do |relative_path|
subdir_path = ::File.expand_path(::File.join(@repo_dir, relative_path))
if ::File.directory?(subdir_path)
# reuse shell with any watch parameters already set but vary the
# initial directory for each submodule.
git_repo.shell.initial_directory = subdir_path
git_repo.clean_all(clean_all_options)
end
end
true
rescue ::RightGit::RightGitError => e
@logger.note_warning(e.message)
false
ensure
git_repo.shell.initial_directory = old_initial_directory
end | [
"def",
"do_clean_all",
"(",
"git_repo",
")",
"old_initial_directory",
"=",
"git_repo",
".",
"repo_dir",
"clean_all_options",
"=",
"{",
":directories",
"=>",
"true",
",",
":gitignored",
"=>",
"true",
",",
":submodules",
"=>",
"true",
"}",
"relative_paths",
"=",
"[",
"'.'",
",",
"git_repo",
".",
"submodule_paths",
"(",
":recursive",
"=>",
"true",
")",
"]",
".",
"flatten",
"relative_paths",
".",
"each",
"do",
"|",
"relative_path",
"|",
"subdir_path",
"=",
"::",
"File",
".",
"expand_path",
"(",
"::",
"File",
".",
"join",
"(",
"@repo_dir",
",",
"relative_path",
")",
")",
"if",
"::",
"File",
".",
"directory?",
"(",
"subdir_path",
")",
"git_repo",
".",
"shell",
".",
"initial_directory",
"=",
"subdir_path",
"git_repo",
".",
"clean_all",
"(",
"clean_all_options",
")",
"end",
"end",
"true",
"rescue",
"::",
"RightGit",
"::",
"RightGitError",
"=>",
"e",
"@logger",
".",
"note_warning",
"(",
"e",
".",
"message",
")",
"false",
"ensure",
"git_repo",
".",
"shell",
".",
"initial_directory",
"=",
"old_initial_directory",
"end"
]
| Cleans anything that is currently untracked in the repo directory and
any submodules. the idea is to prevent untracked items interfering with
the normal behavior that would result if checkout were always to a clean
directory. just switching between branches and updating submodules can
leave untracked artifacts that affect behavior. | [
"Cleans",
"anything",
"that",
"is",
"currently",
"untracked",
"in",
"the",
"repo",
"directory",
"and",
"any",
"submodules",
".",
"the",
"idea",
"is",
"to",
"prevent",
"untracked",
"items",
"interfering",
"with",
"the",
"normal",
"behavior",
"that",
"would",
"result",
"if",
"checkout",
"were",
"always",
"to",
"a",
"clean",
"directory",
".",
"just",
"switching",
"between",
"branches",
"and",
"updating",
"submodules",
"can",
"leave",
"untracked",
"artifacts",
"that",
"affect",
"behavior",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/git.rb#L222-L248 | train |
rightscale/right_scraper | lib/right_scraper/retrievers/git.rb | RightScraper::Retrievers.Git.validate_revision | def validate_revision(git_repo, revision)
branches = git_repo.branches(:all => true)
local_branches = branches.local
remote_branches = branches.remote
by_name = lambda { |item| item.name == revision }
# determine if revision is a tag.
remote_name = nil
if git_repo.tags.any?(&by_name)
if remote_branches.any?(&by_name)
# note that git has some resolution scheme for ambiguous SHA, tag,
# branch names but we do not support ambiguity.
raise RetrieverError, "Ambiguous name is both a remote branch and a tag: #{revision.inspect}"
elsif local_branches.any?(&by_name)
# odd corner case of a name that once was a remote branch (now
# deleted) that has become a tag instead. the user is not exactly
# at fault here (aside from being indecisive) so let's attempt to
# clean up after him. try switching to another local branch
# (i.e. master) and then deleting the obsolete local branch.
error_message = "Ambiguous name is both a local branch and a tag: #{revision.inspect}"
if revision == DEFAULT_BRANCH_NAME
# Darwin Awards winner; scraping with a tag named 'master' :@
raise RetrieverError, error_message
else
begin
# checkout master and delete obsolete local branch.
git_repo.checkout_to(DEFAULT_BRANCH_NAME, :force => true)
git_repo.spit_output("branch -D #{revision}")
rescue ::RightGit::RightGitError
# ignore failed attempt to recover; raise original error.
raise RetrieverError, error_message
end
end
end
else
# not a tag; SHA or branch.
#
# note that we could try to trivially determine if revision was a
# SHA by matching the SHA1 pattern except that:
# 1) git accepts partial SHAs so long as they uniquely distinguish
# a commit for checkout.
# 2) a branch or tag could name could match the SHA pattern (i.e.
# 40 hexadecimal characters) with no warnings from git. git will
# even allow a user to use a SHA as a tag name when that SHA
# exists (and may represent a different commit).
# confusing tags with SHAs should be universally discouraged but we
# need to be flexible here.
#
# a local branch may no longer exist remotely or may be behind or
# have diverged from remote branch. handle all cases.
remotes = remote_branches.select(&by_name)
if remotes.size > 1
# multiple remote branches exist (from different origins); branch
# name is ambiguous.
raise RetrieverError, "Ambiguous remote branch name: #{revision.inspect}"
elsif remotes.size == 1
# a remote branch exists.
remote_name = remotes.first.fullname
elsif local_branches.any?(&by_name)
# local branch only; failure due to missing remote branch.
#
# note that obsolete local branches are not supported by retrieval
# only because it would give the user a false positive.
raise RetrieverError, "Missing remote branch: #{revision.inspect}."
end # else a full or partial SHA or unknown revision
end
remote_name
end | ruby | def validate_revision(git_repo, revision)
branches = git_repo.branches(:all => true)
local_branches = branches.local
remote_branches = branches.remote
by_name = lambda { |item| item.name == revision }
# determine if revision is a tag.
remote_name = nil
if git_repo.tags.any?(&by_name)
if remote_branches.any?(&by_name)
# note that git has some resolution scheme for ambiguous SHA, tag,
# branch names but we do not support ambiguity.
raise RetrieverError, "Ambiguous name is both a remote branch and a tag: #{revision.inspect}"
elsif local_branches.any?(&by_name)
# odd corner case of a name that once was a remote branch (now
# deleted) that has become a tag instead. the user is not exactly
# at fault here (aside from being indecisive) so let's attempt to
# clean up after him. try switching to another local branch
# (i.e. master) and then deleting the obsolete local branch.
error_message = "Ambiguous name is both a local branch and a tag: #{revision.inspect}"
if revision == DEFAULT_BRANCH_NAME
# Darwin Awards winner; scraping with a tag named 'master' :@
raise RetrieverError, error_message
else
begin
# checkout master and delete obsolete local branch.
git_repo.checkout_to(DEFAULT_BRANCH_NAME, :force => true)
git_repo.spit_output("branch -D #{revision}")
rescue ::RightGit::RightGitError
# ignore failed attempt to recover; raise original error.
raise RetrieverError, error_message
end
end
end
else
# not a tag; SHA or branch.
#
# note that we could try to trivially determine if revision was a
# SHA by matching the SHA1 pattern except that:
# 1) git accepts partial SHAs so long as they uniquely distinguish
# a commit for checkout.
# 2) a branch or tag could name could match the SHA pattern (i.e.
# 40 hexadecimal characters) with no warnings from git. git will
# even allow a user to use a SHA as a tag name when that SHA
# exists (and may represent a different commit).
# confusing tags with SHAs should be universally discouraged but we
# need to be flexible here.
#
# a local branch may no longer exist remotely or may be behind or
# have diverged from remote branch. handle all cases.
remotes = remote_branches.select(&by_name)
if remotes.size > 1
# multiple remote branches exist (from different origins); branch
# name is ambiguous.
raise RetrieverError, "Ambiguous remote branch name: #{revision.inspect}"
elsif remotes.size == 1
# a remote branch exists.
remote_name = remotes.first.fullname
elsif local_branches.any?(&by_name)
# local branch only; failure due to missing remote branch.
#
# note that obsolete local branches are not supported by retrieval
# only because it would give the user a false positive.
raise RetrieverError, "Missing remote branch: #{revision.inspect}."
end # else a full or partial SHA or unknown revision
end
remote_name
end | [
"def",
"validate_revision",
"(",
"git_repo",
",",
"revision",
")",
"branches",
"=",
"git_repo",
".",
"branches",
"(",
":all",
"=>",
"true",
")",
"local_branches",
"=",
"branches",
".",
"local",
"remote_branches",
"=",
"branches",
".",
"remote",
"by_name",
"=",
"lambda",
"{",
"|",
"item",
"|",
"item",
".",
"name",
"==",
"revision",
"}",
"remote_name",
"=",
"nil",
"if",
"git_repo",
".",
"tags",
".",
"any?",
"(",
"&",
"by_name",
")",
"if",
"remote_branches",
".",
"any?",
"(",
"&",
"by_name",
")",
"raise",
"RetrieverError",
",",
"\"Ambiguous name is both a remote branch and a tag: #{revision.inspect}\"",
"elsif",
"local_branches",
".",
"any?",
"(",
"&",
"by_name",
")",
"error_message",
"=",
"\"Ambiguous name is both a local branch and a tag: #{revision.inspect}\"",
"if",
"revision",
"==",
"DEFAULT_BRANCH_NAME",
"raise",
"RetrieverError",
",",
"error_message",
"else",
"begin",
"git_repo",
".",
"checkout_to",
"(",
"DEFAULT_BRANCH_NAME",
",",
":force",
"=>",
"true",
")",
"git_repo",
".",
"spit_output",
"(",
"\"branch -D #{revision}\"",
")",
"rescue",
"::",
"RightGit",
"::",
"RightGitError",
"raise",
"RetrieverError",
",",
"error_message",
"end",
"end",
"end",
"else",
"remotes",
"=",
"remote_branches",
".",
"select",
"(",
"&",
"by_name",
")",
"if",
"remotes",
".",
"size",
">",
"1",
"raise",
"RetrieverError",
",",
"\"Ambiguous remote branch name: #{revision.inspect}\"",
"elsif",
"remotes",
".",
"size",
"==",
"1",
"remote_name",
"=",
"remotes",
".",
"first",
".",
"fullname",
"elsif",
"local_branches",
".",
"any?",
"(",
"&",
"by_name",
")",
"raise",
"RetrieverError",
",",
"\"Missing remote branch: #{revision.inspect}.\"",
"end",
"end",
"remote_name",
"end"
]
| Validates the given revision string to ensure it is safe and sane before
attempting to use it.
@param [::RightGit::Git::Repository] git_repo for validation
@param [String] revision for validation
@return [String] remote_name (for branch reset) or nil
@raise [RetrieverError] on validation failure | [
"Validates",
"the",
"given",
"revision",
"string",
"to",
"ensure",
"it",
"is",
"safe",
"and",
"sane",
"before",
"attempting",
"to",
"use",
"it",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/git.rb#L264-L331 | train |
rightscale/right_scraper | lib/right_scraper/retrievers/git.rb | RightScraper::Retrievers.Git.without_size_limit | def without_size_limit(git_repo)
old_max_bytes = git_repo.shell.max_bytes
begin
git_repo.shell.max_bytes = nil
yield
ensure
git_repo.shell.max_bytes = old_max_bytes
end
end | ruby | def without_size_limit(git_repo)
old_max_bytes = git_repo.shell.max_bytes
begin
git_repo.shell.max_bytes = nil
yield
ensure
git_repo.shell.max_bytes = old_max_bytes
end
end | [
"def",
"without_size_limit",
"(",
"git_repo",
")",
"old_max_bytes",
"=",
"git_repo",
".",
"shell",
".",
"max_bytes",
"begin",
"git_repo",
".",
"shell",
".",
"max_bytes",
"=",
"nil",
"yield",
"ensure",
"git_repo",
".",
"shell",
".",
"max_bytes",
"=",
"old_max_bytes",
"end",
"end"
]
| Temporarily disables checking the size of the repo_dir against the
configured size limit. This permits performing git queries against a repo
on disk that would normally exceed the size limit if it hadn't already
been fully checked out in the past. If a repo has been scraped in the past
and does not have any new commits, then it is acceptable even if it
would exceed the current size limit. | [
"Temporarily",
"disables",
"checking",
"the",
"size",
"of",
"the",
"repo_dir",
"against",
"the",
"configured",
"size",
"limit",
".",
"This",
"permits",
"performing",
"git",
"queries",
"against",
"a",
"repo",
"on",
"disk",
"that",
"would",
"normally",
"exceed",
"the",
"size",
"limit",
"if",
"it",
"hadn",
"t",
"already",
"been",
"fully",
"checked",
"out",
"in",
"the",
"past",
".",
"If",
"a",
"repo",
"has",
"been",
"scraped",
"in",
"the",
"past",
"and",
"does",
"not",
"have",
"any",
"new",
"commits",
"then",
"it",
"is",
"acceptable",
"even",
"if",
"it",
"would",
"exceed",
"the",
"current",
"size",
"limit",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/git.rb#L339-L347 | train |
rightscale/right_scraper | lib/right_scraper/retrievers/git.rb | RightScraper::Retrievers.Git.without_host_key_checking_linux | def without_host_key_checking_linux
tmpdir = ::Dir.mktmpdir
ssh_cmd = ::File.join(tmpdir, 'ssh')
::File.open(ssh_cmd, 'w') do |cmd|
cmd.puts "#!/bin/bash"
cmd.puts "exec ssh -o StrictHostKeyChecking=no ${@}"
end
::FileUtils.chmod(0700, ssh_cmd)
old_env = ::ENV['GIT_SSH']
::ENV['GIT_SSH'] = ssh_cmd
yield
ensure
::FileUtils.rm_rf(tmpdir)
::ENV['GIT_SSH'] = old_env
end | ruby | def without_host_key_checking_linux
tmpdir = ::Dir.mktmpdir
ssh_cmd = ::File.join(tmpdir, 'ssh')
::File.open(ssh_cmd, 'w') do |cmd|
cmd.puts "#!/bin/bash"
cmd.puts "exec ssh -o StrictHostKeyChecking=no ${@}"
end
::FileUtils.chmod(0700, ssh_cmd)
old_env = ::ENV['GIT_SSH']
::ENV['GIT_SSH'] = ssh_cmd
yield
ensure
::FileUtils.rm_rf(tmpdir)
::ENV['GIT_SSH'] = old_env
end | [
"def",
"without_host_key_checking_linux",
"tmpdir",
"=",
"::",
"Dir",
".",
"mktmpdir",
"ssh_cmd",
"=",
"::",
"File",
".",
"join",
"(",
"tmpdir",
",",
"'ssh'",
")",
"::",
"File",
".",
"open",
"(",
"ssh_cmd",
",",
"'w'",
")",
"do",
"|",
"cmd",
"|",
"cmd",
".",
"puts",
"\"#!/bin/bash\"",
"cmd",
".",
"puts",
"\"exec ssh -o StrictHostKeyChecking=no ${@}\"",
"end",
"::",
"FileUtils",
".",
"chmod",
"(",
"0700",
",",
"ssh_cmd",
")",
"old_env",
"=",
"::",
"ENV",
"[",
"'GIT_SSH'",
"]",
"::",
"ENV",
"[",
"'GIT_SSH'",
"]",
"=",
"ssh_cmd",
"yield",
"ensure",
"::",
"FileUtils",
".",
"rm_rf",
"(",
"tmpdir",
")",
"::",
"ENV",
"[",
"'GIT_SSH'",
"]",
"=",
"old_env",
"end"
]
| Temporarily disable SSH host-key checking for SSH clients invoked by Git, for the duration of the
block that is passed to this method.
@yield after disabling strict host key checking, yields to caller | [
"Temporarily",
"disable",
"SSH",
"host",
"-",
"key",
"checking",
"for",
"SSH",
"clients",
"invoked",
"by",
"Git",
"for",
"the",
"duration",
"of",
"the",
"block",
"that",
"is",
"passed",
"to",
"this",
"method",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/git.rb#L365-L381 | train |
rightscale/right_scraper | lib/right_scraper/retrievers/git.rb | RightScraper::Retrievers.Git.with_replaced_file | def with_replaced_file(filepath, contents)
::Dir.mktmpdir do |temp_dir|
begin
temp_path = ::File.join(temp_dir, ::File.basename(filepath))
::FileUtils.mkdir_p(::File.dirname(filepath))
if ::File.file?(filepath)
::FileUtils.mv(filepath, temp_path, :force => true)
end
::File.open(filepath, 'w') { |f| f.write(contents) }
yield
ensure
begin
if ::File.file?(temp_path)
::FileUtils.mv(temp_path, filepath, :force => true)
elsif ::File.file?(filepath)
::File.unlink(filepath)
end
rescue ::Exception => e
@logger.note_warning("Failed to restore #{filepath.inspect}: #{e.message}")
end
end
end
end | ruby | def with_replaced_file(filepath, contents)
::Dir.mktmpdir do |temp_dir|
begin
temp_path = ::File.join(temp_dir, ::File.basename(filepath))
::FileUtils.mkdir_p(::File.dirname(filepath))
if ::File.file?(filepath)
::FileUtils.mv(filepath, temp_path, :force => true)
end
::File.open(filepath, 'w') { |f| f.write(contents) }
yield
ensure
begin
if ::File.file?(temp_path)
::FileUtils.mv(temp_path, filepath, :force => true)
elsif ::File.file?(filepath)
::File.unlink(filepath)
end
rescue ::Exception => e
@logger.note_warning("Failed to restore #{filepath.inspect}: #{e.message}")
end
end
end
end | [
"def",
"with_replaced_file",
"(",
"filepath",
",",
"contents",
")",
"::",
"Dir",
".",
"mktmpdir",
"do",
"|",
"temp_dir",
"|",
"begin",
"temp_path",
"=",
"::",
"File",
".",
"join",
"(",
"temp_dir",
",",
"::",
"File",
".",
"basename",
"(",
"filepath",
")",
")",
"::",
"FileUtils",
".",
"mkdir_p",
"(",
"::",
"File",
".",
"dirname",
"(",
"filepath",
")",
")",
"if",
"::",
"File",
".",
"file?",
"(",
"filepath",
")",
"::",
"FileUtils",
".",
"mv",
"(",
"filepath",
",",
"temp_path",
",",
":force",
"=>",
"true",
")",
"end",
"::",
"File",
".",
"open",
"(",
"filepath",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"contents",
")",
"}",
"yield",
"ensure",
"begin",
"if",
"::",
"File",
".",
"file?",
"(",
"temp_path",
")",
"::",
"FileUtils",
".",
"mv",
"(",
"temp_path",
",",
"filepath",
",",
":force",
"=>",
"true",
")",
"elsif",
"::",
"File",
".",
"file?",
"(",
"filepath",
")",
"::",
"File",
".",
"unlink",
"(",
"filepath",
")",
"end",
"rescue",
"::",
"Exception",
"=>",
"e",
"@logger",
".",
"note_warning",
"(",
"\"Failed to restore #{filepath.inspect}: #{e.message}\"",
")",
"end",
"end",
"end",
"end"
]
| Utility for replacing a file temporarily within a scope and ensuring it is
restored afterward.
@param [String] filepath to replace
@param [String] contents to substitute
@yield after replacing file | [
"Utility",
"for",
"replacing",
"a",
"file",
"temporarily",
"within",
"a",
"scope",
"and",
"ensuring",
"it",
"is",
"restored",
"afterward",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/git.rb#L411-L433 | train |
rightscale/right_git | lib/right_git/git/repository.rb | RightGit::Git.Repository.fetch_all | def fetch_all(options = {})
options = { :prune => false }.merge(options)
git_args = ['--all']
git_args << '--prune' if options[:prune]
fetch(git_args)
fetch('--tags') # need a separate call for tags or else you don't get all the tags
true
end | ruby | def fetch_all(options = {})
options = { :prune => false }.merge(options)
git_args = ['--all']
git_args << '--prune' if options[:prune]
fetch(git_args)
fetch('--tags') # need a separate call for tags or else you don't get all the tags
true
end | [
"def",
"fetch_all",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":prune",
"=>",
"false",
"}",
".",
"merge",
"(",
"options",
")",
"git_args",
"=",
"[",
"'--all'",
"]",
"git_args",
"<<",
"'--prune'",
"if",
"options",
"[",
":prune",
"]",
"fetch",
"(",
"git_args",
")",
"fetch",
"(",
"'--tags'",
")",
"true",
"end"
]
| Fetches branch and tag information from remote origin.
@param [Hash] options for fetch all
@option options [TrueClass|FalseClass] :prune as true to prune dead branches
@return [TrueClass] always true | [
"Fetches",
"branch",
"and",
"tag",
"information",
"from",
"remote",
"origin",
"."
]
| 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/repository.rb#L111-L118 | train |
rightscale/right_git | lib/right_git/git/repository.rb | RightGit::Git.Repository.log | def log(revision, options = {})
options = {
:skip => nil,
:tail => 10_000,
:merges => false,
:no_merges => false,
:full_hashes => false,
}.merge(options)
skip = options[:skip]
git_args = [
'log',
"-n#{options[:tail]}",
"--format=\"#{options[:full_hashes] ? Commit::LOG_FORMAT_LONG : Commit::LOG_FORMAT}\"" # double-quotes are Windows friendly
]
git_args << "--skip #{skip}" if skip
git_args << "--merges" if options[:merges]
git_args << "--no-merges" if options[:no_merges]
git_args << revision if revision
git_output(git_args).lines.map { |line| Commit.new(self, line.strip) }
end | ruby | def log(revision, options = {})
options = {
:skip => nil,
:tail => 10_000,
:merges => false,
:no_merges => false,
:full_hashes => false,
}.merge(options)
skip = options[:skip]
git_args = [
'log',
"-n#{options[:tail]}",
"--format=\"#{options[:full_hashes] ? Commit::LOG_FORMAT_LONG : Commit::LOG_FORMAT}\"" # double-quotes are Windows friendly
]
git_args << "--skip #{skip}" if skip
git_args << "--merges" if options[:merges]
git_args << "--no-merges" if options[:no_merges]
git_args << revision if revision
git_output(git_args).lines.map { |line| Commit.new(self, line.strip) }
end | [
"def",
"log",
"(",
"revision",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":skip",
"=>",
"nil",
",",
":tail",
"=>",
"10_000",
",",
":merges",
"=>",
"false",
",",
":no_merges",
"=>",
"false",
",",
":full_hashes",
"=>",
"false",
",",
"}",
".",
"merge",
"(",
"options",
")",
"skip",
"=",
"options",
"[",
":skip",
"]",
"git_args",
"=",
"[",
"'log'",
",",
"\"-n#{options[:tail]}\"",
",",
"\"--format=\\\"#{options[:full_hashes] ? Commit::LOG_FORMAT_LONG : Commit::LOG_FORMAT}\\\"\"",
"]",
"git_args",
"<<",
"\"--skip #{skip}\"",
"if",
"skip",
"git_args",
"<<",
"\"--merges\"",
"if",
"options",
"[",
":merges",
"]",
"git_args",
"<<",
"\"--no-merges\"",
"if",
"options",
"[",
":no_merges",
"]",
"git_args",
"<<",
"revision",
"if",
"revision",
"git_output",
"(",
"git_args",
")",
".",
"lines",
".",
"map",
"{",
"|",
"line",
"|",
"Commit",
".",
"new",
"(",
"self",
",",
"line",
".",
"strip",
")",
"}",
"end"
]
| Generates a list of commits using the given 'git log' arguments.
@param [String] revision to log or nil
@param [Hash] options for log
@option options [Integer] :skip as lines of most recent history to skip (Default = include most recent)
@option options [Integer] :tail as max history of log
@option options [TrueClass|FalseClass] :merges as true to exclude non-merge commits
@option options [TrueClass|FalseClass] :no_merges as true to exclude merge commits
@option options [TrueClass|FalseClass] :full_hashes as true show full hashes, false for (7-character) abbreviations
@return [Array] list of commits | [
"Generates",
"a",
"list",
"of",
"commits",
"using",
"the",
"given",
"git",
"log",
"arguments",
"."
]
| 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/repository.rb#L180-L199 | train |
rightscale/right_git | lib/right_git/git/repository.rb | RightGit::Git.Repository.clean_all | def clean_all(options = {})
options = {
:directories => false,
:gitignored => false,
:submodules => false,
}.merge(options)
git_args = ['-f'] # force is required or else -n only lists files.
git_args << '-f' if options[:submodules] # double-tap -f to kill untracked submodules
git_args << '-d' if options[:directories]
git_args << '-x' if options[:gitignored]
clean(git_args)
true
end | ruby | def clean_all(options = {})
options = {
:directories => false,
:gitignored => false,
:submodules => false,
}.merge(options)
git_args = ['-f'] # force is required or else -n only lists files.
git_args << '-f' if options[:submodules] # double-tap -f to kill untracked submodules
git_args << '-d' if options[:directories]
git_args << '-x' if options[:gitignored]
clean(git_args)
true
end | [
"def",
"clean_all",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":directories",
"=>",
"false",
",",
":gitignored",
"=>",
"false",
",",
":submodules",
"=>",
"false",
",",
"}",
".",
"merge",
"(",
"options",
")",
"git_args",
"=",
"[",
"'-f'",
"]",
"git_args",
"<<",
"'-f'",
"if",
"options",
"[",
":submodules",
"]",
"git_args",
"<<",
"'-d'",
"if",
"options",
"[",
":directories",
"]",
"git_args",
"<<",
"'-x'",
"if",
"options",
"[",
":gitignored",
"]",
"clean",
"(",
"git_args",
")",
"true",
"end"
]
| Cleans everything and optionally cleans .gitignored files.
@param [Hash] options for checkout
@option options [TrueClass|FalseClass] :directories as true to clean untracked directories (but not untracked submodules)
@option options [TrueClass|FalseClass] :gitignored as true to clean gitignored (untracked) files
@option options [TrueClass|FalseClass] :submodules as true to clean untracked submodules (requires force)
@return [TrueClass] always true | [
"Cleans",
"everything",
"and",
"optionally",
"cleans",
".",
"gitignored",
"files",
"."
]
| 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/repository.rb#L220-L232 | train |
rightscale/right_git | lib/right_git/git/repository.rb | RightGit::Git.Repository.submodule_paths | def submodule_paths(options = {})
options = {
:recursive => false
}.merge(options)
git_args = ['submodule', 'status']
git_args << '--recursive' if options[:recursive]
git_output(git_args).lines.map do |line|
data = line.chomp
if matched = SUBMODULE_STATUS_REGEX.match(data)
matched[3]
else
raise GitError,
"Unexpected output from submodule status: #{data.inspect}"
end
end
end | ruby | def submodule_paths(options = {})
options = {
:recursive => false
}.merge(options)
git_args = ['submodule', 'status']
git_args << '--recursive' if options[:recursive]
git_output(git_args).lines.map do |line|
data = line.chomp
if matched = SUBMODULE_STATUS_REGEX.match(data)
matched[3]
else
raise GitError,
"Unexpected output from submodule status: #{data.inspect}"
end
end
end | [
"def",
"submodule_paths",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":recursive",
"=>",
"false",
"}",
".",
"merge",
"(",
"options",
")",
"git_args",
"=",
"[",
"'submodule'",
",",
"'status'",
"]",
"git_args",
"<<",
"'--recursive'",
"if",
"options",
"[",
":recursive",
"]",
"git_output",
"(",
"git_args",
")",
".",
"lines",
".",
"map",
"do",
"|",
"line",
"|",
"data",
"=",
"line",
".",
"chomp",
"if",
"matched",
"=",
"SUBMODULE_STATUS_REGEX",
".",
"match",
"(",
"data",
")",
"matched",
"[",
"3",
"]",
"else",
"raise",
"GitError",
",",
"\"Unexpected output from submodule status: #{data.inspect}\"",
"end",
"end",
"end"
]
| Queries the recursive list of submodule paths for the current workspace.
@param [Hash] options for submodules
@option options [TrueClass|FalseClass] :recursive as true to recursively get submodule paths
@return [Array] list of submodule paths or empty | [
"Queries",
"the",
"recursive",
"list",
"of",
"submodule",
"paths",
"for",
"the",
"current",
"workspace",
"."
]
| 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/repository.rb#L270-L285 | train |
rightscale/right_git | lib/right_git/git/repository.rb | RightGit::Git.Repository.update_submodules | def update_submodules(options = {})
options = {
:recursive => false
}.merge(options)
git_args = ['submodule', 'update', '--init']
git_args << '--recursive' if options[:recursive]
spit_output(git_args)
true
end | ruby | def update_submodules(options = {})
options = {
:recursive => false
}.merge(options)
git_args = ['submodule', 'update', '--init']
git_args << '--recursive' if options[:recursive]
spit_output(git_args)
true
end | [
"def",
"update_submodules",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":recursive",
"=>",
"false",
"}",
".",
"merge",
"(",
"options",
")",
"git_args",
"=",
"[",
"'submodule'",
",",
"'update'",
",",
"'--init'",
"]",
"git_args",
"<<",
"'--recursive'",
"if",
"options",
"[",
":recursive",
"]",
"spit_output",
"(",
"git_args",
")",
"true",
"end"
]
| Updates submodules for the current workspace.
@param [Hash] options for submodules
@option options [TrueClass|FalseClass] :recursive as true to recursively update submodules
@return [TrueClass] always true | [
"Updates",
"submodules",
"for",
"the",
"current",
"workspace",
"."
]
| 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/repository.rb#L293-L301 | train |
rightscale/right_git | lib/right_git/git/repository.rb | RightGit::Git.Repository.sha_for | def sha_for(revision)
# note that 'git show-ref' produces easier-to-parse output but it matches
# both local and remote branch to a simple branch name whereas 'git show'
# matches at-most-one and requires origin/ for remote branches.
git_args = ['show', revision].compact
result = nil
git_output(git_args).lines.each do |line|
if matched = COMMIT_SHA1_REGEX.match(line.strip)
result = matched[1]
break
end
end
unless result
raise GitError, 'Unable to locate commit in show output.'
end
result
end | ruby | def sha_for(revision)
# note that 'git show-ref' produces easier-to-parse output but it matches
# both local and remote branch to a simple branch name whereas 'git show'
# matches at-most-one and requires origin/ for remote branches.
git_args = ['show', revision].compact
result = nil
git_output(git_args).lines.each do |line|
if matched = COMMIT_SHA1_REGEX.match(line.strip)
result = matched[1]
break
end
end
unless result
raise GitError, 'Unable to locate commit in show output.'
end
result
end | [
"def",
"sha_for",
"(",
"revision",
")",
"git_args",
"=",
"[",
"'show'",
",",
"revision",
"]",
".",
"compact",
"result",
"=",
"nil",
"git_output",
"(",
"git_args",
")",
".",
"lines",
".",
"each",
"do",
"|",
"line",
"|",
"if",
"matched",
"=",
"COMMIT_SHA1_REGEX",
".",
"match",
"(",
"line",
".",
"strip",
")",
"result",
"=",
"matched",
"[",
"1",
"]",
"break",
"end",
"end",
"unless",
"result",
"raise",
"GitError",
",",
"'Unable to locate commit in show output.'",
"end",
"result",
"end"
]
| Determines the SHA referenced by the given revision. Raises on failure.
@param [String] revision or nil for current SHA
@return [String] SHA for revision | [
"Determines",
"the",
"SHA",
"referenced",
"by",
"the",
"given",
"revision",
".",
"Raises",
"on",
"failure",
"."
]
| 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/repository.rb#L308-L324 | train |
rightscale/right_git | lib/right_git/git/repository.rb | RightGit::Git.Repository.vet_output | def vet_output(*args)
last_output = git_output(*args).strip
logger.info(last_output) unless last_output.empty?
if last_output.downcase =~ /^(error|fatal):/
raise GitError, "Git exited zero but an error was detected in output."
end
true
end | ruby | def vet_output(*args)
last_output = git_output(*args).strip
logger.info(last_output) unless last_output.empty?
if last_output.downcase =~ /^(error|fatal):/
raise GitError, "Git exited zero but an error was detected in output."
end
true
end | [
"def",
"vet_output",
"(",
"*",
"args",
")",
"last_output",
"=",
"git_output",
"(",
"*",
"args",
")",
".",
"strip",
"logger",
".",
"info",
"(",
"last_output",
")",
"unless",
"last_output",
".",
"empty?",
"if",
"last_output",
".",
"downcase",
"=~",
"/",
"/",
"raise",
"GitError",
",",
"\"Git exited zero but an error was detected in output.\"",
"end",
"true",
"end"
]
| msysgit on Windows exits zero even when checkout|reset|fetch fails so we
need to scan the output for error or fatal messages. it does no harm to do
the same on Linux even though the exit code works properly there.
@param [String|Array] args to execute
@return [TrueClass] always true | [
"msysgit",
"on",
"Windows",
"exits",
"zero",
"even",
"when",
"checkout|reset|fetch",
"fails",
"so",
"we",
"need",
"to",
"scan",
"the",
"output",
"for",
"error",
"or",
"fatal",
"messages",
".",
"it",
"does",
"no",
"harm",
"to",
"do",
"the",
"same",
"on",
"Linux",
"even",
"though",
"the",
"exit",
"code",
"works",
"properly",
"there",
"."
]
| 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/repository.rb#L351-L358 | train |
rightscale/right_scraper | lib/right_scraper/scanners/cookbook_metadata.rb | RightScraper::Scanners.CookbookMetadata.end | def end(resource)
@logger.operation(:metadata_parsing) do
if @read_blk
metadata = ::JSON.parse(@read_blk.call)
resource.metadata = metadata
# check for undefined cookbook name.
#
# note that many specs in right_scraper use badly formed metadata
# that is not even a hash so, to avoid having to fix all of them
# (and also in case the user's metadata.json is not a hash) check
# for the has_key? method.
#
# if real metadata is not a hash then that should cause failure
# at a higher level. if the cookbook name is actually defined as
# being 'undefined' then the user gets a warning anyway.
if (metadata.respond_to?(:has_key?) &&
metadata['name'] == UNDEFINED_COOKBOOK_NAME)
message =
'Cookbook name appears to be undefined and has been' +
' supplied automatically.'
@logger.note_warning(message)
end
else
# should not be scanning at all unless one of the metadata files was
# detected before starting scan.
fail 'Unexpected missing metadata'
end
end
true
ensure
@read_blk = nil
@cookbook = nil
end | ruby | def end(resource)
@logger.operation(:metadata_parsing) do
if @read_blk
metadata = ::JSON.parse(@read_blk.call)
resource.metadata = metadata
# check for undefined cookbook name.
#
# note that many specs in right_scraper use badly formed metadata
# that is not even a hash so, to avoid having to fix all of them
# (and also in case the user's metadata.json is not a hash) check
# for the has_key? method.
#
# if real metadata is not a hash then that should cause failure
# at a higher level. if the cookbook name is actually defined as
# being 'undefined' then the user gets a warning anyway.
if (metadata.respond_to?(:has_key?) &&
metadata['name'] == UNDEFINED_COOKBOOK_NAME)
message =
'Cookbook name appears to be undefined and has been' +
' supplied automatically.'
@logger.note_warning(message)
end
else
# should not be scanning at all unless one of the metadata files was
# detected before starting scan.
fail 'Unexpected missing metadata'
end
end
true
ensure
@read_blk = nil
@cookbook = nil
end | [
"def",
"end",
"(",
"resource",
")",
"@logger",
".",
"operation",
"(",
":metadata_parsing",
")",
"do",
"if",
"@read_blk",
"metadata",
"=",
"::",
"JSON",
".",
"parse",
"(",
"@read_blk",
".",
"call",
")",
"resource",
".",
"metadata",
"=",
"metadata",
"if",
"(",
"metadata",
".",
"respond_to?",
"(",
":has_key?",
")",
"&&",
"metadata",
"[",
"'name'",
"]",
"==",
"UNDEFINED_COOKBOOK_NAME",
")",
"message",
"=",
"'Cookbook name appears to be undefined and has been'",
"+",
"' supplied automatically.'",
"@logger",
".",
"note_warning",
"(",
"message",
")",
"end",
"else",
"fail",
"'Unexpected missing metadata'",
"end",
"end",
"true",
"ensure",
"@read_blk",
"=",
"nil",
"@cookbook",
"=",
"nil",
"end"
]
| Complete a scan for the given resource.
=== Parameters ===
resource(RightScraper::Resources::Base):: resource to scan | [
"Complete",
"a",
"scan",
"for",
"the",
"given",
"resource",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata.rb#L83-L116 | train |
rightscale/right_scraper | lib/right_scraper/scanners/cookbook_metadata.rb | RightScraper::Scanners.CookbookMetadata.finish | def finish
begin
::FileUtils.remove_entry_secure(tls[:tmpdir]) if tls[:tmpdir]
rescue ::Exception => e
@logger.note_warning(e.message)
end
ensure
# Cleanup thread-local storage
tls.clear
end | ruby | def finish
begin
::FileUtils.remove_entry_secure(tls[:tmpdir]) if tls[:tmpdir]
rescue ::Exception => e
@logger.note_warning(e.message)
end
ensure
# Cleanup thread-local storage
tls.clear
end | [
"def",
"finish",
"begin",
"::",
"FileUtils",
".",
"remove_entry_secure",
"(",
"tls",
"[",
":tmpdir",
"]",
")",
"if",
"tls",
"[",
":tmpdir",
"]",
"rescue",
"::",
"Exception",
"=>",
"e",
"@logger",
".",
"note_warning",
"(",
"e",
".",
"message",
")",
"end",
"ensure",
"tls",
".",
"clear",
"end"
]
| All done scanning this repository. | [
"All",
"done",
"scanning",
"this",
"repository",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata.rb#L120-L129 | train |
rightscale/right_scraper | lib/right_scraper/scanners/cookbook_metadata.rb | RightScraper::Scanners.CookbookMetadata.generate_metadata_json | def generate_metadata_json
@logger.operation(:metadata_generation) do
# note we will use the same tmpdir path inside and outside the
# container only because it is non-trivial to invoke mktmpdir inside
# the container.
tmpdir, created = create_tmpdir
# path constants
src_knife_script_path = ::File.expand_path(
::File.join(__FILE__, '../../../../scripts', KNIFE_METADATA_SCRIPT_NAME))
dst_knife_script_dir = tmpdir
dst_knife_script_path = ::File.join(dst_knife_script_dir, KNIFE_METADATA_SCRIPT_NAME)
jailed_repo_dir = ::File.join(tmpdir, UNDEFINED_COOKBOOK_NAME)
jailed_cookbook_dir = (@cookbook.pos == '.' && jailed_repo_dir) || ::File.join(jailed_repo_dir, @cookbook.pos)
jailed_metadata_json_path = ::File.join(jailed_cookbook_dir, JSON_METADATA)
freed_metadata_dir = (@cookbook.pos == '.' && freed_dir) || ::File.join(freed_dir, @cookbook.pos)
freed_metadata_json_path = ::File.join(freed_metadata_dir, JSON_METADATA)
# in the multi-pass case we will run this scanner only on the first pass
# so the 'metadata.json' file should not exist. the read-only scanner,
# which is safe outside of containment, should be used subsequently.
# the entire 'freed' directory should have been removed upon the next
# successful retrieval so that this scanner will succeed.
if ::File.file?(freed_metadata_json_path)
raise MetadataError, "Refused to overwrite already-generated metadata file: #{freed_metadata_json_path}"
end
# jail the repo using the legacy semantics for copying files in and out
# of jail.
copy_out = { jailed_metadata_json_path => freed_metadata_json_path }
# copy files into the jail once per repository (i.e. not once per
# cookbook within the repository).
if created
copy_in = generate_copy_in(@cookbook.repo_dir, jailed_repo_dir)
copy_in[src_knife_script_path] = dst_knife_script_path
# note that at this point we previously used Warden as a container
# for the copied-in files but now we assume that the current process
# is already in a container (i.e. Docker) and so this copying is
# more about creating a writable directory for knife than about
# containment. the checked-out repo should be read-only to this
# contained process due to running with limited privileges.
do_copy_in(copy_in)
end
# HACK: support ad-hoc testing in dev-mode by using the current version
# for rbenv shell.
if ::ENV['RBENV_VERSION'].to_s.empty?
ruby = 'ruby'
else
ruby = `which ruby`.chomp
end
# execute knife as a child process. any constraints are assumed to be
# imposed on the current process by a container (timeout, memory, etc.)
shell = ::RightGit::Shell::Default
output = StringIO.new
begin
shell.execute(
"#{ruby} #{dst_knife_script_path.inspect} #{jailed_cookbook_dir.inspect} 2>&1",
directory: dst_knife_script_dir,
outstream: output,
raise_on_failure: true,
set_env_vars: { LC_ALL: 'en_US.UTF-8' }, # character encoding for emitted JSON
clear_env_vars: %w{BUNDLE_BIN_PATH BUNDLE_GEMFILE},
timeout: KNIFE_METADATA_TIMEOUT)
output = output.string
rescue ::RightGit::Shell::ShellError => e
output = output.string
raise MetadataError, "Failed to run chef knife: #{e.message}\n#{output[0, 1024]}"
end
# free files from jail.
do_copy_out(copy_out)
# load and return freed metadata.
return ::File.read(freed_metadata_json_path)
end
end | ruby | def generate_metadata_json
@logger.operation(:metadata_generation) do
# note we will use the same tmpdir path inside and outside the
# container only because it is non-trivial to invoke mktmpdir inside
# the container.
tmpdir, created = create_tmpdir
# path constants
src_knife_script_path = ::File.expand_path(
::File.join(__FILE__, '../../../../scripts', KNIFE_METADATA_SCRIPT_NAME))
dst_knife_script_dir = tmpdir
dst_knife_script_path = ::File.join(dst_knife_script_dir, KNIFE_METADATA_SCRIPT_NAME)
jailed_repo_dir = ::File.join(tmpdir, UNDEFINED_COOKBOOK_NAME)
jailed_cookbook_dir = (@cookbook.pos == '.' && jailed_repo_dir) || ::File.join(jailed_repo_dir, @cookbook.pos)
jailed_metadata_json_path = ::File.join(jailed_cookbook_dir, JSON_METADATA)
freed_metadata_dir = (@cookbook.pos == '.' && freed_dir) || ::File.join(freed_dir, @cookbook.pos)
freed_metadata_json_path = ::File.join(freed_metadata_dir, JSON_METADATA)
# in the multi-pass case we will run this scanner only on the first pass
# so the 'metadata.json' file should not exist. the read-only scanner,
# which is safe outside of containment, should be used subsequently.
# the entire 'freed' directory should have been removed upon the next
# successful retrieval so that this scanner will succeed.
if ::File.file?(freed_metadata_json_path)
raise MetadataError, "Refused to overwrite already-generated metadata file: #{freed_metadata_json_path}"
end
# jail the repo using the legacy semantics for copying files in and out
# of jail.
copy_out = { jailed_metadata_json_path => freed_metadata_json_path }
# copy files into the jail once per repository (i.e. not once per
# cookbook within the repository).
if created
copy_in = generate_copy_in(@cookbook.repo_dir, jailed_repo_dir)
copy_in[src_knife_script_path] = dst_knife_script_path
# note that at this point we previously used Warden as a container
# for the copied-in files but now we assume that the current process
# is already in a container (i.e. Docker) and so this copying is
# more about creating a writable directory for knife than about
# containment. the checked-out repo should be read-only to this
# contained process due to running with limited privileges.
do_copy_in(copy_in)
end
# HACK: support ad-hoc testing in dev-mode by using the current version
# for rbenv shell.
if ::ENV['RBENV_VERSION'].to_s.empty?
ruby = 'ruby'
else
ruby = `which ruby`.chomp
end
# execute knife as a child process. any constraints are assumed to be
# imposed on the current process by a container (timeout, memory, etc.)
shell = ::RightGit::Shell::Default
output = StringIO.new
begin
shell.execute(
"#{ruby} #{dst_knife_script_path.inspect} #{jailed_cookbook_dir.inspect} 2>&1",
directory: dst_knife_script_dir,
outstream: output,
raise_on_failure: true,
set_env_vars: { LC_ALL: 'en_US.UTF-8' }, # character encoding for emitted JSON
clear_env_vars: %w{BUNDLE_BIN_PATH BUNDLE_GEMFILE},
timeout: KNIFE_METADATA_TIMEOUT)
output = output.string
rescue ::RightGit::Shell::ShellError => e
output = output.string
raise MetadataError, "Failed to run chef knife: #{e.message}\n#{output[0, 1024]}"
end
# free files from jail.
do_copy_out(copy_out)
# load and return freed metadata.
return ::File.read(freed_metadata_json_path)
end
end | [
"def",
"generate_metadata_json",
"@logger",
".",
"operation",
"(",
":metadata_generation",
")",
"do",
"tmpdir",
",",
"created",
"=",
"create_tmpdir",
"src_knife_script_path",
"=",
"::",
"File",
".",
"expand_path",
"(",
"::",
"File",
".",
"join",
"(",
"__FILE__",
",",
"'../../../../scripts'",
",",
"KNIFE_METADATA_SCRIPT_NAME",
")",
")",
"dst_knife_script_dir",
"=",
"tmpdir",
"dst_knife_script_path",
"=",
"::",
"File",
".",
"join",
"(",
"dst_knife_script_dir",
",",
"KNIFE_METADATA_SCRIPT_NAME",
")",
"jailed_repo_dir",
"=",
"::",
"File",
".",
"join",
"(",
"tmpdir",
",",
"UNDEFINED_COOKBOOK_NAME",
")",
"jailed_cookbook_dir",
"=",
"(",
"@cookbook",
".",
"pos",
"==",
"'.'",
"&&",
"jailed_repo_dir",
")",
"||",
"::",
"File",
".",
"join",
"(",
"jailed_repo_dir",
",",
"@cookbook",
".",
"pos",
")",
"jailed_metadata_json_path",
"=",
"::",
"File",
".",
"join",
"(",
"jailed_cookbook_dir",
",",
"JSON_METADATA",
")",
"freed_metadata_dir",
"=",
"(",
"@cookbook",
".",
"pos",
"==",
"'.'",
"&&",
"freed_dir",
")",
"||",
"::",
"File",
".",
"join",
"(",
"freed_dir",
",",
"@cookbook",
".",
"pos",
")",
"freed_metadata_json_path",
"=",
"::",
"File",
".",
"join",
"(",
"freed_metadata_dir",
",",
"JSON_METADATA",
")",
"if",
"::",
"File",
".",
"file?",
"(",
"freed_metadata_json_path",
")",
"raise",
"MetadataError",
",",
"\"Refused to overwrite already-generated metadata file: #{freed_metadata_json_path}\"",
"end",
"copy_out",
"=",
"{",
"jailed_metadata_json_path",
"=>",
"freed_metadata_json_path",
"}",
"if",
"created",
"copy_in",
"=",
"generate_copy_in",
"(",
"@cookbook",
".",
"repo_dir",
",",
"jailed_repo_dir",
")",
"copy_in",
"[",
"src_knife_script_path",
"]",
"=",
"dst_knife_script_path",
"do_copy_in",
"(",
"copy_in",
")",
"end",
"if",
"::",
"ENV",
"[",
"'RBENV_VERSION'",
"]",
".",
"to_s",
".",
"empty?",
"ruby",
"=",
"'ruby'",
"else",
"ruby",
"=",
"`",
"`",
".",
"chomp",
"end",
"shell",
"=",
"::",
"RightGit",
"::",
"Shell",
"::",
"Default",
"output",
"=",
"StringIO",
".",
"new",
"begin",
"shell",
".",
"execute",
"(",
"\"#{ruby} #{dst_knife_script_path.inspect} #{jailed_cookbook_dir.inspect} 2>&1\"",
",",
"directory",
":",
"dst_knife_script_dir",
",",
"outstream",
":",
"output",
",",
"raise_on_failure",
":",
"true",
",",
"set_env_vars",
":",
"{",
"LC_ALL",
":",
"'en_US.UTF-8'",
"}",
",",
"clear_env_vars",
":",
"%w{",
"BUNDLE_BIN_PATH",
"BUNDLE_GEMFILE",
"}",
",",
"timeout",
":",
"KNIFE_METADATA_TIMEOUT",
")",
"output",
"=",
"output",
".",
"string",
"rescue",
"::",
"RightGit",
"::",
"Shell",
"::",
"ShellError",
"=>",
"e",
"output",
"=",
"output",
".",
"string",
"raise",
"MetadataError",
",",
"\"Failed to run chef knife: #{e.message}\\n#{output[0, 1024]}\"",
"end",
"do_copy_out",
"(",
"copy_out",
")",
"return",
"::",
"File",
".",
"read",
"(",
"freed_metadata_json_path",
")",
"end",
"end"
]
| Executes the 'metadata.rb' file from a cookbook. Because we don't want
to evaluate arbitrary Ruby code, we need to sandbox it first.
in order for knife metadata to succeed in the general case we need to
copy some (but not all) of the cookbook directory AND its ancestors (if
any) into the container. we will try and restrict copying to what might
plausibly be referenced by 'metadata.rb' but this could be anything like
a LICENSE, README, etc. the best heuristic seems to be to copy any file
whose size is small (less than 128K) because 'metadata.rb' should not be
executing binaries and should only consume text files of a reasonable
size. if these restrictions cause a problem then the user is free to
pre-knife his own 'metadata.json' file and check it into the repo.
note the selection of the jailed cookbook dir is specific to the
behavior of knife metadata. the cookbook name is defined when the
'metadata.rb' declares the name attribute, but the name attribute is
optional. when no name attribute is declared, the metadata automagically
uses the parent directory name. this works okay so long as the parent
directory name is actually the cookbook name. in the case of a repo with
'metadata.rb' at the root (i.e. no checked-in parent directory) then the
cookbook name is undefined. in this case, we want the cookbook name to
be 'undefined' to remind the user to declare the name explicitly.
=== Returns
@return [String] metadata JSON text | [
"Executes",
"the",
"metadata",
".",
"rb",
"file",
"from",
"a",
"cookbook",
".",
"Because",
"we",
"don",
"t",
"want",
"to",
"evaluate",
"arbitrary",
"Ruby",
"code",
"we",
"need",
"to",
"sandbox",
"it",
"first",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata.rb#L192-L271 | train |
rightscale/right_scraper | lib/right_scraper/scanners/cookbook_metadata.rb | RightScraper::Scanners.CookbookMetadata.do_copy_in | def do_copy_in(path_map)
path_map.each do |src_path, dst_path|
if src_path != dst_path
::FileUtils.mkdir_p(::File.dirname(dst_path))
::FileUtils.cp(src_path, dst_path)
end
end
true
end | ruby | def do_copy_in(path_map)
path_map.each do |src_path, dst_path|
if src_path != dst_path
::FileUtils.mkdir_p(::File.dirname(dst_path))
::FileUtils.cp(src_path, dst_path)
end
end
true
end | [
"def",
"do_copy_in",
"(",
"path_map",
")",
"path_map",
".",
"each",
"do",
"|",
"src_path",
",",
"dst_path",
"|",
"if",
"src_path",
"!=",
"dst_path",
"::",
"FileUtils",
".",
"mkdir_p",
"(",
"::",
"File",
".",
"dirname",
"(",
"dst_path",
")",
")",
"::",
"FileUtils",
".",
"cp",
"(",
"src_path",
",",
"dst_path",
")",
"end",
"end",
"true",
"end"
]
| copies files into jail. we no longer start a new container so this is only
a local file copying operation. we still need files to appear in a
writable directory location because knife will write to the directory. | [
"copies",
"files",
"into",
"jail",
".",
"we",
"no",
"longer",
"start",
"a",
"new",
"container",
"so",
"this",
"is",
"only",
"a",
"local",
"file",
"copying",
"operation",
".",
"we",
"still",
"need",
"files",
"to",
"appear",
"in",
"a",
"writable",
"directory",
"location",
"because",
"knife",
"will",
"write",
"to",
"the",
"directory",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata.rb#L276-L284 | train |
rightscale/right_scraper | lib/right_scraper/scanners/cookbook_metadata.rb | RightScraper::Scanners.CookbookMetadata.do_copy_out | def do_copy_out(path_map)
path_map.each do |src_path, dst_path|
# constraining the generated 'metadata.json' size is debatable, but
# our UI attempts to load metadata JSON into memory far too often to
# be blasé about generating multi-megabyte JSON files.
unless ::File.file?(src_path)
raise MetadataError, "Expected generated file was not found: #{src_path}"
end
src_size = ::File.stat(src_path).size
if src_size <= FREED_FILE_SIZE_CONSTRAINT
::FileUtils.mkdir_p(::File.dirname(dst_path))
::FileUtils.cp(src_path, dst_path)
else
raise MetadataError,
"Generated file size of" +
" #{src_size / 1024} KB" +
" exceeded the allowed limit of" +
" #{FREED_FILE_SIZE_CONSTRAINT / 1024} KB"
end
end
true
end | ruby | def do_copy_out(path_map)
path_map.each do |src_path, dst_path|
# constraining the generated 'metadata.json' size is debatable, but
# our UI attempts to load metadata JSON into memory far too often to
# be blasé about generating multi-megabyte JSON files.
unless ::File.file?(src_path)
raise MetadataError, "Expected generated file was not found: #{src_path}"
end
src_size = ::File.stat(src_path).size
if src_size <= FREED_FILE_SIZE_CONSTRAINT
::FileUtils.mkdir_p(::File.dirname(dst_path))
::FileUtils.cp(src_path, dst_path)
else
raise MetadataError,
"Generated file size of" +
" #{src_size / 1024} KB" +
" exceeded the allowed limit of" +
" #{FREED_FILE_SIZE_CONSTRAINT / 1024} KB"
end
end
true
end | [
"def",
"do_copy_out",
"(",
"path_map",
")",
"path_map",
".",
"each",
"do",
"|",
"src_path",
",",
"dst_path",
"|",
"unless",
"::",
"File",
".",
"file?",
"(",
"src_path",
")",
"raise",
"MetadataError",
",",
"\"Expected generated file was not found: #{src_path}\"",
"end",
"src_size",
"=",
"::",
"File",
".",
"stat",
"(",
"src_path",
")",
".",
"size",
"if",
"src_size",
"<=",
"FREED_FILE_SIZE_CONSTRAINT",
"::",
"FileUtils",
".",
"mkdir_p",
"(",
"::",
"File",
".",
"dirname",
"(",
"dst_path",
")",
")",
"::",
"FileUtils",
".",
"cp",
"(",
"src_path",
",",
"dst_path",
")",
"else",
"raise",
"MetadataError",
",",
"\"Generated file size of\"",
"+",
"\" #{src_size / 1024} KB\"",
"+",
"\" exceeded the allowed limit of\"",
"+",
"\" #{FREED_FILE_SIZE_CONSTRAINT / 1024} KB\"",
"end",
"end",
"true",
"end"
]
| copies files out of jail by mapping of jail to free path. | [
"copies",
"files",
"out",
"of",
"jail",
"by",
"mapping",
"of",
"jail",
"to",
"free",
"path",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata.rb#L287-L308 | train |
rightscale/right_scraper | lib/right_scraper/scanners/cookbook_metadata.rb | RightScraper::Scanners.CookbookMetadata.generate_copy_in | def generate_copy_in(src_base_path, dst_base_path)
src_base_path = ::File.expand_path(src_base_path)
dst_base_path = ::File.expand_path(dst_base_path)
copy_in = []
recursive_generate_copy_in(copy_in, src_base_path)
src_base_path += '/'
src_base_path_len = src_base_path.length
dst_base_path += '/'
copy_in.inject({}) do |h, src_path|
h[src_path] = ::File.join(dst_base_path, src_path[src_base_path_len..-1])
h
end
end | ruby | def generate_copy_in(src_base_path, dst_base_path)
src_base_path = ::File.expand_path(src_base_path)
dst_base_path = ::File.expand_path(dst_base_path)
copy_in = []
recursive_generate_copy_in(copy_in, src_base_path)
src_base_path += '/'
src_base_path_len = src_base_path.length
dst_base_path += '/'
copy_in.inject({}) do |h, src_path|
h[src_path] = ::File.join(dst_base_path, src_path[src_base_path_len..-1])
h
end
end | [
"def",
"generate_copy_in",
"(",
"src_base_path",
",",
"dst_base_path",
")",
"src_base_path",
"=",
"::",
"File",
".",
"expand_path",
"(",
"src_base_path",
")",
"dst_base_path",
"=",
"::",
"File",
".",
"expand_path",
"(",
"dst_base_path",
")",
"copy_in",
"=",
"[",
"]",
"recursive_generate_copy_in",
"(",
"copy_in",
",",
"src_base_path",
")",
"src_base_path",
"+=",
"'/'",
"src_base_path_len",
"=",
"src_base_path",
".",
"length",
"dst_base_path",
"+=",
"'/'",
"copy_in",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"h",
",",
"src_path",
"|",
"h",
"[",
"src_path",
"]",
"=",
"::",
"File",
".",
"join",
"(",
"dst_base_path",
",",
"src_path",
"[",
"src_base_path_len",
"..",
"-",
"1",
"]",
")",
"h",
"end",
"end"
]
| need to enumerate files relative to the cookbook directory because we
have no idea what the metadata script will attempt to consume from the
files available in its repository. it may even attempt to manipulate
files in the system or go out to the network, which may or may not be
allowed by the conditions of the jail.
some cookbooks (for Windows, especially) will have large binaries
included in the repository. we don't want to spend time copying these
files into jail so limit the files that metadata can reference by size.
presumably the jail would also be limiting disk space so it is important
to avoid this source of failure.
again, the user can work around these contraints by generating his own
metadata and checking it into the repository.
@return [Hash] path_map as map of source to destination file paths | [
"need",
"to",
"enumerate",
"files",
"relative",
"to",
"the",
"cookbook",
"directory",
"because",
"we",
"have",
"no",
"idea",
"what",
"the",
"metadata",
"script",
"will",
"attempt",
"to",
"consume",
"from",
"the",
"files",
"available",
"in",
"its",
"repository",
".",
"it",
"may",
"even",
"attempt",
"to",
"manipulate",
"files",
"in",
"the",
"system",
"or",
"go",
"out",
"to",
"the",
"network",
"which",
"may",
"or",
"may",
"not",
"be",
"allowed",
"by",
"the",
"conditions",
"of",
"the",
"jail",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata.rb#L326-L339 | train |
rightscale/right_scraper | lib/right_scraper/scanners/cookbook_metadata.rb | RightScraper::Scanners.CookbookMetadata.recursive_generate_copy_in | def recursive_generate_copy_in(copy_in, current_path)
limited_files_of(current_path) { |file| copy_in << file }
directories_of(current_path) do |dir|
recursive_generate_copy_in(copy_in, ::File.join(dir))
end
true
end | ruby | def recursive_generate_copy_in(copy_in, current_path)
limited_files_of(current_path) { |file| copy_in << file }
directories_of(current_path) do |dir|
recursive_generate_copy_in(copy_in, ::File.join(dir))
end
true
end | [
"def",
"recursive_generate_copy_in",
"(",
"copy_in",
",",
"current_path",
")",
"limited_files_of",
"(",
"current_path",
")",
"{",
"|",
"file",
"|",
"copy_in",
"<<",
"file",
"}",
"directories_of",
"(",
"current_path",
")",
"do",
"|",
"dir",
"|",
"recursive_generate_copy_in",
"(",
"copy_in",
",",
"::",
"File",
".",
"join",
"(",
"dir",
")",
")",
"end",
"true",
"end"
]
| recursive part of generate_copy_in | [
"recursive",
"part",
"of",
"generate_copy_in"
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata.rb#L342-L348 | train |
rightscale/right_scraper | lib/right_scraper/scanners/cookbook_metadata.rb | RightScraper::Scanners.CookbookMetadata.limited_files_of | def limited_files_of(parent)
::Dir["#{parent}/*"].each do |item|
if ::File.file?(item)
if ::File.stat(item).size <= JAILED_FILE_SIZE_CONSTRAINT
yield item
else
if ::File.basename(item) == RUBY_METADATA
raise MetadataError,
'Metadata source file' +
" #{relative_to_repo_dir(item).inspect}" +
' in repository exceeded size constraint of' +
" #{JAILED_FILE_SIZE_CONSTRAINT / 1024} KB"
else
message = 'Ignored a repository file during metadata' +
' generation due to exceeding size constraint of' +
" #{JAILED_FILE_SIZE_CONSTRAINT / 1024} KB:" +
" #{relative_to_repo_dir(item).inspect}"
@logger.info(message)
end
end
end
end
end | ruby | def limited_files_of(parent)
::Dir["#{parent}/*"].each do |item|
if ::File.file?(item)
if ::File.stat(item).size <= JAILED_FILE_SIZE_CONSTRAINT
yield item
else
if ::File.basename(item) == RUBY_METADATA
raise MetadataError,
'Metadata source file' +
" #{relative_to_repo_dir(item).inspect}" +
' in repository exceeded size constraint of' +
" #{JAILED_FILE_SIZE_CONSTRAINT / 1024} KB"
else
message = 'Ignored a repository file during metadata' +
' generation due to exceeding size constraint of' +
" #{JAILED_FILE_SIZE_CONSTRAINT / 1024} KB:" +
" #{relative_to_repo_dir(item).inspect}"
@logger.info(message)
end
end
end
end
end | [
"def",
"limited_files_of",
"(",
"parent",
")",
"::",
"Dir",
"[",
"\"#{parent}/*\"",
"]",
".",
"each",
"do",
"|",
"item",
"|",
"if",
"::",
"File",
".",
"file?",
"(",
"item",
")",
"if",
"::",
"File",
".",
"stat",
"(",
"item",
")",
".",
"size",
"<=",
"JAILED_FILE_SIZE_CONSTRAINT",
"yield",
"item",
"else",
"if",
"::",
"File",
".",
"basename",
"(",
"item",
")",
"==",
"RUBY_METADATA",
"raise",
"MetadataError",
",",
"'Metadata source file'",
"+",
"\" #{relative_to_repo_dir(item).inspect}\"",
"+",
"' in repository exceeded size constraint of'",
"+",
"\" #{JAILED_FILE_SIZE_CONSTRAINT / 1024} KB\"",
"else",
"message",
"=",
"'Ignored a repository file during metadata'",
"+",
"' generation due to exceeding size constraint of'",
"+",
"\" #{JAILED_FILE_SIZE_CONSTRAINT / 1024} KB:\"",
"+",
"\" #{relative_to_repo_dir(item).inspect}\"",
"@logger",
".",
"info",
"(",
"message",
")",
"end",
"end",
"end",
"end",
"end"
]
| yields files in parent meeting size criteria. | [
"yields",
"files",
"in",
"parent",
"meeting",
"size",
"criteria",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata.rb#L351-L373 | train |
rightscale/right_scraper | lib/right_scraper/scanners/cookbook_metadata.rb | RightScraper::Scanners.CookbookMetadata.directories_of | def directories_of(parent)
::Dir["#{parent}/*"].each do |item|
case item
when '.', '..'
# do nothing
else
yield item if ::File.directory?(item)
end
end
end | ruby | def directories_of(parent)
::Dir["#{parent}/*"].each do |item|
case item
when '.', '..'
# do nothing
else
yield item if ::File.directory?(item)
end
end
end | [
"def",
"directories_of",
"(",
"parent",
")",
"::",
"Dir",
"[",
"\"#{parent}/*\"",
"]",
".",
"each",
"do",
"|",
"item",
"|",
"case",
"item",
"when",
"'.'",
",",
"'..'",
"else",
"yield",
"item",
"if",
"::",
"File",
".",
"directory?",
"(",
"item",
")",
"end",
"end",
"end"
]
| yields directories of parent. | [
"yields",
"directories",
"of",
"parent",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata.rb#L376-L385 | train |
rightscale/right_scraper | lib/right_scraper/retrievers/checkout_base.rb | RightScraper::Retrievers.CheckoutBase.retrieve | def retrieve
raise RetrieverError.new("retriever is unavailable") unless available?
updated = false
explanation = ''
if exists?
@logger.operation(:updating) do
# a retriever may be able to determine that the repo directory is
# already pointing to the same commit as the revision. in that case
# we can return quickly.
if remote_differs?
# there is no point in updating and failing the size check when the
# directory on disk already exceeds size limit; fall back to a clean
# checkout in hopes that the latest revision corrects the issue.
if size_limit_exceeded?
explanation = 'switching to checkout due to existing directory exceeding size limimt'
else
# attempt update.
begin
do_update
updated = true
rescue ::RightScraper::Processes::Shell::LimitError
# update exceeded a limitation; requires user intervention
raise
rescue Exception => e
# retry with clean checkout after discarding repo dir.
explanation = 'switching to checkout after unsuccessful update'
end
end
else
# no retrieval needed but warn exactly why we didn't do full
# checkout to avoid being challenged about it.
repo_ref = @repository.tag
do_update_tag
full_head_ref = @repository.tag
abbreviated_head_ref = full_head_ref[0..6]
if repo_ref == full_head_ref || repo_ref == abbreviated_head_ref
detail = abbreviated_head_ref
else
detail = "#{repo_ref} = #{abbreviated_head_ref}"
end
message =
"Skipped updating local directory due to the HEAD commit SHA " +
"on local matching the remote repository reference (#{detail})."
@logger.note_warning(message)
return false
end
end
end
# Clean checkout only if not updated.
unless updated
@logger.operation(:checkout, explanation) do
# remove any full or partial directory before attempting a clean
# checkout in case repo_dir is in a bad state.
if exists?
::FileUtils.remove_entry_secure(@repo_dir)
end
::FileUtils.mkdir_p(@repo_dir)
begin
do_checkout
rescue Exception
# clean checkout failed; repo directory is in an undetermined
# state and must be deleted to prevent a future update attempt.
if exists?
::FileUtils.remove_entry_secure(@repo_dir) rescue nil
end
raise
end
end
end
true
end | ruby | def retrieve
raise RetrieverError.new("retriever is unavailable") unless available?
updated = false
explanation = ''
if exists?
@logger.operation(:updating) do
# a retriever may be able to determine that the repo directory is
# already pointing to the same commit as the revision. in that case
# we can return quickly.
if remote_differs?
# there is no point in updating and failing the size check when the
# directory on disk already exceeds size limit; fall back to a clean
# checkout in hopes that the latest revision corrects the issue.
if size_limit_exceeded?
explanation = 'switching to checkout due to existing directory exceeding size limimt'
else
# attempt update.
begin
do_update
updated = true
rescue ::RightScraper::Processes::Shell::LimitError
# update exceeded a limitation; requires user intervention
raise
rescue Exception => e
# retry with clean checkout after discarding repo dir.
explanation = 'switching to checkout after unsuccessful update'
end
end
else
# no retrieval needed but warn exactly why we didn't do full
# checkout to avoid being challenged about it.
repo_ref = @repository.tag
do_update_tag
full_head_ref = @repository.tag
abbreviated_head_ref = full_head_ref[0..6]
if repo_ref == full_head_ref || repo_ref == abbreviated_head_ref
detail = abbreviated_head_ref
else
detail = "#{repo_ref} = #{abbreviated_head_ref}"
end
message =
"Skipped updating local directory due to the HEAD commit SHA " +
"on local matching the remote repository reference (#{detail})."
@logger.note_warning(message)
return false
end
end
end
# Clean checkout only if not updated.
unless updated
@logger.operation(:checkout, explanation) do
# remove any full or partial directory before attempting a clean
# checkout in case repo_dir is in a bad state.
if exists?
::FileUtils.remove_entry_secure(@repo_dir)
end
::FileUtils.mkdir_p(@repo_dir)
begin
do_checkout
rescue Exception
# clean checkout failed; repo directory is in an undetermined
# state and must be deleted to prevent a future update attempt.
if exists?
::FileUtils.remove_entry_secure(@repo_dir) rescue nil
end
raise
end
end
end
true
end | [
"def",
"retrieve",
"raise",
"RetrieverError",
".",
"new",
"(",
"\"retriever is unavailable\"",
")",
"unless",
"available?",
"updated",
"=",
"false",
"explanation",
"=",
"''",
"if",
"exists?",
"@logger",
".",
"operation",
"(",
":updating",
")",
"do",
"if",
"remote_differs?",
"if",
"size_limit_exceeded?",
"explanation",
"=",
"'switching to checkout due to existing directory exceeding size limimt'",
"else",
"begin",
"do_update",
"updated",
"=",
"true",
"rescue",
"::",
"RightScraper",
"::",
"Processes",
"::",
"Shell",
"::",
"LimitError",
"raise",
"rescue",
"Exception",
"=>",
"e",
"explanation",
"=",
"'switching to checkout after unsuccessful update'",
"end",
"end",
"else",
"repo_ref",
"=",
"@repository",
".",
"tag",
"do_update_tag",
"full_head_ref",
"=",
"@repository",
".",
"tag",
"abbreviated_head_ref",
"=",
"full_head_ref",
"[",
"0",
"..",
"6",
"]",
"if",
"repo_ref",
"==",
"full_head_ref",
"||",
"repo_ref",
"==",
"abbreviated_head_ref",
"detail",
"=",
"abbreviated_head_ref",
"else",
"detail",
"=",
"\"#{repo_ref} = #{abbreviated_head_ref}\"",
"end",
"message",
"=",
"\"Skipped updating local directory due to the HEAD commit SHA \"",
"+",
"\"on local matching the remote repository reference (#{detail}).\"",
"@logger",
".",
"note_warning",
"(",
"message",
")",
"return",
"false",
"end",
"end",
"end",
"unless",
"updated",
"@logger",
".",
"operation",
"(",
":checkout",
",",
"explanation",
")",
"do",
"if",
"exists?",
"::",
"FileUtils",
".",
"remove_entry_secure",
"(",
"@repo_dir",
")",
"end",
"::",
"FileUtils",
".",
"mkdir_p",
"(",
"@repo_dir",
")",
"begin",
"do_checkout",
"rescue",
"Exception",
"if",
"exists?",
"::",
"FileUtils",
".",
"remove_entry_secure",
"(",
"@repo_dir",
")",
"rescue",
"nil",
"end",
"raise",
"end",
"end",
"end",
"true",
"end"
]
| Attempts to update and then resorts to clean checkout for repository. | [
"Attempts",
"to",
"update",
"and",
"then",
"resorts",
"to",
"clean",
"checkout",
"for",
"repository",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/checkout_base.rb#L39-L110 | train |
rightscale/right_scraper | lib/right_scraper/retrievers/checkout_base.rb | RightScraper::Retrievers.CheckoutBase.size_limit_exceeded? | def size_limit_exceeded?
if @max_bytes
# note that Dir.glob ignores hidden directories (e.g. ".git") so the
# size total correctly excludes those hidden contents that are not to
# be uploaded after scrape. this may cause the on-disk directory size
# to far exceed the upload size.
globbie = ::File.join(@repo_dir, '**/*')
size = 0
::Dir.glob(globbie) do |f|
size += ::File.stat(f).size rescue 0 if ::File.file?(f)
break if size > @max_bytes
end
size > @max_bytes
else
false
end
end | ruby | def size_limit_exceeded?
if @max_bytes
# note that Dir.glob ignores hidden directories (e.g. ".git") so the
# size total correctly excludes those hidden contents that are not to
# be uploaded after scrape. this may cause the on-disk directory size
# to far exceed the upload size.
globbie = ::File.join(@repo_dir, '**/*')
size = 0
::Dir.glob(globbie) do |f|
size += ::File.stat(f).size rescue 0 if ::File.file?(f)
break if size > @max_bytes
end
size > @max_bytes
else
false
end
end | [
"def",
"size_limit_exceeded?",
"if",
"@max_bytes",
"globbie",
"=",
"::",
"File",
".",
"join",
"(",
"@repo_dir",
",",
"'**/*'",
")",
"size",
"=",
"0",
"::",
"Dir",
".",
"glob",
"(",
"globbie",
")",
"do",
"|",
"f",
"|",
"size",
"+=",
"::",
"File",
".",
"stat",
"(",
"f",
")",
".",
"size",
"rescue",
"0",
"if",
"::",
"File",
".",
"file?",
"(",
"f",
")",
"break",
"if",
"size",
">",
"@max_bytes",
"end",
"size",
">",
"@max_bytes",
"else",
"false",
"end",
"end"
]
| Determines if total size of files in repo_dir has exceeded size limit.
=== Return
@return [TrueClass|FalseClass] true if size limit exceeded | [
"Determines",
"if",
"total",
"size",
"of",
"files",
"in",
"repo_dir",
"has",
"exceeded",
"size",
"limit",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/checkout_base.rb#L135-L151 | train |
rightscale/right_scraper | lib/right_scraper/resources/cookbook.rb | RightScraper::Resources.Cookbook.to_hash | def to_hash
{
repository: repository,
resource_hash: resource_hash, # location of cookbook manifest in S3
metadata: ::JSON.dump(metadata), # pass as opaque JSON blob
pos: pos
}
end | ruby | def to_hash
{
repository: repository,
resource_hash: resource_hash, # location of cookbook manifest in S3
metadata: ::JSON.dump(metadata), # pass as opaque JSON blob
pos: pos
}
end | [
"def",
"to_hash",
"{",
"repository",
":",
"repository",
",",
"resource_hash",
":",
"resource_hash",
",",
"metadata",
":",
"::",
"JSON",
".",
"dump",
"(",
"metadata",
")",
",",
"pos",
":",
"pos",
"}",
"end"
]
| marshal cookbook to hash | [
"marshal",
"cookbook",
"to",
"hash"
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/resources/cookbook.rb#L72-L79 | train |
rightscale/right_git | lib/right_git/git/branch_collection.rb | RightGit::Git.BranchCollection.current | def current
lines = @repo.git_output(['symbolic-ref', 'HEAD'], :raise_on_failure => false).lines
if lines.size == 1
line = lines.first.strip
if (match = HEAD_REF.match(line))
@branches.detect { |b| b.fullname == match[1] }
elsif line == NO_HEAD_REF
nil
end
else
raise GitError, "Unexpected output from 'git symbolic-ref'; need 1 lines, got #{lines.size}"
end
end | ruby | def current
lines = @repo.git_output(['symbolic-ref', 'HEAD'], :raise_on_failure => false).lines
if lines.size == 1
line = lines.first.strip
if (match = HEAD_REF.match(line))
@branches.detect { |b| b.fullname == match[1] }
elsif line == NO_HEAD_REF
nil
end
else
raise GitError, "Unexpected output from 'git symbolic-ref'; need 1 lines, got #{lines.size}"
end
end | [
"def",
"current",
"lines",
"=",
"@repo",
".",
"git_output",
"(",
"[",
"'symbolic-ref'",
",",
"'HEAD'",
"]",
",",
":raise_on_failure",
"=>",
"false",
")",
".",
"lines",
"if",
"lines",
".",
"size",
"==",
"1",
"line",
"=",
"lines",
".",
"first",
".",
"strip",
"if",
"(",
"match",
"=",
"HEAD_REF",
".",
"match",
"(",
"line",
")",
")",
"@branches",
".",
"detect",
"{",
"|",
"b",
"|",
"b",
".",
"fullname",
"==",
"match",
"[",
"1",
"]",
"}",
"elsif",
"line",
"==",
"NO_HEAD_REF",
"nil",
"end",
"else",
"raise",
"GitError",
",",
"\"Unexpected output from 'git symbolic-ref'; need 1 lines, got #{lines.size}\"",
"end",
"end"
]
| Return a Branch object representing whichever branch is currently checked out, IF AND ONLY IF
that branch is a member of the collection. If the current branch isn't part of the collection
or HEAD refers to something other than a branch, return nil.
@return [Branch] the current branch if any, nil otherwise | [
"Return",
"a",
"Branch",
"object",
"representing",
"whichever",
"branch",
"is",
"currently",
"checked",
"out",
"IF",
"AND",
"ONLY",
"IF",
"that",
"branch",
"is",
"a",
"member",
"of",
"the",
"collection",
".",
"If",
"the",
"current",
"branch",
"isn",
"t",
"part",
"of",
"the",
"collection",
"or",
"HEAD",
"refers",
"to",
"something",
"other",
"than",
"a",
"branch",
"return",
"nil",
"."
]
| 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/branch_collection.rb#L92-L105 | train |
rightscale/right_git | lib/right_git/git/branch_collection.rb | RightGit::Git.BranchCollection.merged | def merged(revision)
# By hand, build a list of all branches known to be merged into master
git_args = ['branch', '-a', '--merged', revision]
all_merged = []
@repo.git_output(git_args).lines.each do |line|
line.strip!
all_merged << Branch.new(@repo, line)
end
# Filter the contents of this collection according to the big list
merged = []
@branches.each do |candidate|
# For some reason Set#include? does not play nice with our overridden comparison operators
# for branches, so we need to do this the hard way :(
merged << candidate if all_merged.detect { |b| candidate == b }
end
BranchCollection.new(@repo, merged)
end | ruby | def merged(revision)
# By hand, build a list of all branches known to be merged into master
git_args = ['branch', '-a', '--merged', revision]
all_merged = []
@repo.git_output(git_args).lines.each do |line|
line.strip!
all_merged << Branch.new(@repo, line)
end
# Filter the contents of this collection according to the big list
merged = []
@branches.each do |candidate|
# For some reason Set#include? does not play nice with our overridden comparison operators
# for branches, so we need to do this the hard way :(
merged << candidate if all_merged.detect { |b| candidate == b }
end
BranchCollection.new(@repo, merged)
end | [
"def",
"merged",
"(",
"revision",
")",
"git_args",
"=",
"[",
"'branch'",
",",
"'-a'",
",",
"'--merged'",
",",
"revision",
"]",
"all_merged",
"=",
"[",
"]",
"@repo",
".",
"git_output",
"(",
"git_args",
")",
".",
"lines",
".",
"each",
"do",
"|",
"line",
"|",
"line",
".",
"strip!",
"all_merged",
"<<",
"Branch",
".",
"new",
"(",
"@repo",
",",
"line",
")",
"end",
"merged",
"=",
"[",
"]",
"@branches",
".",
"each",
"do",
"|",
"candidate",
"|",
"merged",
"<<",
"candidate",
"if",
"all_merged",
".",
"detect",
"{",
"|",
"b",
"|",
"candidate",
"==",
"b",
"}",
"end",
"BranchCollection",
".",
"new",
"(",
"@repo",
",",
"merged",
")",
"end"
]
| Queries and filters on branches reachable from the given revision, if any.
@param [String] revision for listing reachable merged branches
@return [BranchCollection] merged branches | [
"Queries",
"and",
"filters",
"on",
"branches",
"reachable",
"from",
"the",
"given",
"revision",
"if",
"any",
"."
]
| 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/branch_collection.rb#L138-L156 | train |
rightscale/right_git | lib/right_git/git/branch_collection.rb | RightGit::Git.BranchCollection.[] | def [](argument)
case argument
when String
target = Branch.new(@repo, argument)
@branches.detect { |b| b == target }
else
@branches.__send__(:[], argument)
end
end | ruby | def [](argument)
case argument
when String
target = Branch.new(@repo, argument)
@branches.detect { |b| b == target }
else
@branches.__send__(:[], argument)
end
end | [
"def",
"[]",
"(",
"argument",
")",
"case",
"argument",
"when",
"String",
"target",
"=",
"Branch",
".",
"new",
"(",
"@repo",
",",
"argument",
")",
"@branches",
".",
"detect",
"{",
"|",
"b",
"|",
"b",
"==",
"target",
"}",
"else",
"@branches",
".",
"__send__",
"(",
":[]",
",",
"argument",
")",
"end",
"end"
]
| Accessor that acts like either a Hash or Array accessor | [
"Accessor",
"that",
"acts",
"like",
"either",
"a",
"Hash",
"or",
"Array",
"accessor"
]
| 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/branch_collection.rb#L159-L167 | train |
rightscale/right_git | lib/right_git/git/branch_collection.rb | RightGit::Git.BranchCollection.method_missing | def method_missing(meth, *args, &block)
result = @branches.__send__(meth, *args, &block)
if result.is_a?(::Array)
BranchCollection.new(@repo, result)
else
result
end
end | ruby | def method_missing(meth, *args, &block)
result = @branches.__send__(meth, *args, &block)
if result.is_a?(::Array)
BranchCollection.new(@repo, result)
else
result
end
end | [
"def",
"method_missing",
"(",
"meth",
",",
"*",
"args",
",",
"&",
"block",
")",
"result",
"=",
"@branches",
".",
"__send__",
"(",
"meth",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"result",
".",
"is_a?",
"(",
"::",
"Array",
")",
"BranchCollection",
".",
"new",
"(",
"@repo",
",",
"result",
")",
"else",
"result",
"end",
"end"
]
| Dispatch to the underlying Array of Branch objects, allowing the branch collection to act a
bit like an Array.
If the dispatched-to method returns an Array, it is wrapped in another BranchCollection object
before returning to the caller. This allows array-like method calls to be chained together
without losing the BranchCollection-ness of the underlying object. | [
"Dispatch",
"to",
"the",
"underlying",
"Array",
"of",
"Branch",
"objects",
"allowing",
"the",
"branch",
"collection",
"to",
"act",
"a",
"bit",
"like",
"an",
"Array",
"."
]
| 285f33996f56f08bc3f62b216695a6dbff12151d | https://github.com/rightscale/right_git/blob/285f33996f56f08bc3f62b216695a6dbff12151d/lib/right_git/git/branch_collection.rb#L175-L183 | train |
rightscale/right_scraper | lib/right_scraper/scanners/cookbook_s3_upload.rb | RightScraper::Scanners.CookbookS3Upload.notice | def notice(relative_position)
contents = yield
name = Digest::MD5.hexdigest(contents)
path = File.join('Files', name)
unless @bucket.key(path).exists?
@bucket.put(path, contents)
end
end | ruby | def notice(relative_position)
contents = yield
name = Digest::MD5.hexdigest(contents)
path = File.join('Files', name)
unless @bucket.key(path).exists?
@bucket.put(path, contents)
end
end | [
"def",
"notice",
"(",
"relative_position",
")",
"contents",
"=",
"yield",
"name",
"=",
"Digest",
"::",
"MD5",
".",
"hexdigest",
"(",
"contents",
")",
"path",
"=",
"File",
".",
"join",
"(",
"'Files'",
",",
"name",
")",
"unless",
"@bucket",
".",
"key",
"(",
"path",
")",
".",
"exists?",
"@bucket",
".",
"put",
"(",
"path",
",",
"contents",
")",
"end",
"end"
]
| Upload a file during scanning.
=== Block
Return the data for this file. We use a block because it may
not always be necessary to read the data.
=== Parameters
relative_position(String):: relative pathname for file from root of cookbook | [
"Upload",
"a",
"file",
"during",
"scanning",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_s3_upload.rb#L79-L86 | train |
noprompt/vic | lib/vic/color.rb | Vic.Color.to_gui | def to_gui
return to_standard_hex if hexadecimal?
return Convert.xterm_to_hex(@value) if cterm?
return :NONE if none?
raise ColorError.new "can't convert \"#{ @value }\" to gui"
end | ruby | def to_gui
return to_standard_hex if hexadecimal?
return Convert.xterm_to_hex(@value) if cterm?
return :NONE if none?
raise ColorError.new "can't convert \"#{ @value }\" to gui"
end | [
"def",
"to_gui",
"return",
"to_standard_hex",
"if",
"hexadecimal?",
"return",
"Convert",
".",
"xterm_to_hex",
"(",
"@value",
")",
"if",
"cterm?",
"return",
":NONE",
"if",
"none?",
"raise",
"ColorError",
".",
"new",
"\"can't convert \\\"#{ @value }\\\" to gui\"",
"end"
]
| Convert the color value to a hexadecimal color
@return [Symbol,String]
the color as either "NONE" or hexadecimal
@api public | [
"Convert",
"the",
"color",
"value",
"to",
"a",
"hexadecimal",
"color"
]
| 276e18fc5d81727023d3abfdf95829648818a9c4 | https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/color.rb#L17-L23 | train |
noprompt/vic | lib/vic/color.rb | Vic.Color.to_cterm | def to_cterm
return @value if cterm?
return Convert.hex_to_xterm(to_standard_hex) if hexadecimal?
return :NONE if none?
raise ColorError.new "can't convert \"#{ @value }\" to cterm"
end | ruby | def to_cterm
return @value if cterm?
return Convert.hex_to_xterm(to_standard_hex) if hexadecimal?
return :NONE if none?
raise ColorError.new "can't convert \"#{ @value }\" to cterm"
end | [
"def",
"to_cterm",
"return",
"@value",
"if",
"cterm?",
"return",
"Convert",
".",
"hex_to_xterm",
"(",
"to_standard_hex",
")",
"if",
"hexadecimal?",
"return",
":NONE",
"if",
"none?",
"raise",
"ColorError",
".",
"new",
"\"can't convert \\\"#{ @value }\\\" to cterm\"",
"end"
]
| Convert the color value to a cterm compatible color
@return [Fixnum]
the color as either "NONE" or cterm color
@api public | [
"Convert",
"the",
"color",
"value",
"to",
"a",
"cterm",
"compatible",
"color"
]
| 276e18fc5d81727023d3abfdf95829648818a9c4 | https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/color.rb#L31-L37 | train |
noprompt/vic | lib/vic/color.rb | Vic.Color.to_standard_hex | def to_standard_hex
color = @value.dup
color.insert(0, '#') unless color.start_with? '#'
# Convert shorthand hex to standard hex.
if color.size == 4
color.slice!(1, 3).chars { |char| color << char * 2 }
end
color
end | ruby | def to_standard_hex
color = @value.dup
color.insert(0, '#') unless color.start_with? '#'
# Convert shorthand hex to standard hex.
if color.size == 4
color.slice!(1, 3).chars { |char| color << char * 2 }
end
color
end | [
"def",
"to_standard_hex",
"color",
"=",
"@value",
".",
"dup",
"color",
".",
"insert",
"(",
"0",
",",
"'#'",
")",
"unless",
"color",
".",
"start_with?",
"'#'",
"if",
"color",
".",
"size",
"==",
"4",
"color",
".",
"slice!",
"(",
"1",
",",
"3",
")",
".",
"chars",
"{",
"|",
"char",
"|",
"color",
"<<",
"char",
"*",
"2",
"}",
"end",
"color",
"end"
]
| Convert the color value to a standard hexadecimal value
@example
Color.new('333').send(:to_standard_hex) # => '#333333'
@return [String]
the color in standard hexadecimal format
@api private | [
"Convert",
"the",
"color",
"value",
"to",
"a",
"standard",
"hexadecimal",
"value"
]
| 276e18fc5d81727023d3abfdf95829648818a9c4 | https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/color.rb#L93-L102 | train |
rightscale/right_scraper | lib/right_scraper/retrievers/svn.rb | RightScraper::Retrievers.Svn.resolve_revision | def resolve_revision
revision = @repository.tag.to_s.strip
if revision.empty?
revision = nil
elsif (revision =~ SVN_REVISION_REGEX).nil?
raise RetrieverError, "Revision reference contained illegal characters: #{revision.inspect}"
end
# timestamps can contain spaces; surround them with double quotes.
revision = revision.inspect if revision.index(' ')
revision
end | ruby | def resolve_revision
revision = @repository.tag.to_s.strip
if revision.empty?
revision = nil
elsif (revision =~ SVN_REVISION_REGEX).nil?
raise RetrieverError, "Revision reference contained illegal characters: #{revision.inspect}"
end
# timestamps can contain spaces; surround them with double quotes.
revision = revision.inspect if revision.index(' ')
revision
end | [
"def",
"resolve_revision",
"revision",
"=",
"@repository",
".",
"tag",
".",
"to_s",
".",
"strip",
"if",
"revision",
".",
"empty?",
"revision",
"=",
"nil",
"elsif",
"(",
"revision",
"=~",
"SVN_REVISION_REGEX",
")",
".",
"nil?",
"raise",
"RetrieverError",
",",
"\"Revision reference contained illegal characters: #{revision.inspect}\"",
"end",
"revision",
"=",
"revision",
".",
"inspect",
"if",
"revision",
".",
"index",
"(",
"' '",
")",
"revision",
"end"
]
| ignoring additional info after revision | [
"ignoring",
"additional",
"info",
"after",
"revision"
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/svn.rb#L116-L126 | train |
aidistan/ruby-biotcm | lib/biotcm/table.rb | BioTCM.Table.row_keys= | def row_keys=(val)
raise ArgumentError, 'Illegal agrument type' unless val.is_a?(Array)
raise ArgumentError, 'Unmatched size' if val.size < @row_keys.size
@row_keys = val.map.with_index { |v, i| [v, i] }.to_h
end | ruby | def row_keys=(val)
raise ArgumentError, 'Illegal agrument type' unless val.is_a?(Array)
raise ArgumentError, 'Unmatched size' if val.size < @row_keys.size
@row_keys = val.map.with_index { |v, i| [v, i] }.to_h
end | [
"def",
"row_keys",
"=",
"(",
"val",
")",
"raise",
"ArgumentError",
",",
"'Illegal agrument type'",
"unless",
"val",
".",
"is_a?",
"(",
"Array",
")",
"raise",
"ArgumentError",
",",
"'Unmatched size'",
"if",
"val",
".",
"size",
"<",
"@row_keys",
".",
"size",
"@row_keys",
"=",
"val",
".",
"map",
".",
"with_index",
"{",
"|",
"v",
",",
"i",
"|",
"[",
"v",
",",
"i",
"]",
"}",
".",
"to_h",
"end"
]
| Set row keys
@param val [Array] | [
"Set",
"row",
"keys"
]
| 89b798acc1773087d9e8b754187c884d57fd06d7 | https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L77-L81 | train |
aidistan/ruby-biotcm | lib/biotcm/table.rb | BioTCM.Table.ele | def ele(row, col, val = nil)
if val.nil?
get_ele(row, col)
else
set_ele(row, col, val)
end
end | ruby | def ele(row, col, val = nil)
if val.nil?
get_ele(row, col)
else
set_ele(row, col, val)
end
end | [
"def",
"ele",
"(",
"row",
",",
"col",
",",
"val",
"=",
"nil",
")",
"if",
"val",
".",
"nil?",
"get_ele",
"(",
"row",
",",
"col",
")",
"else",
"set_ele",
"(",
"row",
",",
"col",
",",
"val",
")",
"end",
"end"
]
| Access an element
@overload ele(row, col)
Get an element
@param row [String]
@param col [String]
@return [String]
@overload ele(row, col, val)
Set an element
@param row [String]
@param col [String]
@param val [String]
@return [Table] | [
"Access",
"an",
"element"
]
| 89b798acc1773087d9e8b754187c884d57fd06d7 | https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L119-L125 | train |
aidistan/ruby-biotcm | lib/biotcm/table.rb | BioTCM.Table.get_ele | def get_ele(row, col)
row = @row_keys[row]
col = @col_keys[col]
row && col ? @content[row][col] : nil
end | ruby | def get_ele(row, col)
row = @row_keys[row]
col = @col_keys[col]
row && col ? @content[row][col] : nil
end | [
"def",
"get_ele",
"(",
"row",
",",
"col",
")",
"row",
"=",
"@row_keys",
"[",
"row",
"]",
"col",
"=",
"@col_keys",
"[",
"col",
"]",
"row",
"&&",
"col",
"?",
"@content",
"[",
"row",
"]",
"[",
"col",
"]",
":",
"nil",
"end"
]
| Get an element
@param row [String]
@param col [String]
@return [String] | [
"Get",
"an",
"element"
]
| 89b798acc1773087d9e8b754187c884d57fd06d7 | https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L131-L135 | train |
aidistan/ruby-biotcm | lib/biotcm/table.rb | BioTCM.Table.set_ele | def set_ele(row, col, val)
unless row.is_a?(String) && col.is_a?(String) && val.respond_to?(:to_s)
raise ArgumentError, 'Illegal argument type'
end
set_row(row, [''] * @col_keys.size) unless @row_keys[row]
set_col(col, [''] * @row_keys.size) unless @col_keys[col]
row = @row_keys[row]
col = @col_keys[col]
@content[row][col] = val.to_s
self
end | ruby | def set_ele(row, col, val)
unless row.is_a?(String) && col.is_a?(String) && val.respond_to?(:to_s)
raise ArgumentError, 'Illegal argument type'
end
set_row(row, [''] * @col_keys.size) unless @row_keys[row]
set_col(col, [''] * @row_keys.size) unless @col_keys[col]
row = @row_keys[row]
col = @col_keys[col]
@content[row][col] = val.to_s
self
end | [
"def",
"set_ele",
"(",
"row",
",",
"col",
",",
"val",
")",
"unless",
"row",
".",
"is_a?",
"(",
"String",
")",
"&&",
"col",
".",
"is_a?",
"(",
"String",
")",
"&&",
"val",
".",
"respond_to?",
"(",
":to_s",
")",
"raise",
"ArgumentError",
",",
"'Illegal argument type'",
"end",
"set_row",
"(",
"row",
",",
"[",
"''",
"]",
"*",
"@col_keys",
".",
"size",
")",
"unless",
"@row_keys",
"[",
"row",
"]",
"set_col",
"(",
"col",
",",
"[",
"''",
"]",
"*",
"@row_keys",
".",
"size",
")",
"unless",
"@col_keys",
"[",
"col",
"]",
"row",
"=",
"@row_keys",
"[",
"row",
"]",
"col",
"=",
"@col_keys",
"[",
"col",
"]",
"@content",
"[",
"row",
"]",
"[",
"col",
"]",
"=",
"val",
".",
"to_s",
"self",
"end"
]
| Set an element
@param row [String]
@param col [String]
@param val [String]
@return [Table] | [
"Set",
"an",
"element"
]
| 89b798acc1773087d9e8b754187c884d57fd06d7 | https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L142-L155 | train |
aidistan/ruby-biotcm | lib/biotcm/table.rb | BioTCM.Table.row | def row(row, val = nil)
if val.nil?
get_row(row)
else
set_row(row, val)
end
end | ruby | def row(row, val = nil)
if val.nil?
get_row(row)
else
set_row(row, val)
end
end | [
"def",
"row",
"(",
"row",
",",
"val",
"=",
"nil",
")",
"if",
"val",
".",
"nil?",
"get_row",
"(",
"row",
")",
"else",
"set_row",
"(",
"row",
",",
"val",
")",
"end",
"end"
]
| Access a row
@overload row(row)
Get a row
@param row [String]
@return [Hash]
@overload row(row, val)
Set a row
@param row [String]
@param val [Hash, Array]
@return [Table] | [
"Access",
"a",
"row"
]
| 89b798acc1773087d9e8b754187c884d57fd06d7 | https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L167-L173 | train |
aidistan/ruby-biotcm | lib/biotcm/table.rb | BioTCM.Table.get_row | def get_row(row)
row = @row_keys[row]
row.nil? ? nil : @col_keys.map { |c, ci| [c, @content[row][ci]] }.to_h
end | ruby | def get_row(row)
row = @row_keys[row]
row.nil? ? nil : @col_keys.map { |c, ci| [c, @content[row][ci]] }.to_h
end | [
"def",
"get_row",
"(",
"row",
")",
"row",
"=",
"@row_keys",
"[",
"row",
"]",
"row",
".",
"nil?",
"?",
"nil",
":",
"@col_keys",
".",
"map",
"{",
"|",
"c",
",",
"ci",
"|",
"[",
"c",
",",
"@content",
"[",
"row",
"]",
"[",
"ci",
"]",
"]",
"}",
".",
"to_h",
"end"
]
| Get a row
@param row [String]
@return [Hash] | [
"Get",
"a",
"row"
]
| 89b798acc1773087d9e8b754187c884d57fd06d7 | https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L178-L181 | train |
aidistan/ruby-biotcm | lib/biotcm/table.rb | BioTCM.Table.set_row | def set_row(row, val)
# Setter
if !row.is_a?(String) || (!val.is_a?(Hash) && !val.is_a?(Array))
raise ArgumentError, 'Illegal argument type'
elsif val.is_a?(Array) && val.size != col_keys.size
raise ArgumentError, 'Column size not match'
end
case val
when Array
if @row_keys[row]
row = @row_keys[row]
@content[row] = val
else
@row_keys[row] = @row_keys.size
@content << val
end
when Hash
unless @row_keys[row]
@row_keys[row] = @row_keys.size
@content << ([''] * @col_keys.size)
end
row = @row_keys[row]
val.each do |k, v|
col = @col_keys[k]
@content[row][col] = v if col
end
end
self
end | ruby | def set_row(row, val)
# Setter
if !row.is_a?(String) || (!val.is_a?(Hash) && !val.is_a?(Array))
raise ArgumentError, 'Illegal argument type'
elsif val.is_a?(Array) && val.size != col_keys.size
raise ArgumentError, 'Column size not match'
end
case val
when Array
if @row_keys[row]
row = @row_keys[row]
@content[row] = val
else
@row_keys[row] = @row_keys.size
@content << val
end
when Hash
unless @row_keys[row]
@row_keys[row] = @row_keys.size
@content << ([''] * @col_keys.size)
end
row = @row_keys[row]
val.each do |k, v|
col = @col_keys[k]
@content[row][col] = v if col
end
end
self
end | [
"def",
"set_row",
"(",
"row",
",",
"val",
")",
"if",
"!",
"row",
".",
"is_a?",
"(",
"String",
")",
"||",
"(",
"!",
"val",
".",
"is_a?",
"(",
"Hash",
")",
"&&",
"!",
"val",
".",
"is_a?",
"(",
"Array",
")",
")",
"raise",
"ArgumentError",
",",
"'Illegal argument type'",
"elsif",
"val",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"val",
".",
"size",
"!=",
"col_keys",
".",
"size",
"raise",
"ArgumentError",
",",
"'Column size not match'",
"end",
"case",
"val",
"when",
"Array",
"if",
"@row_keys",
"[",
"row",
"]",
"row",
"=",
"@row_keys",
"[",
"row",
"]",
"@content",
"[",
"row",
"]",
"=",
"val",
"else",
"@row_keys",
"[",
"row",
"]",
"=",
"@row_keys",
".",
"size",
"@content",
"<<",
"val",
"end",
"when",
"Hash",
"unless",
"@row_keys",
"[",
"row",
"]",
"@row_keys",
"[",
"row",
"]",
"=",
"@row_keys",
".",
"size",
"@content",
"<<",
"(",
"[",
"''",
"]",
"*",
"@col_keys",
".",
"size",
")",
"end",
"row",
"=",
"@row_keys",
"[",
"row",
"]",
"val",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"col",
"=",
"@col_keys",
"[",
"k",
"]",
"@content",
"[",
"row",
"]",
"[",
"col",
"]",
"=",
"v",
"if",
"col",
"end",
"end",
"self",
"end"
]
| Set a row
@param row [String]
@param val [Hash, Array]
@return [Table] | [
"Set",
"a",
"row"
]
| 89b798acc1773087d9e8b754187c884d57fd06d7 | https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L187-L218 | train |
aidistan/ruby-biotcm | lib/biotcm/table.rb | BioTCM.Table.col | def col(col, val = nil)
if val.nil?
get_col(col)
else
set_col(col, val)
end
end | ruby | def col(col, val = nil)
if val.nil?
get_col(col)
else
set_col(col, val)
end
end | [
"def",
"col",
"(",
"col",
",",
"val",
"=",
"nil",
")",
"if",
"val",
".",
"nil?",
"get_col",
"(",
"col",
")",
"else",
"set_col",
"(",
"col",
",",
"val",
")",
"end",
"end"
]
| Access a column
@overload col(col)
Get a column
@param col [String]
@return [Hash]
@overload col(col, val)
Set a column
@param col [String]
@param val [Hash, Array]
@return [Table] | [
"Access",
"a",
"column"
]
| 89b798acc1773087d9e8b754187c884d57fd06d7 | https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L230-L236 | train |
aidistan/ruby-biotcm | lib/biotcm/table.rb | BioTCM.Table.get_col | def get_col(col)
col = @col_keys[col]
col.nil? ? nil : @row_keys.map { |r, ri| [r, @content[ri][col]] }.to_h
end | ruby | def get_col(col)
col = @col_keys[col]
col.nil? ? nil : @row_keys.map { |r, ri| [r, @content[ri][col]] }.to_h
end | [
"def",
"get_col",
"(",
"col",
")",
"col",
"=",
"@col_keys",
"[",
"col",
"]",
"col",
".",
"nil?",
"?",
"nil",
":",
"@row_keys",
".",
"map",
"{",
"|",
"r",
",",
"ri",
"|",
"[",
"r",
",",
"@content",
"[",
"ri",
"]",
"[",
"col",
"]",
"]",
"}",
".",
"to_h",
"end"
]
| Get a column
@param col [String]
@return [Hash] | [
"Get",
"a",
"column"
]
| 89b798acc1773087d9e8b754187c884d57fd06d7 | https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L241-L244 | train |
aidistan/ruby-biotcm | lib/biotcm/table.rb | BioTCM.Table.set_col | def set_col(col, val)
if !col.is_a?(String) || (!val.is_a?(Hash) && !val.is_a?(Array))
raise ArgumentError, 'Illegal argument type'
elsif val.is_a?(Array) && val.size != row_keys.size
raise ArgumentError, 'Row size not match'
end
case val
when Array
if @col_keys[col]
col = @col_keys[col]
val.each_with_index { |v, row| @content[row][col] = v }
else
col = @col_keys[col] = @col_keys.size
val.each_with_index { |v, row| @content[row] << v }
end
when Hash
unless @col_keys[col]
@col_keys[col] = @col_keys.size
@content.each { |arr| arr << '' }
end
col = @col_keys[col]
val.each do |k, v|
row = @row_keys[k]
@content[row][col] = v if row
end
end
self
end | ruby | def set_col(col, val)
if !col.is_a?(String) || (!val.is_a?(Hash) && !val.is_a?(Array))
raise ArgumentError, 'Illegal argument type'
elsif val.is_a?(Array) && val.size != row_keys.size
raise ArgumentError, 'Row size not match'
end
case val
when Array
if @col_keys[col]
col = @col_keys[col]
val.each_with_index { |v, row| @content[row][col] = v }
else
col = @col_keys[col] = @col_keys.size
val.each_with_index { |v, row| @content[row] << v }
end
when Hash
unless @col_keys[col]
@col_keys[col] = @col_keys.size
@content.each { |arr| arr << '' }
end
col = @col_keys[col]
val.each do |k, v|
row = @row_keys[k]
@content[row][col] = v if row
end
end
self
end | [
"def",
"set_col",
"(",
"col",
",",
"val",
")",
"if",
"!",
"col",
".",
"is_a?",
"(",
"String",
")",
"||",
"(",
"!",
"val",
".",
"is_a?",
"(",
"Hash",
")",
"&&",
"!",
"val",
".",
"is_a?",
"(",
"Array",
")",
")",
"raise",
"ArgumentError",
",",
"'Illegal argument type'",
"elsif",
"val",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"val",
".",
"size",
"!=",
"row_keys",
".",
"size",
"raise",
"ArgumentError",
",",
"'Row size not match'",
"end",
"case",
"val",
"when",
"Array",
"if",
"@col_keys",
"[",
"col",
"]",
"col",
"=",
"@col_keys",
"[",
"col",
"]",
"val",
".",
"each_with_index",
"{",
"|",
"v",
",",
"row",
"|",
"@content",
"[",
"row",
"]",
"[",
"col",
"]",
"=",
"v",
"}",
"else",
"col",
"=",
"@col_keys",
"[",
"col",
"]",
"=",
"@col_keys",
".",
"size",
"val",
".",
"each_with_index",
"{",
"|",
"v",
",",
"row",
"|",
"@content",
"[",
"row",
"]",
"<<",
"v",
"}",
"end",
"when",
"Hash",
"unless",
"@col_keys",
"[",
"col",
"]",
"@col_keys",
"[",
"col",
"]",
"=",
"@col_keys",
".",
"size",
"@content",
".",
"each",
"{",
"|",
"arr",
"|",
"arr",
"<<",
"''",
"}",
"end",
"col",
"=",
"@col_keys",
"[",
"col",
"]",
"val",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"row",
"=",
"@row_keys",
"[",
"k",
"]",
"@content",
"[",
"row",
"]",
"[",
"col",
"]",
"=",
"v",
"if",
"row",
"end",
"end",
"self",
"end"
]
| Set a column
@param col [String]
@param val [Hash, Array]
@return [Table] | [
"Set",
"a",
"column"
]
| 89b798acc1773087d9e8b754187c884d57fd06d7 | https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L250-L280 | train |
aidistan/ruby-biotcm | lib/biotcm/table.rb | BioTCM.Table.each_row | def each_row
if block_given?
@row_keys.each_key { |r| yield(r, row(r)) }
self
else
Enumerator.new do |y|
@row_keys.each_key { |r| y << [r, row(r)] }
end
end
end | ruby | def each_row
if block_given?
@row_keys.each_key { |r| yield(r, row(r)) }
self
else
Enumerator.new do |y|
@row_keys.each_key { |r| y << [r, row(r)] }
end
end
end | [
"def",
"each_row",
"if",
"block_given?",
"@row_keys",
".",
"each_key",
"{",
"|",
"r",
"|",
"yield",
"(",
"r",
",",
"row",
"(",
"r",
")",
")",
"}",
"self",
"else",
"Enumerator",
".",
"new",
"do",
"|",
"y",
"|",
"@row_keys",
".",
"each_key",
"{",
"|",
"r",
"|",
"y",
"<<",
"[",
"r",
",",
"row",
"(",
"r",
")",
"]",
"}",
"end",
"end",
"end"
]
| Iterate by row | [
"Iterate",
"by",
"row"
]
| 89b798acc1773087d9e8b754187c884d57fd06d7 | https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L283-L292 | train |
aidistan/ruby-biotcm | lib/biotcm/table.rb | BioTCM.Table.each_col | def each_col
if block_given?
@col_keys.each_key { |c| yield(c, col(c)) }
self
else
Enumerator.new do |y|
@col_keys.each_key { |c| y << [c, col(c)] }
end
end
end | ruby | def each_col
if block_given?
@col_keys.each_key { |c| yield(c, col(c)) }
self
else
Enumerator.new do |y|
@col_keys.each_key { |c| y << [c, col(c)] }
end
end
end | [
"def",
"each_col",
"if",
"block_given?",
"@col_keys",
".",
"each_key",
"{",
"|",
"c",
"|",
"yield",
"(",
"c",
",",
"col",
"(",
"c",
")",
")",
"}",
"self",
"else",
"Enumerator",
".",
"new",
"do",
"|",
"y",
"|",
"@col_keys",
".",
"each_key",
"{",
"|",
"c",
"|",
"y",
"<<",
"[",
"c",
",",
"col",
"(",
"c",
")",
"]",
"}",
"end",
"end",
"end"
]
| Iterate by col | [
"Iterate",
"by",
"col"
]
| 89b798acc1773087d9e8b754187c884d57fd06d7 | https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/table.rb#L295-L304 | train |
aidistan/ruby-biotcm | lib/biotcm/databases/hgnc/rescuer.rb | BioTCM::Databases::HGNC.Rescuer.rescue_symbol | def rescue_symbol(symbol, method = @rescue_method, rehearsal = false)
return @rescue_history[symbol] if @rescue_history[symbol]
case method
when :auto
auto_rescue = ''
if @symbol2hgncid[symbol.upcase]
auto_rescue = symbol.upcase
elsif @symbol2hgncid[symbol.downcase]
auto_rescue = symbol.downcase
elsif @symbol2hgncid[symbol.delete('-')]
auto_rescue = symbol.delete('-')
elsif @symbol2hgncid[symbol.upcase.delete('-')]
auto_rescue = symbol.upcase.delete('-')
elsif @symbol2hgncid[symbol.downcase.delete('-')]
auto_rescue = symbol.downcase.delete('-')
# Add more rules here
end
# Record
unless rehearsal
BioTCM.logger.warn('HGNC') { "Unrecognized symbol \"#{symbol}\", \"#{auto_rescue}\" used instead" }
@rescue_history[symbol] = auto_rescue
end
return auto_rescue
when :manual
# Try automatic rescue first
if (auto_rescue = rescue_symbol(symbol, :auto, true)) != ''
print "\"#{symbol}\" unrecognized. Use \"#{auto_rescue}\" instead? [Yn] "
unless gets.chomp == 'n'
@rescue_history[symbol] = auto_rescue unless rehearsal # rubocop:disable Metrics/BlockNesting
return auto_rescue
end
end
# Manually rescue
loop do
print "Please correct \"#{symbol}\" or press enter directly to return empty String instead:\n"
unless (manual_rescue = gets.chomp) == '' || @symbol2hgncid[manual_rescue]
puts "Failed to recognize \"#{manual_rescue}\""
next
end
unless rehearsal
@rescue_history[symbol] = manual_rescue
File.open(@rescue_history_filepath, 'a').print(symbol, "\t", manual_rescue, "\n")
end
return manual_rescue
end
end
end | ruby | def rescue_symbol(symbol, method = @rescue_method, rehearsal = false)
return @rescue_history[symbol] if @rescue_history[symbol]
case method
when :auto
auto_rescue = ''
if @symbol2hgncid[symbol.upcase]
auto_rescue = symbol.upcase
elsif @symbol2hgncid[symbol.downcase]
auto_rescue = symbol.downcase
elsif @symbol2hgncid[symbol.delete('-')]
auto_rescue = symbol.delete('-')
elsif @symbol2hgncid[symbol.upcase.delete('-')]
auto_rescue = symbol.upcase.delete('-')
elsif @symbol2hgncid[symbol.downcase.delete('-')]
auto_rescue = symbol.downcase.delete('-')
# Add more rules here
end
# Record
unless rehearsal
BioTCM.logger.warn('HGNC') { "Unrecognized symbol \"#{symbol}\", \"#{auto_rescue}\" used instead" }
@rescue_history[symbol] = auto_rescue
end
return auto_rescue
when :manual
# Try automatic rescue first
if (auto_rescue = rescue_symbol(symbol, :auto, true)) != ''
print "\"#{symbol}\" unrecognized. Use \"#{auto_rescue}\" instead? [Yn] "
unless gets.chomp == 'n'
@rescue_history[symbol] = auto_rescue unless rehearsal # rubocop:disable Metrics/BlockNesting
return auto_rescue
end
end
# Manually rescue
loop do
print "Please correct \"#{symbol}\" or press enter directly to return empty String instead:\n"
unless (manual_rescue = gets.chomp) == '' || @symbol2hgncid[manual_rescue]
puts "Failed to recognize \"#{manual_rescue}\""
next
end
unless rehearsal
@rescue_history[symbol] = manual_rescue
File.open(@rescue_history_filepath, 'a').print(symbol, "\t", manual_rescue, "\n")
end
return manual_rescue
end
end
end | [
"def",
"rescue_symbol",
"(",
"symbol",
",",
"method",
"=",
"@rescue_method",
",",
"rehearsal",
"=",
"false",
")",
"return",
"@rescue_history",
"[",
"symbol",
"]",
"if",
"@rescue_history",
"[",
"symbol",
"]",
"case",
"method",
"when",
":auto",
"auto_rescue",
"=",
"''",
"if",
"@symbol2hgncid",
"[",
"symbol",
".",
"upcase",
"]",
"auto_rescue",
"=",
"symbol",
".",
"upcase",
"elsif",
"@symbol2hgncid",
"[",
"symbol",
".",
"downcase",
"]",
"auto_rescue",
"=",
"symbol",
".",
"downcase",
"elsif",
"@symbol2hgncid",
"[",
"symbol",
".",
"delete",
"(",
"'-'",
")",
"]",
"auto_rescue",
"=",
"symbol",
".",
"delete",
"(",
"'-'",
")",
"elsif",
"@symbol2hgncid",
"[",
"symbol",
".",
"upcase",
".",
"delete",
"(",
"'-'",
")",
"]",
"auto_rescue",
"=",
"symbol",
".",
"upcase",
".",
"delete",
"(",
"'-'",
")",
"elsif",
"@symbol2hgncid",
"[",
"symbol",
".",
"downcase",
".",
"delete",
"(",
"'-'",
")",
"]",
"auto_rescue",
"=",
"symbol",
".",
"downcase",
".",
"delete",
"(",
"'-'",
")",
"end",
"unless",
"rehearsal",
"BioTCM",
".",
"logger",
".",
"warn",
"(",
"'HGNC'",
")",
"{",
"\"Unrecognized symbol \\\"#{symbol}\\\", \\\"#{auto_rescue}\\\" used instead\"",
"}",
"@rescue_history",
"[",
"symbol",
"]",
"=",
"auto_rescue",
"end",
"return",
"auto_rescue",
"when",
":manual",
"if",
"(",
"auto_rescue",
"=",
"rescue_symbol",
"(",
"symbol",
",",
":auto",
",",
"true",
")",
")",
"!=",
"''",
"print",
"\"\\\"#{symbol}\\\" unrecognized. Use \\\"#{auto_rescue}\\\" instead? [Yn] \"",
"unless",
"gets",
".",
"chomp",
"==",
"'n'",
"@rescue_history",
"[",
"symbol",
"]",
"=",
"auto_rescue",
"unless",
"rehearsal",
"return",
"auto_rescue",
"end",
"end",
"loop",
"do",
"print",
"\"Please correct \\\"#{symbol}\\\" or press enter directly to return empty String instead:\\n\"",
"unless",
"(",
"manual_rescue",
"=",
"gets",
".",
"chomp",
")",
"==",
"''",
"||",
"@symbol2hgncid",
"[",
"manual_rescue",
"]",
"puts",
"\"Failed to recognize \\\"#{manual_rescue}\\\"\"",
"next",
"end",
"unless",
"rehearsal",
"@rescue_history",
"[",
"symbol",
"]",
"=",
"manual_rescue",
"File",
".",
"open",
"(",
"@rescue_history_filepath",
",",
"'a'",
")",
".",
"print",
"(",
"symbol",
",",
"\"\\t\"",
",",
"manual_rescue",
",",
"\"\\n\"",
")",
"end",
"return",
"manual_rescue",
"end",
"end",
"end"
]
| Try to rescue a gene symbol
@param symbol [String] Gene symbol
@param method [Symbol] :auto or :manual
@param rehearsal [Boolean] When set to true, neither outputing warnings nor modifying rescue history
@return [String] "" if rescue failed | [
"Try",
"to",
"rescue",
"a",
"gene",
"symbol"
]
| 89b798acc1773087d9e8b754187c884d57fd06d7 | https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/databases/hgnc/rescuer.rb#L34-L85 | train |
codez/seed-fu-ndo | lib/seed-fu-ndo/seeder.rb | SeedFu.Seeder.seed_with_undo | def seed_with_undo
if r = SeedFuNdo.recorder
r.record self
# return existing records in case they are processed by the caller
@data.map { |record_data| find_record(record_data) }
else
seed_without_undo
end
end | ruby | def seed_with_undo
if r = SeedFuNdo.recorder
r.record self
# return existing records in case they are processed by the caller
@data.map { |record_data| find_record(record_data) }
else
seed_without_undo
end
end | [
"def",
"seed_with_undo",
"if",
"r",
"=",
"SeedFuNdo",
".",
"recorder",
"r",
".",
"record",
"self",
"@data",
".",
"map",
"{",
"|",
"record_data",
"|",
"find_record",
"(",
"record_data",
")",
"}",
"else",
"seed_without_undo",
"end",
"end"
]
| Record instead of inserting the data if in recording mode. | [
"Record",
"instead",
"of",
"inserting",
"the",
"data",
"if",
"in",
"recording",
"mode",
"."
]
| 342995939e204a2c55f580778fc7f7c442fc1499 | https://github.com/codez/seed-fu-ndo/blob/342995939e204a2c55f580778fc7f7c442fc1499/lib/seed-fu-ndo/seeder.rb#L7-L16 | train |
spatchcock/quantify | lib/quantify/dimensions.rb | Quantify.Dimensions.units | def units(by=nil)
Unit.units.values.select { |unit| unit.dimensions == self }.map(&by).to_a
end | ruby | def units(by=nil)
Unit.units.values.select { |unit| unit.dimensions == self }.map(&by).to_a
end | [
"def",
"units",
"(",
"by",
"=",
"nil",
")",
"Unit",
".",
"units",
".",
"values",
".",
"select",
"{",
"|",
"unit",
"|",
"unit",
".",
"dimensions",
"==",
"self",
"}",
".",
"map",
"(",
"&",
"by",
")",
".",
"to_a",
"end"
]
| Returns an array containing the known units which represent the physical
quantity described by self
If no argument is given, the array holds instances of Unit::Base (or
subclasses) which represent each unit. Alternatively only the names or
symbols of each unit can be returned by providing the appropriate unit
attribute as a symbolized argument, e.g.
Dimensions.energy.units #=> [ #<Quantify::Dimensions: .. >,
#<Quantify::Dimensions: .. >,
... ]
Dimensions.mass.units :name #=> [ 'kilogram', 'ounce',
'pound', ... ]
Dimensions.length.units :symbol #=> [ 'm', 'ft', 'yd', ... ] | [
"Returns",
"an",
"array",
"containing",
"the",
"known",
"units",
"which",
"represent",
"the",
"physical",
"quantity",
"described",
"by",
"self"
]
| e99c1995491d49667c7e89a2843389e1d924b446 | https://github.com/spatchcock/quantify/blob/e99c1995491d49667c7e89a2843389e1d924b446/lib/quantify/dimensions.rb#L276-L278 | train |
spatchcock/quantify | lib/quantify/dimensions.rb | Quantify.Dimensions.si_unit | def si_unit
return Unit.steridian if describe == 'solid angle'
return Unit.radian if describe == 'plane angle'
val = si_base_units
return nil unless val
return val[0] if val.length == 1
val = val.inject(Unit.unity) do |compound,unit|
compound * unit
end
val = val.or_equivalent unless val.acts_as_equivalent_unit
end | ruby | def si_unit
return Unit.steridian if describe == 'solid angle'
return Unit.radian if describe == 'plane angle'
val = si_base_units
return nil unless val
return val[0] if val.length == 1
val = val.inject(Unit.unity) do |compound,unit|
compound * unit
end
val = val.or_equivalent unless val.acts_as_equivalent_unit
end | [
"def",
"si_unit",
"return",
"Unit",
".",
"steridian",
"if",
"describe",
"==",
"'solid angle'",
"return",
"Unit",
".",
"radian",
"if",
"describe",
"==",
"'plane angle'",
"val",
"=",
"si_base_units",
"return",
"nil",
"unless",
"val",
"return",
"val",
"[",
"0",
"]",
"if",
"val",
".",
"length",
"==",
"1",
"val",
"=",
"val",
".",
"inject",
"(",
"Unit",
".",
"unity",
")",
"do",
"|",
"compound",
",",
"unit",
"|",
"compound",
"*",
"unit",
"end",
"val",
"=",
"val",
".",
"or_equivalent",
"unless",
"val",
".",
"acts_as_equivalent_unit",
"end"
]
| Returns the SI unit for the physical quantity described by self.
Plane/solid angle are special cases which are dimensionless units, and so
are handled explicitly. Otherwise, the si base units for each of the base
dimensions of self are indentified and the corresponding compound unit is
derived. If this new unit is the same as a known (SI derived) unit, the
known unit is returned.
Dimensions.energy.units #=> #<Quantify::Dimensions: .. >
Dimensions.energy.si_unit.name #=> 'joule'
Dimensions.kinematic_viscosity.si_unit.name
#=> 'metre squared per second' | [
"Returns",
"the",
"SI",
"unit",
"for",
"the",
"physical",
"quantity",
"described",
"by",
"self",
"."
]
| e99c1995491d49667c7e89a2843389e1d924b446 | https://github.com/spatchcock/quantify/blob/e99c1995491d49667c7e89a2843389e1d924b446/lib/quantify/dimensions.rb#L296-L307 | train |
spatchcock/quantify | lib/quantify/dimensions.rb | Quantify.Dimensions.si_base_units | def si_base_units(by=nil)
val = self.to_hash.map do |dimension, index|
dimension_name = dimension.remove_underscores
Unit.base_quantity_si_units.select do |unit|
unit.measures == dimension_name
end.first.clone ** index
end
val = val.map(&by) if by
val.to_a
end | ruby | def si_base_units(by=nil)
val = self.to_hash.map do |dimension, index|
dimension_name = dimension.remove_underscores
Unit.base_quantity_si_units.select do |unit|
unit.measures == dimension_name
end.first.clone ** index
end
val = val.map(&by) if by
val.to_a
end | [
"def",
"si_base_units",
"(",
"by",
"=",
"nil",
")",
"val",
"=",
"self",
".",
"to_hash",
".",
"map",
"do",
"|",
"dimension",
",",
"index",
"|",
"dimension_name",
"=",
"dimension",
".",
"remove_underscores",
"Unit",
".",
"base_quantity_si_units",
".",
"select",
"do",
"|",
"unit",
"|",
"unit",
".",
"measures",
"==",
"dimension_name",
"end",
".",
"first",
".",
"clone",
"**",
"index",
"end",
"val",
"=",
"val",
".",
"map",
"(",
"&",
"by",
")",
"if",
"by",
"val",
".",
"to_a",
"end"
]
| Returns an array representing the base SI units for the physical quantity
described by self
If no argument is given, the array holds instances of Unit::Base (or
subclasses) which represent each base unit. Alternatively only the names
or symbols of each unit can be returned by providing the appropriate unit
attribute as a symbolized argument, e.g.
Dimensions.energy.si_base_units #=> [ #<Quantify::Unit: .. >,
#<Quantify::Unit: .. >,
... ]
Dimensions.energy.si_base_units :name
#=> [ "metre squared",
"per second squared",
"kilogram"]
Dimensions.force.units :symbol #=> [ "m", "s^-2", "kg"] | [
"Returns",
"an",
"array",
"representing",
"the",
"base",
"SI",
"units",
"for",
"the",
"physical",
"quantity",
"described",
"by",
"self"
]
| e99c1995491d49667c7e89a2843389e1d924b446 | https://github.com/spatchcock/quantify/blob/e99c1995491d49667c7e89a2843389e1d924b446/lib/quantify/dimensions.rb#L329-L339 | train |
spatchcock/quantify | lib/quantify/dimensions.rb | Quantify.Dimensions.init_base_quantities | def init_base_quantities(options = { })
if options.has_key?(:physical_quantity)
pq = options.delete(:physical_quantity)
self.physical_quantity = pq.remove_underscores.downcase if pq
end
options.each_pair do |base_quantity, index|
base_quantity = base_quantity.to_s.downcase.to_sym
unless index.is_a?(Integer) && BASE_QUANTITIES.include?(base_quantity)
raise Exceptions::InvalidDimensionError, "An invalid base quantity was specified (#{base_quantity})"
end
if @base_quantity_hash.has_key?(base_quantity)
new_index = @base_quantity_hash[base_quantity] + index
if new_index == 0
@base_quantity_hash.delete(base_quantity)
else
@base_quantity_hash[base_quantity] = new_index
end
else
@base_quantity_hash[base_quantity] = index
end
end
end | ruby | def init_base_quantities(options = { })
if options.has_key?(:physical_quantity)
pq = options.delete(:physical_quantity)
self.physical_quantity = pq.remove_underscores.downcase if pq
end
options.each_pair do |base_quantity, index|
base_quantity = base_quantity.to_s.downcase.to_sym
unless index.is_a?(Integer) && BASE_QUANTITIES.include?(base_quantity)
raise Exceptions::InvalidDimensionError, "An invalid base quantity was specified (#{base_quantity})"
end
if @base_quantity_hash.has_key?(base_quantity)
new_index = @base_quantity_hash[base_quantity] + index
if new_index == 0
@base_quantity_hash.delete(base_quantity)
else
@base_quantity_hash[base_quantity] = new_index
end
else
@base_quantity_hash[base_quantity] = index
end
end
end | [
"def",
"init_base_quantities",
"(",
"options",
"=",
"{",
"}",
")",
"if",
"options",
".",
"has_key?",
"(",
":physical_quantity",
")",
"pq",
"=",
"options",
".",
"delete",
"(",
":physical_quantity",
")",
"self",
".",
"physical_quantity",
"=",
"pq",
".",
"remove_underscores",
".",
"downcase",
"if",
"pq",
"end",
"options",
".",
"each_pair",
"do",
"|",
"base_quantity",
",",
"index",
"|",
"base_quantity",
"=",
"base_quantity",
".",
"to_s",
".",
"downcase",
".",
"to_sym",
"unless",
"index",
".",
"is_a?",
"(",
"Integer",
")",
"&&",
"BASE_QUANTITIES",
".",
"include?",
"(",
"base_quantity",
")",
"raise",
"Exceptions",
"::",
"InvalidDimensionError",
",",
"\"An invalid base quantity was specified (#{base_quantity})\"",
"end",
"if",
"@base_quantity_hash",
".",
"has_key?",
"(",
"base_quantity",
")",
"new_index",
"=",
"@base_quantity_hash",
"[",
"base_quantity",
"]",
"+",
"index",
"if",
"new_index",
"==",
"0",
"@base_quantity_hash",
".",
"delete",
"(",
"base_quantity",
")",
"else",
"@base_quantity_hash",
"[",
"base_quantity",
"]",
"=",
"new_index",
"end",
"else",
"@base_quantity_hash",
"[",
"base_quantity",
"]",
"=",
"index",
"end",
"end",
"end"
]
| Method for initializing the base quantities of self.
Where base quantities are already defined, the new indices are added to
the existing ones. This represents the multiplication of base quantities
(multiplication of similar quantities involves the addition of their
powers).
This method is therefore used in the multiplication of Dimensions objects,
but also in divisions and raising of powers following other operations. | [
"Method",
"for",
"initializing",
"the",
"base",
"quantities",
"of",
"self",
"."
]
| e99c1995491d49667c7e89a2843389e1d924b446 | https://github.com/spatchcock/quantify/blob/e99c1995491d49667c7e89a2843389e1d924b446/lib/quantify/dimensions.rb#L506-L527 | train |
spatchcock/quantify | lib/quantify/quantity.rb | Quantify.Quantity.to_s | def to_s format=:symbol
if format == :name
unit_string = @value == 1 || @value == -1 ? @unit.name : @unit.pluralized_name
else
unit_string = @unit.send format
end
string = "#{@value}"
string += " #{unit_string}" unless unit_string.empty?
string
end | ruby | def to_s format=:symbol
if format == :name
unit_string = @value == 1 || @value == -1 ? @unit.name : @unit.pluralized_name
else
unit_string = @unit.send format
end
string = "#{@value}"
string += " #{unit_string}" unless unit_string.empty?
string
end | [
"def",
"to_s",
"format",
"=",
":symbol",
"if",
"format",
"==",
":name",
"unit_string",
"=",
"@value",
"==",
"1",
"||",
"@value",
"==",
"-",
"1",
"?",
"@unit",
".",
"name",
":",
"@unit",
".",
"pluralized_name",
"else",
"unit_string",
"=",
"@unit",
".",
"send",
"format",
"end",
"string",
"=",
"\"#{@value}\"",
"string",
"+=",
"\" #{unit_string}\"",
"unless",
"unit_string",
".",
"empty?",
"string",
"end"
]
| Returns a string representation of the quantity, using the unit symbol | [
"Returns",
"a",
"string",
"representation",
"of",
"the",
"quantity",
"using",
"the",
"unit",
"symbol"
]
| e99c1995491d49667c7e89a2843389e1d924b446 | https://github.com/spatchcock/quantify/blob/e99c1995491d49667c7e89a2843389e1d924b446/lib/quantify/quantity.rb#L178-L189 | train |
spatchcock/quantify | lib/quantify/quantity.rb | Quantify.Quantity.to_si | def to_si
if @unit.is_compound_unit?
Quantity.new(@value,@unit).convert_compound_unit_to_si!
elsif @unit.is_dimensionless?
return self.clone
elsif @value.nil?
return Quantity.new(nil, @unit.si_unit)
else
self.to(@unit.si_unit)
end
end | ruby | def to_si
if @unit.is_compound_unit?
Quantity.new(@value,@unit).convert_compound_unit_to_si!
elsif @unit.is_dimensionless?
return self.clone
elsif @value.nil?
return Quantity.new(nil, @unit.si_unit)
else
self.to(@unit.si_unit)
end
end | [
"def",
"to_si",
"if",
"@unit",
".",
"is_compound_unit?",
"Quantity",
".",
"new",
"(",
"@value",
",",
"@unit",
")",
".",
"convert_compound_unit_to_si!",
"elsif",
"@unit",
".",
"is_dimensionless?",
"return",
"self",
".",
"clone",
"elsif",
"@value",
".",
"nil?",
"return",
"Quantity",
".",
"new",
"(",
"nil",
",",
"@unit",
".",
"si_unit",
")",
"else",
"self",
".",
"to",
"(",
"@unit",
".",
"si_unit",
")",
"end",
"end"
]
| Converts a quantity to the equivalent quantity using only SI units | [
"Converts",
"a",
"quantity",
"to",
"the",
"equivalent",
"quantity",
"using",
"only",
"SI",
"units"
]
| e99c1995491d49667c7e89a2843389e1d924b446 | https://github.com/spatchcock/quantify/blob/e99c1995491d49667c7e89a2843389e1d924b446/lib/quantify/quantity.rb#L232-L242 | train |
noprompt/vic | lib/vic/color_scheme.rb | Vic.ColorScheme.highlight! | def highlight!(group, attributes={})
highlight(group, attributes.dup.tap { |hash| hash[:force] = true })
end | ruby | def highlight!(group, attributes={})
highlight(group, attributes.dup.tap { |hash| hash[:force] = true })
end | [
"def",
"highlight!",
"(",
"group",
",",
"attributes",
"=",
"{",
"}",
")",
"highlight",
"(",
"group",
",",
"attributes",
".",
"dup",
".",
"tap",
"{",
"|",
"hash",
"|",
"hash",
"[",
":force",
"]",
"=",
"true",
"}",
")",
"end"
]
| Add or update a forced highlight
@example
scheme.highlight!(:Normal, fg: 'eee', bg: '333').force? # => true
@param [Hash] attributes
the attributes to set or update
@return [Vic::Highlight]
the highlight
@api public | [
"Add",
"or",
"update",
"a",
"forced",
"highlight"
]
| 276e18fc5d81727023d3abfdf95829648818a9c4 | https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/color_scheme.rb#L143-L145 | train |
noprompt/vic | lib/vic/color_scheme.rb | Vic.ColorScheme.link | def link(*from_groups, to_group)
from_groups.flatten.map do |from_group|
# Don't add anything we don't already have.
next if find_link(from_group, to_group)
link = Link.new(from_group, to_group)
link.tap { |l| @links << l }
end.compact
end | ruby | def link(*from_groups, to_group)
from_groups.flatten.map do |from_group|
# Don't add anything we don't already have.
next if find_link(from_group, to_group)
link = Link.new(from_group, to_group)
link.tap { |l| @links << l }
end.compact
end | [
"def",
"link",
"(",
"*",
"from_groups",
",",
"to_group",
")",
"from_groups",
".",
"flatten",
".",
"map",
"do",
"|",
"from_group",
"|",
"next",
"if",
"find_link",
"(",
"from_group",
",",
"to_group",
")",
"link",
"=",
"Link",
".",
"new",
"(",
"from_group",
",",
"to_group",
")",
"link",
".",
"tap",
"{",
"|",
"l",
"|",
"@links",
"<<",
"l",
"}",
"end",
".",
"compact",
"end"
]
| Add highlight links to the colorscheme
@example
scheme.link(:rubyInstanceVariable, :rubyClassVariable)
@param [String,Symbol] from_groups
a list of groups to link from
@param [String,Symbol] to_groups
the group to link to
@return [Array]
the added links
@api public | [
"Add",
"highlight",
"links",
"to",
"the",
"colorscheme"
]
| 276e18fc5d81727023d3abfdf95829648818a9c4 | https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/color_scheme.rb#L173-L180 | train |
noprompt/vic | lib/vic/color_scheme.rb | Vic.ColorScheme.link! | def link!(*from_groups, to_group)
# Use the default method first.
self.link(from_groups, to_group)
# Then update the links.
from_groups.flatten.map do |from_group|
link = find_link(from_group, to_group)
link.tap(&:force!)
end
end | ruby | def link!(*from_groups, to_group)
# Use the default method first.
self.link(from_groups, to_group)
# Then update the links.
from_groups.flatten.map do |from_group|
link = find_link(from_group, to_group)
link.tap(&:force!)
end
end | [
"def",
"link!",
"(",
"*",
"from_groups",
",",
"to_group",
")",
"self",
".",
"link",
"(",
"from_groups",
",",
"to_group",
")",
"from_groups",
".",
"flatten",
".",
"map",
"do",
"|",
"from_group",
"|",
"link",
"=",
"find_link",
"(",
"from_group",
",",
"to_group",
")",
"link",
".",
"tap",
"(",
"&",
":force!",
")",
"end",
"end"
]
| Add forced highlight links to the colorscheme
@example
scheme.link!(:rubyInstanceVariable, :rubyClassVariable)
link = scheme.links.find do |l|
l.from_group == :rubyInstanceVariable and l.to_group = :rubyClassVariable
end
link.force? # => true
@param [String,Symbol] from_groups
a list of groups to link from
@param [String,Symbol] to_groups
the group to link to
@return [Array]
the added/updated links
@api public | [
"Add",
"forced",
"highlight",
"links",
"to",
"the",
"colorscheme"
]
| 276e18fc5d81727023d3abfdf95829648818a9c4 | https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/color_scheme.rb#L201-L210 | train |
noprompt/vic | lib/vic/color_scheme.rb | Vic.ColorScheme.language | def language(name = nil, &block)
return @language unless name and block_given?
previous_language = self.language
@language = name
block.arity == 0 ? instance_eval(&block) : yield(self)
@language = previous_language
end | ruby | def language(name = nil, &block)
return @language unless name and block_given?
previous_language = self.language
@language = name
block.arity == 0 ? instance_eval(&block) : yield(self)
@language = previous_language
end | [
"def",
"language",
"(",
"name",
"=",
"nil",
",",
"&",
"block",
")",
"return",
"@language",
"unless",
"name",
"and",
"block_given?",
"previous_language",
"=",
"self",
".",
"language",
"@language",
"=",
"name",
"block",
".",
"arity",
"==",
"0",
"?",
"instance_eval",
"(",
"&",
"block",
")",
":",
"yield",
"(",
"self",
")",
"@language",
"=",
"previous_language",
"end"
]
| Return the language
If a name and a block is passed the language will be temporarily set to
name inside the block.
@example
scheme.language :ruby do |s|
s.hi(:InstanceVariable)
s.hi(:ClassVariable)
end
scheme.highlights.any? { |h| h.group == :rubyClassVarible } # => true
@param [String,Symbol] name
the language to temporarily set if a block is given
@yieldparam [Vic::Colorscheme]
the colorscheme
@return [String,Symbol]
the language setting
@api public | [
"Return",
"the",
"language"
]
| 276e18fc5d81727023d3abfdf95829648818a9c4 | https://github.com/noprompt/vic/blob/276e18fc5d81727023d3abfdf95829648818a9c4/lib/vic/color_scheme.rb#L251-L258 | train |
rightscale/right_scraper | lib/right_scraper/scanners/cookbook_metadata_readonly.rb | RightScraper::Scanners.CookbookMetadataReadOnly.generated_metadata_json_readonly | def generated_metadata_json_readonly
@logger.operation(:metadata_readonly) do
# path constants
freed_metadata_dir = (@cookbook.pos == '.' && freed_dir) || ::File.join(freed_dir, @cookbook.pos)
freed_metadata_json_path = ::File.join(freed_metadata_dir, JSON_METADATA)
# in the multi-pass case we will run this scanner only on the second
# and any subsequent passed, which are outside of containment. the
# metadata must have already been generated at this point or else it
# should be considered an internal error.
return ::File.read(freed_metadata_json_path)
end
end | ruby | def generated_metadata_json_readonly
@logger.operation(:metadata_readonly) do
# path constants
freed_metadata_dir = (@cookbook.pos == '.' && freed_dir) || ::File.join(freed_dir, @cookbook.pos)
freed_metadata_json_path = ::File.join(freed_metadata_dir, JSON_METADATA)
# in the multi-pass case we will run this scanner only on the second
# and any subsequent passed, which are outside of containment. the
# metadata must have already been generated at this point or else it
# should be considered an internal error.
return ::File.read(freed_metadata_json_path)
end
end | [
"def",
"generated_metadata_json_readonly",
"@logger",
".",
"operation",
"(",
":metadata_readonly",
")",
"do",
"freed_metadata_dir",
"=",
"(",
"@cookbook",
".",
"pos",
"==",
"'.'",
"&&",
"freed_dir",
")",
"||",
"::",
"File",
".",
"join",
"(",
"freed_dir",
",",
"@cookbook",
".",
"pos",
")",
"freed_metadata_json_path",
"=",
"::",
"File",
".",
"join",
"(",
"freed_metadata_dir",
",",
"JSON_METADATA",
")",
"return",
"::",
"File",
".",
"read",
"(",
"freed_metadata_json_path",
")",
"end",
"end"
]
| Reads the existing generated 'metadata.json' or else fails.
=== Returns
@return [String] metadata JSON text | [
"Reads",
"the",
"existing",
"generated",
"metadata",
".",
"json",
"or",
"else",
"fails",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/cookbook_metadata_readonly.rb#L58-L70 | train |
aidistan/ruby-biotcm | lib/biotcm/layer.rb | BioTCM.Layer.save | def save(path, prefix = '')
FileUtils.mkdir_p(path)
@edge_tab.save(File.expand_path(prefix + 'edges.tab', path))
@node_tab.save(File.expand_path(prefix + 'nodes.tab', path))
end | ruby | def save(path, prefix = '')
FileUtils.mkdir_p(path)
@edge_tab.save(File.expand_path(prefix + 'edges.tab', path))
@node_tab.save(File.expand_path(prefix + 'nodes.tab', path))
end | [
"def",
"save",
"(",
"path",
",",
"prefix",
"=",
"''",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"path",
")",
"@edge_tab",
".",
"save",
"(",
"File",
".",
"expand_path",
"(",
"prefix",
"+",
"'edges.tab'",
",",
"path",
")",
")",
"@node_tab",
".",
"save",
"(",
"File",
".",
"expand_path",
"(",
"prefix",
"+",
"'nodes.tab'",
",",
"path",
")",
")",
"end"
]
| Create a layer from an edge tab and a node tab
@param edge_tab [Table]
@param node_tab [Table]
Save the layer to disk
@param path [String] path to output directory
@param prefix [String] | [
"Create",
"a",
"layer",
"from",
"an",
"edge",
"tab",
"and",
"a",
"node",
"tab"
]
| 89b798acc1773087d9e8b754187c884d57fd06d7 | https://github.com/aidistan/ruby-biotcm/blob/89b798acc1773087d9e8b754187c884d57fd06d7/lib/biotcm/layer.rb#L120-L124 | train |
rightscale/right_scraper | lib/right_scraper/main.rb | RightScraper.Main.scrape | def scrape(repo, incremental=true, &callback)
old_logger_callback = @logger.callback
@logger.callback = callback
errorlen = errors.size
begin
if retrieved = retrieve(repo)
scan(retrieved)
end
rescue Exception
# legacy logger handles communication with the end user and appending
# to our error list; we just need to keep going. the new methodology
# has no such guaranteed communication so the caller will decide how to
# handle errors, etc.
ensure
@logger.callback = old_logger_callback
cleanup
end
errors.size == errorlen
end | ruby | def scrape(repo, incremental=true, &callback)
old_logger_callback = @logger.callback
@logger.callback = callback
errorlen = errors.size
begin
if retrieved = retrieve(repo)
scan(retrieved)
end
rescue Exception
# legacy logger handles communication with the end user and appending
# to our error list; we just need to keep going. the new methodology
# has no such guaranteed communication so the caller will decide how to
# handle errors, etc.
ensure
@logger.callback = old_logger_callback
cleanup
end
errors.size == errorlen
end | [
"def",
"scrape",
"(",
"repo",
",",
"incremental",
"=",
"true",
",",
"&",
"callback",
")",
"old_logger_callback",
"=",
"@logger",
".",
"callback",
"@logger",
".",
"callback",
"=",
"callback",
"errorlen",
"=",
"errors",
".",
"size",
"begin",
"if",
"retrieved",
"=",
"retrieve",
"(",
"repo",
")",
"scan",
"(",
"retrieved",
")",
"end",
"rescue",
"Exception",
"ensure",
"@logger",
".",
"callback",
"=",
"old_logger_callback",
"cleanup",
"end",
"errors",
".",
"size",
"==",
"errorlen",
"end"
]
| Initialize scrape destination directory
=== Options
<tt>:kind</tt>:: Type of scraper that will traverse directory for resources, one of :cookbook or :workflow
<tt>:basedir</tt>:: Local directory where files are retrieved and scraped, use temporary directory if nil
<tt>:max_bytes</tt>:: Maximum number of bytes to read from remote repo, unlimited if nil
<tt>:max_seconds</tt>:: Maximum number of seconds to spend reading from remote repo, unlimited if nil
Scrapes and scans a given repository.
@deprecated the newer methodology will perform these operations in stages
controlled externally instead of calling this all-in-one method.
=== Parameters
repo(Hash|RightScraper::Repositories::Base):: Repository to be scraped
Note: repo can either be a Hash or a RightScraper::Repositories::Base instance.
See the RightScraper::Repositories::Base class for valid Hash keys.
=== Block
If a block is given, it will be called back with progress information
the block should take four arguments:
- first argument is one of <tt>:begin</tt>, <tt>:commit</tt>,
<tt>:abort</tt> which signifies what
the scraper is trying to do and where it is when it does it
- second argument is a symbol describing the operation being performed
in an easy-to-match way
- third argument is optional further explanation
- fourth argument is the exception pending (only relevant for <tt>:abort</tt>)
=== Return
true:: If scrape was successful
false:: If scrape failed, call errors for information on failure
=== Raise
'Invalid repository type':: If repository type is not known | [
"Initialize",
"scrape",
"destination",
"directory"
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/main.rb#L110-L128 | train |
rightscale/right_scraper | lib/right_scraper/retrievers/download.rb | RightScraper::Retrievers.Download.retrieve | def retrieve
raise RetrieverError.new("download retriever is unavailable") unless available?
::FileUtils.remove_entry_secure @repo_dir if File.exists?(@repo_dir)
::FileUtils.remove_entry_secure workdir if File.exists?(workdir)
::FileUtils.mkdir_p @repo_dir
::FileUtils.mkdir_p workdir
file = ::File.join(workdir, "package")
# TEAL FIX: we have to always-download the tarball before we can
# determine if contents have changed, but afterward we can compare the
# previous download against the latest downloaded and short-circuit the
# remaining flow for the no-difference case.
@logger.operation(:downloading) do
credential_command = if @repository.first_credential && @repository.second_credential
['-u', "#{@repository.first_credential}:#{@repository.second_credential}"]
else
[]
end
@output = ::RightScale::RightPopen::SafeOutputBuffer.new
@cmd = [
'curl',
'--silent', '--show-error', '--location', '--fail',
'--location-trusted', '-o', file, credential_command,
@repository.url
].flatten
begin
::RightScale::RightPopen.popen3_sync(
@cmd,
:target => self,
:pid_handler => :pid_download,
:timeout_handler => :timeout_download,
:size_limit_handler => :size_limit_download,
:exit_handler => :exit_download,
:stderr_handler => :output_download,
:stdout_handler => :output_download,
:inherit_io => true, # avoid killing any rails connection
:watch_directory => workdir,
:size_limit_bytes => @max_bytes,
:timeout_seconds => @max_seconds)
rescue Exception => e
@logger.note_phase(:abort, :running_command, 'curl', e)
raise
end
end
note_tag(file)
@logger.operation(:unpacking) do
path = @repository.to_url.path
if path =~ /\.gz$/
extraction = "xzf"
elsif path =~ /\.bz2$/
extraction = "xjf"
else
extraction = "xf"
end
Dir.chdir(@repo_dir) do
@output = ::RightScale::RightPopen::SafeOutputBuffer.new
@cmd = ['tar', extraction, file]
begin
::RightScale::RightPopen.popen3_sync(
@cmd,
:target => self,
:pid_handler => :pid_download,
:timeout_handler => :timeout_download,
:size_limit_handler => :size_limit_download,
:exit_handler => :exit_download,
:stderr_handler => :output_download,
:stdout_handler => :output_download,
:inherit_io => true, # avoid killing any rails connection
:watch_directory => @repo_dir,
:size_limit_bytes => @max_bytes,
:timeout_seconds => @max_seconds)
rescue Exception => e
@logger.note_phase(:abort, :running_command, @cmd.first, e)
raise
end
end
end
true
end | ruby | def retrieve
raise RetrieverError.new("download retriever is unavailable") unless available?
::FileUtils.remove_entry_secure @repo_dir if File.exists?(@repo_dir)
::FileUtils.remove_entry_secure workdir if File.exists?(workdir)
::FileUtils.mkdir_p @repo_dir
::FileUtils.mkdir_p workdir
file = ::File.join(workdir, "package")
# TEAL FIX: we have to always-download the tarball before we can
# determine if contents have changed, but afterward we can compare the
# previous download against the latest downloaded and short-circuit the
# remaining flow for the no-difference case.
@logger.operation(:downloading) do
credential_command = if @repository.first_credential && @repository.second_credential
['-u', "#{@repository.first_credential}:#{@repository.second_credential}"]
else
[]
end
@output = ::RightScale::RightPopen::SafeOutputBuffer.new
@cmd = [
'curl',
'--silent', '--show-error', '--location', '--fail',
'--location-trusted', '-o', file, credential_command,
@repository.url
].flatten
begin
::RightScale::RightPopen.popen3_sync(
@cmd,
:target => self,
:pid_handler => :pid_download,
:timeout_handler => :timeout_download,
:size_limit_handler => :size_limit_download,
:exit_handler => :exit_download,
:stderr_handler => :output_download,
:stdout_handler => :output_download,
:inherit_io => true, # avoid killing any rails connection
:watch_directory => workdir,
:size_limit_bytes => @max_bytes,
:timeout_seconds => @max_seconds)
rescue Exception => e
@logger.note_phase(:abort, :running_command, 'curl', e)
raise
end
end
note_tag(file)
@logger.operation(:unpacking) do
path = @repository.to_url.path
if path =~ /\.gz$/
extraction = "xzf"
elsif path =~ /\.bz2$/
extraction = "xjf"
else
extraction = "xf"
end
Dir.chdir(@repo_dir) do
@output = ::RightScale::RightPopen::SafeOutputBuffer.new
@cmd = ['tar', extraction, file]
begin
::RightScale::RightPopen.popen3_sync(
@cmd,
:target => self,
:pid_handler => :pid_download,
:timeout_handler => :timeout_download,
:size_limit_handler => :size_limit_download,
:exit_handler => :exit_download,
:stderr_handler => :output_download,
:stdout_handler => :output_download,
:inherit_io => true, # avoid killing any rails connection
:watch_directory => @repo_dir,
:size_limit_bytes => @max_bytes,
:timeout_seconds => @max_seconds)
rescue Exception => e
@logger.note_phase(:abort, :running_command, @cmd.first, e)
raise
end
end
end
true
end | [
"def",
"retrieve",
"raise",
"RetrieverError",
".",
"new",
"(",
"\"download retriever is unavailable\"",
")",
"unless",
"available?",
"::",
"FileUtils",
".",
"remove_entry_secure",
"@repo_dir",
"if",
"File",
".",
"exists?",
"(",
"@repo_dir",
")",
"::",
"FileUtils",
".",
"remove_entry_secure",
"workdir",
"if",
"File",
".",
"exists?",
"(",
"workdir",
")",
"::",
"FileUtils",
".",
"mkdir_p",
"@repo_dir",
"::",
"FileUtils",
".",
"mkdir_p",
"workdir",
"file",
"=",
"::",
"File",
".",
"join",
"(",
"workdir",
",",
"\"package\"",
")",
"@logger",
".",
"operation",
"(",
":downloading",
")",
"do",
"credential_command",
"=",
"if",
"@repository",
".",
"first_credential",
"&&",
"@repository",
".",
"second_credential",
"[",
"'-u'",
",",
"\"#{@repository.first_credential}:#{@repository.second_credential}\"",
"]",
"else",
"[",
"]",
"end",
"@output",
"=",
"::",
"RightScale",
"::",
"RightPopen",
"::",
"SafeOutputBuffer",
".",
"new",
"@cmd",
"=",
"[",
"'curl'",
",",
"'--silent'",
",",
"'--show-error'",
",",
"'--location'",
",",
"'--fail'",
",",
"'--location-trusted'",
",",
"'-o'",
",",
"file",
",",
"credential_command",
",",
"@repository",
".",
"url",
"]",
".",
"flatten",
"begin",
"::",
"RightScale",
"::",
"RightPopen",
".",
"popen3_sync",
"(",
"@cmd",
",",
":target",
"=>",
"self",
",",
":pid_handler",
"=>",
":pid_download",
",",
":timeout_handler",
"=>",
":timeout_download",
",",
":size_limit_handler",
"=>",
":size_limit_download",
",",
":exit_handler",
"=>",
":exit_download",
",",
":stderr_handler",
"=>",
":output_download",
",",
":stdout_handler",
"=>",
":output_download",
",",
":inherit_io",
"=>",
"true",
",",
":watch_directory",
"=>",
"workdir",
",",
":size_limit_bytes",
"=>",
"@max_bytes",
",",
":timeout_seconds",
"=>",
"@max_seconds",
")",
"rescue",
"Exception",
"=>",
"e",
"@logger",
".",
"note_phase",
"(",
":abort",
",",
":running_command",
",",
"'curl'",
",",
"e",
")",
"raise",
"end",
"end",
"note_tag",
"(",
"file",
")",
"@logger",
".",
"operation",
"(",
":unpacking",
")",
"do",
"path",
"=",
"@repository",
".",
"to_url",
".",
"path",
"if",
"path",
"=~",
"/",
"\\.",
"/",
"extraction",
"=",
"\"xzf\"",
"elsif",
"path",
"=~",
"/",
"\\.",
"/",
"extraction",
"=",
"\"xjf\"",
"else",
"extraction",
"=",
"\"xf\"",
"end",
"Dir",
".",
"chdir",
"(",
"@repo_dir",
")",
"do",
"@output",
"=",
"::",
"RightScale",
"::",
"RightPopen",
"::",
"SafeOutputBuffer",
".",
"new",
"@cmd",
"=",
"[",
"'tar'",
",",
"extraction",
",",
"file",
"]",
"begin",
"::",
"RightScale",
"::",
"RightPopen",
".",
"popen3_sync",
"(",
"@cmd",
",",
":target",
"=>",
"self",
",",
":pid_handler",
"=>",
":pid_download",
",",
":timeout_handler",
"=>",
":timeout_download",
",",
":size_limit_handler",
"=>",
":size_limit_download",
",",
":exit_handler",
"=>",
":exit_download",
",",
":stderr_handler",
"=>",
":output_download",
",",
":stdout_handler",
"=>",
":output_download",
",",
":inherit_io",
"=>",
"true",
",",
":watch_directory",
"=>",
"@repo_dir",
",",
":size_limit_bytes",
"=>",
"@max_bytes",
",",
":timeout_seconds",
"=>",
"@max_seconds",
")",
"rescue",
"Exception",
"=>",
"e",
"@logger",
".",
"note_phase",
"(",
":abort",
",",
":running_command",
",",
"@cmd",
".",
"first",
",",
"e",
")",
"raise",
"end",
"end",
"end",
"true",
"end"
]
| Download tarball and unpack it | [
"Download",
"tarball",
"and",
"unpack",
"it"
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/retrievers/download.rb#L69-L149 | train |
gively/cadmus | lib/cadmus/renderers.rb | Cadmus.Renderable.setup_renderer | def setup_renderer(renderer)
renderer.default_assigns = liquid_assigns if respond_to?(:liquid_assigns, true)
renderer.default_registers = liquid_registers if respond_to?(:liquid_registers, true)
renderer.default_filters = liquid_filters if respond_to?(:liquid_filters, true)
end | ruby | def setup_renderer(renderer)
renderer.default_assigns = liquid_assigns if respond_to?(:liquid_assigns, true)
renderer.default_registers = liquid_registers if respond_to?(:liquid_registers, true)
renderer.default_filters = liquid_filters if respond_to?(:liquid_filters, true)
end | [
"def",
"setup_renderer",
"(",
"renderer",
")",
"renderer",
".",
"default_assigns",
"=",
"liquid_assigns",
"if",
"respond_to?",
"(",
":liquid_assigns",
",",
"true",
")",
"renderer",
".",
"default_registers",
"=",
"liquid_registers",
"if",
"respond_to?",
"(",
":liquid_registers",
",",
"true",
")",
"renderer",
".",
"default_filters",
"=",
"liquid_filters",
"if",
"respond_to?",
"(",
":liquid_filters",
",",
"true",
")",
"end"
]
| Sets the values of +default_assigns+, +default_registers+ and +default_filters+ on a given
renderer using the +liquid_assigns+, +liquid_registers+ and +liquid_filters+ methods, if
they're defined. | [
"Sets",
"the",
"values",
"of",
"+",
"default_assigns",
"+",
"+",
"default_registers",
"+",
"and",
"+",
"default_filters",
"+",
"on",
"a",
"given",
"renderer",
"using",
"the",
"+",
"liquid_assigns",
"+",
"+",
"liquid_registers",
"+",
"and",
"+",
"liquid_filters",
"+",
"methods",
"if",
"they",
"re",
"defined",
"."
]
| 5e0f8b6404da14e320d858eb8dacd12ae79dcfb0 | https://github.com/gively/cadmus/blob/5e0f8b6404da14e320d858eb8dacd12ae79dcfb0/lib/cadmus/renderers.rb#L118-L122 | train |
fixrb/spectus | lib/spectus/expectation_target.rb | Spectus.ExpectationTarget.MUST | def MUST(m)
RequirementLevel::High.new(m, false, subject, *challenges).result
end | ruby | def MUST(m)
RequirementLevel::High.new(m, false, subject, *challenges).result
end | [
"def",
"MUST",
"(",
"m",
")",
"RequirementLevel",
"::",
"High",
".",
"new",
"(",
"m",
",",
"false",
",",
"subject",
",",
"*",
"challenges",
")",
".",
"result",
"end"
]
| Create a new expection target
@api private
@param subject [Proc] The value which is compared with the expected value.
rubocop:disable Style/MethodName
rubocop:disable Naming/UncommunicativeMethodParamName
@api public
This word, or the terms "REQUIRED" or "SHALL", mean that the
definition is an absolute requirement of the specification.
@example _Absolute requirement_ definition
it { 'foo'.upcase }.MUST eql 'FOO'
@param m [#matches?] The matcher.
@return [Result::Fail, Result::Pass] Report if the spec pass or fail. | [
"Create",
"a",
"new",
"expection",
"target"
]
| 547d994dede16de462f52f960948b80fa71fb515 | https://github.com/fixrb/spectus/blob/547d994dede16de462f52f960948b80fa71fb515/lib/spectus/expectation_target.rb#L37-L39 | train |
fixrb/spectus | lib/spectus/expectation_target.rb | Spectus.ExpectationTarget.MUST_NOT | def MUST_NOT(m)
RequirementLevel::High.new(m, true, subject, *challenges).result
end | ruby | def MUST_NOT(m)
RequirementLevel::High.new(m, true, subject, *challenges).result
end | [
"def",
"MUST_NOT",
"(",
"m",
")",
"RequirementLevel",
"::",
"High",
".",
"new",
"(",
"m",
",",
"true",
",",
"subject",
",",
"*",
"challenges",
")",
".",
"result",
"end"
]
| This phrase, or the phrase "SHALL NOT", mean that the
definition is an absolute prohibition of the specification.
@example _Absolute prohibition_ definition
it { 'foo'.size }.MUST_NOT equal 42
@param m [#matches?] The matcher.
@return [Result::Fail, Result::Pass] Report if the spec pass or fail. | [
"This",
"phrase",
"or",
"the",
"phrase",
"SHALL",
"NOT",
"mean",
"that",
"the",
"definition",
"is",
"an",
"absolute",
"prohibition",
"of",
"the",
"specification",
"."
]
| 547d994dede16de462f52f960948b80fa71fb515 | https://github.com/fixrb/spectus/blob/547d994dede16de462f52f960948b80fa71fb515/lib/spectus/expectation_target.rb#L58-L60 | train |
fixrb/spectus | lib/spectus/expectation_target.rb | Spectus.ExpectationTarget.SHOULD | def SHOULD(m)
RequirementLevel::Medium.new(m, false, subject, *challenges).result
end | ruby | def SHOULD(m)
RequirementLevel::Medium.new(m, false, subject, *challenges).result
end | [
"def",
"SHOULD",
"(",
"m",
")",
"RequirementLevel",
"::",
"Medium",
".",
"new",
"(",
"m",
",",
"false",
",",
"subject",
",",
"*",
"challenges",
")",
".",
"result",
"end"
]
| This word, or the adjective "RECOMMENDED", mean that there
may exist valid reasons in particular circumstances to ignore a
particular item, but the full implications must be understood and
carefully weighed before choosing a different course.
@example _Recommended_ definition
it { 'foo'.valid_encoding? }.SHOULD equal true
@param m [#matches?] The matcher.
@return [Result::Fail, Result::Pass] Report if the spec pass or fail. | [
"This",
"word",
"or",
"the",
"adjective",
"RECOMMENDED",
"mean",
"that",
"there",
"may",
"exist",
"valid",
"reasons",
"in",
"particular",
"circumstances",
"to",
"ignore",
"a",
"particular",
"item",
"but",
"the",
"full",
"implications",
"must",
"be",
"understood",
"and",
"carefully",
"weighed",
"before",
"choosing",
"a",
"different",
"course",
"."
]
| 547d994dede16de462f52f960948b80fa71fb515 | https://github.com/fixrb/spectus/blob/547d994dede16de462f52f960948b80fa71fb515/lib/spectus/expectation_target.rb#L81-L83 | train |
fixrb/spectus | lib/spectus/expectation_target.rb | Spectus.ExpectationTarget.SHOULD_NOT | def SHOULD_NOT(m)
RequirementLevel::Medium.new(m, true, subject, *challenges).result
end | ruby | def SHOULD_NOT(m)
RequirementLevel::Medium.new(m, true, subject, *challenges).result
end | [
"def",
"SHOULD_NOT",
"(",
"m",
")",
"RequirementLevel",
"::",
"Medium",
".",
"new",
"(",
"m",
",",
"true",
",",
"subject",
",",
"*",
"challenges",
")",
".",
"result",
"end"
]
| This phrase, or the phrase "NOT RECOMMENDED" mean that
there may exist valid reasons in particular circumstances when the
particular behavior is acceptable or even useful, but the full
implications should be understood and the case carefully weighed
before implementing any behavior described with this label.
@example _Not recommended_ definition
it { ''.blank? }.SHOULD_NOT raise_exception NoMethodError
@param m [#matches?] The matcher.
@return [Result::Fail, Result::Pass] Report if the spec pass or fail. | [
"This",
"phrase",
"or",
"the",
"phrase",
"NOT",
"RECOMMENDED",
"mean",
"that",
"there",
"may",
"exist",
"valid",
"reasons",
"in",
"particular",
"circumstances",
"when",
"the",
"particular",
"behavior",
"is",
"acceptable",
"or",
"even",
"useful",
"but",
"the",
"full",
"implications",
"should",
"be",
"understood",
"and",
"the",
"case",
"carefully",
"weighed",
"before",
"implementing",
"any",
"behavior",
"described",
"with",
"this",
"label",
"."
]
| 547d994dede16de462f52f960948b80fa71fb515 | https://github.com/fixrb/spectus/blob/547d994dede16de462f52f960948b80fa71fb515/lib/spectus/expectation_target.rb#L105-L107 | train |
rightscale/right_scraper | lib/right_scraper/scrapers/cookbook.rb | RightScraper::Scrapers.Cookbook.find_next | def find_next(dir)
@logger.operation(:finding_next_cookbook, "in #{dir.path}") do
if COOKBOOK_SENTINELS.any? { |f| File.exists?(File.join(dir.path, f)) }
@logger.operation(:reading_cookbook, "from #{dir.path}") do
cookbook = RightScraper::Resources::Cookbook.new(
@repository,
strip_repo_dir(dir.path),
repo_dir)
@builder.go(dir.path, cookbook)
cookbook
end
else
@stack << dir
search_dirs
end
end
end | ruby | def find_next(dir)
@logger.operation(:finding_next_cookbook, "in #{dir.path}") do
if COOKBOOK_SENTINELS.any? { |f| File.exists?(File.join(dir.path, f)) }
@logger.operation(:reading_cookbook, "from #{dir.path}") do
cookbook = RightScraper::Resources::Cookbook.new(
@repository,
strip_repo_dir(dir.path),
repo_dir)
@builder.go(dir.path, cookbook)
cookbook
end
else
@stack << dir
search_dirs
end
end
end | [
"def",
"find_next",
"(",
"dir",
")",
"@logger",
".",
"operation",
"(",
":finding_next_cookbook",
",",
"\"in #{dir.path}\"",
")",
"do",
"if",
"COOKBOOK_SENTINELS",
".",
"any?",
"{",
"|",
"f",
"|",
"File",
".",
"exists?",
"(",
"File",
".",
"join",
"(",
"dir",
".",
"path",
",",
"f",
")",
")",
"}",
"@logger",
".",
"operation",
"(",
":reading_cookbook",
",",
"\"from #{dir.path}\"",
")",
"do",
"cookbook",
"=",
"RightScraper",
"::",
"Resources",
"::",
"Cookbook",
".",
"new",
"(",
"@repository",
",",
"strip_repo_dir",
"(",
"dir",
".",
"path",
")",
",",
"repo_dir",
")",
"@builder",
".",
"go",
"(",
"dir",
".",
"path",
",",
"cookbook",
")",
"cookbook",
"end",
"else",
"@stack",
"<<",
"dir",
"search_dirs",
"end",
"end",
"end"
]
| Find the next cookbook, starting in dir.
=== Parameters
dir(Dir):: directory to begin search in | [
"Find",
"the",
"next",
"cookbook",
"starting",
"in",
"dir",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scrapers/cookbook.rb#L37-L53 | train |
rightscale/right_scraper | lib/right_scraper/scrapers/base.rb | RightScraper::Scrapers.Base.search_dirs | def search_dirs
@logger.operation(:searching) do
until @stack.empty?
dir = @stack.last
entry = dir.read
if entry == nil
dir.close
@stack.pop
next
end
next if entry == '.' || entry == '..'
next if ignorable?(entry)
fullpath = File.join(dir.path, entry)
if File.directory?(fullpath)
result = find_next(Dir.new(fullpath))
break
end
end
result
end
end | ruby | def search_dirs
@logger.operation(:searching) do
until @stack.empty?
dir = @stack.last
entry = dir.read
if entry == nil
dir.close
@stack.pop
next
end
next if entry == '.' || entry == '..'
next if ignorable?(entry)
fullpath = File.join(dir.path, entry)
if File.directory?(fullpath)
result = find_next(Dir.new(fullpath))
break
end
end
result
end
end | [
"def",
"search_dirs",
"@logger",
".",
"operation",
"(",
":searching",
")",
"do",
"until",
"@stack",
".",
"empty?",
"dir",
"=",
"@stack",
".",
"last",
"entry",
"=",
"dir",
".",
"read",
"if",
"entry",
"==",
"nil",
"dir",
".",
"close",
"@stack",
".",
"pop",
"next",
"end",
"next",
"if",
"entry",
"==",
"'.'",
"||",
"entry",
"==",
"'..'",
"next",
"if",
"ignorable?",
"(",
"entry",
")",
"fullpath",
"=",
"File",
".",
"join",
"(",
"dir",
".",
"path",
",",
"entry",
")",
"if",
"File",
".",
"directory?",
"(",
"fullpath",
")",
"result",
"=",
"find_next",
"(",
"Dir",
".",
"new",
"(",
"fullpath",
")",
")",
"break",
"end",
"end",
"result",
"end",
"end"
]
| Search the directory stack looking for the next resource. | [
"Search",
"the",
"directory",
"stack",
"looking",
"for",
"the",
"next",
"resource",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scrapers/base.rb#L247-L270 | train |
rightscale/right_scraper | lib/right_scraper/scanners/union.rb | RightScraper::Scanners.Union.notice | def notice(relative_position)
data = nil
@subscanners.each {|scanner| scanner.notice(relative_position) {
data = yield if data.nil?
data
}
}
end | ruby | def notice(relative_position)
data = nil
@subscanners.each {|scanner| scanner.notice(relative_position) {
data = yield if data.nil?
data
}
}
end | [
"def",
"notice",
"(",
"relative_position",
")",
"data",
"=",
"nil",
"@subscanners",
".",
"each",
"{",
"|",
"scanner",
"|",
"scanner",
".",
"notice",
"(",
"relative_position",
")",
"{",
"data",
"=",
"yield",
"if",
"data",
".",
"nil?",
"data",
"}",
"}",
"end"
]
| Notice a file during scanning.
=== Block
Return the data for this file. We use a block because it may
not always be necessary to read the data.
=== Parameters
relative_position(String):: relative pathname for the file from the root of resource | [
"Notice",
"a",
"file",
"during",
"scanning",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/scanners/union.rb#L71-L78 | train |
rightscale/right_scraper | spec/spec_helper.rb | RightScraper.SpecHelpers.create_file_layout | def create_file_layout(path, layout)
FileUtils.mkdir_p(path)
result = []
layout.each do |elem|
if elem.is_a?(Hash)
elem.each do |k, v|
full_path = File.join(path, k)
FileUtils.mkdir_p(full_path)
result += create_file_layout(full_path, v)
end
elsif elem.is_a?(FileContent)
fullpath = ::File.join(path, elem.name)
File.open(fullpath, 'w') { |f| f.write elem.content }
result << fullpath
else
fullpath = ::File.join(path, elem.to_s)
File.open(fullpath, 'w') { |f| f.puts elem.to_s }
result << fullpath
end
end
result
end | ruby | def create_file_layout(path, layout)
FileUtils.mkdir_p(path)
result = []
layout.each do |elem|
if elem.is_a?(Hash)
elem.each do |k, v|
full_path = File.join(path, k)
FileUtils.mkdir_p(full_path)
result += create_file_layout(full_path, v)
end
elsif elem.is_a?(FileContent)
fullpath = ::File.join(path, elem.name)
File.open(fullpath, 'w') { |f| f.write elem.content }
result << fullpath
else
fullpath = ::File.join(path, elem.to_s)
File.open(fullpath, 'w') { |f| f.puts elem.to_s }
result << fullpath
end
end
result
end | [
"def",
"create_file_layout",
"(",
"path",
",",
"layout",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"path",
")",
"result",
"=",
"[",
"]",
"layout",
".",
"each",
"do",
"|",
"elem",
"|",
"if",
"elem",
".",
"is_a?",
"(",
"Hash",
")",
"elem",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"full_path",
"=",
"File",
".",
"join",
"(",
"path",
",",
"k",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"full_path",
")",
"result",
"+=",
"create_file_layout",
"(",
"full_path",
",",
"v",
")",
"end",
"elsif",
"elem",
".",
"is_a?",
"(",
"FileContent",
")",
"fullpath",
"=",
"::",
"File",
".",
"join",
"(",
"path",
",",
"elem",
".",
"name",
")",
"File",
".",
"open",
"(",
"fullpath",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"elem",
".",
"content",
"}",
"result",
"<<",
"fullpath",
"else",
"fullpath",
"=",
"::",
"File",
".",
"join",
"(",
"path",
",",
"elem",
".",
"to_s",
")",
"File",
".",
"open",
"(",
"fullpath",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"puts",
"elem",
".",
"to_s",
"}",
"result",
"<<",
"fullpath",
"end",
"end",
"result",
"end"
]
| Create file layout from given array
Strings in array correspond to files while Hashes correspond to folders
File content is equal to filename
=== Parameters
@param [String] path where layout should be created
@param [Array] layout to be created
=== Return
@return [Array] list of created file paths | [
"Create",
"file",
"layout",
"from",
"given",
"array",
"Strings",
"in",
"array",
"correspond",
"to",
"files",
"while",
"Hashes",
"correspond",
"to",
"folders",
"File",
"content",
"is",
"equal",
"to",
"filename"
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/spec/spec_helper.rb#L181-L202 | train |
rightscale/right_scraper | spec/spec_helper.rb | RightScraper.SpecHelpers.extract_file_layout | def extract_file_layout(path, ignore=[])
return [] unless File.directory?(path)
dirs = []
files = []
ignore += [ '.', '..' ]
Dir.foreach(path) do |f|
next if ignore.include?(f)
full_path = File.join(path, f)
if File.directory?(full_path)
dirs << { f => extract_file_layout(full_path, ignore) }
else
files << f
end
end
dirs + files.sort
end | ruby | def extract_file_layout(path, ignore=[])
return [] unless File.directory?(path)
dirs = []
files = []
ignore += [ '.', '..' ]
Dir.foreach(path) do |f|
next if ignore.include?(f)
full_path = File.join(path, f)
if File.directory?(full_path)
dirs << { f => extract_file_layout(full_path, ignore) }
else
files << f
end
end
dirs + files.sort
end | [
"def",
"extract_file_layout",
"(",
"path",
",",
"ignore",
"=",
"[",
"]",
")",
"return",
"[",
"]",
"unless",
"File",
".",
"directory?",
"(",
"path",
")",
"dirs",
"=",
"[",
"]",
"files",
"=",
"[",
"]",
"ignore",
"+=",
"[",
"'.'",
",",
"'..'",
"]",
"Dir",
".",
"foreach",
"(",
"path",
")",
"do",
"|",
"f",
"|",
"next",
"if",
"ignore",
".",
"include?",
"(",
"f",
")",
"full_path",
"=",
"File",
".",
"join",
"(",
"path",
",",
"f",
")",
"if",
"File",
".",
"directory?",
"(",
"full_path",
")",
"dirs",
"<<",
"{",
"f",
"=>",
"extract_file_layout",
"(",
"full_path",
",",
"ignore",
")",
"}",
"else",
"files",
"<<",
"f",
"end",
"end",
"dirs",
"+",
"files",
".",
"sort",
"end"
]
| Extract array representing file layout for given directory
=== Parameters
path(String):: Path to directory whose layout is to be retrieved
layout(Array):: Array being updated with layout, same as return value, empty array by default
ignore(Array):: Optional: Name of files or directories that should be ignored
=== Return
layout(Array):: Corresponding layout as used by 'create_file_layout' | [
"Extract",
"array",
"representing",
"file",
"layout",
"for",
"given",
"directory"
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/spec/spec_helper.rb#L213-L228 | train |
rightscale/right_scraper | lib/right_scraper/repositories/base.rb | RightScraper::Repositories.Base.equal_repo? | def equal_repo?(other)
if other.is_a?(RightScraper::Repositories::Base)
repository_hash == other.repository_hash
else
false
end
end | ruby | def equal_repo?(other)
if other.is_a?(RightScraper::Repositories::Base)
repository_hash == other.repository_hash
else
false
end
end | [
"def",
"equal_repo?",
"(",
"other",
")",
"if",
"other",
".",
"is_a?",
"(",
"RightScraper",
"::",
"Repositories",
"::",
"Base",
")",
"repository_hash",
"==",
"other",
".",
"repository_hash",
"else",
"false",
"end",
"end"
]
| Return true if this repository and +other+ represent the same
repository including the same checkout tag.
=== Parameters
other(Repositories::Base):: repository to compare with
=== Returns
Boolean:: true iff this repository and +other+ are the same
Return true if this repository and +other+ represent the same
repository, excluding the checkout tag.
=== Parameters
other(Repositories::Base):: repository to compare with
=== Returns
Boolean:: true iff this repository and +other+ are the same | [
"Return",
"true",
"if",
"this",
"repository",
"and",
"+",
"other",
"+",
"represent",
"the",
"same",
"repository",
"including",
"the",
"same",
"checkout",
"tag",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/repositories/base.rb#L206-L212 | train |
rightscale/right_scraper | lib/right_scraper/repositories/base.rb | RightScraper::Repositories.Base.add_users_to | def add_users_to(uri, username=nil, password=nil)
begin
uri = URI.parse(uri) if uri.instance_of?(String)
if username
userinfo = URI.escape(username, USERPW)
userinfo += ":" + URI.escape(password, USERPW) unless password.nil?
uri.userinfo = userinfo
end
uri
rescue URI::InvalidURIError
if uri =~ PATTERN::GIT_URI
user, host, path = $1, $2, $3
userinfo = URI.escape(user, USERPW)
userinfo += ":" + URI.escape(username, USERPW) unless username.nil?
path = "/" + path unless path.start_with?('/')
URI::Generic::build({:scheme => "ssh",
:userinfo => userinfo,
:host => host,
:path => path
})
else
raise
end
end
end | ruby | def add_users_to(uri, username=nil, password=nil)
begin
uri = URI.parse(uri) if uri.instance_of?(String)
if username
userinfo = URI.escape(username, USERPW)
userinfo += ":" + URI.escape(password, USERPW) unless password.nil?
uri.userinfo = userinfo
end
uri
rescue URI::InvalidURIError
if uri =~ PATTERN::GIT_URI
user, host, path = $1, $2, $3
userinfo = URI.escape(user, USERPW)
userinfo += ":" + URI.escape(username, USERPW) unless username.nil?
path = "/" + path unless path.start_with?('/')
URI::Generic::build({:scheme => "ssh",
:userinfo => userinfo,
:host => host,
:path => path
})
else
raise
end
end
end | [
"def",
"add_users_to",
"(",
"uri",
",",
"username",
"=",
"nil",
",",
"password",
"=",
"nil",
")",
"begin",
"uri",
"=",
"URI",
".",
"parse",
"(",
"uri",
")",
"if",
"uri",
".",
"instance_of?",
"(",
"String",
")",
"if",
"username",
"userinfo",
"=",
"URI",
".",
"escape",
"(",
"username",
",",
"USERPW",
")",
"userinfo",
"+=",
"\":\"",
"+",
"URI",
".",
"escape",
"(",
"password",
",",
"USERPW",
")",
"unless",
"password",
".",
"nil?",
"uri",
".",
"userinfo",
"=",
"userinfo",
"end",
"uri",
"rescue",
"URI",
"::",
"InvalidURIError",
"if",
"uri",
"=~",
"PATTERN",
"::",
"GIT_URI",
"user",
",",
"host",
",",
"path",
"=",
"$1",
",",
"$2",
",",
"$3",
"userinfo",
"=",
"URI",
".",
"escape",
"(",
"user",
",",
"USERPW",
")",
"userinfo",
"+=",
"\":\"",
"+",
"URI",
".",
"escape",
"(",
"username",
",",
"USERPW",
")",
"unless",
"username",
".",
"nil?",
"path",
"=",
"\"/\"",
"+",
"path",
"unless",
"path",
".",
"start_with?",
"(",
"'/'",
")",
"URI",
"::",
"Generic",
"::",
"build",
"(",
"{",
":scheme",
"=>",
"\"ssh\"",
",",
":userinfo",
"=>",
"userinfo",
",",
":host",
"=>",
"host",
",",
":path",
"=>",
"path",
"}",
")",
"else",
"raise",
"end",
"end",
"end"
]
| Return a URI with the given username and password set.
=== Parameters
uri(URI or String):: URI to add user identification to
=== Returns
URI:: URI with username and password identification added | [
"Return",
"a",
"URI",
"with",
"the",
"given",
"username",
"and",
"password",
"set",
"."
]
| 8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae | https://github.com/rightscale/right_scraper/blob/8ec1555c65e2649a55a03ff16dc8cbe215a0e8ae/lib/right_scraper/repositories/base.rb#L250-L274 | train |
mare-imbrium/canis | lib/canis/core/util/rcommandwindow.rb | Canis.KeyDispatcher.process_key | def process_key ch
chr = nil
if ch > 0 and ch < 256
chr = ch.chr
end
return :UNHANDLED unless @key_map
@key_map.each_pair do |k,p|
#$log.debug "KKK: processing key #{ch} #{chr} "
if (k == ch || k == chr)
#$log.debug "KKK: checking match == #{k}: #{ch} #{chr} "
# compare both int key and chr
#$log.debug "KKK: found match 1 #{ch} #{chr} "
p.call(self, ch)
return 0
elsif k.respond_to? :include?
#$log.debug "KKK: checking match include #{k}: #{ch} #{chr} "
# this bombs if its a String and we check for include of a ch.
if !k.is_a?( String ) && (k.include?( ch ) || k.include?(chr))
#$log.debug "KKK: found match include #{ch} #{chr} "
p.call(self, ch)
return 0
end
elsif k.is_a? Regexp
if k.match(chr)
#$log.debug "KKK: found match regex #{ch} #{chr} "
p.call(self, ch)
return 0
end
end
end
return :UNHANDLED
end | ruby | def process_key ch
chr = nil
if ch > 0 and ch < 256
chr = ch.chr
end
return :UNHANDLED unless @key_map
@key_map.each_pair do |k,p|
#$log.debug "KKK: processing key #{ch} #{chr} "
if (k == ch || k == chr)
#$log.debug "KKK: checking match == #{k}: #{ch} #{chr} "
# compare both int key and chr
#$log.debug "KKK: found match 1 #{ch} #{chr} "
p.call(self, ch)
return 0
elsif k.respond_to? :include?
#$log.debug "KKK: checking match include #{k}: #{ch} #{chr} "
# this bombs if its a String and we check for include of a ch.
if !k.is_a?( String ) && (k.include?( ch ) || k.include?(chr))
#$log.debug "KKK: found match include #{ch} #{chr} "
p.call(self, ch)
return 0
end
elsif k.is_a? Regexp
if k.match(chr)
#$log.debug "KKK: found match regex #{ch} #{chr} "
p.call(self, ch)
return 0
end
end
end
return :UNHANDLED
end | [
"def",
"process_key",
"ch",
"chr",
"=",
"nil",
"if",
"ch",
">",
"0",
"and",
"ch",
"<",
"256",
"chr",
"=",
"ch",
".",
"chr",
"end",
"return",
":UNHANDLED",
"unless",
"@key_map",
"@key_map",
".",
"each_pair",
"do",
"|",
"k",
",",
"p",
"|",
"if",
"(",
"k",
"==",
"ch",
"||",
"k",
"==",
"chr",
")",
"p",
".",
"call",
"(",
"self",
",",
"ch",
")",
"return",
"0",
"elsif",
"k",
".",
"respond_to?",
":include?",
"if",
"!",
"k",
".",
"is_a?",
"(",
"String",
")",
"&&",
"(",
"k",
".",
"include?",
"(",
"ch",
")",
"||",
"k",
".",
"include?",
"(",
"chr",
")",
")",
"p",
".",
"call",
"(",
"self",
",",
"ch",
")",
"return",
"0",
"end",
"elsif",
"k",
".",
"is_a?",
"Regexp",
"if",
"k",
".",
"match",
"(",
"chr",
")",
"p",
".",
"call",
"(",
"self",
",",
"ch",
")",
"return",
"0",
"end",
"end",
"end",
"return",
":UNHANDLED",
"end"
]
| checks the key against +@key_map+ if its set
@param [Integer] ch character read by +Window+
@return [0, :UNHANDLED] 0 if processed, :UNHANDLED if not processed so higher level can process | [
"checks",
"the",
"key",
"against",
"+"
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L463-L494 | train |
mare-imbrium/canis | lib/canis/core/util/rcommandwindow.rb | Canis.KeyDispatcher.default_string_key_map | def default_string_key_map
require 'canis/core/include/action'
@key_map ||= {}
@key_map[ Regexp.new('[a-zA-Z0-9_\.\/]') ] = Action.new("Append to pattern") { |obj, ch|
obj.buffer << ch.chr
obj.buffer_changed
}
@key_map[ [127, ?\C-h.getbyte(0)] ] = Action.new("Delete Prev Char") { |obj, ch|
# backspace
buff = obj.buffer
buff = buff[0..-2] unless buff == ""
obj.set_buffer buff
}
end | ruby | def default_string_key_map
require 'canis/core/include/action'
@key_map ||= {}
@key_map[ Regexp.new('[a-zA-Z0-9_\.\/]') ] = Action.new("Append to pattern") { |obj, ch|
obj.buffer << ch.chr
obj.buffer_changed
}
@key_map[ [127, ?\C-h.getbyte(0)] ] = Action.new("Delete Prev Char") { |obj, ch|
# backspace
buff = obj.buffer
buff = buff[0..-2] unless buff == ""
obj.set_buffer buff
}
end | [
"def",
"default_string_key_map",
"require",
"'canis/core/include/action'",
"@key_map",
"||=",
"{",
"}",
"@key_map",
"[",
"Regexp",
".",
"new",
"(",
"'[a-zA-Z0-9_\\.\\/]'",
")",
"]",
"=",
"Action",
".",
"new",
"(",
"\"Append to pattern\"",
")",
"{",
"|",
"obj",
",",
"ch",
"|",
"obj",
".",
"buffer",
"<<",
"ch",
".",
"chr",
"obj",
".",
"buffer_changed",
"}",
"@key_map",
"[",
"[",
"127",
",",
"?\\C-h",
".",
"getbyte",
"(",
"0",
")",
"]",
"]",
"=",
"Action",
".",
"new",
"(",
"\"Delete Prev Char\"",
")",
"{",
"|",
"obj",
",",
"ch",
"|",
"buff",
"=",
"obj",
".",
"buffer",
"buff",
"=",
"buff",
"[",
"0",
"..",
"-",
"2",
"]",
"unless",
"buff",
"==",
"\"\"",
"obj",
".",
"set_buffer",
"buff",
"}",
"end"
]
| setting up some keys
This is currently an insertion key map, if you want a String named +@buffer+ updated.
Expects buffer_changed and set_buffer to exist as well as +buffer()+.
TODO add left and right arrow keys for changing insertion point. And other keys.
XXX Why are we trying to duplicate a Field here ?? | [
"setting",
"up",
"some",
"keys",
"This",
"is",
"currently",
"an",
"insertion",
"key",
"map",
"if",
"you",
"want",
"a",
"String",
"named",
"+"
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L500-L513 | train |
mare-imbrium/canis | lib/canis/core/util/rcommandwindow.rb | Canis.CommandWindow.press | def press ch
ch = ch.getbyte(0) if ch.class==String ## 1.9
$log.debug " XXX press #{ch} " if $log.debug?
case ch
when -1
return
when KEY_F1, 27, ?\C-q.getbyte(0)
@stop = true
return
when KEY_ENTER, 10, 13
#$log.debug "popup ENTER : #{@selected_index} "
#$log.debug "popup ENTER : #{field.name}" if !field.nil?
@stop = true
return
when ?\C-d.getbyte(0)
@start += @height-1
bounds_check
when KEY_UP
@start -= 1
@start = 0 if @start < 0
when KEY_DOWN
@start += 1
bounds_check
when ?\C-b.getbyte(0)
@start -= @height-1
@start = 0 if @start < 0
when 0
@start = 0
end
Ncurses::Panel.update_panels();
Ncurses.doupdate();
@window.wrefresh
end | ruby | def press ch
ch = ch.getbyte(0) if ch.class==String ## 1.9
$log.debug " XXX press #{ch} " if $log.debug?
case ch
when -1
return
when KEY_F1, 27, ?\C-q.getbyte(0)
@stop = true
return
when KEY_ENTER, 10, 13
#$log.debug "popup ENTER : #{@selected_index} "
#$log.debug "popup ENTER : #{field.name}" if !field.nil?
@stop = true
return
when ?\C-d.getbyte(0)
@start += @height-1
bounds_check
when KEY_UP
@start -= 1
@start = 0 if @start < 0
when KEY_DOWN
@start += 1
bounds_check
when ?\C-b.getbyte(0)
@start -= @height-1
@start = 0 if @start < 0
when 0
@start = 0
end
Ncurses::Panel.update_panels();
Ncurses.doupdate();
@window.wrefresh
end | [
"def",
"press",
"ch",
"ch",
"=",
"ch",
".",
"getbyte",
"(",
"0",
")",
"if",
"ch",
".",
"class",
"==",
"String",
"$log",
".",
"debug",
"\" XXX press #{ch} \"",
"if",
"$log",
".",
"debug?",
"case",
"ch",
"when",
"-",
"1",
"return",
"when",
"KEY_F1",
",",
"27",
",",
"?\\C-q",
".",
"getbyte",
"(",
"0",
")",
"@stop",
"=",
"true",
"return",
"when",
"KEY_ENTER",
",",
"10",
",",
"13",
"@stop",
"=",
"true",
"return",
"when",
"?\\C-d",
".",
"getbyte",
"(",
"0",
")",
"@start",
"+=",
"@height",
"-",
"1",
"bounds_check",
"when",
"KEY_UP",
"@start",
"-=",
"1",
"@start",
"=",
"0",
"if",
"@start",
"<",
"0",
"when",
"KEY_DOWN",
"@start",
"+=",
"1",
"bounds_check",
"when",
"?\\C-b",
".",
"getbyte",
"(",
"0",
")",
"@start",
"-=",
"@height",
"-",
"1",
"@start",
"=",
"0",
"if",
"@start",
"<",
"0",
"when",
"0",
"@start",
"=",
"0",
"end",
"Ncurses",
"::",
"Panel",
".",
"update_panels",
"(",
")",
";",
"Ncurses",
".",
"doupdate",
"(",
")",
";",
"@window",
".",
"wrefresh",
"end"
]
| handles a key, commandline | [
"handles",
"a",
"key",
"commandline"
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L226-L258 | train |
mare-imbrium/canis | lib/canis/core/util/rcommandwindow.rb | Canis.CommandWindow.configure | def configure(*val , &block)
case val.size
when 1
return @config[val[0]]
when 2
@config[val[0]] = val[1]
instance_variable_set("@#{val[0]}", val[1])
end
instance_eval &block if block_given?
end | ruby | def configure(*val , &block)
case val.size
when 1
return @config[val[0]]
when 2
@config[val[0]] = val[1]
instance_variable_set("@#{val[0]}", val[1])
end
instance_eval &block if block_given?
end | [
"def",
"configure",
"(",
"*",
"val",
",",
"&",
"block",
")",
"case",
"val",
".",
"size",
"when",
"1",
"return",
"@config",
"[",
"val",
"[",
"0",
"]",
"]",
"when",
"2",
"@config",
"[",
"val",
"[",
"0",
"]",
"]",
"=",
"val",
"[",
"1",
"]",
"instance_variable_set",
"(",
"\"@#{val[0]}\"",
",",
"val",
"[",
"1",
"]",
")",
"end",
"instance_eval",
"&",
"block",
"if",
"block_given?",
"end"
]
| might as well add more keys for paging. | [
"might",
"as",
"well",
"add",
"more",
"keys",
"for",
"paging",
"."
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L261-L270 | train |
mare-imbrium/canis | lib/canis/core/util/rcommandwindow.rb | Canis.ControlPHandler.recursive_search | def recursive_search glob="**/*"
@command = Proc.new {|str| Dir.glob(glob).select do |p| p.index str; end }
end | ruby | def recursive_search glob="**/*"
@command = Proc.new {|str| Dir.glob(glob).select do |p| p.index str; end }
end | [
"def",
"recursive_search",
"glob",
"=",
"\"**/*\"",
"@command",
"=",
"Proc",
".",
"new",
"{",
"|",
"str",
"|",
"Dir",
".",
"glob",
"(",
"glob",
")",
".",
"select",
"do",
"|",
"p",
"|",
"p",
".",
"index",
"str",
";",
"end",
"}",
"end"
]
| a default proc to requery data based on glob supplied and the pattern user enters | [
"a",
"default",
"proc",
"to",
"requery",
"data",
"based",
"on",
"glob",
"supplied",
"and",
"the",
"pattern",
"user",
"enters"
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L788-L790 | train |
mare-imbrium/canis | lib/canis/core/util/rcommandwindow.rb | Canis.ControlPHandler.data_changed | def data_changed list
sz = list.size
@source.text(list)
wh = @source.form.window.height
@source.form.window.hide
th = @source.height
sh = Ncurses.LINES-1
if sz < @maxht
# rows is less than tp size so reduce tp and window
@source.height = sz
nl = _new_layout sz+1
$log.debug "XXX: adjust ht to #{sz} layout is #{nl} size is #{sz}"
@source.form.window.resize_with(nl)
#Window.refresh_all
else
# expand the window ht to maxht
tt = @maxht-1
@source.height = tt
nl = _new_layout tt+1
$log.debug "XXX: increase ht to #{tt} def layout is #{nl} size is #{sz}"
@source.form.window.resize_with(nl)
end
@source.fire_dimension_changed
@source.init_vars # do if rows is less than current_index.
@source.set_form_row
@source.form.window.show
#Window.refresh_all
@source.form.window.wrefresh
Ncurses::Panel.update_panels();
Ncurses.doupdate();
end | ruby | def data_changed list
sz = list.size
@source.text(list)
wh = @source.form.window.height
@source.form.window.hide
th = @source.height
sh = Ncurses.LINES-1
if sz < @maxht
# rows is less than tp size so reduce tp and window
@source.height = sz
nl = _new_layout sz+1
$log.debug "XXX: adjust ht to #{sz} layout is #{nl} size is #{sz}"
@source.form.window.resize_with(nl)
#Window.refresh_all
else
# expand the window ht to maxht
tt = @maxht-1
@source.height = tt
nl = _new_layout tt+1
$log.debug "XXX: increase ht to #{tt} def layout is #{nl} size is #{sz}"
@source.form.window.resize_with(nl)
end
@source.fire_dimension_changed
@source.init_vars # do if rows is less than current_index.
@source.set_form_row
@source.form.window.show
#Window.refresh_all
@source.form.window.wrefresh
Ncurses::Panel.update_panels();
Ncurses.doupdate();
end | [
"def",
"data_changed",
"list",
"sz",
"=",
"list",
".",
"size",
"@source",
".",
"text",
"(",
"list",
")",
"wh",
"=",
"@source",
".",
"form",
".",
"window",
".",
"height",
"@source",
".",
"form",
".",
"window",
".",
"hide",
"th",
"=",
"@source",
".",
"height",
"sh",
"=",
"Ncurses",
".",
"LINES",
"-",
"1",
"if",
"sz",
"<",
"@maxht",
"@source",
".",
"height",
"=",
"sz",
"nl",
"=",
"_new_layout",
"sz",
"+",
"1",
"$log",
".",
"debug",
"\"XXX: adjust ht to #{sz} layout is #{nl} size is #{sz}\"",
"@source",
".",
"form",
".",
"window",
".",
"resize_with",
"(",
"nl",
")",
"else",
"tt",
"=",
"@maxht",
"-",
"1",
"@source",
".",
"height",
"=",
"tt",
"nl",
"=",
"_new_layout",
"tt",
"+",
"1",
"$log",
".",
"debug",
"\"XXX: increase ht to #{tt} def layout is #{nl} size is #{sz}\"",
"@source",
".",
"form",
".",
"window",
".",
"resize_with",
"(",
"nl",
")",
"end",
"@source",
".",
"fire_dimension_changed",
"@source",
".",
"init_vars",
"@source",
".",
"set_form_row",
"@source",
".",
"form",
".",
"window",
".",
"show",
"@source",
".",
"form",
".",
"window",
".",
"wrefresh",
"Ncurses",
"::",
"Panel",
".",
"update_panels",
"(",
")",
";",
"Ncurses",
".",
"doupdate",
"(",
")",
";",
"end"
]
| specify command to requery data
def command &block
@command = block
end
alias :command= :command
signal that the data has changed and should be redisplayed
with window resizing etc. | [
"specify",
"command",
"to",
"requery",
"data",
"def",
"command",
"&block"
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L800-L833 | train |
mare-imbrium/canis | lib/canis/core/util/rcommandwindow.rb | Canis.ControlPHandler.buffer_changed | def buffer_changed
# display the pattern on the header
@header.text1(">>>#{@buffer}_") if @header
@header.text_right(Dir.pwd) if @header
@no_match = false
if @command
@list = @command.call(@buffer)
else
@list = @__list.select do |line|
line.index @buffer
end
end
sz = @list.size
if sz == 0
Ncurses.beep
#return 1
#this should make ENTER and arrow keys unusable except for BS or Esc,
@list = ["No entries"]
@no_match = true
end
data_changed @list
0
end | ruby | def buffer_changed
# display the pattern on the header
@header.text1(">>>#{@buffer}_") if @header
@header.text_right(Dir.pwd) if @header
@no_match = false
if @command
@list = @command.call(@buffer)
else
@list = @__list.select do |line|
line.index @buffer
end
end
sz = @list.size
if sz == 0
Ncurses.beep
#return 1
#this should make ENTER and arrow keys unusable except for BS or Esc,
@list = ["No entries"]
@no_match = true
end
data_changed @list
0
end | [
"def",
"buffer_changed",
"@header",
".",
"text1",
"(",
"\">>>#{@buffer}_\"",
")",
"if",
"@header",
"@header",
".",
"text_right",
"(",
"Dir",
".",
"pwd",
")",
"if",
"@header",
"@no_match",
"=",
"false",
"if",
"@command",
"@list",
"=",
"@command",
".",
"call",
"(",
"@buffer",
")",
"else",
"@list",
"=",
"@__list",
".",
"select",
"do",
"|",
"line",
"|",
"line",
".",
"index",
"@buffer",
"end",
"end",
"sz",
"=",
"@list",
".",
"size",
"if",
"sz",
"==",
"0",
"Ncurses",
".",
"beep",
"@list",
"=",
"[",
"\"No entries\"",
"]",
"@no_match",
"=",
"true",
"end",
"data_changed",
"@list",
"0",
"end"
]
| signal that the user has added or deleted a char from the pattern
and data should be requeried, etc | [
"signal",
"that",
"the",
"user",
"has",
"added",
"or",
"deleted",
"a",
"char",
"from",
"the",
"pattern",
"and",
"data",
"should",
"be",
"requeried",
"etc"
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L842-L865 | train |
mare-imbrium/canis | lib/canis/core/util/rcommandwindow.rb | Canis.ControlPHandler.handle_key | def handle_key ch
$log.debug " HANDLER GOT KEY #{ch} "
@keyint = ch
@keychr = nil
# accumulate keys in a string
# need to track insertion point if user uses left and right arrow
@buffer ||= ""
chr = nil
chr = ch.chr if ch > 47 and ch < 127
@keychr = chr
# Don't let user hit enter or keys if no match
if [13,10, KEY_ENTER, KEY_UP, KEY_DOWN].include? ch
if @no_match
$log.warn "XXX: KEY GOT WAS #{ch}, #{chr} "
# viewer has already blocked KEY_ENTER !
return 0 if [13,10, KEY_ENTER, KEY_UP, KEY_DOWN].include? ch
else
if [13,10, KEY_ENTER].include? ch
@source.form.window.ungetch(1001)
return 0
end
end
end
ret = process_key ch
# revert to the basic handling of key_map and refreshing pad.
# but this will rerun the keys and may once again run a mapping.
@source._handle_key(ch) if ret == :UNHANDLED
end | ruby | def handle_key ch
$log.debug " HANDLER GOT KEY #{ch} "
@keyint = ch
@keychr = nil
# accumulate keys in a string
# need to track insertion point if user uses left and right arrow
@buffer ||= ""
chr = nil
chr = ch.chr if ch > 47 and ch < 127
@keychr = chr
# Don't let user hit enter or keys if no match
if [13,10, KEY_ENTER, KEY_UP, KEY_DOWN].include? ch
if @no_match
$log.warn "XXX: KEY GOT WAS #{ch}, #{chr} "
# viewer has already blocked KEY_ENTER !
return 0 if [13,10, KEY_ENTER, KEY_UP, KEY_DOWN].include? ch
else
if [13,10, KEY_ENTER].include? ch
@source.form.window.ungetch(1001)
return 0
end
end
end
ret = process_key ch
# revert to the basic handling of key_map and refreshing pad.
# but this will rerun the keys and may once again run a mapping.
@source._handle_key(ch) if ret == :UNHANDLED
end | [
"def",
"handle_key",
"ch",
"$log",
".",
"debug",
"\" HANDLER GOT KEY #{ch} \"",
"@keyint",
"=",
"ch",
"@keychr",
"=",
"nil",
"@buffer",
"||=",
"\"\"",
"chr",
"=",
"nil",
"chr",
"=",
"ch",
".",
"chr",
"if",
"ch",
">",
"47",
"and",
"ch",
"<",
"127",
"@keychr",
"=",
"chr",
"if",
"[",
"13",
",",
"10",
",",
"KEY_ENTER",
",",
"KEY_UP",
",",
"KEY_DOWN",
"]",
".",
"include?",
"ch",
"if",
"@no_match",
"$log",
".",
"warn",
"\"XXX: KEY GOT WAS #{ch}, #{chr} \"",
"return",
"0",
"if",
"[",
"13",
",",
"10",
",",
"KEY_ENTER",
",",
"KEY_UP",
",",
"KEY_DOWN",
"]",
".",
"include?",
"ch",
"else",
"if",
"[",
"13",
",",
"10",
",",
"KEY_ENTER",
"]",
".",
"include?",
"ch",
"@source",
".",
"form",
".",
"window",
".",
"ungetch",
"(",
"1001",
")",
"return",
"0",
"end",
"end",
"end",
"ret",
"=",
"process_key",
"ch",
"@source",
".",
"_handle_key",
"(",
"ch",
")",
"if",
"ret",
"==",
":UNHANDLED",
"end"
]
| key handler of Controlphandler which overrides KeyDispatcher since we need to
intercept KEY_ENTER
@param [Integer] ch is key read by window.
WARNING: Please note that if this is used in +Viewer.view+, that +view+
has already trapped CLOSE_KEY which is KEY_ENTER/13 for closing, so we won't get 13
anywhere | [
"key",
"handler",
"of",
"Controlphandler",
"which",
"overrides",
"KeyDispatcher",
"since",
"we",
"need",
"to",
"intercept",
"KEY_ENTER"
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L873-L900 | train |
mare-imbrium/canis | lib/canis/core/util/rcommandwindow.rb | Canis.ControlPHandler.default_key_map | def default_key_map
tp = source
source.bind_key(?\M-n.getbyte(0), 'goto_end'){ tp.goto_end }
source.bind_key(?\M-p.getbyte(0), 'goto_start'){ tp.goto_start }
end | ruby | def default_key_map
tp = source
source.bind_key(?\M-n.getbyte(0), 'goto_end'){ tp.goto_end }
source.bind_key(?\M-p.getbyte(0), 'goto_start'){ tp.goto_start }
end | [
"def",
"default_key_map",
"tp",
"=",
"source",
"source",
".",
"bind_key",
"(",
"?\\M-n",
".",
"getbyte",
"(",
"0",
")",
",",
"'goto_end'",
")",
"{",
"tp",
".",
"goto_end",
"}",
"source",
".",
"bind_key",
"(",
"?\\M-p",
".",
"getbyte",
"(",
"0",
")",
",",
"'goto_start'",
")",
"{",
"tp",
".",
"goto_start",
"}",
"end"
]
| setting up some keys | [
"setting",
"up",
"some",
"keys"
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L903-L907 | train |
mare-imbrium/canis | lib/canis/core/util/rcommandwindow.rb | Canis.ControlPHandler.directory_key_map | def directory_key_map
@key_map["<"] = Action.new("Goto Parent Dir") { |obj|
# go to parent dir
$log.debug "KKK: called proc for <"
Dir.chdir("..")
obj.buffer_changed
}
@key_map[">"] = Action.new("Change Dir"){ |obj|
$log.debug "KKK: called proc for > : #{obj.current_value} "
# step into directory
dir = obj.current_value
if File.directory? dir
Dir.chdir dir
obj.buffer_changed
end
}
end | ruby | def directory_key_map
@key_map["<"] = Action.new("Goto Parent Dir") { |obj|
# go to parent dir
$log.debug "KKK: called proc for <"
Dir.chdir("..")
obj.buffer_changed
}
@key_map[">"] = Action.new("Change Dir"){ |obj|
$log.debug "KKK: called proc for > : #{obj.current_value} "
# step into directory
dir = obj.current_value
if File.directory? dir
Dir.chdir dir
obj.buffer_changed
end
}
end | [
"def",
"directory_key_map",
"@key_map",
"[",
"\"<\"",
"]",
"=",
"Action",
".",
"new",
"(",
"\"Goto Parent Dir\"",
")",
"{",
"|",
"obj",
"|",
"$log",
".",
"debug",
"\"KKK: called proc for <\"",
"Dir",
".",
"chdir",
"(",
"\"..\"",
")",
"obj",
".",
"buffer_changed",
"}",
"@key_map",
"[",
"\">\"",
"]",
"=",
"Action",
".",
"new",
"(",
"\"Change Dir\"",
")",
"{",
"|",
"obj",
"|",
"$log",
".",
"debug",
"\"KKK: called proc for > : #{obj.current_value} \"",
"dir",
"=",
"obj",
".",
"current_value",
"if",
"File",
".",
"directory?",
"dir",
"Dir",
".",
"chdir",
"dir",
"obj",
".",
"buffer_changed",
"end",
"}",
"end"
]
| specific actions for directory listers
currently for stepping into directory under cursor
and going to parent dir. | [
"specific",
"actions",
"for",
"directory",
"listers",
"currently",
"for",
"stepping",
"into",
"directory",
"under",
"cursor",
"and",
"going",
"to",
"parent",
"dir",
"."
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/rcommandwindow.rb#L912-L929 | train |
mare-imbrium/canis | lib/canis/core/include/bordertitle.rb | Canis.BorderTitle.print_borders | def print_borders
bordertitle_init unless @_bordertitle_init_called
raise ArgumentError, "Graphic not set" unless @graphic
raise "#{self} needs width" unless @width
raise "#{self} needs height" unless @height
width = @width
height = @height-1
window = @graphic
startcol = @col
startrow = @row
@color_pair = get_color($datacolor)
bordercolor = @border_color || @color_pair
borderatt = @border_attrib || Ncurses::A_NORMAL
window.print_border startrow, startcol, height, width, bordercolor, borderatt
print_title
end | ruby | def print_borders
bordertitle_init unless @_bordertitle_init_called
raise ArgumentError, "Graphic not set" unless @graphic
raise "#{self} needs width" unless @width
raise "#{self} needs height" unless @height
width = @width
height = @height-1
window = @graphic
startcol = @col
startrow = @row
@color_pair = get_color($datacolor)
bordercolor = @border_color || @color_pair
borderatt = @border_attrib || Ncurses::A_NORMAL
window.print_border startrow, startcol, height, width, bordercolor, borderatt
print_title
end | [
"def",
"print_borders",
"bordertitle_init",
"unless",
"@_bordertitle_init_called",
"raise",
"ArgumentError",
",",
"\"Graphic not set\"",
"unless",
"@graphic",
"raise",
"\"#{self} needs width\"",
"unless",
"@width",
"raise",
"\"#{self} needs height\"",
"unless",
"@height",
"width",
"=",
"@width",
"height",
"=",
"@height",
"-",
"1",
"window",
"=",
"@graphic",
"startcol",
"=",
"@col",
"startrow",
"=",
"@row",
"@color_pair",
"=",
"get_color",
"(",
"$datacolor",
")",
"bordercolor",
"=",
"@border_color",
"||",
"@color_pair",
"borderatt",
"=",
"@border_attrib",
"||",
"Ncurses",
"::",
"A_NORMAL",
"window",
".",
"print_border",
"startrow",
",",
"startcol",
",",
"height",
",",
"width",
",",
"bordercolor",
",",
"borderatt",
"print_title",
"end"
]
| why the dash does it reduce height by one. | [
"why",
"the",
"dash",
"does",
"it",
"reduce",
"height",
"by",
"one",
"."
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/include/bordertitle.rb#L16-L31 | train |
mare-imbrium/canis | lib/canis/core/widgets/deprecated/rlist.rb | Canis.List.list | def list *val
return @list if val.empty?
alist = val[0]
case alist
when Array
@list = alist
# I possibly should call init_vars in these 3 cases but am doing the minimal 2013-04-10 - 18:27
# Based no issue: https://github.com/mare-imbrium/canis/issues/15
@current_index = @toprow = @pcol = 0
when NilClass
@list = [] # or nil ?
@current_index = @toprow = @pcol = 0
when Variable
@list = alist.value
@current_index = @toprow = @pcol = 0
else
raise ArgumentError, "Listbox list(): do not know how to handle #{alist.class} "
end
clear_selection
@repaint_required = true
@widget_scrolled = true # 2011-10-15
@list
end | ruby | def list *val
return @list if val.empty?
alist = val[0]
case alist
when Array
@list = alist
# I possibly should call init_vars in these 3 cases but am doing the minimal 2013-04-10 - 18:27
# Based no issue: https://github.com/mare-imbrium/canis/issues/15
@current_index = @toprow = @pcol = 0
when NilClass
@list = [] # or nil ?
@current_index = @toprow = @pcol = 0
when Variable
@list = alist.value
@current_index = @toprow = @pcol = 0
else
raise ArgumentError, "Listbox list(): do not know how to handle #{alist.class} "
end
clear_selection
@repaint_required = true
@widget_scrolled = true # 2011-10-15
@list
end | [
"def",
"list",
"*",
"val",
"return",
"@list",
"if",
"val",
".",
"empty?",
"alist",
"=",
"val",
"[",
"0",
"]",
"case",
"alist",
"when",
"Array",
"@list",
"=",
"alist",
"@current_index",
"=",
"@toprow",
"=",
"@pcol",
"=",
"0",
"when",
"NilClass",
"@list",
"=",
"[",
"]",
"@current_index",
"=",
"@toprow",
"=",
"@pcol",
"=",
"0",
"when",
"Variable",
"@list",
"=",
"alist",
".",
"value",
"@current_index",
"=",
"@toprow",
"=",
"@pcol",
"=",
"0",
"else",
"raise",
"ArgumentError",
",",
"\"Listbox list(): do not know how to handle #{alist.class} \"",
"end",
"clear_selection",
"@repaint_required",
"=",
"true",
"@widget_scrolled",
"=",
"true",
"@list",
"end"
]
| provide data to List in the form of an Array or Variable or
ListDataModel. This will create a default ListSelectionModel.
CHANGE as on 2010-09-21 12:53:
If explicit nil passed then dummy datamodel and selection model created
From now on, constructor will call this, so this can always
happen.
NOTE: sometimes this can be added much after its painted.
Do not expect this to be called from constructor, although that
is the usual case. it can be dependent on some other list or tree.
@param [Array, Variable, ListDataModel] data to populate list with
@return [ListDataModel] just created or assigned | [
"provide",
"data",
"to",
"List",
"in",
"the",
"form",
"of",
"an",
"Array",
"or",
"Variable",
"or",
"ListDataModel",
".",
"This",
"will",
"create",
"a",
"default",
"ListSelectionModel",
"."
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/deprecated/rlist.rb#L175-L198 | train |
mare-imbrium/canis | lib/canis/core/widgets/deprecated/rlist.rb | Canis.List.ask_search_backward | def ask_search_backward
regex = get_string("Enter regex to search (backward)")
@last_regex = regex
ix = @list.find_prev regex, @current_index
if ix.nil?
alert("No matching data for: #{regex}")
else
set_focus_on(ix)
end
end | ruby | def ask_search_backward
regex = get_string("Enter regex to search (backward)")
@last_regex = regex
ix = @list.find_prev regex, @current_index
if ix.nil?
alert("No matching data for: #{regex}")
else
set_focus_on(ix)
end
end | [
"def",
"ask_search_backward",
"regex",
"=",
"get_string",
"(",
"\"Enter regex to search (backward)\"",
")",
"@last_regex",
"=",
"regex",
"ix",
"=",
"@list",
".",
"find_prev",
"regex",
",",
"@current_index",
"if",
"ix",
".",
"nil?",
"alert",
"(",
"\"No matching data for: #{regex}\"",
")",
"else",
"set_focus_on",
"(",
"ix",
")",
"end",
"end"
]
| gets string to search and calls data models find prev | [
"gets",
"string",
"to",
"search",
"and",
"calls",
"data",
"models",
"find",
"prev"
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/deprecated/rlist.rb#L360-L369 | train |
mare-imbrium/canis | lib/canis/core/widgets/deprecated/rlist.rb | Canis.List.repaint | def repaint #:nodoc:
return unless @repaint_required
#
# TRYING OUT dangerous 2011-10-15
@repaint_required = false
@repaint_required = true if @widget_scrolled || @pcol != @old_pcol || @record_changed || @property_changed
unless @repaint_required
unhighlight_row @old_selected_index
highlight_selected_row
end
return unless @repaint_required
$log.debug "BASICLIST REPAINT WILL HAPPEN #{current_index} "
# not sure where to put this, once for all or repeat 2010-02-17 23:07 RFED16
my_win = @form ? @form.window : @target_window
@graphic = my_win unless @graphic
raise " #{@name} neither form, nor target window given LB paint " unless my_win
raise " #{@name} NO GRAPHIC set as yet LB paint " unless @graphic
raise "width or height not given w:#{@width} , h:#{@height} " if @width.nil? || @height.nil?
@win_left = my_win.left
@win_top = my_win.top
@left_margin ||= @row_selected_symbol.length
# we are making sure display len does not exceed width XXX hope this does not wreak havoc elsewhere
_dl = [@display_length || 100, @width-@internal_width-@left_margin].min # 2011-09-17 RK overwriting when we move grabbar in vimsplit
$log.debug "basiclistbox repaint #{@name} graphic #{@graphic}"
#$log.debug "XXX repaint to_print #{@to_print_borders} "
print_borders unless @suppress_borders # do this once only, unless everything changes
#maxlen = @maxlen || @width-2
tm = list()
rc = row_count
@longest_line = @width
$log.debug " rbasiclistbox #{row_count}, w:#{@width} , maxlen:#{@maxlen} "
if rc > 0 # just added in case no data passed
tr = @toprow
acolor = get_color $datacolor
h = scrollatrow()
r,c = rowcol
0.upto(h) do |hh|
crow = tr+hh
if crow < rc
_focussed = @current_index == crow ? true : false # row focussed ?
focus_type = _focussed
focus_type = :SOFT_FOCUS if _focussed && !@focussed
selected = is_row_selected crow
content = tm[crow] # 2009-01-17 18:37 chomp giving error in some cases says frozen
content = convert_value_to_text content, crow # 2010-09-23 20:12
# by now it has to be a String
if content.is_a? String
content = content.dup
sanitize content if @sanitization_required
truncate content if @truncation_required
end
## set the selector symbol if requested
selection_symbol = ''
if @show_selector
if selected
selection_symbol = @row_selected_symbol
else
selection_symbol = @row_unselected_symbol
end
@graphic.printstring r+hh, c, selection_symbol, acolor,@attr
end
#renderer = get_default_cell_renderer_for_class content.class.to_s
renderer = cell_renderer()
renderer.display_length = _dl # 2011-09-17 RK overwriting when we move grabbar in vimsplit
renderer.repaint @graphic, r+hh, c+@left_margin, crow, content, focus_type, selected
else
# clear rows
@graphic.printstring r+hh, c, " " * (@width-@internal_width), acolor,@attr
end
end
end # rc == 0
@repaint_required = false
# 2011-10-13
@widget_scrolled = false
@record_changed = false
@property_changed = false
@old_pcol = @pcol
end | ruby | def repaint #:nodoc:
return unless @repaint_required
#
# TRYING OUT dangerous 2011-10-15
@repaint_required = false
@repaint_required = true if @widget_scrolled || @pcol != @old_pcol || @record_changed || @property_changed
unless @repaint_required
unhighlight_row @old_selected_index
highlight_selected_row
end
return unless @repaint_required
$log.debug "BASICLIST REPAINT WILL HAPPEN #{current_index} "
# not sure where to put this, once for all or repeat 2010-02-17 23:07 RFED16
my_win = @form ? @form.window : @target_window
@graphic = my_win unless @graphic
raise " #{@name} neither form, nor target window given LB paint " unless my_win
raise " #{@name} NO GRAPHIC set as yet LB paint " unless @graphic
raise "width or height not given w:#{@width} , h:#{@height} " if @width.nil? || @height.nil?
@win_left = my_win.left
@win_top = my_win.top
@left_margin ||= @row_selected_symbol.length
# we are making sure display len does not exceed width XXX hope this does not wreak havoc elsewhere
_dl = [@display_length || 100, @width-@internal_width-@left_margin].min # 2011-09-17 RK overwriting when we move grabbar in vimsplit
$log.debug "basiclistbox repaint #{@name} graphic #{@graphic}"
#$log.debug "XXX repaint to_print #{@to_print_borders} "
print_borders unless @suppress_borders # do this once only, unless everything changes
#maxlen = @maxlen || @width-2
tm = list()
rc = row_count
@longest_line = @width
$log.debug " rbasiclistbox #{row_count}, w:#{@width} , maxlen:#{@maxlen} "
if rc > 0 # just added in case no data passed
tr = @toprow
acolor = get_color $datacolor
h = scrollatrow()
r,c = rowcol
0.upto(h) do |hh|
crow = tr+hh
if crow < rc
_focussed = @current_index == crow ? true : false # row focussed ?
focus_type = _focussed
focus_type = :SOFT_FOCUS if _focussed && !@focussed
selected = is_row_selected crow
content = tm[crow] # 2009-01-17 18:37 chomp giving error in some cases says frozen
content = convert_value_to_text content, crow # 2010-09-23 20:12
# by now it has to be a String
if content.is_a? String
content = content.dup
sanitize content if @sanitization_required
truncate content if @truncation_required
end
## set the selector symbol if requested
selection_symbol = ''
if @show_selector
if selected
selection_symbol = @row_selected_symbol
else
selection_symbol = @row_unselected_symbol
end
@graphic.printstring r+hh, c, selection_symbol, acolor,@attr
end
#renderer = get_default_cell_renderer_for_class content.class.to_s
renderer = cell_renderer()
renderer.display_length = _dl # 2011-09-17 RK overwriting when we move grabbar in vimsplit
renderer.repaint @graphic, r+hh, c+@left_margin, crow, content, focus_type, selected
else
# clear rows
@graphic.printstring r+hh, c, " " * (@width-@internal_width), acolor,@attr
end
end
end # rc == 0
@repaint_required = false
# 2011-10-13
@widget_scrolled = false
@record_changed = false
@property_changed = false
@old_pcol = @pcol
end | [
"def",
"repaint",
"return",
"unless",
"@repaint_required",
"@repaint_required",
"=",
"false",
"@repaint_required",
"=",
"true",
"if",
"@widget_scrolled",
"||",
"@pcol",
"!=",
"@old_pcol",
"||",
"@record_changed",
"||",
"@property_changed",
"unless",
"@repaint_required",
"unhighlight_row",
"@old_selected_index",
"highlight_selected_row",
"end",
"return",
"unless",
"@repaint_required",
"$log",
".",
"debug",
"\"BASICLIST REPAINT WILL HAPPEN #{current_index} \"",
"my_win",
"=",
"@form",
"?",
"@form",
".",
"window",
":",
"@target_window",
"@graphic",
"=",
"my_win",
"unless",
"@graphic",
"raise",
"\" #{@name} neither form, nor target window given LB paint \"",
"unless",
"my_win",
"raise",
"\" #{@name} NO GRAPHIC set as yet LB paint \"",
"unless",
"@graphic",
"raise",
"\"width or height not given w:#{@width} , h:#{@height} \"",
"if",
"@width",
".",
"nil?",
"||",
"@height",
".",
"nil?",
"@win_left",
"=",
"my_win",
".",
"left",
"@win_top",
"=",
"my_win",
".",
"top",
"@left_margin",
"||=",
"@row_selected_symbol",
".",
"length",
"_dl",
"=",
"[",
"@display_length",
"||",
"100",
",",
"@width",
"-",
"@internal_width",
"-",
"@left_margin",
"]",
".",
"min",
"$log",
".",
"debug",
"\"basiclistbox repaint #{@name} graphic #{@graphic}\"",
"print_borders",
"unless",
"@suppress_borders",
"tm",
"=",
"list",
"(",
")",
"rc",
"=",
"row_count",
"@longest_line",
"=",
"@width",
"$log",
".",
"debug",
"\" rbasiclistbox #{row_count}, w:#{@width} , maxlen:#{@maxlen} \"",
"if",
"rc",
">",
"0",
"tr",
"=",
"@toprow",
"acolor",
"=",
"get_color",
"$datacolor",
"h",
"=",
"scrollatrow",
"(",
")",
"r",
",",
"c",
"=",
"rowcol",
"0",
".",
"upto",
"(",
"h",
")",
"do",
"|",
"hh",
"|",
"crow",
"=",
"tr",
"+",
"hh",
"if",
"crow",
"<",
"rc",
"_focussed",
"=",
"@current_index",
"==",
"crow",
"?",
"true",
":",
"false",
"focus_type",
"=",
"_focussed",
"focus_type",
"=",
":SOFT_FOCUS",
"if",
"_focussed",
"&&",
"!",
"@focussed",
"selected",
"=",
"is_row_selected",
"crow",
"content",
"=",
"tm",
"[",
"crow",
"]",
"content",
"=",
"convert_value_to_text",
"content",
",",
"crow",
"if",
"content",
".",
"is_a?",
"String",
"content",
"=",
"content",
".",
"dup",
"sanitize",
"content",
"if",
"@sanitization_required",
"truncate",
"content",
"if",
"@truncation_required",
"end",
"selection_symbol",
"=",
"''",
"if",
"@show_selector",
"if",
"selected",
"selection_symbol",
"=",
"@row_selected_symbol",
"else",
"selection_symbol",
"=",
"@row_unselected_symbol",
"end",
"@graphic",
".",
"printstring",
"r",
"+",
"hh",
",",
"c",
",",
"selection_symbol",
",",
"acolor",
",",
"@attr",
"end",
"renderer",
"=",
"cell_renderer",
"(",
")",
"renderer",
".",
"display_length",
"=",
"_dl",
"renderer",
".",
"repaint",
"@graphic",
",",
"r",
"+",
"hh",
",",
"c",
"+",
"@left_margin",
",",
"crow",
",",
"content",
",",
"focus_type",
",",
"selected",
"else",
"@graphic",
".",
"printstring",
"r",
"+",
"hh",
",",
"c",
",",
"\" \"",
"*",
"(",
"@width",
"-",
"@internal_width",
")",
",",
"acolor",
",",
"@attr",
"end",
"end",
"end",
"@repaint_required",
"=",
"false",
"@widget_scrolled",
"=",
"false",
"@record_changed",
"=",
"false",
"@property_changed",
"=",
"false",
"@old_pcol",
"=",
"@pcol",
"end"
]
| this method chops the data to length before giving it to the
renderer, this can cause problems if the renderer does some
processing. also, it pans the data horizontally giving the renderer
a section of it. | [
"this",
"method",
"chops",
"the",
"data",
"to",
"length",
"before",
"giving",
"it",
"to",
"the",
"renderer",
"this",
"can",
"cause",
"problems",
"if",
"the",
"renderer",
"does",
"some",
"processing",
".",
"also",
"it",
"pans",
"the",
"data",
"horizontally",
"giving",
"the",
"renderer",
"a",
"section",
"of",
"it",
"."
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/deprecated/rlist.rb#L416-L495 | train |
mare-imbrium/canis | lib/canis/core/widgets/deprecated/rlist.rb | Canis.List.sanitize | def sanitize content #:nodoc:
if content.is_a? String
content.chomp!
content.gsub!(/\t/, ' ') # don't display tab
content.gsub!(/[^[:print:]]/, '') # don't display non print characters
else
content
end
end | ruby | def sanitize content #:nodoc:
if content.is_a? String
content.chomp!
content.gsub!(/\t/, ' ') # don't display tab
content.gsub!(/[^[:print:]]/, '') # don't display non print characters
else
content
end
end | [
"def",
"sanitize",
"content",
"if",
"content",
".",
"is_a?",
"String",
"content",
".",
"chomp!",
"content",
".",
"gsub!",
"(",
"/",
"\\t",
"/",
",",
"' '",
")",
"content",
".",
"gsub!",
"(",
"/",
"/",
",",
"''",
")",
"else",
"content",
"end",
"end"
]
| takes a block, this way anyone extending this klass can just pass a block to do his job
This modifies the string | [
"takes",
"a",
"block",
"this",
"way",
"anyone",
"extending",
"this",
"klass",
"can",
"just",
"pass",
"a",
"block",
"to",
"do",
"his",
"job",
"This",
"modifies",
"the",
"string"
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/deprecated/rlist.rb#L536-L544 | train |
mare-imbrium/canis | lib/canis/core/widgets/deprecated/rlist.rb | Canis.List.init_actions | def init_actions
am = action_manager()
am.add_action(Action.new("&Disable selection") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )
am.add_action(Action.new("&Edit Toggle") { @edit_toggle = !@edit_toggle; $status_message.value = "Edit toggle is #{@edit_toggle}" })
end | ruby | def init_actions
am = action_manager()
am.add_action(Action.new("&Disable selection") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )
am.add_action(Action.new("&Edit Toggle") { @edit_toggle = !@edit_toggle; $status_message.value = "Edit toggle is #{@edit_toggle}" })
end | [
"def",
"init_actions",
"am",
"=",
"action_manager",
"(",
")",
"am",
".",
"add_action",
"(",
"Action",
".",
"new",
"(",
"\"&Disable selection\"",
")",
"{",
"@selection_mode",
"=",
":none",
";",
"unbind_key",
"(",
"32",
")",
";",
"bind_key",
"(",
"32",
",",
":scroll_forward",
")",
";",
"}",
")",
"am",
".",
"add_action",
"(",
"Action",
".",
"new",
"(",
"\"&Edit Toggle\"",
")",
"{",
"@edit_toggle",
"=",
"!",
"@edit_toggle",
";",
"$status_message",
".",
"value",
"=",
"\"Edit toggle is #{@edit_toggle}\"",
"}",
")",
"end"
]
| Define actions that can be popped up by PromptMenu or other menubar
Currently, only PromptMenu, but we can start contextually appending to Menubar or others | [
"Define",
"actions",
"that",
"can",
"be",
"popped",
"up",
"by",
"PromptMenu",
"or",
"other",
"menubar",
"Currently",
"only",
"PromptMenu",
"but",
"we",
"can",
"start",
"contextually",
"appending",
"to",
"Menubar",
"or",
"others"
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/deprecated/rlist.rb#L625-L629 | train |
mare-imbrium/canis | lib/canis/core/widgets/box.rb | Canis.Box.repaint | def repaint
return unless @repaint_required
bc = $datacolor
bordercolor = @border_color || bc
borderatt = @border_attrib || Ncurses::A_NORMAL
@window.print_border row, col, height, width, bordercolor, borderatt
#print_borders
print_title
@repaint_required = false
end | ruby | def repaint
return unless @repaint_required
bc = $datacolor
bordercolor = @border_color || bc
borderatt = @border_attrib || Ncurses::A_NORMAL
@window.print_border row, col, height, width, bordercolor, borderatt
#print_borders
print_title
@repaint_required = false
end | [
"def",
"repaint",
"return",
"unless",
"@repaint_required",
"bc",
"=",
"$datacolor",
"bordercolor",
"=",
"@border_color",
"||",
"bc",
"borderatt",
"=",
"@border_attrib",
"||",
"Ncurses",
"::",
"A_NORMAL",
"@window",
".",
"print_border",
"row",
",",
"col",
",",
"height",
",",
"width",
",",
"bordercolor",
",",
"borderatt",
"print_title",
"@repaint_required",
"=",
"false",
"end"
]
| repaint the scrollbar | [
"repaint",
"the",
"scrollbar"
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/widgets/box.rb#L42-L51 | train |
mare-imbrium/canis | lib/canis/core/util/widgetshortcuts.rb | Canis.WidgetShortcuts.dock | def dock labels, config={}, &block
require 'canis/core/widgets/keylabelprinter'
klp = Canis::KeyLabelPrinter.new @form, labels, config, &block
end | ruby | def dock labels, config={}, &block
require 'canis/core/widgets/keylabelprinter'
klp = Canis::KeyLabelPrinter.new @form, labels, config, &block
end | [
"def",
"dock",
"labels",
",",
"config",
"=",
"{",
"}",
",",
"&",
"block",
"require",
"'canis/core/widgets/keylabelprinter'",
"klp",
"=",
"Canis",
"::",
"KeyLabelPrinter",
".",
"new",
"@form",
",",
"labels",
",",
"config",
",",
"&",
"block",
"end"
]
| prints pine-like key labels | [
"prints",
"pine",
"-",
"like",
"key",
"labels"
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/widgetshortcuts.rb#L198-L201 | train |
mare-imbrium/canis | lib/canis/core/util/widgetshortcuts.rb | Canis.WidgetShortcuts.status_line | def status_line config={}, &block
require 'canis/core/widgets/statusline'
sl = Canis::StatusLine.new @form, config, &block
end | ruby | def status_line config={}, &block
require 'canis/core/widgets/statusline'
sl = Canis::StatusLine.new @form, config, &block
end | [
"def",
"status_line",
"config",
"=",
"{",
"}",
",",
"&",
"block",
"require",
"'canis/core/widgets/statusline'",
"sl",
"=",
"Canis",
"::",
"StatusLine",
".",
"new",
"@form",
",",
"config",
",",
"&",
"block",
"end"
]
| prints a status line at bottom where mode's statuses et can be reflected | [
"prints",
"a",
"status",
"line",
"at",
"bottom",
"where",
"mode",
"s",
"statuses",
"et",
"can",
"be",
"reflected"
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/widgetshortcuts.rb#L205-L208 | train |
mare-imbrium/canis | lib/canis/core/util/widgetshortcuts.rb | Canis.WidgetShortcuts.table | def table config={}, &block
#def tabular_widget config={}, &block
require 'canis/core/widgets/table'
events = [:PROPERTY_CHANGE, :LEAVE, :ENTER, :CHANGE, :ENTER_ROW, :PRESS ]
block_event = nil
# if no width given, expand to stack width
#config.delete :title
useform = nil
w = Table.new useform, config # NO BLOCK GIVEN
w.width ||= :expand
w.height ||= :expand # TODO This has to come before other in stack next one will overwrite.
_position(w)
if block_given?
#@current_object << w
yield_or_eval &block
#@current_object.pop
end
return w
end | ruby | def table config={}, &block
#def tabular_widget config={}, &block
require 'canis/core/widgets/table'
events = [:PROPERTY_CHANGE, :LEAVE, :ENTER, :CHANGE, :ENTER_ROW, :PRESS ]
block_event = nil
# if no width given, expand to stack width
#config.delete :title
useform = nil
w = Table.new useform, config # NO BLOCK GIVEN
w.width ||= :expand
w.height ||= :expand # TODO This has to come before other in stack next one will overwrite.
_position(w)
if block_given?
#@current_object << w
yield_or_eval &block
#@current_object.pop
end
return w
end | [
"def",
"table",
"config",
"=",
"{",
"}",
",",
"&",
"block",
"require",
"'canis/core/widgets/table'",
"events",
"=",
"[",
":PROPERTY_CHANGE",
",",
":LEAVE",
",",
":ENTER",
",",
":CHANGE",
",",
":ENTER_ROW",
",",
":PRESS",
"]",
"block_event",
"=",
"nil",
"useform",
"=",
"nil",
"w",
"=",
"Table",
".",
"new",
"useform",
",",
"config",
"w",
".",
"width",
"||=",
":expand",
"w",
".",
"height",
"||=",
":expand",
"_position",
"(",
"w",
")",
"if",
"block_given?",
"yield_or_eval",
"&",
"block",
"end",
"return",
"w",
"end"
]
| creates a simple readonly table, that allows users to click on rows
and also on the header. Header clicking is for column-sorting. | [
"creates",
"a",
"simple",
"readonly",
"table",
"that",
"allows",
"users",
"to",
"click",
"on",
"rows",
"and",
"also",
"on",
"the",
"header",
".",
"Header",
"clicking",
"is",
"for",
"column",
"-",
"sorting",
"."
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/widgetshortcuts.rb#L273-L292 | train |
mare-imbrium/canis | lib/canis/core/util/widgetshortcuts.rb | Canis.WidgetShortcuts._configure | def _configure s
s[:row] ||= 0
s[:col] ||= 0
s[:row] += (s[:margin_top] || 0)
s[:col] += (s[:margin_left] || 0)
s[:width] = FFI::NCurses.COLS-s[:col] if s[:width] == :expand
s[:height] = FFI::NCurses.LINES-s[:row] if s[:height] == :expand # 2011-11-30
last = @_ws_active.last
if last
if s[:width_pc]
if last.is_a? WsStack
s[:width] = (last[:width] * (s[:width_pc].to_i * 0.01)).floor
else
# i think this width is picked up by next stack in this flow
last[:item_width] = (last[:width] * (s[:width_pc].to_i* 0.01)).floor
end
end
if s[:height_pc]
if last.is_a? WsFlow
s[:height] = ( (last[:height] * s[:height_pc].to_i)/100).floor
else
# this works only for flows within stacks not for an object unless
# you put a single object in a flow
s[:item_height] = ( (last[:height] * s[:height_pc].to_i)/100).floor
end
#alert "item height set as #{s[:height]} for #{s} "
end
if last.is_a? WsStack
s[:row] += (last[:row] || 0)
s[:col] += (last[:col] || 0)
else
s[:row] += (last[:row] || 0)
s[:col] += (last[:col] || 0) # we are updating with item_width as each st finishes
s[:width] ||= last[:item_width] #
end
else
# this should be outer most flow or stack, if nothing mentioned
# trying this out
s[:width] ||= :expand
s[:height] ||= :expand
s[:width] = FFI::NCurses.COLS-s[:col] if s[:width] == :expand
s[:height] = FFI::NCurses.LINES-s[:row] if s[:height] == :expand # 2011-11-30
end
s[:components] = []
end | ruby | def _configure s
s[:row] ||= 0
s[:col] ||= 0
s[:row] += (s[:margin_top] || 0)
s[:col] += (s[:margin_left] || 0)
s[:width] = FFI::NCurses.COLS-s[:col] if s[:width] == :expand
s[:height] = FFI::NCurses.LINES-s[:row] if s[:height] == :expand # 2011-11-30
last = @_ws_active.last
if last
if s[:width_pc]
if last.is_a? WsStack
s[:width] = (last[:width] * (s[:width_pc].to_i * 0.01)).floor
else
# i think this width is picked up by next stack in this flow
last[:item_width] = (last[:width] * (s[:width_pc].to_i* 0.01)).floor
end
end
if s[:height_pc]
if last.is_a? WsFlow
s[:height] = ( (last[:height] * s[:height_pc].to_i)/100).floor
else
# this works only for flows within stacks not for an object unless
# you put a single object in a flow
s[:item_height] = ( (last[:height] * s[:height_pc].to_i)/100).floor
end
#alert "item height set as #{s[:height]} for #{s} "
end
if last.is_a? WsStack
s[:row] += (last[:row] || 0)
s[:col] += (last[:col] || 0)
else
s[:row] += (last[:row] || 0)
s[:col] += (last[:col] || 0) # we are updating with item_width as each st finishes
s[:width] ||= last[:item_width] #
end
else
# this should be outer most flow or stack, if nothing mentioned
# trying this out
s[:width] ||= :expand
s[:height] ||= :expand
s[:width] = FFI::NCurses.COLS-s[:col] if s[:width] == :expand
s[:height] = FFI::NCurses.LINES-s[:row] if s[:height] == :expand # 2011-11-30
end
s[:components] = []
end | [
"def",
"_configure",
"s",
"s",
"[",
":row",
"]",
"||=",
"0",
"s",
"[",
":col",
"]",
"||=",
"0",
"s",
"[",
":row",
"]",
"+=",
"(",
"s",
"[",
":margin_top",
"]",
"||",
"0",
")",
"s",
"[",
":col",
"]",
"+=",
"(",
"s",
"[",
":margin_left",
"]",
"||",
"0",
")",
"s",
"[",
":width",
"]",
"=",
"FFI",
"::",
"NCurses",
".",
"COLS",
"-",
"s",
"[",
":col",
"]",
"if",
"s",
"[",
":width",
"]",
"==",
":expand",
"s",
"[",
":height",
"]",
"=",
"FFI",
"::",
"NCurses",
".",
"LINES",
"-",
"s",
"[",
":row",
"]",
"if",
"s",
"[",
":height",
"]",
"==",
":expand",
"last",
"=",
"@_ws_active",
".",
"last",
"if",
"last",
"if",
"s",
"[",
":width_pc",
"]",
"if",
"last",
".",
"is_a?",
"WsStack",
"s",
"[",
":width",
"]",
"=",
"(",
"last",
"[",
":width",
"]",
"*",
"(",
"s",
"[",
":width_pc",
"]",
".",
"to_i",
"*",
"0.01",
")",
")",
".",
"floor",
"else",
"last",
"[",
":item_width",
"]",
"=",
"(",
"last",
"[",
":width",
"]",
"*",
"(",
"s",
"[",
":width_pc",
"]",
".",
"to_i",
"*",
"0.01",
")",
")",
".",
"floor",
"end",
"end",
"if",
"s",
"[",
":height_pc",
"]",
"if",
"last",
".",
"is_a?",
"WsFlow",
"s",
"[",
":height",
"]",
"=",
"(",
"(",
"last",
"[",
":height",
"]",
"*",
"s",
"[",
":height_pc",
"]",
".",
"to_i",
")",
"/",
"100",
")",
".",
"floor",
"else",
"s",
"[",
":item_height",
"]",
"=",
"(",
"(",
"last",
"[",
":height",
"]",
"*",
"s",
"[",
":height_pc",
"]",
".",
"to_i",
")",
"/",
"100",
")",
".",
"floor",
"end",
"end",
"if",
"last",
".",
"is_a?",
"WsStack",
"s",
"[",
":row",
"]",
"+=",
"(",
"last",
"[",
":row",
"]",
"||",
"0",
")",
"s",
"[",
":col",
"]",
"+=",
"(",
"last",
"[",
":col",
"]",
"||",
"0",
")",
"else",
"s",
"[",
":row",
"]",
"+=",
"(",
"last",
"[",
":row",
"]",
"||",
"0",
")",
"s",
"[",
":col",
"]",
"+=",
"(",
"last",
"[",
":col",
"]",
"||",
"0",
")",
"s",
"[",
":width",
"]",
"||=",
"last",
"[",
":item_width",
"]",
"end",
"else",
"s",
"[",
":width",
"]",
"||=",
":expand",
"s",
"[",
":height",
"]",
"||=",
":expand",
"s",
"[",
":width",
"]",
"=",
"FFI",
"::",
"NCurses",
".",
"COLS",
"-",
"s",
"[",
":col",
"]",
"if",
"s",
"[",
":width",
"]",
"==",
":expand",
"s",
"[",
":height",
"]",
"=",
"FFI",
"::",
"NCurses",
".",
"LINES",
"-",
"s",
"[",
":row",
"]",
"if",
"s",
"[",
":height",
"]",
"==",
":expand",
"end",
"s",
"[",
":components",
"]",
"=",
"[",
"]",
"end"
]
| This configures a stack or flow not the objects inside | [
"This",
"configures",
"a",
"stack",
"or",
"flow",
"not",
"the",
"objects",
"inside"
]
| 8bce60ff9dad321e299a6124620deb4771740b0b | https://github.com/mare-imbrium/canis/blob/8bce60ff9dad321e299a6124620deb4771740b0b/lib/canis/core/util/widgetshortcuts.rb#L469-L513 | train |
CloudStack-extras/knife-cloudstack | lib/chef/knife/cs_server_create.rb | KnifeCloudstack.CsServerCreate.is_ssh_open? | def is_ssh_open?(ip)
s = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
sa = Socket.sockaddr_in(locate_config_value(:ssh_port), ip)
begin
s.connect_nonblock(sa)
rescue Errno::EINPROGRESS
resp = IO.select(nil, [s], nil, 1)
if resp.nil?
sleep SSH_POLL_INTERVAL
return false
end
begin
s.connect_nonblock(sa)
rescue Errno::EISCONN
Chef::Log.debug("sshd accepting connections on #{ip}")
yield
return true
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
sleep SSH_POLL_INTERVAL
return false
end
ensure
s && s.close
end
end | ruby | def is_ssh_open?(ip)
s = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
sa = Socket.sockaddr_in(locate_config_value(:ssh_port), ip)
begin
s.connect_nonblock(sa)
rescue Errno::EINPROGRESS
resp = IO.select(nil, [s], nil, 1)
if resp.nil?
sleep SSH_POLL_INTERVAL
return false
end
begin
s.connect_nonblock(sa)
rescue Errno::EISCONN
Chef::Log.debug("sshd accepting connections on #{ip}")
yield
return true
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
sleep SSH_POLL_INTERVAL
return false
end
ensure
s && s.close
end
end | [
"def",
"is_ssh_open?",
"(",
"ip",
")",
"s",
"=",
"Socket",
".",
"new",
"(",
"Socket",
"::",
"AF_INET",
",",
"Socket",
"::",
"SOCK_STREAM",
",",
"0",
")",
"sa",
"=",
"Socket",
".",
"sockaddr_in",
"(",
"locate_config_value",
"(",
":ssh_port",
")",
",",
"ip",
")",
"begin",
"s",
".",
"connect_nonblock",
"(",
"sa",
")",
"rescue",
"Errno",
"::",
"EINPROGRESS",
"resp",
"=",
"IO",
".",
"select",
"(",
"nil",
",",
"[",
"s",
"]",
",",
"nil",
",",
"1",
")",
"if",
"resp",
".",
"nil?",
"sleep",
"SSH_POLL_INTERVAL",
"return",
"false",
"end",
"begin",
"s",
".",
"connect_nonblock",
"(",
"sa",
")",
"rescue",
"Errno",
"::",
"EISCONN",
"Chef",
"::",
"Log",
".",
"debug",
"(",
"\"sshd accepting connections on #{ip}\"",
")",
"yield",
"return",
"true",
"rescue",
"Errno",
"::",
"ECONNREFUSED",
",",
"Errno",
"::",
"EHOSTUNREACH",
"sleep",
"SSH_POLL_INTERVAL",
"return",
"false",
"end",
"ensure",
"s",
"&&",
"s",
".",
"close",
"end",
"end"
]
| noinspection RubyArgCount,RubyResolve | [
"noinspection",
"RubyArgCount",
"RubyResolve"
]
| 7fa996cabac740b8c29e7b0c84508134372823bd | https://github.com/CloudStack-extras/knife-cloudstack/blob/7fa996cabac740b8c29e7b0c84508134372823bd/lib/chef/knife/cs_server_create.rb#L539-L565 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.