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
mikejmoore/docker-swarm-sdk
lib/docker-swarm.rb
Docker.Swarm.validate_version!
def validate_version! Docker.info true rescue Docker::Error::DockerError raise Docker::Error::VersionError, "Expected API Version: #{API_VERSION}" end
ruby
def validate_version! Docker.info true rescue Docker::Error::DockerError raise Docker::Error::VersionError, "Expected API Version: #{API_VERSION}" end
[ "def", "validate_version!", "Docker", ".", "info", "true", "rescue", "Docker", "::", "Error", "::", "DockerError", "raise", "Docker", "::", "Error", "::", "VersionError", ",", "\"Expected API Version: #{API_VERSION}\"", "end" ]
When the correct version of Docker is installed, returns true. Otherwise, raises a VersionError.
[ "When", "the", "correct", "version", "of", "Docker", "is", "installed", "returns", "true", ".", "Otherwise", "raises", "a", "VersionError", "." ]
7f69f295900af880211d6a3a830eff0458df5526
https://github.com/mikejmoore/docker-swarm-sdk/blob/7f69f295900af880211d6a3a830eff0458df5526/lib/docker-swarm.rb#L127-L132
train
moio/tetra
spec/spec_helper.rb
Tetra.Mockers.create_mock_project
def create_mock_project @project_path = File.join("spec", "data", "test-project") Tetra::Project.init(@project_path, false) @project = Tetra::Project.new(@project_path) end
ruby
def create_mock_project @project_path = File.join("spec", "data", "test-project") Tetra::Project.init(@project_path, false) @project = Tetra::Project.new(@project_path) end
[ "def", "create_mock_project", "@project_path", "=", "File", ".", "join", "(", "\"spec\"", ",", "\"data\"", ",", "\"test-project\"", ")", "Tetra", "::", "Project", ".", "init", "(", "@project_path", ",", "false", ")", "@project", "=", "Tetra", "::", "Project", ".", "new", "(", "@project_path", ")", "end" ]
creates a minimal tetra project
[ "creates", "a", "minimal", "tetra", "project" ]
de06d766502b885bd62bd7cd9dc8da678abd7cb0
https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/spec/spec_helper.rb#L28-L32
train
moio/tetra
spec/spec_helper.rb
Tetra.Mockers.create_mock_executable
def create_mock_executable(executable_name) Dir.chdir(@project_path) do dir = mock_executable_dir(executable_name) FileUtils.mkdir_p(dir) executable_path = mock_executable_path(executable_name) File.open(executable_path, "w") { |io| io.puts "echo $0 $*>test_out" } File.chmod(0777, executable_path) executable_path end end
ruby
def create_mock_executable(executable_name) Dir.chdir(@project_path) do dir = mock_executable_dir(executable_name) FileUtils.mkdir_p(dir) executable_path = mock_executable_path(executable_name) File.open(executable_path, "w") { |io| io.puts "echo $0 $*>test_out" } File.chmod(0777, executable_path) executable_path end end
[ "def", "create_mock_executable", "(", "executable_name", ")", "Dir", ".", "chdir", "(", "@project_path", ")", "do", "dir", "=", "mock_executable_dir", "(", "executable_name", ")", "FileUtils", ".", "mkdir_p", "(", "dir", ")", "executable_path", "=", "mock_executable_path", "(", "executable_name", ")", "File", ".", "open", "(", "executable_path", ",", "\"w\"", ")", "{", "|", "io", "|", "io", ".", "puts", "\"echo $0 $*>test_out\"", "}", "File", ".", "chmod", "(", "0777", ",", "executable_path", ")", "executable_path", "end", "end" ]
creates an executable in kit that will print its parameters in a test_out file for checking. Returns mocked executable full path
[ "creates", "an", "executable", "in", "kit", "that", "will", "print", "its", "parameters", "in", "a", "test_out", "file", "for", "checking", ".", "Returns", "mocked", "executable", "full", "path" ]
de06d766502b885bd62bd7cd9dc8da678abd7cb0
https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/spec/spec_helper.rb#L42-L51
train
moio/tetra
lib/tetra/pom_getter.rb
Tetra.PomGetter.get_pom_from_jar
def get_pom_from_jar(file) log.debug("Attempting unpack of #{file} to find a POM") begin Zip::File.foreach(file) do |entry| if entry.name =~ %r{/pom.xml$} log.info("pom.xml found in #{file}##{entry.name}") return entry.get_input_stream.read, :found_in_jar end end rescue Zip::Error log.warn("#{file} does not seem to be a valid jar archive, skipping") rescue TypeError log.warn("#{file} seems to be a valid jar archive but is corrupt, skipping") end nil end
ruby
def get_pom_from_jar(file) log.debug("Attempting unpack of #{file} to find a POM") begin Zip::File.foreach(file) do |entry| if entry.name =~ %r{/pom.xml$} log.info("pom.xml found in #{file}##{entry.name}") return entry.get_input_stream.read, :found_in_jar end end rescue Zip::Error log.warn("#{file} does not seem to be a valid jar archive, skipping") rescue TypeError log.warn("#{file} seems to be a valid jar archive but is corrupt, skipping") end nil end
[ "def", "get_pom_from_jar", "(", "file", ")", "log", ".", "debug", "(", "\"Attempting unpack of #{file} to find a POM\"", ")", "begin", "Zip", "::", "File", ".", "foreach", "(", "file", ")", "do", "|", "entry", "|", "if", "entry", ".", "name", "=~", "%r{", "}", "log", ".", "info", "(", "\"pom.xml found in #{file}##{entry.name}\"", ")", "return", "entry", ".", "get_input_stream", ".", "read", ",", ":found_in_jar", "end", "end", "rescue", "Zip", "::", "Error", "log", ".", "warn", "(", "\"#{file} does not seem to be a valid jar archive, skipping\"", ")", "rescue", "TypeError", "log", ".", "warn", "(", "\"#{file} seems to be a valid jar archive but is corrupt, skipping\"", ")", "end", "nil", "end" ]
returns a pom embedded in a jar file
[ "returns", "a", "pom", "embedded", "in", "a", "jar", "file" ]
de06d766502b885bd62bd7cd9dc8da678abd7cb0
https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/pom_getter.rb#L20-L35
train
moio/tetra
lib/tetra/pom_getter.rb
Tetra.PomGetter.get_pom_from_sha1
def get_pom_from_sha1(file) log.debug("Attempting SHA1 POM lookup for #{file}") begin if File.file?(file) site = MavenWebsite.new sha1 = Digest::SHA1.hexdigest File.read(file) results = site.search_by_sha1(sha1).select { |result| result["ec"].include?(".pom") } result = results.first unless result.nil? log.info("pom.xml for #{file} found on search.maven.org for sha1 #{sha1}\ (#{result['g']}:#{result['a']}:#{result['v']})" ) group_id, artifact_id, version = site.get_maven_id_from result return site.download_pom(group_id, artifact_id, version), :found_via_sha1 end end rescue NotFoundOnMavenWebsiteError log.warn("Got a 404 error while looking for #{file}'s SHA1 in search.maven.org") end nil end
ruby
def get_pom_from_sha1(file) log.debug("Attempting SHA1 POM lookup for #{file}") begin if File.file?(file) site = MavenWebsite.new sha1 = Digest::SHA1.hexdigest File.read(file) results = site.search_by_sha1(sha1).select { |result| result["ec"].include?(".pom") } result = results.first unless result.nil? log.info("pom.xml for #{file} found on search.maven.org for sha1 #{sha1}\ (#{result['g']}:#{result['a']}:#{result['v']})" ) group_id, artifact_id, version = site.get_maven_id_from result return site.download_pom(group_id, artifact_id, version), :found_via_sha1 end end rescue NotFoundOnMavenWebsiteError log.warn("Got a 404 error while looking for #{file}'s SHA1 in search.maven.org") end nil end
[ "def", "get_pom_from_sha1", "(", "file", ")", "log", ".", "debug", "(", "\"Attempting SHA1 POM lookup for #{file}\"", ")", "begin", "if", "File", ".", "file?", "(", "file", ")", "site", "=", "MavenWebsite", ".", "new", "sha1", "=", "Digest", "::", "SHA1", ".", "hexdigest", "File", ".", "read", "(", "file", ")", "results", "=", "site", ".", "search_by_sha1", "(", "sha1", ")", ".", "select", "{", "|", "result", "|", "result", "[", "\"ec\"", "]", ".", "include?", "(", "\".pom\"", ")", "}", "result", "=", "results", ".", "first", "unless", "result", ".", "nil?", "log", ".", "info", "(", "\"pom.xml for #{file} found on search.maven.org for sha1 #{sha1}\\ (#{result['g']}:#{result['a']}:#{result['v']})\"", ")", "group_id", ",", "artifact_id", ",", "version", "=", "site", ".", "get_maven_id_from", "result", "return", "site", ".", "download_pom", "(", "group_id", ",", "artifact_id", ",", "version", ")", ",", ":found_via_sha1", "end", "end", "rescue", "NotFoundOnMavenWebsiteError", "log", ".", "warn", "(", "\"Got a 404 error while looking for #{file}'s SHA1 in search.maven.org\"", ")", "end", "nil", "end" ]
returns a pom from search.maven.org with a jar sha1 search
[ "returns", "a", "pom", "from", "search", ".", "maven", ".", "org", "with", "a", "jar", "sha1", "search" ]
de06d766502b885bd62bd7cd9dc8da678abd7cb0
https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/pom_getter.rb#L38-L58
train
moio/tetra
lib/tetra/pom_getter.rb
Tetra.PomGetter.get_pom_from_heuristic
def get_pom_from_heuristic(filename) begin log.debug("Attempting heuristic POM search for #{filename}") site = MavenWebsite.new filename = cleanup_name(filename) version_matcher = VersionMatcher.new my_artifact_id, my_version = version_matcher.split_version(filename) log.debug("Guessed artifact id: #{my_artifact_id}, version: #{my_version}") result = site.search_by_name(my_artifact_id).first log.debug("Artifact id search result: #{result}") unless result.nil? group_id, artifact_id, = site.get_maven_id_from result results = site.search_by_group_id_and_artifact_id(group_id, artifact_id) log.debug("All versions: #{results}") their_versions = results.map { |doc| doc["v"] } best_matched_version = ( if !my_version.nil? version_matcher.best_match(my_version, their_versions) else their_versions.max end ) best_matched_result = (results.select { |r| r["v"] == best_matched_version }).first group_id, artifact_id, version = site.get_maven_id_from(best_matched_result) log.warn("pom.xml for #{filename} found on search.maven.org with heuristic search\ (#{group_id}:#{artifact_id}:#{version})" ) return site.download_pom(group_id, artifact_id, version), :found_via_heuristic end rescue NotFoundOnMavenWebsiteError log.warn("Got a 404 error while looking for #{filename} heuristically in search.maven.org") end nil end
ruby
def get_pom_from_heuristic(filename) begin log.debug("Attempting heuristic POM search for #{filename}") site = MavenWebsite.new filename = cleanup_name(filename) version_matcher = VersionMatcher.new my_artifact_id, my_version = version_matcher.split_version(filename) log.debug("Guessed artifact id: #{my_artifact_id}, version: #{my_version}") result = site.search_by_name(my_artifact_id).first log.debug("Artifact id search result: #{result}") unless result.nil? group_id, artifact_id, = site.get_maven_id_from result results = site.search_by_group_id_and_artifact_id(group_id, artifact_id) log.debug("All versions: #{results}") their_versions = results.map { |doc| doc["v"] } best_matched_version = ( if !my_version.nil? version_matcher.best_match(my_version, their_versions) else their_versions.max end ) best_matched_result = (results.select { |r| r["v"] == best_matched_version }).first group_id, artifact_id, version = site.get_maven_id_from(best_matched_result) log.warn("pom.xml for #{filename} found on search.maven.org with heuristic search\ (#{group_id}:#{artifact_id}:#{version})" ) return site.download_pom(group_id, artifact_id, version), :found_via_heuristic end rescue NotFoundOnMavenWebsiteError log.warn("Got a 404 error while looking for #{filename} heuristically in search.maven.org") end nil end
[ "def", "get_pom_from_heuristic", "(", "filename", ")", "begin", "log", ".", "debug", "(", "\"Attempting heuristic POM search for #{filename}\"", ")", "site", "=", "MavenWebsite", ".", "new", "filename", "=", "cleanup_name", "(", "filename", ")", "version_matcher", "=", "VersionMatcher", ".", "new", "my_artifact_id", ",", "my_version", "=", "version_matcher", ".", "split_version", "(", "filename", ")", "log", ".", "debug", "(", "\"Guessed artifact id: #{my_artifact_id}, version: #{my_version}\"", ")", "result", "=", "site", ".", "search_by_name", "(", "my_artifact_id", ")", ".", "first", "log", ".", "debug", "(", "\"Artifact id search result: #{result}\"", ")", "unless", "result", ".", "nil?", "group_id", ",", "artifact_id", ",", "=", "site", ".", "get_maven_id_from", "result", "results", "=", "site", ".", "search_by_group_id_and_artifact_id", "(", "group_id", ",", "artifact_id", ")", "log", ".", "debug", "(", "\"All versions: #{results}\"", ")", "their_versions", "=", "results", ".", "map", "{", "|", "doc", "|", "doc", "[", "\"v\"", "]", "}", "best_matched_version", "=", "(", "if", "!", "my_version", ".", "nil?", "version_matcher", ".", "best_match", "(", "my_version", ",", "their_versions", ")", "else", "their_versions", ".", "max", "end", ")", "best_matched_result", "=", "(", "results", ".", "select", "{", "|", "r", "|", "r", "[", "\"v\"", "]", "==", "best_matched_version", "}", ")", ".", "first", "group_id", ",", "artifact_id", ",", "version", "=", "site", ".", "get_maven_id_from", "(", "best_matched_result", ")", "log", ".", "warn", "(", "\"pom.xml for #{filename} found on search.maven.org with heuristic search\\ (#{group_id}:#{artifact_id}:#{version})\"", ")", "return", "site", ".", "download_pom", "(", "group_id", ",", "artifact_id", ",", "version", ")", ",", ":found_via_heuristic", "end", "rescue", "NotFoundOnMavenWebsiteError", "log", ".", "warn", "(", "\"Got a 404 error while looking for #{filename} heuristically in search.maven.org\"", ")", "end", "nil", "end" ]
returns a pom from search.maven.org with a heuristic name search
[ "returns", "a", "pom", "from", "search", ".", "maven", ".", "org", "with", "a", "heuristic", "name", "search" ]
de06d766502b885bd62bd7cd9dc8da678abd7cb0
https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/pom_getter.rb#L61-L97
train
moio/tetra
lib/tetra/packages/scriptable.rb
Tetra.Scriptable._to_script
def _to_script(project) project.from_directory do script_lines = [ "#!/bin/bash", "set -xe", "PROJECT_PREFIX=`readlink -e .`", "cd #{project.latest_dry_run_directory}" ] + aliases(project) + project.build_script_lines new_content = script_lines.join("\n") + "\n" result_dir = File.join(project.packages_dir, project.name) FileUtils.mkdir_p(result_dir) result_path = File.join(result_dir, "build.sh") conflict_count = project.merge_new_content(new_content, result_path, "Build script generated", "script") [result_path, conflict_count] end end
ruby
def _to_script(project) project.from_directory do script_lines = [ "#!/bin/bash", "set -xe", "PROJECT_PREFIX=`readlink -e .`", "cd #{project.latest_dry_run_directory}" ] + aliases(project) + project.build_script_lines new_content = script_lines.join("\n") + "\n" result_dir = File.join(project.packages_dir, project.name) FileUtils.mkdir_p(result_dir) result_path = File.join(result_dir, "build.sh") conflict_count = project.merge_new_content(new_content, result_path, "Build script generated", "script") [result_path, conflict_count] end end
[ "def", "_to_script", "(", "project", ")", "project", ".", "from_directory", "do", "script_lines", "=", "[", "\"#!/bin/bash\"", ",", "\"set -xe\"", ",", "\"PROJECT_PREFIX=`readlink -e .`\"", ",", "\"cd #{project.latest_dry_run_directory}\"", "]", "+", "aliases", "(", "project", ")", "+", "project", ".", "build_script_lines", "new_content", "=", "script_lines", ".", "join", "(", "\"\\n\"", ")", "+", "\"\\n\"", "result_dir", "=", "File", ".", "join", "(", "project", ".", "packages_dir", ",", "project", ".", "name", ")", "FileUtils", ".", "mkdir_p", "(", "result_dir", ")", "result_path", "=", "File", ".", "join", "(", "result_dir", ",", "\"build.sh\"", ")", "conflict_count", "=", "project", ".", "merge_new_content", "(", "new_content", ",", "result_path", ",", "\"Build script generated\"", ",", "\"script\"", ")", "[", "result_path", ",", "conflict_count", "]", "end", "end" ]
returns a build script for this package
[ "returns", "a", "build", "script", "for", "this", "package" ]
de06d766502b885bd62bd7cd9dc8da678abd7cb0
https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/packages/scriptable.rb#L7-L26
train
moio/tetra
lib/tetra/packages/scriptable.rb
Tetra.Scriptable.aliases
def aliases(project) kit = Tetra::Kit.new(project) aliases = [] ant_path = kit.find_executable("ant") ant_commandline = Tetra::Ant.commandline("$PROJECT_PREFIX", ant_path) aliases << "alias ant='#{ant_commandline}'" mvn_path = kit.find_executable("mvn") mvn_commandline = Tetra::Mvn.commandline("$PROJECT_PREFIX", mvn_path) aliases << "alias mvn='#{mvn_commandline} -o'" aliases end
ruby
def aliases(project) kit = Tetra::Kit.new(project) aliases = [] ant_path = kit.find_executable("ant") ant_commandline = Tetra::Ant.commandline("$PROJECT_PREFIX", ant_path) aliases << "alias ant='#{ant_commandline}'" mvn_path = kit.find_executable("mvn") mvn_commandline = Tetra::Mvn.commandline("$PROJECT_PREFIX", mvn_path) aliases << "alias mvn='#{mvn_commandline} -o'" aliases end
[ "def", "aliases", "(", "project", ")", "kit", "=", "Tetra", "::", "Kit", ".", "new", "(", "project", ")", "aliases", "=", "[", "]", "ant_path", "=", "kit", ".", "find_executable", "(", "\"ant\"", ")", "ant_commandline", "=", "Tetra", "::", "Ant", ".", "commandline", "(", "\"$PROJECT_PREFIX\"", ",", "ant_path", ")", "aliases", "<<", "\"alias ant='#{ant_commandline}'\"", "mvn_path", "=", "kit", ".", "find_executable", "(", "\"mvn\"", ")", "mvn_commandline", "=", "Tetra", "::", "Mvn", ".", "commandline", "(", "\"$PROJECT_PREFIX\"", ",", "mvn_path", ")", "aliases", "<<", "\"alias mvn='#{mvn_commandline} -o'\"", "aliases", "end" ]
setup aliases for adjusted versions of the packaging tools
[ "setup", "aliases", "for", "adjusted", "versions", "of", "the", "packaging", "tools" ]
de06d766502b885bd62bd7cd9dc8da678abd7cb0
https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/packages/scriptable.rb#L29-L42
train
moio/tetra
lib/tetra/project_initer.rb
Tetra.ProjectIniter.template_files
def template_files(include_bundled_software) result = { "kit" => ".", "packages" => ".", "src" => "." } if include_bundled_software Dir.chdir(TEMPLATE_PATH) do Dir.glob(File.join("bundled", "*")).each do |file| result[file] = "kit" end end end result end
ruby
def template_files(include_bundled_software) result = { "kit" => ".", "packages" => ".", "src" => "." } if include_bundled_software Dir.chdir(TEMPLATE_PATH) do Dir.glob(File.join("bundled", "*")).each do |file| result[file] = "kit" end end end result end
[ "def", "template_files", "(", "include_bundled_software", ")", "result", "=", "{", "\"kit\"", "=>", "\".\"", ",", "\"packages\"", "=>", "\".\"", ",", "\"src\"", "=>", "\".\"", "}", "if", "include_bundled_software", "Dir", ".", "chdir", "(", "TEMPLATE_PATH", ")", "do", "Dir", ".", "glob", "(", "File", ".", "join", "(", "\"bundled\"", ",", "\"*\"", ")", ")", ".", "each", "do", "|", "file", "|", "result", "[", "file", "]", "=", "\"kit\"", "end", "end", "end", "result", "end" ]
returns a hash that maps filenames that should be copied from TEMPLATE_PATH to the value directory
[ "returns", "a", "hash", "that", "maps", "filenames", "that", "should", "be", "copied", "from", "TEMPLATE_PATH", "to", "the", "value", "directory" ]
de06d766502b885bd62bd7cd9dc8da678abd7cb0
https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/project_initer.rb#L50-L66
train
moio/tetra
lib/tetra/project_initer.rb
Tetra.ProjectIniter.commit_source_archive
def commit_source_archive(file, message) from_directory do result_dir = File.join(packages_dir, name) FileUtils.mkdir_p(result_dir) result_path = File.join(result_dir, File.basename(file)) FileUtils.cp(file, result_path) @git.commit_file(result_path, "Source archive added") unarchiver = if file =~ /\.zip$/ Tetra::Unzip.new else Tetra::Tar.new end Dir.glob(File.join("src", "*")).each { |f| FileUtils.rm_rf(f) } unarchiver.decompress(file, "src") commit_sources(message, true) end end
ruby
def commit_source_archive(file, message) from_directory do result_dir = File.join(packages_dir, name) FileUtils.mkdir_p(result_dir) result_path = File.join(result_dir, File.basename(file)) FileUtils.cp(file, result_path) @git.commit_file(result_path, "Source archive added") unarchiver = if file =~ /\.zip$/ Tetra::Unzip.new else Tetra::Tar.new end Dir.glob(File.join("src", "*")).each { |f| FileUtils.rm_rf(f) } unarchiver.decompress(file, "src") commit_sources(message, true) end end
[ "def", "commit_source_archive", "(", "file", ",", "message", ")", "from_directory", "do", "result_dir", "=", "File", ".", "join", "(", "packages_dir", ",", "name", ")", "FileUtils", ".", "mkdir_p", "(", "result_dir", ")", "result_path", "=", "File", ".", "join", "(", "result_dir", ",", "File", ".", "basename", "(", "file", ")", ")", "FileUtils", ".", "cp", "(", "file", ",", "result_path", ")", "@git", ".", "commit_file", "(", "result_path", ",", "\"Source archive added\"", ")", "unarchiver", "=", "if", "file", "=~", "/", "\\.", "/", "Tetra", "::", "Unzip", ".", "new", "else", "Tetra", "::", "Tar", ".", "new", "end", "Dir", ".", "glob", "(", "File", ".", "join", "(", "\"src\"", ",", "\"*\"", ")", ")", ".", "each", "{", "|", "f", "|", "FileUtils", ".", "rm_rf", "(", "f", ")", "}", "unarchiver", ".", "decompress", "(", "file", ",", "\"src\"", ")", "commit_sources", "(", "message", ",", "true", ")", "end", "end" ]
adds a source archive at the project, both in original and unpacked forms
[ "adds", "a", "source", "archive", "at", "the", "project", "both", "in", "original", "and", "unpacked", "forms" ]
de06d766502b885bd62bd7cd9dc8da678abd7cb0
https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/project_initer.rb#L69-L88
train
jantman/serverspec-extended-types
lib/serverspec_extended_types/http_get.rb
Serverspec.Type.http_get
def http_get(port, host_header, path, timeout_sec=10, protocol='http', bypass_ssl_verify=false) Http_Get.new(port, host_header, path, timeout_sec, protocol, bypass_ssl_verify) end
ruby
def http_get(port, host_header, path, timeout_sec=10, protocol='http', bypass_ssl_verify=false) Http_Get.new(port, host_header, path, timeout_sec, protocol, bypass_ssl_verify) end
[ "def", "http_get", "(", "port", ",", "host_header", ",", "path", ",", "timeout_sec", "=", "10", ",", "protocol", "=", "'http'", ",", "bypass_ssl_verify", "=", "false", ")", "Http_Get", ".", "new", "(", "port", ",", "host_header", ",", "path", ",", "timeout_sec", ",", "protocol", ",", "bypass_ssl_verify", ")", "end" ]
ServerSpec Type wrapper for http_get @example describe http_get(80, 'myhostname', '/') do # tests here end @param port [Int] the port to connect to HTTP over @param host_header [String] the value to set in the 'Host' HTTP request header @param path [String] the URI/path to request from the server @param timeout_sec [Int] how many seconds to allow request to run before timing out and setting @timed_out_status to True @param protocol [String] the protocol to connect to the server (default 'http', can be 'https') @param bypass_ssl_verify [Boolean] if true, SSL verification will be bypassed (useful for self-signed certificates) @api public @return [Serverspec::Type::Http_Get]
[ "ServerSpec", "Type", "wrapper", "for", "http_get" ]
28437dcccc403ab71abe8bf481ec4d22d4eed395
https://github.com/jantman/serverspec-extended-types/blob/28437dcccc403ab71abe8bf481ec4d22d4eed395/lib/serverspec_extended_types/http_get.rb#L215-L217
train
moio/tetra
lib/tetra/generatable.rb
Tetra.Generatable.generate
def generate(template_name, object_binding) erb = ERB.new(File.read(File.join(template_path, template_name)), nil, "<>") erb.result(object_binding) end
ruby
def generate(template_name, object_binding) erb = ERB.new(File.read(File.join(template_path, template_name)), nil, "<>") erb.result(object_binding) end
[ "def", "generate", "(", "template_name", ",", "object_binding", ")", "erb", "=", "ERB", ".", "new", "(", "File", ".", "read", "(", "File", ".", "join", "(", "template_path", ",", "template_name", ")", ")", ",", "nil", ",", "\"<>\"", ")", "erb", ".", "result", "(", "object_binding", ")", "end" ]
generates content from an ERB template and an object binding
[ "generates", "content", "from", "an", "ERB", "template", "and", "an", "object", "binding" ]
de06d766502b885bd62bd7cd9dc8da678abd7cb0
https://github.com/moio/tetra/blob/de06d766502b885bd62bd7cd9dc8da678abd7cb0/lib/tetra/generatable.rb#L12-L15
train
acquia/fluent-plugin-sumologic-cloud-syslog
lib/sumologic_cloud_syslog/logger.rb
SumologicCloudSyslog.Logger.log
def log(severity, message, time: nil) time ||= Time.now m = SumologicCloudSyslog::Message.new # Include authentication header m.structured_data << @default_structured_data # Adjust header with current timestamp and severity m.header = @default_header.dup m.header.severity = severity m.header.timestamp = time yield m.header if block_given? m.msg = message transport.write(m.to_s) end
ruby
def log(severity, message, time: nil) time ||= Time.now m = SumologicCloudSyslog::Message.new # Include authentication header m.structured_data << @default_structured_data # Adjust header with current timestamp and severity m.header = @default_header.dup m.header.severity = severity m.header.timestamp = time yield m.header if block_given? m.msg = message transport.write(m.to_s) end
[ "def", "log", "(", "severity", ",", "message", ",", "time", ":", "nil", ")", "time", "||=", "Time", ".", "now", "m", "=", "SumologicCloudSyslog", "::", "Message", ".", "new", "m", ".", "structured_data", "<<", "@default_structured_data", "m", ".", "header", "=", "@default_header", ".", "dup", "m", ".", "header", ".", "severity", "=", "severity", "m", ".", "header", ".", "timestamp", "=", "time", "yield", "m", ".", "header", "if", "block_given?", "m", ".", "msg", "=", "message", "transport", ".", "write", "(", "m", ".", "to_s", ")", "end" ]
Send log message with severity to Sumologic
[ "Send", "log", "message", "with", "severity", "to", "Sumologic" ]
9e4e741fe0ad5ed518739acf95bbe5df64d959d9
https://github.com/acquia/fluent-plugin-sumologic-cloud-syslog/blob/9e4e741fe0ad5ed518739acf95bbe5df64d959d9/lib/sumologic_cloud_syslog/logger.rb#L61-L79
train
poise/poise-languages
lib/poise_languages/utils.rb
PoiseLanguages.Utils.shelljoin
def shelljoin(cmd, whitelist: SHELLJOIN_WHITELIST) cmd.map do |str| if whitelist.any? {|pat| str =~ pat } str else Shellwords.shellescape(str) end end.join(' ') end
ruby
def shelljoin(cmd, whitelist: SHELLJOIN_WHITELIST) cmd.map do |str| if whitelist.any? {|pat| str =~ pat } str else Shellwords.shellescape(str) end end.join(' ') end
[ "def", "shelljoin", "(", "cmd", ",", "whitelist", ":", "SHELLJOIN_WHITELIST", ")", "cmd", ".", "map", "do", "|", "str", "|", "if", "whitelist", ".", "any?", "{", "|", "pat", "|", "str", "=~", "pat", "}", "str", "else", "Shellwords", ".", "shellescape", "(", "str", ")", "end", "end", ".", "join", "(", "' '", ")", "end" ]
An improved version of Shellwords.shelljoin that doesn't escape a few things. @param cmd [Array<String>] Command array to join. @param whitelist [Array<Regexp>] Array of patterns to whitelist. @return [String]
[ "An", "improved", "version", "of", "Shellwords", ".", "shelljoin", "that", "doesn", "t", "escape", "a", "few", "things", "." ]
cdce222faaf6263b13f4b026992600b6ee3d1ff4
https://github.com/poise/poise-languages/blob/cdce222faaf6263b13f4b026992600b6ee3d1ff4/lib/poise_languages/utils.rb#L36-L44
train
poise/poise-languages
lib/poise_languages/utils.rb
PoiseLanguages.Utils.absolute_command
def absolute_command(cmd, path: nil) was_array = cmd.is_a?(Array) cmd = if was_array cmd.dup else Shellwords.split(cmd) end # Don't try to touch anything if the first value looks like a flag or a path. if cmd.first && !cmd.first.start_with?('-') && !cmd.first.include?(::File::SEPARATOR) # If which returns false, just leave it I guess. cmd[0] = which(cmd.first, path: path) || cmd.first end cmd = shelljoin(cmd) unless was_array cmd end
ruby
def absolute_command(cmd, path: nil) was_array = cmd.is_a?(Array) cmd = if was_array cmd.dup else Shellwords.split(cmd) end # Don't try to touch anything if the first value looks like a flag or a path. if cmd.first && !cmd.first.start_with?('-') && !cmd.first.include?(::File::SEPARATOR) # If which returns false, just leave it I guess. cmd[0] = which(cmd.first, path: path) || cmd.first end cmd = shelljoin(cmd) unless was_array cmd end
[ "def", "absolute_command", "(", "cmd", ",", "path", ":", "nil", ")", "was_array", "=", "cmd", ".", "is_a?", "(", "Array", ")", "cmd", "=", "if", "was_array", "cmd", ".", "dup", "else", "Shellwords", ".", "split", "(", "cmd", ")", "end", "if", "cmd", ".", "first", "&&", "!", "cmd", ".", "first", ".", "start_with?", "(", "'-'", ")", "&&", "!", "cmd", ".", "first", ".", "include?", "(", "::", "File", "::", "SEPARATOR", ")", "cmd", "[", "0", "]", "=", "which", "(", "cmd", ".", "first", ",", "path", ":", "path", ")", "||", "cmd", ".", "first", "end", "cmd", "=", "shelljoin", "(", "cmd", ")", "unless", "was_array", "cmd", "end" ]
Convert the executable in a string or array command to an absolute path. @param cmd [String, Array<String>] Command to fix up. @param path [String, nil] Replacement $PATH for executable lookup. @return [String, Array<String>]
[ "Convert", "the", "executable", "in", "a", "string", "or", "array", "command", "to", "an", "absolute", "path", "." ]
cdce222faaf6263b13f4b026992600b6ee3d1ff4
https://github.com/poise/poise-languages/blob/cdce222faaf6263b13f4b026992600b6ee3d1ff4/lib/poise_languages/utils.rb#L51-L65
train
danielgerlag/workflow_rb
workflow_rb/lib/workflow_rb/services/workflow_builder.rb
WorkflowRb.StepBuilder.then
def then(body, &setup) new_step = WorkflowStep.new new_step.body = body @workflow_builder.add_step(new_step) new_builder = StepBuilder.new(@workflow_builder, new_step) if body.kind_of?(Class) new_step.name = body.name end if setup setup.call(new_builder) end new_outcome = StepOutcome.new new_outcome.next_step = new_step.id new_outcome.value = nil @step.outcomes << new_outcome new_builder end
ruby
def then(body, &setup) new_step = WorkflowStep.new new_step.body = body @workflow_builder.add_step(new_step) new_builder = StepBuilder.new(@workflow_builder, new_step) if body.kind_of?(Class) new_step.name = body.name end if setup setup.call(new_builder) end new_outcome = StepOutcome.new new_outcome.next_step = new_step.id new_outcome.value = nil @step.outcomes << new_outcome new_builder end
[ "def", "then", "(", "body", ",", "&", "setup", ")", "new_step", "=", "WorkflowStep", ".", "new", "new_step", ".", "body", "=", "body", "@workflow_builder", ".", "add_step", "(", "new_step", ")", "new_builder", "=", "StepBuilder", ".", "new", "(", "@workflow_builder", ",", "new_step", ")", "if", "body", ".", "kind_of?", "(", "Class", ")", "new_step", ".", "name", "=", "body", ".", "name", "end", "if", "setup", "setup", ".", "call", "(", "new_builder", ")", "end", "new_outcome", "=", "StepOutcome", ".", "new", "new_outcome", ".", "next_step", "=", "new_step", ".", "id", "new_outcome", ".", "value", "=", "nil", "@step", ".", "outcomes", "<<", "new_outcome", "new_builder", "end" ]
Adds a new step to the workflow @param body [Class] the step body implementation class
[ "Adds", "a", "new", "step", "to", "the", "workflow" ]
5a4d8326a2f797ac0fc4802f358831d72bcc4f0f
https://github.com/danielgerlag/workflow_rb/blob/5a4d8326a2f797ac0fc4802f358831d72bcc4f0f/workflow_rb/lib/workflow_rb/services/workflow_builder.rb#L67-L88
train
danielgerlag/workflow_rb
workflow_rb/lib/workflow_rb/services/workflow_builder.rb
WorkflowRb.StepBuilder.input
def input(step_property, &value) mapping = IOMapping.new mapping.property = step_property mapping.value = value @step.inputs << mapping self end
ruby
def input(step_property, &value) mapping = IOMapping.new mapping.property = step_property mapping.value = value @step.inputs << mapping self end
[ "def", "input", "(", "step_property", ",", "&", "value", ")", "mapping", "=", "IOMapping", ".", "new", "mapping", ".", "property", "=", "step_property", "mapping", ".", "value", "=", "value", "@step", ".", "inputs", "<<", "mapping", "self", "end" ]
Map workflow instance data to a property on the step @param step_property [Symbol] the attribute on the step body class
[ "Map", "workflow", "instance", "data", "to", "a", "property", "on", "the", "step" ]
5a4d8326a2f797ac0fc4802f358831d72bcc4f0f
https://github.com/danielgerlag/workflow_rb/blob/5a4d8326a2f797ac0fc4802f358831d72bcc4f0f/workflow_rb/lib/workflow_rb/services/workflow_builder.rb#L105-L111
train
1and1/rijndael
lib/rijndael/base.rb
Rijndael.Base.decrypt
def decrypt(encrypted) fail ArgumentError, 'No cipher text supplied.' if encrypted.nil? || encrypted.empty? matches = CIPHER_PATTERN.match(encrypted) fail ArgumentError, 'Cipher text has an unsupported format.' if matches.nil? cipher = self.class.cipher cipher.decrypt cipher.key = Base64.decode64(@key) cipher.iv = Base64.decode64(matches[1]) decrypted = cipher.update(Base64.decode64(matches[2])) decrypted << cipher.final end
ruby
def decrypt(encrypted) fail ArgumentError, 'No cipher text supplied.' if encrypted.nil? || encrypted.empty? matches = CIPHER_PATTERN.match(encrypted) fail ArgumentError, 'Cipher text has an unsupported format.' if matches.nil? cipher = self.class.cipher cipher.decrypt cipher.key = Base64.decode64(@key) cipher.iv = Base64.decode64(matches[1]) decrypted = cipher.update(Base64.decode64(matches[2])) decrypted << cipher.final end
[ "def", "decrypt", "(", "encrypted", ")", "fail", "ArgumentError", ",", "'No cipher text supplied.'", "if", "encrypted", ".", "nil?", "||", "encrypted", ".", "empty?", "matches", "=", "CIPHER_PATTERN", ".", "match", "(", "encrypted", ")", "fail", "ArgumentError", ",", "'Cipher text has an unsupported format.'", "if", "matches", ".", "nil?", "cipher", "=", "self", ".", "class", ".", "cipher", "cipher", ".", "decrypt", "cipher", ".", "key", "=", "Base64", ".", "decode64", "(", "@key", ")", "cipher", ".", "iv", "=", "Base64", ".", "decode64", "(", "matches", "[", "1", "]", ")", "decrypted", "=", "cipher", ".", "update", "(", "Base64", ".", "decode64", "(", "matches", "[", "2", "]", ")", ")", "decrypted", "<<", "cipher", ".", "final", "end" ]
This method expects a base64 encoded cipher text and decrypts it. @param encrypted [String] Cipher text. @return [String] Plain text.
[ "This", "method", "expects", "a", "base64", "encoded", "cipher", "text", "and", "decrypts", "it", "." ]
8eee6e72381dc7e84cd2bd19ca96c2d0202d8034
https://github.com/1and1/rijndael/blob/8eee6e72381dc7e84cd2bd19ca96c2d0202d8034/lib/rijndael/base.rb#L56-L70
train
acquia/fluent-plugin-sumologic-cloud-syslog
lib/fluent/plugin/out_sumologic_cloud_syslog.rb
Fluent.SumologicCloudSyslogOutput.logger
def logger(tag) # Try to reuse existing logger @loggers[tag] ||= new_logger(tag) # Create new logger if old one is closed if @loggers[tag].closed? @loggers[tag] = new_logger(tag) end @loggers[tag] end
ruby
def logger(tag) # Try to reuse existing logger @loggers[tag] ||= new_logger(tag) # Create new logger if old one is closed if @loggers[tag].closed? @loggers[tag] = new_logger(tag) end @loggers[tag] end
[ "def", "logger", "(", "tag", ")", "@loggers", "[", "tag", "]", "||=", "new_logger", "(", "tag", ")", "if", "@loggers", "[", "tag", "]", ".", "closed?", "@loggers", "[", "tag", "]", "=", "new_logger", "(", "tag", ")", "end", "@loggers", "[", "tag", "]", "end" ]
Get logger for given tag
[ "Get", "logger", "for", "given", "tag" ]
9e4e741fe0ad5ed518739acf95bbe5df64d959d9
https://github.com/acquia/fluent-plugin-sumologic-cloud-syslog/blob/9e4e741fe0ad5ed518739acf95bbe5df64d959d9/lib/fluent/plugin/out_sumologic_cloud_syslog.rb#L72-L82
train
MartinJNash/Royce
lib/royce/methods.rb
Royce.Methods.add_role
def add_role name if allowed_role? name return if has_role? name role = Role.find_by(name: name.to_s) roles << role end end
ruby
def add_role name if allowed_role? name return if has_role? name role = Role.find_by(name: name.to_s) roles << role end end
[ "def", "add_role", "name", "if", "allowed_role?", "name", "return", "if", "has_role?", "name", "role", "=", "Role", ".", "find_by", "(", "name", ":", "name", ".", "to_s", ")", "roles", "<<", "role", "end", "end" ]
These methods are included in all User instances
[ "These", "methods", "are", "included", "in", "all", "User", "instances" ]
aa8e5bc2573ff3166a2002f42e3b181b23b530fc
https://github.com/MartinJNash/Royce/blob/aa8e5bc2573ff3166a2002f42e3b181b23b530fc/lib/royce/methods.rb#L30-L36
train
norman/utf8_utils
lib/utf8_utils.rb
UTF8Utils.StringExt.tidy_bytes
def tidy_bytes(force = false) if force return unpack("C*").map do |b| tidy_byte(b) end.flatten.compact.pack("C*").unpack("U*").pack("U*") end bytes = unpack("C*") conts_expected = 0 last_lead = 0 bytes.each_index do |i| byte = bytes[i] is_ascii = byte < 128 is_cont = byte > 127 && byte < 192 is_lead = byte > 191 && byte < 245 is_unused = byte > 240 is_restricted = byte > 244 # Impossible or highly unlikely byte? Clean it. if is_unused || is_restricted bytes[i] = tidy_byte(byte) elsif is_cont # Not expecting contination byte? Clean up. Otherwise, now expect one less. conts_expected == 0 ? bytes[i] = tidy_byte(byte) : conts_expected -= 1 else if conts_expected > 0 # Expected continuation, but got ASCII or leading? Clean backwards up to # the leading byte. (1..(i - last_lead)).each {|j| bytes[i - j] = tidy_byte(bytes[i - j])} conts_expected = 0 end if is_lead # Final byte is leading? Clean it. if i == bytes.length - 1 bytes[i] = tidy_byte(bytes.last) else # Valid leading byte? Expect continuations determined by position of # first zero bit, with max of 3. conts_expected = byte < 224 ? 1 : byte < 240 ? 2 : 3 last_lead = i end end end end bytes.empty? ? "" : bytes.flatten.compact.pack("C*").unpack("U*").pack("U*") end
ruby
def tidy_bytes(force = false) if force return unpack("C*").map do |b| tidy_byte(b) end.flatten.compact.pack("C*").unpack("U*").pack("U*") end bytes = unpack("C*") conts_expected = 0 last_lead = 0 bytes.each_index do |i| byte = bytes[i] is_ascii = byte < 128 is_cont = byte > 127 && byte < 192 is_lead = byte > 191 && byte < 245 is_unused = byte > 240 is_restricted = byte > 244 # Impossible or highly unlikely byte? Clean it. if is_unused || is_restricted bytes[i] = tidy_byte(byte) elsif is_cont # Not expecting contination byte? Clean up. Otherwise, now expect one less. conts_expected == 0 ? bytes[i] = tidy_byte(byte) : conts_expected -= 1 else if conts_expected > 0 # Expected continuation, but got ASCII or leading? Clean backwards up to # the leading byte. (1..(i - last_lead)).each {|j| bytes[i - j] = tidy_byte(bytes[i - j])} conts_expected = 0 end if is_lead # Final byte is leading? Clean it. if i == bytes.length - 1 bytes[i] = tidy_byte(bytes.last) else # Valid leading byte? Expect continuations determined by position of # first zero bit, with max of 3. conts_expected = byte < 224 ? 1 : byte < 240 ? 2 : 3 last_lead = i end end end end bytes.empty? ? "" : bytes.flatten.compact.pack("C*").unpack("U*").pack("U*") end
[ "def", "tidy_bytes", "(", "force", "=", "false", ")", "if", "force", "return", "unpack", "(", "\"C*\"", ")", ".", "map", "do", "|", "b", "|", "tidy_byte", "(", "b", ")", "end", ".", "flatten", ".", "compact", ".", "pack", "(", "\"C*\"", ")", ".", "unpack", "(", "\"U*\"", ")", ".", "pack", "(", "\"U*\"", ")", "end", "bytes", "=", "unpack", "(", "\"C*\"", ")", "conts_expected", "=", "0", "last_lead", "=", "0", "bytes", ".", "each_index", "do", "|", "i", "|", "byte", "=", "bytes", "[", "i", "]", "is_ascii", "=", "byte", "<", "128", "is_cont", "=", "byte", ">", "127", "&&", "byte", "<", "192", "is_lead", "=", "byte", ">", "191", "&&", "byte", "<", "245", "is_unused", "=", "byte", ">", "240", "is_restricted", "=", "byte", ">", "244", "if", "is_unused", "||", "is_restricted", "bytes", "[", "i", "]", "=", "tidy_byte", "(", "byte", ")", "elsif", "is_cont", "conts_expected", "==", "0", "?", "bytes", "[", "i", "]", "=", "tidy_byte", "(", "byte", ")", ":", "conts_expected", "-=", "1", "else", "if", "conts_expected", ">", "0", "(", "1", "..", "(", "i", "-", "last_lead", ")", ")", ".", "each", "{", "|", "j", "|", "bytes", "[", "i", "-", "j", "]", "=", "tidy_byte", "(", "bytes", "[", "i", "-", "j", "]", ")", "}", "conts_expected", "=", "0", "end", "if", "is_lead", "if", "i", "==", "bytes", ".", "length", "-", "1", "bytes", "[", "i", "]", "=", "tidy_byte", "(", "bytes", ".", "last", ")", "else", "conts_expected", "=", "byte", "<", "224", "?", "1", ":", "byte", "<", "240", "?", "2", ":", "3", "last_lead", "=", "i", "end", "end", "end", "end", "bytes", ".", "empty?", "?", "\"\"", ":", "bytes", ".", "flatten", ".", "compact", ".", "pack", "(", "\"C*\"", ")", ".", "unpack", "(", "\"U*\"", ")", ".", "pack", "(", "\"U*\"", ")", "end" ]
Attempt to replace invalid UTF-8 bytes with valid ones. This method naively assumes if you have invalid UTF8 bytes, they are either Windows CP-1252 or ISO8859-1. In practice this isn't a bad assumption, but may not always work. Passing +true+ will forcibly tidy all bytes, assuming that the string's encoding is CP-1252 or ISO-8859-1.
[ "Attempt", "to", "replace", "invalid", "UTF", "-", "8", "bytes", "with", "valid", "ones", ".", "This", "method", "naively", "assumes", "if", "you", "have", "invalid", "UTF8", "bytes", "they", "are", "either", "Windows", "CP", "-", "1252", "or", "ISO8859", "-", "1", ".", "In", "practice", "this", "isn", "t", "a", "bad", "assumption", "but", "may", "not", "always", "work", "." ]
878add7657dfe4cd6a24fb0de2690883fe289c6c
https://github.com/norman/utf8_utils/blob/878add7657dfe4cd6a24fb0de2690883fe289c6c/lib/utf8_utils.rb#L51-L99
train
jgraichen/paginate-responder
spec/support/05-setup-and-teardown-adapter.rb
SetupAndTeardownAdapter.ClassMethods.setup
def setup(*methods, &block) methods.each do |method| if method.to_s =~ /^setup_(with_controller|fixtures|controller_request_and_response)$/ prepend_before { __send__ method } else before { __send__ method } end end before(&block) if block end
ruby
def setup(*methods, &block) methods.each do |method| if method.to_s =~ /^setup_(with_controller|fixtures|controller_request_and_response)$/ prepend_before { __send__ method } else before { __send__ method } end end before(&block) if block end
[ "def", "setup", "(", "*", "methods", ",", "&", "block", ")", "methods", ".", "each", "do", "|", "method", "|", "if", "method", ".", "to_s", "=~", "/", "/", "prepend_before", "{", "__send__", "method", "}", "else", "before", "{", "__send__", "method", "}", "end", "end", "before", "(", "&", "block", ")", "if", "block", "end" ]
Wraps `setup` calls from within Rails' testing framework in `before` hooks.
[ "Wraps", "setup", "calls", "from", "within", "Rails", "testing", "framework", "in", "before", "hooks", "." ]
15fd3ec0a5f9f39812a0e91eeacab6be87791b00
https://github.com/jgraichen/paginate-responder/blob/15fd3ec0a5f9f39812a0e91eeacab6be87791b00/spec/support/05-setup-and-teardown-adapter.rb#L7-L16
train
jiananlu/faked_csv
lib/faked_csv/config.rb
FakedCSV.Config.parse
def parse if @config["rows"].nil? || @config["rows"].to_i < 0 @row_count = 100 # default value else @row_count = @config["rows"].to_i end @fields = [] if @config["fields"].nil? || @config["fields"].empty? raise "need 'fields' in the config file and at least 1 field in it" end @config["fields"].each do |cfg| field = {} if cfg["name"].nil? raise "field needs a name" end field[:name] = cfg["name"].to_s if cfg["type"].nil? || cfg["type"].empty? raise "field needs a type" end field[:type] = cfg["type"].to_s unless cfg["inject"].nil? || cfg["inject"].empty? || !cfg["inject"].kind_of?(Array) field[:inject] = cfg["inject"].uniq # get rid of duplicates end unless cfg["rotate"].nil? field[:rotate] = _validate_rotate cfg["rotate"] end case field[:type] when /inc:int/i field[:type] = :inc_int field[:start] = cfg["start"].nil? ? 1 : cfg["start"].to_i field[:step] = cfg["step"].nil? ? 1 : cfg["step"].to_i when /rand:int/i field[:type] = :rand_int if cfg["range"].nil? # no range specified? use the default range: [0, 100] field[:min], field[:max] = 0, 100 else field[:min], field[:max] = _min_max cfg["range"] end when /rand:float/i field[:type] = :rand_float if cfg["range"].nil? # no range specified? use the default range: [0, 1] field[:min], field[:max] = 0, 1 else field[:min], field[:max] = _min_max cfg["range"] end field[:precision] = cfg["precision"].nil? ? 1 : cfg["precision"].to_i when /rand:char/i field[:type] = :rand_char field[:length] = cfg["length"].nil? ? 10 : cfg["length"] field[:format] = cfg["format"] when /fixed/i field[:type] = :fixed raise "need values for fixed type" if cfg["values"].nil? field[:values] = cfg["values"] when /faker:\S+/i field[:type] = cfg["type"] else raise "unsupported type: #{field[:type]}. supported types: #{_supported_types}" end fields << field end end
ruby
def parse if @config["rows"].nil? || @config["rows"].to_i < 0 @row_count = 100 # default value else @row_count = @config["rows"].to_i end @fields = [] if @config["fields"].nil? || @config["fields"].empty? raise "need 'fields' in the config file and at least 1 field in it" end @config["fields"].each do |cfg| field = {} if cfg["name"].nil? raise "field needs a name" end field[:name] = cfg["name"].to_s if cfg["type"].nil? || cfg["type"].empty? raise "field needs a type" end field[:type] = cfg["type"].to_s unless cfg["inject"].nil? || cfg["inject"].empty? || !cfg["inject"].kind_of?(Array) field[:inject] = cfg["inject"].uniq # get rid of duplicates end unless cfg["rotate"].nil? field[:rotate] = _validate_rotate cfg["rotate"] end case field[:type] when /inc:int/i field[:type] = :inc_int field[:start] = cfg["start"].nil? ? 1 : cfg["start"].to_i field[:step] = cfg["step"].nil? ? 1 : cfg["step"].to_i when /rand:int/i field[:type] = :rand_int if cfg["range"].nil? # no range specified? use the default range: [0, 100] field[:min], field[:max] = 0, 100 else field[:min], field[:max] = _min_max cfg["range"] end when /rand:float/i field[:type] = :rand_float if cfg["range"].nil? # no range specified? use the default range: [0, 1] field[:min], field[:max] = 0, 1 else field[:min], field[:max] = _min_max cfg["range"] end field[:precision] = cfg["precision"].nil? ? 1 : cfg["precision"].to_i when /rand:char/i field[:type] = :rand_char field[:length] = cfg["length"].nil? ? 10 : cfg["length"] field[:format] = cfg["format"] when /fixed/i field[:type] = :fixed raise "need values for fixed type" if cfg["values"].nil? field[:values] = cfg["values"] when /faker:\S+/i field[:type] = cfg["type"] else raise "unsupported type: #{field[:type]}. supported types: #{_supported_types}" end fields << field end end
[ "def", "parse", "if", "@config", "[", "\"rows\"", "]", ".", "nil?", "||", "@config", "[", "\"rows\"", "]", ".", "to_i", "<", "0", "@row_count", "=", "100", "else", "@row_count", "=", "@config", "[", "\"rows\"", "]", ".", "to_i", "end", "@fields", "=", "[", "]", "if", "@config", "[", "\"fields\"", "]", ".", "nil?", "||", "@config", "[", "\"fields\"", "]", ".", "empty?", "raise", "\"need 'fields' in the config file and at least 1 field in it\"", "end", "@config", "[", "\"fields\"", "]", ".", "each", "do", "|", "cfg", "|", "field", "=", "{", "}", "if", "cfg", "[", "\"name\"", "]", ".", "nil?", "raise", "\"field needs a name\"", "end", "field", "[", ":name", "]", "=", "cfg", "[", "\"name\"", "]", ".", "to_s", "if", "cfg", "[", "\"type\"", "]", ".", "nil?", "||", "cfg", "[", "\"type\"", "]", ".", "empty?", "raise", "\"field needs a type\"", "end", "field", "[", ":type", "]", "=", "cfg", "[", "\"type\"", "]", ".", "to_s", "unless", "cfg", "[", "\"inject\"", "]", ".", "nil?", "||", "cfg", "[", "\"inject\"", "]", ".", "empty?", "||", "!", "cfg", "[", "\"inject\"", "]", ".", "kind_of?", "(", "Array", ")", "field", "[", ":inject", "]", "=", "cfg", "[", "\"inject\"", "]", ".", "uniq", "end", "unless", "cfg", "[", "\"rotate\"", "]", ".", "nil?", "field", "[", ":rotate", "]", "=", "_validate_rotate", "cfg", "[", "\"rotate\"", "]", "end", "case", "field", "[", ":type", "]", "when", "/", "/i", "field", "[", ":type", "]", "=", ":inc_int", "field", "[", ":start", "]", "=", "cfg", "[", "\"start\"", "]", ".", "nil?", "?", "1", ":", "cfg", "[", "\"start\"", "]", ".", "to_i", "field", "[", ":step", "]", "=", "cfg", "[", "\"step\"", "]", ".", "nil?", "?", "1", ":", "cfg", "[", "\"step\"", "]", ".", "to_i", "when", "/", "/i", "field", "[", ":type", "]", "=", ":rand_int", "if", "cfg", "[", "\"range\"", "]", ".", "nil?", "field", "[", ":min", "]", ",", "field", "[", ":max", "]", "=", "0", ",", "100", "else", "field", "[", ":min", "]", ",", "field", "[", ":max", "]", "=", "_min_max", "cfg", "[", "\"range\"", "]", "end", "when", "/", "/i", "field", "[", ":type", "]", "=", ":rand_float", "if", "cfg", "[", "\"range\"", "]", ".", "nil?", "field", "[", ":min", "]", ",", "field", "[", ":max", "]", "=", "0", ",", "1", "else", "field", "[", ":min", "]", ",", "field", "[", ":max", "]", "=", "_min_max", "cfg", "[", "\"range\"", "]", "end", "field", "[", ":precision", "]", "=", "cfg", "[", "\"precision\"", "]", ".", "nil?", "?", "1", ":", "cfg", "[", "\"precision\"", "]", ".", "to_i", "when", "/", "/i", "field", "[", ":type", "]", "=", ":rand_char", "field", "[", ":length", "]", "=", "cfg", "[", "\"length\"", "]", ".", "nil?", "?", "10", ":", "cfg", "[", "\"length\"", "]", "field", "[", ":format", "]", "=", "cfg", "[", "\"format\"", "]", "when", "/", "/i", "field", "[", ":type", "]", "=", ":fixed", "raise", "\"need values for fixed type\"", "if", "cfg", "[", "\"values\"", "]", ".", "nil?", "field", "[", ":values", "]", "=", "cfg", "[", "\"values\"", "]", "when", "/", "\\S", "/i", "field", "[", ":type", "]", "=", "cfg", "[", "\"type\"", "]", "else", "raise", "\"unsupported type: #{field[:type]}. supported types: #{_supported_types}\"", "end", "fields", "<<", "field", "end", "end" ]
prepare the json config and generate the fields
[ "prepare", "the", "json", "config", "and", "generate", "the", "fields" ]
d30520dc71efb6171908bddbdf28b4fb61203ca0
https://github.com/jiananlu/faked_csv/blob/d30520dc71efb6171908bddbdf28b4fb61203ca0/lib/faked_csv/config.rb#L19-L90
train
subakva/haproxy-tools
lib/haproxy/parser.rb
HAProxy.Parser.parse_server_attributes
def parse_server_attributes(value) parts = value.to_s.split(/\s/) current_name = nil pairs = parts.each_with_object({}) { |part, attrs| if SERVER_ATTRIBUTE_NAMES.include?(part) current_name = part attrs[current_name] = [] elsif current_name.nil? raise "Invalid server attribute: #{part}" else attrs[current_name] << part end } clean_parsed_server_attributes(pairs) end
ruby
def parse_server_attributes(value) parts = value.to_s.split(/\s/) current_name = nil pairs = parts.each_with_object({}) { |part, attrs| if SERVER_ATTRIBUTE_NAMES.include?(part) current_name = part attrs[current_name] = [] elsif current_name.nil? raise "Invalid server attribute: #{part}" else attrs[current_name] << part end } clean_parsed_server_attributes(pairs) end
[ "def", "parse_server_attributes", "(", "value", ")", "parts", "=", "value", ".", "to_s", ".", "split", "(", "/", "\\s", "/", ")", "current_name", "=", "nil", "pairs", "=", "parts", ".", "each_with_object", "(", "{", "}", ")", "{", "|", "part", ",", "attrs", "|", "if", "SERVER_ATTRIBUTE_NAMES", ".", "include?", "(", "part", ")", "current_name", "=", "part", "attrs", "[", "current_name", "]", "=", "[", "]", "elsif", "current_name", ".", "nil?", "raise", "\"Invalid server attribute: #{part}\"", "else", "attrs", "[", "current_name", "]", "<<", "part", "end", "}", "clean_parsed_server_attributes", "(", "pairs", ")", "end" ]
Parses server attributes from the server value. I couldn't manage to get treetop to do this. Types of server attributes to support: ipv4, boolean, string, integer, time (us, ms, s, m, h, d), url, source attributes BUG: If an attribute value matches an attribute name, the parser will assume that a new attribute value has started. I don't know how haproxy itself handles that situation.
[ "Parses", "server", "attributes", "from", "the", "server", "value", ".", "I", "couldn", "t", "manage", "to", "get", "treetop", "to", "do", "this", "." ]
1edf787aca21513312581cefb7f349d41ad859e4
https://github.com/subakva/haproxy-tools/blob/1edf787aca21513312581cefb7f349d41ad859e4/lib/haproxy/parser.rb#L199-L214
train
subakva/haproxy-tools
lib/haproxy/parser.rb
HAProxy.Parser.clean_parsed_server_attributes
def clean_parsed_server_attributes(pairs) pairs.each do |k, v| pairs[k] = if v.empty? true else v.join(" ") end end end
ruby
def clean_parsed_server_attributes(pairs) pairs.each do |k, v| pairs[k] = if v.empty? true else v.join(" ") end end end
[ "def", "clean_parsed_server_attributes", "(", "pairs", ")", "pairs", ".", "each", "do", "|", "k", ",", "v", "|", "pairs", "[", "k", "]", "=", "if", "v", ".", "empty?", "true", "else", "v", ".", "join", "(", "\" \"", ")", "end", "end", "end" ]
Converts attributes with no values to true, and combines everything else into space- separated strings.
[ "Converts", "attributes", "with", "no", "values", "to", "true", "and", "combines", "everything", "else", "into", "space", "-", "separated", "strings", "." ]
1edf787aca21513312581cefb7f349d41ad859e4
https://github.com/subakva/haproxy-tools/blob/1edf787aca21513312581cefb7f349d41ad859e4/lib/haproxy/parser.rb#L218-L226
train
ploubser/JSON-Grep
lib/parser/parser.rb
JGrep.Parser.parse
def parse(substatement = nil, token_index = 0) p_token = nil if substatement c_token, c_token_value = substatement[token_index] else c_token, c_token_value = @scanner.get_token end parenth = 0 until c_token.nil? if substatement token_index += 1 n_token, n_token_value = substatement[token_index] else @scanner.token_index += 1 n_token, n_token_value = @scanner.get_token end next if n_token == " " case c_token when "and" unless (n_token =~ /not|statement|\(|\+|-/) || (scanner.token_index == scanner.arguments.size) raise "Error at column #{scanner.token_index}. \nExpected 'not', 'statement' or '('. Found '#{n_token_value}'" end raise "Error at column #{scanner.token_index}. \n Expression cannot start with 'and'" if p_token.nil? raise "Error at column #{scanner.token_index}. \n #{p_token} cannot be followed by 'and'" if %w[and or].include?(p_token) when "or" unless (n_token =~ /not|statement|\(|\+|-/) || (scanner.token_index == scanner.arguments.size) raise "Error at column #{scanner.token_index}. \nExpected 'not', 'statement', '('. Found '#{n_token_value}'" end raise "Error at column #{scanner.token_index}. \n Expression cannot start with 'or'" if p_token.nil? raise "Error at column #{scanner.token_index}. \n #{p_token} cannot be followed by 'or'" if %w[and or].include?(p_token) when "not" unless n_token =~ /statement|\(|not|\+|-/ raise "Error at column #{scanner.token_index}. \nExpected 'statement' or '('. Found '#{n_token_value}'" end when "statement" if c_token_value.is_a? Array raise "Error at column #{scanner.token_index}\nError, cannot define '[' in a '[...]' block." if substatement parse(c_token_value, 0) end if c_token_value =~ /!=/ c_token_value = c_token_value.gsub("!=", "=") @execution_stack << {"not" => "not"} end if !n_token.nil? && !n_token.match(/and|or|\)/) raise "Error at column #{scanner.token_index}. \nExpected 'and', 'or', ')'. Found '#{n_token_value}'" end when "+" if !n_token.nil? && !n_token.match(/and|or|\)/) raise "Error at column #{scanner.token_index}. \nExpected 'and', 'or', ')'. Found '#{n_token_value}'" end when "-" if !n_token.nil? && !n_token.match(/and|or|\)/) raise "Error at column #{scanner.token_index}. \nExpected 'and', 'or', ')'. Found '#{n_token_value}'" end when ")" if !n_token.nil? && !n_token =~ /|and|or|not|\(/ raise "Error at column #{scanner.token_index}. \nExpected 'and', 'or', 'not' or '('. Found '#{n_token_value}'" end parenth += 1 when "(" unless n_token =~ /statement|not|\(|\+|-/ raise "Error at column #{scanner.token_index}. \nExpected 'statement', '(', not. Found '#{n_token_value}'" end parenth -= 1 else raise "Unexpected token found at column #{scanner.token_index}. '#{c_token_value}'" end unless n_token == " " || substatement @execution_stack << {c_token => c_token_value} end p_token = c_token c_token = n_token c_token_value = n_token_value end return if substatement raise "Error. Missing parentheses ')'." if parenth < 0 raise "Error. Missing parentheses '('." if parenth > 0 end
ruby
def parse(substatement = nil, token_index = 0) p_token = nil if substatement c_token, c_token_value = substatement[token_index] else c_token, c_token_value = @scanner.get_token end parenth = 0 until c_token.nil? if substatement token_index += 1 n_token, n_token_value = substatement[token_index] else @scanner.token_index += 1 n_token, n_token_value = @scanner.get_token end next if n_token == " " case c_token when "and" unless (n_token =~ /not|statement|\(|\+|-/) || (scanner.token_index == scanner.arguments.size) raise "Error at column #{scanner.token_index}. \nExpected 'not', 'statement' or '('. Found '#{n_token_value}'" end raise "Error at column #{scanner.token_index}. \n Expression cannot start with 'and'" if p_token.nil? raise "Error at column #{scanner.token_index}. \n #{p_token} cannot be followed by 'and'" if %w[and or].include?(p_token) when "or" unless (n_token =~ /not|statement|\(|\+|-/) || (scanner.token_index == scanner.arguments.size) raise "Error at column #{scanner.token_index}. \nExpected 'not', 'statement', '('. Found '#{n_token_value}'" end raise "Error at column #{scanner.token_index}. \n Expression cannot start with 'or'" if p_token.nil? raise "Error at column #{scanner.token_index}. \n #{p_token} cannot be followed by 'or'" if %w[and or].include?(p_token) when "not" unless n_token =~ /statement|\(|not|\+|-/ raise "Error at column #{scanner.token_index}. \nExpected 'statement' or '('. Found '#{n_token_value}'" end when "statement" if c_token_value.is_a? Array raise "Error at column #{scanner.token_index}\nError, cannot define '[' in a '[...]' block." if substatement parse(c_token_value, 0) end if c_token_value =~ /!=/ c_token_value = c_token_value.gsub("!=", "=") @execution_stack << {"not" => "not"} end if !n_token.nil? && !n_token.match(/and|or|\)/) raise "Error at column #{scanner.token_index}. \nExpected 'and', 'or', ')'. Found '#{n_token_value}'" end when "+" if !n_token.nil? && !n_token.match(/and|or|\)/) raise "Error at column #{scanner.token_index}. \nExpected 'and', 'or', ')'. Found '#{n_token_value}'" end when "-" if !n_token.nil? && !n_token.match(/and|or|\)/) raise "Error at column #{scanner.token_index}. \nExpected 'and', 'or', ')'. Found '#{n_token_value}'" end when ")" if !n_token.nil? && !n_token =~ /|and|or|not|\(/ raise "Error at column #{scanner.token_index}. \nExpected 'and', 'or', 'not' or '('. Found '#{n_token_value}'" end parenth += 1 when "(" unless n_token =~ /statement|not|\(|\+|-/ raise "Error at column #{scanner.token_index}. \nExpected 'statement', '(', not. Found '#{n_token_value}'" end parenth -= 1 else raise "Unexpected token found at column #{scanner.token_index}. '#{c_token_value}'" end unless n_token == " " || substatement @execution_stack << {c_token => c_token_value} end p_token = c_token c_token = n_token c_token_value = n_token_value end return if substatement raise "Error. Missing parentheses ')'." if parenth < 0 raise "Error. Missing parentheses '('." if parenth > 0 end
[ "def", "parse", "(", "substatement", "=", "nil", ",", "token_index", "=", "0", ")", "p_token", "=", "nil", "if", "substatement", "c_token", ",", "c_token_value", "=", "substatement", "[", "token_index", "]", "else", "c_token", ",", "c_token_value", "=", "@scanner", ".", "get_token", "end", "parenth", "=", "0", "until", "c_token", ".", "nil?", "if", "substatement", "token_index", "+=", "1", "n_token", ",", "n_token_value", "=", "substatement", "[", "token_index", "]", "else", "@scanner", ".", "token_index", "+=", "1", "n_token", ",", "n_token_value", "=", "@scanner", ".", "get_token", "end", "next", "if", "n_token", "==", "\" \"", "case", "c_token", "when", "\"and\"", "unless", "(", "n_token", "=~", "/", "\\(", "\\+", "/", ")", "||", "(", "scanner", ".", "token_index", "==", "scanner", ".", "arguments", ".", "size", ")", "raise", "\"Error at column #{scanner.token_index}. \\nExpected 'not', 'statement' or '('. Found '#{n_token_value}'\"", "end", "raise", "\"Error at column #{scanner.token_index}. \\n Expression cannot start with 'and'\"", "if", "p_token", ".", "nil?", "raise", "\"Error at column #{scanner.token_index}. \\n #{p_token} cannot be followed by 'and'\"", "if", "%w[", "and", "or", "]", ".", "include?", "(", "p_token", ")", "when", "\"or\"", "unless", "(", "n_token", "=~", "/", "\\(", "\\+", "/", ")", "||", "(", "scanner", ".", "token_index", "==", "scanner", ".", "arguments", ".", "size", ")", "raise", "\"Error at column #{scanner.token_index}. \\nExpected 'not', 'statement', '('. Found '#{n_token_value}'\"", "end", "raise", "\"Error at column #{scanner.token_index}. \\n Expression cannot start with 'or'\"", "if", "p_token", ".", "nil?", "raise", "\"Error at column #{scanner.token_index}. \\n #{p_token} cannot be followed by 'or'\"", "if", "%w[", "and", "or", "]", ".", "include?", "(", "p_token", ")", "when", "\"not\"", "unless", "n_token", "=~", "/", "\\(", "\\+", "/", "raise", "\"Error at column #{scanner.token_index}. \\nExpected 'statement' or '('. Found '#{n_token_value}'\"", "end", "when", "\"statement\"", "if", "c_token_value", ".", "is_a?", "Array", "raise", "\"Error at column #{scanner.token_index}\\nError, cannot define '[' in a '[...]' block.\"", "if", "substatement", "parse", "(", "c_token_value", ",", "0", ")", "end", "if", "c_token_value", "=~", "/", "/", "c_token_value", "=", "c_token_value", ".", "gsub", "(", "\"!=\"", ",", "\"=\"", ")", "@execution_stack", "<<", "{", "\"not\"", "=>", "\"not\"", "}", "end", "if", "!", "n_token", ".", "nil?", "&&", "!", "n_token", ".", "match", "(", "/", "\\)", "/", ")", "raise", "\"Error at column #{scanner.token_index}. \\nExpected 'and', 'or', ')'. Found '#{n_token_value}'\"", "end", "when", "\"+\"", "if", "!", "n_token", ".", "nil?", "&&", "!", "n_token", ".", "match", "(", "/", "\\)", "/", ")", "raise", "\"Error at column #{scanner.token_index}. \\nExpected 'and', 'or', ')'. Found '#{n_token_value}'\"", "end", "when", "\"-\"", "if", "!", "n_token", ".", "nil?", "&&", "!", "n_token", ".", "match", "(", "/", "\\)", "/", ")", "raise", "\"Error at column #{scanner.token_index}. \\nExpected 'and', 'or', ')'. Found '#{n_token_value}'\"", "end", "when", "\")\"", "if", "!", "n_token", ".", "nil?", "&&", "!", "n_token", "=~", "/", "\\(", "/", "raise", "\"Error at column #{scanner.token_index}. \\nExpected 'and', 'or', 'not' or '('. Found '#{n_token_value}'\"", "end", "parenth", "+=", "1", "when", "\"(\"", "unless", "n_token", "=~", "/", "\\(", "\\+", "/", "raise", "\"Error at column #{scanner.token_index}. \\nExpected 'statement', '(', not. Found '#{n_token_value}'\"", "end", "parenth", "-=", "1", "else", "raise", "\"Unexpected token found at column #{scanner.token_index}. '#{c_token_value}'\"", "end", "unless", "n_token", "==", "\" \"", "||", "substatement", "@execution_stack", "<<", "{", "c_token", "=>", "c_token_value", "}", "end", "p_token", "=", "c_token", "c_token", "=", "n_token", "c_token_value", "=", "n_token_value", "end", "return", "if", "substatement", "raise", "\"Error. Missing parentheses ')'.\"", "if", "parenth", "<", "0", "raise", "\"Error. Missing parentheses '('.\"", "if", "parenth", ">", "0", "end" ]
Parse the input string, one token at a time a contruct the call stack
[ "Parse", "the", "input", "string", "one", "token", "at", "a", "time", "a", "contruct", "the", "call", "stack" ]
3d96a6bb6d090d3fcb956e5d8aef96b493034115
https://github.com/ploubser/JSON-Grep/blob/3d96a6bb6d090d3fcb956e5d8aef96b493034115/lib/parser/parser.rb#L13-L114
train
ploubser/JSON-Grep
lib/parser/scanner.rb
JGrep.Scanner.get_token
def get_token return nil if @token_index >= @arguments.size begin case chr(@arguments[@token_index]) when "[" return "statement", gen_substatement when "]" return "]" when "(" return "(", "(" when ")" return ")", ")" when "n" if (chr(@arguments[@token_index + 1]) == "o") && (chr(@arguments[@token_index + 2]) == "t") && ((chr(@arguments[@token_index + 3]) == " ") || (chr(@arguments[@token_index + 3]) == "(")) @token_index += 2 return "not", "not" else gen_statement end when "!" return "not", "not" when "a" if (chr(@arguments[@token_index + 1]) == "n") && (chr(@arguments[@token_index + 2]) == "d") && ((chr(@arguments[@token_index + 3]) == " ") || (chr(@arguments[@token_index + 3]) == "(")) @token_index += 2 return "and", "and" else gen_statement end when "&" if chr(@arguments[@token_index + 1]) == "&" @token_index += 1 return "and", "and" else gen_statement end when "o" if (chr(@arguments[@token_index + 1]) == "r") && ((chr(@arguments[@token_index + 2]) == " ") || (chr(@arguments[@token_index + 2]) == "(")) @token_index += 1 return "or", "or" else gen_statement end when "|" if chr(@arguments[@token_index + 1]) == "|" @token_index += 1 return "or", "or" else gen_statement end when "+" value = "" i = @token_index + 1 begin value += chr(@arguments[i]) i += 1 end until (i >= @arguments.size) || (chr(@arguments[i]) =~ /\s|\)/) @token_index = i - 1 return "+", value when "-" value = "" i = @token_index + 1 begin value += chr(@arguments[i]) i += 1 end until (i >= @arguments.size) || (chr(@arguments[i]) =~ /\s|\)/) @token_index = i - 1 return "-", value when " " return " ", " " else gen_statement end end rescue NoMethodError raise "Error. Expression cannot be parsed." end
ruby
def get_token return nil if @token_index >= @arguments.size begin case chr(@arguments[@token_index]) when "[" return "statement", gen_substatement when "]" return "]" when "(" return "(", "(" when ")" return ")", ")" when "n" if (chr(@arguments[@token_index + 1]) == "o") && (chr(@arguments[@token_index + 2]) == "t") && ((chr(@arguments[@token_index + 3]) == " ") || (chr(@arguments[@token_index + 3]) == "(")) @token_index += 2 return "not", "not" else gen_statement end when "!" return "not", "not" when "a" if (chr(@arguments[@token_index + 1]) == "n") && (chr(@arguments[@token_index + 2]) == "d") && ((chr(@arguments[@token_index + 3]) == " ") || (chr(@arguments[@token_index + 3]) == "(")) @token_index += 2 return "and", "and" else gen_statement end when "&" if chr(@arguments[@token_index + 1]) == "&" @token_index += 1 return "and", "and" else gen_statement end when "o" if (chr(@arguments[@token_index + 1]) == "r") && ((chr(@arguments[@token_index + 2]) == " ") || (chr(@arguments[@token_index + 2]) == "(")) @token_index += 1 return "or", "or" else gen_statement end when "|" if chr(@arguments[@token_index + 1]) == "|" @token_index += 1 return "or", "or" else gen_statement end when "+" value = "" i = @token_index + 1 begin value += chr(@arguments[i]) i += 1 end until (i >= @arguments.size) || (chr(@arguments[i]) =~ /\s|\)/) @token_index = i - 1 return "+", value when "-" value = "" i = @token_index + 1 begin value += chr(@arguments[i]) i += 1 end until (i >= @arguments.size) || (chr(@arguments[i]) =~ /\s|\)/) @token_index = i - 1 return "-", value when " " return " ", " " else gen_statement end end rescue NoMethodError raise "Error. Expression cannot be parsed." end
[ "def", "get_token", "return", "nil", "if", "@token_index", ">=", "@arguments", ".", "size", "begin", "case", "chr", "(", "@arguments", "[", "@token_index", "]", ")", "when", "\"[\"", "return", "\"statement\"", ",", "gen_substatement", "when", "\"]\"", "return", "\"]\"", "when", "\"(\"", "return", "\"(\"", ",", "\"(\"", "when", "\")\"", "return", "\")\"", ",", "\")\"", "when", "\"n\"", "if", "(", "chr", "(", "@arguments", "[", "@token_index", "+", "1", "]", ")", "==", "\"o\"", ")", "&&", "(", "chr", "(", "@arguments", "[", "@token_index", "+", "2", "]", ")", "==", "\"t\"", ")", "&&", "(", "(", "chr", "(", "@arguments", "[", "@token_index", "+", "3", "]", ")", "==", "\" \"", ")", "||", "(", "chr", "(", "@arguments", "[", "@token_index", "+", "3", "]", ")", "==", "\"(\"", ")", ")", "@token_index", "+=", "2", "return", "\"not\"", ",", "\"not\"", "else", "gen_statement", "end", "when", "\"!\"", "return", "\"not\"", ",", "\"not\"", "when", "\"a\"", "if", "(", "chr", "(", "@arguments", "[", "@token_index", "+", "1", "]", ")", "==", "\"n\"", ")", "&&", "(", "chr", "(", "@arguments", "[", "@token_index", "+", "2", "]", ")", "==", "\"d\"", ")", "&&", "(", "(", "chr", "(", "@arguments", "[", "@token_index", "+", "3", "]", ")", "==", "\" \"", ")", "||", "(", "chr", "(", "@arguments", "[", "@token_index", "+", "3", "]", ")", "==", "\"(\"", ")", ")", "@token_index", "+=", "2", "return", "\"and\"", ",", "\"and\"", "else", "gen_statement", "end", "when", "\"&\"", "if", "chr", "(", "@arguments", "[", "@token_index", "+", "1", "]", ")", "==", "\"&\"", "@token_index", "+=", "1", "return", "\"and\"", ",", "\"and\"", "else", "gen_statement", "end", "when", "\"o\"", "if", "(", "chr", "(", "@arguments", "[", "@token_index", "+", "1", "]", ")", "==", "\"r\"", ")", "&&", "(", "(", "chr", "(", "@arguments", "[", "@token_index", "+", "2", "]", ")", "==", "\" \"", ")", "||", "(", "chr", "(", "@arguments", "[", "@token_index", "+", "2", "]", ")", "==", "\"(\"", ")", ")", "@token_index", "+=", "1", "return", "\"or\"", ",", "\"or\"", "else", "gen_statement", "end", "when", "\"|\"", "if", "chr", "(", "@arguments", "[", "@token_index", "+", "1", "]", ")", "==", "\"|\"", "@token_index", "+=", "1", "return", "\"or\"", ",", "\"or\"", "else", "gen_statement", "end", "when", "\"+\"", "value", "=", "\"\"", "i", "=", "@token_index", "+", "1", "begin", "value", "+=", "chr", "(", "@arguments", "[", "i", "]", ")", "i", "+=", "1", "end", "until", "(", "i", ">=", "@arguments", ".", "size", ")", "||", "(", "chr", "(", "@arguments", "[", "i", "]", ")", "=~", "/", "\\s", "\\)", "/", ")", "@token_index", "=", "i", "-", "1", "return", "\"+\"", ",", "value", "when", "\"-\"", "value", "=", "\"\"", "i", "=", "@token_index", "+", "1", "begin", "value", "+=", "chr", "(", "@arguments", "[", "i", "]", ")", "i", "+=", "1", "end", "until", "(", "i", ">=", "@arguments", ".", "size", ")", "||", "(", "chr", "(", "@arguments", "[", "i", "]", ")", "=~", "/", "\\s", "\\)", "/", ")", "@token_index", "=", "i", "-", "1", "return", "\"-\"", ",", "value", "when", "\" \"", "return", "\" \"", ",", "\" \"", "else", "gen_statement", "end", "end", "rescue", "NoMethodError", "raise", "\"Error. Expression cannot be parsed.\"", "end" ]
Scans the input string and identifies single language tokens
[ "Scans", "the", "input", "string", "and", "identifies", "single", "language", "tokens" ]
3d96a6bb6d090d3fcb956e5d8aef96b493034115
https://github.com/ploubser/JSON-Grep/blob/3d96a6bb6d090d3fcb956e5d8aef96b493034115/lib/parser/scanner.rb#L11-L104
train
agardiner/arg-parser
lib/arg-parser/definition.rb
ArgParser.Definition.<<
def <<(arg) case arg when PositionalArgument, KeywordArgument, FlagArgument, RestArgument if @arguments[arg.key] raise ArgumentError, "An argument with key '#{arg.key}' has already been defined" end if arg.short_key && @short_keys[arg.short_key] raise ArgumentError, "The short key '#{arg.short_key}' has already been registered by the '#{ @short_keys[arg.short_key]}' argument" end if arg.is_a?(RestArgument) && rest_args raise ArgumentError, "Only one rest argument can be defined" end @arguments[arg.key] = arg @short_keys[arg.short_key] = arg if arg.short_key else raise ArgumentError, "arg must be an instance of PositionalArgument, KeywordArgument, " + "FlagArgument or RestArgument" end end
ruby
def <<(arg) case arg when PositionalArgument, KeywordArgument, FlagArgument, RestArgument if @arguments[arg.key] raise ArgumentError, "An argument with key '#{arg.key}' has already been defined" end if arg.short_key && @short_keys[arg.short_key] raise ArgumentError, "The short key '#{arg.short_key}' has already been registered by the '#{ @short_keys[arg.short_key]}' argument" end if arg.is_a?(RestArgument) && rest_args raise ArgumentError, "Only one rest argument can be defined" end @arguments[arg.key] = arg @short_keys[arg.short_key] = arg if arg.short_key else raise ArgumentError, "arg must be an instance of PositionalArgument, KeywordArgument, " + "FlagArgument or RestArgument" end end
[ "def", "<<", "(", "arg", ")", "case", "arg", "when", "PositionalArgument", ",", "KeywordArgument", ",", "FlagArgument", ",", "RestArgument", "if", "@arguments", "[", "arg", ".", "key", "]", "raise", "ArgumentError", ",", "\"An argument with key '#{arg.key}' has already been defined\"", "end", "if", "arg", ".", "short_key", "&&", "@short_keys", "[", "arg", ".", "short_key", "]", "raise", "ArgumentError", ",", "\"The short key '#{arg.short_key}' has already been registered by the '#{ @short_keys[arg.short_key]}' argument\"", "end", "if", "arg", ".", "is_a?", "(", "RestArgument", ")", "&&", "rest_args", "raise", "ArgumentError", ",", "\"Only one rest argument can be defined\"", "end", "@arguments", "[", "arg", ".", "key", "]", "=", "arg", "@short_keys", "[", "arg", ".", "short_key", "]", "=", "arg", "if", "arg", ".", "short_key", "else", "raise", "ArgumentError", ",", "\"arg must be an instance of PositionalArgument, KeywordArgument, \"", "+", "\"FlagArgument or RestArgument\"", "end", "end" ]
Adds the specified argument to the command-line definition. @param arg [Argument] An Argument sub-class to be added to the command- line definition.
[ "Adds", "the", "specified", "argument", "to", "the", "command", "-", "line", "definition", "." ]
43c04fb7af45ef4f00bc52253780152a38aeb257
https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/definition.rb#L54-L73
train
agardiner/arg-parser
lib/arg-parser/definition.rb
ArgParser.Definition.positional_arg
def positional_arg(key, desc, opts = {}, &block) self << ArgParser::PositionalArgument.new(key, desc, opts, &block) end
ruby
def positional_arg(key, desc, opts = {}, &block) self << ArgParser::PositionalArgument.new(key, desc, opts, &block) end
[ "def", "positional_arg", "(", "key", ",", "desc", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "self", "<<", "ArgParser", "::", "PositionalArgument", ".", "new", "(", "key", ",", "desc", ",", "opts", ",", "&", "block", ")", "end" ]
Add a positional argument to the set of arguments in this command-line argument definition. @see PositionalArgument#initialize
[ "Add", "a", "positional", "argument", "to", "the", "set", "of", "arguments", "in", "this", "command", "-", "line", "argument", "definition", "." ]
43c04fb7af45ef4f00bc52253780152a38aeb257
https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/definition.rb#L79-L81
train
agardiner/arg-parser
lib/arg-parser/definition.rb
ArgParser.Definition.keyword_arg
def keyword_arg(key, desc, opts = {}, &block) self << ArgParser::KeywordArgument.new(key, desc, opts, &block) end
ruby
def keyword_arg(key, desc, opts = {}, &block) self << ArgParser::KeywordArgument.new(key, desc, opts, &block) end
[ "def", "keyword_arg", "(", "key", ",", "desc", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "self", "<<", "ArgParser", "::", "KeywordArgument", ".", "new", "(", "key", ",", "desc", ",", "opts", ",", "&", "block", ")", "end" ]
Add a keyword argument to the set of arguments in this command-line argument definition. @see KeywordArgument#initialize
[ "Add", "a", "keyword", "argument", "to", "the", "set", "of", "arguments", "in", "this", "command", "-", "line", "argument", "definition", "." ]
43c04fb7af45ef4f00bc52253780152a38aeb257
https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/definition.rb#L87-L89
train
agardiner/arg-parser
lib/arg-parser/definition.rb
ArgParser.Definition.flag_arg
def flag_arg(key, desc, opts = {}, &block) self << ArgParser::FlagArgument.new(key, desc, opts, &block) end
ruby
def flag_arg(key, desc, opts = {}, &block) self << ArgParser::FlagArgument.new(key, desc, opts, &block) end
[ "def", "flag_arg", "(", "key", ",", "desc", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "self", "<<", "ArgParser", "::", "FlagArgument", ".", "new", "(", "key", ",", "desc", ",", "opts", ",", "&", "block", ")", "end" ]
Add a flag argument to the set of arguments in this command-line argument definition. @see FlagArgument#initialize
[ "Add", "a", "flag", "argument", "to", "the", "set", "of", "arguments", "in", "this", "command", "-", "line", "argument", "definition", "." ]
43c04fb7af45ef4f00bc52253780152a38aeb257
https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/definition.rb#L95-L97
train
agardiner/arg-parser
lib/arg-parser/definition.rb
ArgParser.Definition.rest_arg
def rest_arg(key, desc, opts = {}, &block) self << ArgParser::RestArgument.new(key, desc, opts, &block) end
ruby
def rest_arg(key, desc, opts = {}, &block) self << ArgParser::RestArgument.new(key, desc, opts, &block) end
[ "def", "rest_arg", "(", "key", ",", "desc", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "self", "<<", "ArgParser", "::", "RestArgument", ".", "new", "(", "key", ",", "desc", ",", "opts", ",", "&", "block", ")", "end" ]
Add a rest argument to the set of arguments in this command-line argument definition. @see RestArgument#initialize
[ "Add", "a", "rest", "argument", "to", "the", "set", "of", "arguments", "in", "this", "command", "-", "line", "argument", "definition", "." ]
43c04fb7af45ef4f00bc52253780152a38aeb257
https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/definition.rb#L103-L105
train
agardiner/arg-parser
lib/arg-parser/definition.rb
ArgParser.Definition.validate_requirements
def validate_requirements(args) errors = [] @require_set.each do |req, sets| sets.each do |set| count = set.count{ |arg| args.has_key?(arg.key) && args[arg.key] } case req when :one if count == 0 errors << "No argument has been specified for one of: #{set.join(', ')}" elsif count > 1 errors << "Only one argument can been specified from: #{set.join(', ')}" end when :any if count == 0 errors << "At least one of the arguments must be specified from: #{set.join(', ')}" end end end end errors end
ruby
def validate_requirements(args) errors = [] @require_set.each do |req, sets| sets.each do |set| count = set.count{ |arg| args.has_key?(arg.key) && args[arg.key] } case req when :one if count == 0 errors << "No argument has been specified for one of: #{set.join(', ')}" elsif count > 1 errors << "Only one argument can been specified from: #{set.join(', ')}" end when :any if count == 0 errors << "At least one of the arguments must be specified from: #{set.join(', ')}" end end end end errors end
[ "def", "validate_requirements", "(", "args", ")", "errors", "=", "[", "]", "@require_set", ".", "each", "do", "|", "req", ",", "sets", "|", "sets", ".", "each", "do", "|", "set", "|", "count", "=", "set", ".", "count", "{", "|", "arg", "|", "args", ".", "has_key?", "(", "arg", ".", "key", ")", "&&", "args", "[", "arg", ".", "key", "]", "}", "case", "req", "when", ":one", "if", "count", "==", "0", "errors", "<<", "\"No argument has been specified for one of: #{set.join(', ')}\"", "elsif", "count", ">", "1", "errors", "<<", "\"Only one argument can been specified from: #{set.join(', ')}\"", "end", "when", ":any", "if", "count", "==", "0", "errors", "<<", "\"At least one of the arguments must be specified from: #{set.join(', ')}\"", "end", "end", "end", "end", "errors", "end" ]
Validates the supplied +args+ Hash object, verifying that any argument set requirements have been satisfied. Returns an array of error messages for each set requirement that is not satisfied. @param args [Hash] a Hash containing the keys and values identified by the parser. @return [Array] a list of errors for any argument requirements that have not been satisfied.
[ "Validates", "the", "supplied", "+", "args", "+", "Hash", "object", "verifying", "that", "any", "argument", "set", "requirements", "have", "been", "satisfied", ".", "Returns", "an", "array", "of", "error", "messages", "for", "each", "set", "requirement", "that", "is", "not", "satisfied", "." ]
43c04fb7af45ef4f00bc52253780152a38aeb257
https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/definition.rb#L208-L228
train
agardiner/arg-parser
lib/arg-parser/definition.rb
ArgParser.Definition.show_usage
def show_usage(out = STDERR, width = 80) lines = [''] pos_args = positional_args opt_args = size - pos_args.size usage_args = pos_args.map(&:to_use) usage_args << (requires_some? ? 'OPTIONS' : '[OPTIONS]') if opt_args > 0 usage_args << rest_args.to_use if rest_args? lines.concat(wrap_text("USAGE: #{RUBY_ENGINE} #{$0} #{usage_args.join(' ')}", width)) lines << '' lines << 'Specify the /? or --help option for more detailed help' lines << '' lines.each{ |line| out.puts line } if out lines end
ruby
def show_usage(out = STDERR, width = 80) lines = [''] pos_args = positional_args opt_args = size - pos_args.size usage_args = pos_args.map(&:to_use) usage_args << (requires_some? ? 'OPTIONS' : '[OPTIONS]') if opt_args > 0 usage_args << rest_args.to_use if rest_args? lines.concat(wrap_text("USAGE: #{RUBY_ENGINE} #{$0} #{usage_args.join(' ')}", width)) lines << '' lines << 'Specify the /? or --help option for more detailed help' lines << '' lines.each{ |line| out.puts line } if out lines end
[ "def", "show_usage", "(", "out", "=", "STDERR", ",", "width", "=", "80", ")", "lines", "=", "[", "''", "]", "pos_args", "=", "positional_args", "opt_args", "=", "size", "-", "pos_args", ".", "size", "usage_args", "=", "pos_args", ".", "map", "(", "&", ":to_use", ")", "usage_args", "<<", "(", "requires_some?", "?", "'OPTIONS'", ":", "'[OPTIONS]'", ")", "if", "opt_args", ">", "0", "usage_args", "<<", "rest_args", ".", "to_use", "if", "rest_args?", "lines", ".", "concat", "(", "wrap_text", "(", "\"USAGE: #{RUBY_ENGINE} #{$0} #{usage_args.join(' ')}\"", ",", "width", ")", ")", "lines", "<<", "''", "lines", "<<", "'Specify the /? or --help option for more detailed help'", "lines", "<<", "''", "lines", ".", "each", "{", "|", "line", "|", "out", ".", "puts", "line", "}", "if", "out", "lines", "end" ]
Generates a usage display string
[ "Generates", "a", "usage", "display", "string" ]
43c04fb7af45ef4f00bc52253780152a38aeb257
https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/definition.rb#L325-L338
train
agardiner/arg-parser
lib/arg-parser/definition.rb
ArgParser.Definition.show_help
def show_help(out = STDOUT, width = 80) lines = ['', ''] lines << title lines << title.gsub(/./, '=') lines << '' if purpose lines.concat(wrap_text(purpose, width)) lines << '' end if copyright lines.concat(wrap_text("Copyright (c) #{copyright}", width)) lines << '' end lines << 'USAGE' lines << '-----' pos_args = positional_args opt_args = size - pos_args.size usage_args = pos_args.map(&:to_use) usage_args << (requires_some? ? 'OPTIONS' : '[OPTIONS]') if opt_args > 0 usage_args << rest_args.to_use if rest_args? lines.concat(wrap_text(" #{RUBY_ENGINE} #{$0} #{usage_args.join(' ')}", width)) lines << '' if positional_args? max = positional_args.map{ |a| a.to_s.length }.max pos_args = positional_args pos_args << rest_args if rest_args? pos_args.each do |arg| if arg.usage_break lines << '' lines << arg.usage_break end desc = arg.description desc << "\n[Default: #{arg.default}]" unless arg.default.nil? wrap_text(desc, width - max - 6).each_with_index do |line, i| lines << " %-#{max}s %s" % [[arg.to_s][i], line] end end lines << '' end if non_positional_args? lines << '' lines << 'OPTIONS' lines << '-------' max = non_positional_args.map{ |a| a.to_use.length }.max non_positional_args.each do |arg| if arg.usage_break lines << '' lines << arg.usage_break end desc = arg.description desc << "\n[Default: #{arg.default}]" unless arg.default.nil? wrap_text(desc, width - max - 6).each_with_index do |line, i| lines << " %-#{max}s %s" % [[arg.to_use][i], line] end end end lines << '' lines.each{ |line| line.length < width ? out.puts(line) : out.print(line) } if out lines end
ruby
def show_help(out = STDOUT, width = 80) lines = ['', ''] lines << title lines << title.gsub(/./, '=') lines << '' if purpose lines.concat(wrap_text(purpose, width)) lines << '' end if copyright lines.concat(wrap_text("Copyright (c) #{copyright}", width)) lines << '' end lines << 'USAGE' lines << '-----' pos_args = positional_args opt_args = size - pos_args.size usage_args = pos_args.map(&:to_use) usage_args << (requires_some? ? 'OPTIONS' : '[OPTIONS]') if opt_args > 0 usage_args << rest_args.to_use if rest_args? lines.concat(wrap_text(" #{RUBY_ENGINE} #{$0} #{usage_args.join(' ')}", width)) lines << '' if positional_args? max = positional_args.map{ |a| a.to_s.length }.max pos_args = positional_args pos_args << rest_args if rest_args? pos_args.each do |arg| if arg.usage_break lines << '' lines << arg.usage_break end desc = arg.description desc << "\n[Default: #{arg.default}]" unless arg.default.nil? wrap_text(desc, width - max - 6).each_with_index do |line, i| lines << " %-#{max}s %s" % [[arg.to_s][i], line] end end lines << '' end if non_positional_args? lines << '' lines << 'OPTIONS' lines << '-------' max = non_positional_args.map{ |a| a.to_use.length }.max non_positional_args.each do |arg| if arg.usage_break lines << '' lines << arg.usage_break end desc = arg.description desc << "\n[Default: #{arg.default}]" unless arg.default.nil? wrap_text(desc, width - max - 6).each_with_index do |line, i| lines << " %-#{max}s %s" % [[arg.to_use][i], line] end end end lines << '' lines.each{ |line| line.length < width ? out.puts(line) : out.print(line) } if out lines end
[ "def", "show_help", "(", "out", "=", "STDOUT", ",", "width", "=", "80", ")", "lines", "=", "[", "''", ",", "''", "]", "lines", "<<", "title", "lines", "<<", "title", ".", "gsub", "(", "/", "/", ",", "'='", ")", "lines", "<<", "''", "if", "purpose", "lines", ".", "concat", "(", "wrap_text", "(", "purpose", ",", "width", ")", ")", "lines", "<<", "''", "end", "if", "copyright", "lines", ".", "concat", "(", "wrap_text", "(", "\"Copyright (c) #{copyright}\"", ",", "width", ")", ")", "lines", "<<", "''", "end", "lines", "<<", "'USAGE'", "lines", "<<", "'-----'", "pos_args", "=", "positional_args", "opt_args", "=", "size", "-", "pos_args", ".", "size", "usage_args", "=", "pos_args", ".", "map", "(", "&", ":to_use", ")", "usage_args", "<<", "(", "requires_some?", "?", "'OPTIONS'", ":", "'[OPTIONS]'", ")", "if", "opt_args", ">", "0", "usage_args", "<<", "rest_args", ".", "to_use", "if", "rest_args?", "lines", ".", "concat", "(", "wrap_text", "(", "\" #{RUBY_ENGINE} #{$0} #{usage_args.join(' ')}\"", ",", "width", ")", ")", "lines", "<<", "''", "if", "positional_args?", "max", "=", "positional_args", ".", "map", "{", "|", "a", "|", "a", ".", "to_s", ".", "length", "}", ".", "max", "pos_args", "=", "positional_args", "pos_args", "<<", "rest_args", "if", "rest_args?", "pos_args", ".", "each", "do", "|", "arg", "|", "if", "arg", ".", "usage_break", "lines", "<<", "''", "lines", "<<", "arg", ".", "usage_break", "end", "desc", "=", "arg", ".", "description", "desc", "<<", "\"\\n[Default: #{arg.default}]\"", "unless", "arg", ".", "default", ".", "nil?", "wrap_text", "(", "desc", ",", "width", "-", "max", "-", "6", ")", ".", "each_with_index", "do", "|", "line", ",", "i", "|", "lines", "<<", "\" %-#{max}s %s\"", "%", "[", "[", "arg", ".", "to_s", "]", "[", "i", "]", ",", "line", "]", "end", "end", "lines", "<<", "''", "end", "if", "non_positional_args?", "lines", "<<", "''", "lines", "<<", "'OPTIONS'", "lines", "<<", "'-------'", "max", "=", "non_positional_args", ".", "map", "{", "|", "a", "|", "a", ".", "to_use", ".", "length", "}", ".", "max", "non_positional_args", ".", "each", "do", "|", "arg", "|", "if", "arg", ".", "usage_break", "lines", "<<", "''", "lines", "<<", "arg", ".", "usage_break", "end", "desc", "=", "arg", ".", "description", "desc", "<<", "\"\\n[Default: #{arg.default}]\"", "unless", "arg", ".", "default", ".", "nil?", "wrap_text", "(", "desc", ",", "width", "-", "max", "-", "6", ")", ".", "each_with_index", "do", "|", "line", ",", "i", "|", "lines", "<<", "\" %-#{max}s %s\"", "%", "[", "[", "arg", ".", "to_use", "]", "[", "i", "]", ",", "line", "]", "end", "end", "end", "lines", "<<", "''", "lines", ".", "each", "{", "|", "line", "|", "line", ".", "length", "<", "width", "?", "out", ".", "puts", "(", "line", ")", ":", "out", ".", "print", "(", "line", ")", "}", "if", "out", "lines", "end" ]
Generates a more detailed help screen. @param out [IO] an IO object on which the help information will be output. Pass +nil+ if no output to any device is desired. @param width [Integer] the width at which to wrap text. @return [Array] An array of lines of text, containing the help text.
[ "Generates", "a", "more", "detailed", "help", "screen", "." ]
43c04fb7af45ef4f00bc52253780152a38aeb257
https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/definition.rb#L346-L408
train
agardiner/arg-parser
lib/arg-parser/definition.rb
ArgParser.Definition.wrap_text
def wrap_text(text, width) if width > 0 && (text.length > width || text.index("\n")) lines = [] start, nl_pos, ws_pos, wb_pos, end_pos = 0, 0, 0, 0, text.rindex(/[^\s]/) while start < end_pos last_start = start nl_pos = text.index("\n", start) ws_pos = text.rindex(/ +/, start + width) wb_pos = text.rindex(/[\-,.;#)}\]\/\\]/, start + width - 1) ### Debug code ### #STDERR.puts self #ind = ' ' * end_pos #ind[start] = '(' #ind[start+width < end_pos ? start+width : end_pos] = ']' #ind[nl_pos] = 'n' if nl_pos #ind[wb_pos] = 'b' if wb_pos #ind[ws_pos] = 's' if ws_pos #STDERR.puts ind ### End debug code ### if nl_pos && nl_pos <= start + width lines << text[start...nl_pos].strip start = nl_pos + 1 elsif end_pos < start + width lines << text[start..end_pos] start = end_pos elsif ws_pos && ws_pos > start && ((wb_pos.nil? || ws_pos > wb_pos) || (wb_pos && wb_pos > 5 && wb_pos - 5 < ws_pos)) lines << text[start...ws_pos] start = text.index(/[^\s]/, ws_pos + 1) elsif wb_pos && wb_pos > start lines << text[start..wb_pos] start = wb_pos + 1 else lines << text[start...(start+width)] start += width end if start <= last_start # Detect an infinite loop, and just return the original text STDERR.puts "Inifinite loop detected at #{__FILE__}:#{__LINE__}" STDERR.puts " width: #{width}, start: #{start}, nl_pos: #{nl_pos}, " + "ws_pos: #{ws_pos}, wb_pos: #{wb_pos}" return [text] end end lines else [text] end end
ruby
def wrap_text(text, width) if width > 0 && (text.length > width || text.index("\n")) lines = [] start, nl_pos, ws_pos, wb_pos, end_pos = 0, 0, 0, 0, text.rindex(/[^\s]/) while start < end_pos last_start = start nl_pos = text.index("\n", start) ws_pos = text.rindex(/ +/, start + width) wb_pos = text.rindex(/[\-,.;#)}\]\/\\]/, start + width - 1) ### Debug code ### #STDERR.puts self #ind = ' ' * end_pos #ind[start] = '(' #ind[start+width < end_pos ? start+width : end_pos] = ']' #ind[nl_pos] = 'n' if nl_pos #ind[wb_pos] = 'b' if wb_pos #ind[ws_pos] = 's' if ws_pos #STDERR.puts ind ### End debug code ### if nl_pos && nl_pos <= start + width lines << text[start...nl_pos].strip start = nl_pos + 1 elsif end_pos < start + width lines << text[start..end_pos] start = end_pos elsif ws_pos && ws_pos > start && ((wb_pos.nil? || ws_pos > wb_pos) || (wb_pos && wb_pos > 5 && wb_pos - 5 < ws_pos)) lines << text[start...ws_pos] start = text.index(/[^\s]/, ws_pos + 1) elsif wb_pos && wb_pos > start lines << text[start..wb_pos] start = wb_pos + 1 else lines << text[start...(start+width)] start += width end if start <= last_start # Detect an infinite loop, and just return the original text STDERR.puts "Inifinite loop detected at #{__FILE__}:#{__LINE__}" STDERR.puts " width: #{width}, start: #{start}, nl_pos: #{nl_pos}, " + "ws_pos: #{ws_pos}, wb_pos: #{wb_pos}" return [text] end end lines else [text] end end
[ "def", "wrap_text", "(", "text", ",", "width", ")", "if", "width", ">", "0", "&&", "(", "text", ".", "length", ">", "width", "||", "text", ".", "index", "(", "\"\\n\"", ")", ")", "lines", "=", "[", "]", "start", ",", "nl_pos", ",", "ws_pos", ",", "wb_pos", ",", "end_pos", "=", "0", ",", "0", ",", "0", ",", "0", ",", "text", ".", "rindex", "(", "/", "\\s", "/", ")", "while", "start", "<", "end_pos", "last_start", "=", "start", "nl_pos", "=", "text", ".", "index", "(", "\"\\n\"", ",", "start", ")", "ws_pos", "=", "text", ".", "rindex", "(", "/", "/", ",", "start", "+", "width", ")", "wb_pos", "=", "text", ".", "rindex", "(", "/", "\\-", "\\]", "\\/", "\\\\", "/", ",", "start", "+", "width", "-", "1", ")", "if", "nl_pos", "&&", "nl_pos", "<=", "start", "+", "width", "lines", "<<", "text", "[", "start", "...", "nl_pos", "]", ".", "strip", "start", "=", "nl_pos", "+", "1", "elsif", "end_pos", "<", "start", "+", "width", "lines", "<<", "text", "[", "start", "..", "end_pos", "]", "start", "=", "end_pos", "elsif", "ws_pos", "&&", "ws_pos", ">", "start", "&&", "(", "(", "wb_pos", ".", "nil?", "||", "ws_pos", ">", "wb_pos", ")", "||", "(", "wb_pos", "&&", "wb_pos", ">", "5", "&&", "wb_pos", "-", "5", "<", "ws_pos", ")", ")", "lines", "<<", "text", "[", "start", "...", "ws_pos", "]", "start", "=", "text", ".", "index", "(", "/", "\\s", "/", ",", "ws_pos", "+", "1", ")", "elsif", "wb_pos", "&&", "wb_pos", ">", "start", "lines", "<<", "text", "[", "start", "..", "wb_pos", "]", "start", "=", "wb_pos", "+", "1", "else", "lines", "<<", "text", "[", "start", "...", "(", "start", "+", "width", ")", "]", "start", "+=", "width", "end", "if", "start", "<=", "last_start", "STDERR", ".", "puts", "\"Inifinite loop detected at #{__FILE__}:#{__LINE__}\"", "STDERR", ".", "puts", "\" width: #{width}, start: #{start}, nl_pos: #{nl_pos}, \"", "+", "\"ws_pos: #{ws_pos}, wb_pos: #{wb_pos}\"", "return", "[", "text", "]", "end", "end", "lines", "else", "[", "text", "]", "end", "end" ]
Utility method for wrapping lines of +text+ at +width+ characters. @param text [String] a string of text that is to be wrapped to a maximum width. @param width [Integer] the maximum length of each line of text. @return [Array] an Array of lines of text, each no longer than +width+ characters.
[ "Utility", "method", "for", "wrapping", "lines", "of", "+", "text", "+", "at", "+", "width", "+", "characters", "." ]
43c04fb7af45ef4f00bc52253780152a38aeb257
https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/definition.rb#L418-L466
train
agardiner/arg-parser
lib/arg-parser/parser.rb
ArgParser.Parser.parse
def parse(tokens = ARGV) @show_usage = nil @show_help = nil @errors = [] begin pos_vals, kw_vals, rest_vals = classify_tokens(tokens) args = process_args(pos_vals, kw_vals, rest_vals) unless @show_help rescue NoSuchArgumentError => ex self.errors << ex.message @show_usage = true end (@show_usage || @show_help) ? false : args end
ruby
def parse(tokens = ARGV) @show_usage = nil @show_help = nil @errors = [] begin pos_vals, kw_vals, rest_vals = classify_tokens(tokens) args = process_args(pos_vals, kw_vals, rest_vals) unless @show_help rescue NoSuchArgumentError => ex self.errors << ex.message @show_usage = true end (@show_usage || @show_help) ? false : args end
[ "def", "parse", "(", "tokens", "=", "ARGV", ")", "@show_usage", "=", "nil", "@show_help", "=", "nil", "@errors", "=", "[", "]", "begin", "pos_vals", ",", "kw_vals", ",", "rest_vals", "=", "classify_tokens", "(", "tokens", ")", "args", "=", "process_args", "(", "pos_vals", ",", "kw_vals", ",", "rest_vals", ")", "unless", "@show_help", "rescue", "NoSuchArgumentError", "=>", "ex", "self", ".", "errors", "<<", "ex", ".", "message", "@show_usage", "=", "true", "end", "(", "@show_usage", "||", "@show_help", ")", "?", "false", ":", "args", "end" ]
Instantiates a new command-line parser, with the specified command- line definition. A Parser instance delegates unknown methods to the Definition, so its possible to work only with a Parser instance to both define and parse a command-line. @param [Definition] definition A Definition object that defines the possible arguments that may appear in a command-line. If no definition is supplied, an empty definition is created. Parse the specified Array[String] of +tokens+, or ARGV if +tokens+ is nil. Returns false if unable to parse successfully, or an OpenStruct with accessors for every defined argument. Arguments whose values are not specified will contain the agument default value, or nil if no default is specified.
[ "Instantiates", "a", "new", "command", "-", "line", "parser", "with", "the", "specified", "command", "-", "line", "definition", ".", "A", "Parser", "instance", "delegates", "unknown", "methods", "to", "the", "Definition", "so", "its", "possible", "to", "work", "only", "with", "a", "Parser", "instance", "to", "both", "define", "and", "parse", "a", "command", "-", "line", "." ]
43c04fb7af45ef4f00bc52253780152a38aeb257
https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/parser.rb#L48-L60
train
agardiner/arg-parser
lib/arg-parser/parser.rb
ArgParser.Parser.process_arg_val
def process_arg_val(arg, val, hsh, is_default = false) if is_default && arg.required? && (val.nil? || val.empty?) self.errors << "No value was specified for required argument '#{arg}'" return end if !is_default && val.nil? && KeywordArgument === arg if arg.value_optional? val = arg.value_optional else self.errors << "No value was specified for keyword argument '#{arg}'" return end end # Argument value validation if ValueArgument === arg && arg.validation && val case arg.validation when Regexp [val].flatten.each do |v| add_value_error(arg, val) unless v =~ arg.validation end when Array [val].flatten.each do |v| add_value_error(arg, val) unless arg.validation.include?(v) end when Proc begin arg.validation.call(val, arg, hsh) rescue StandardError => ex self.errors << "An error occurred in the validation handler for argument '#{arg}': #{ex}" return end else raise "Unknown validation type: #{arg.validation.class.name}" end end # TODO: Argument value coercion # Call any registered on_parse handler begin val = arg.on_parse.call(val, arg, hsh) if val && arg.on_parse rescue StandardError => ex self.errors << "An error occurred in the on_parse handler for argument '#{arg}': #{ex}" return end # Return result val end
ruby
def process_arg_val(arg, val, hsh, is_default = false) if is_default && arg.required? && (val.nil? || val.empty?) self.errors << "No value was specified for required argument '#{arg}'" return end if !is_default && val.nil? && KeywordArgument === arg if arg.value_optional? val = arg.value_optional else self.errors << "No value was specified for keyword argument '#{arg}'" return end end # Argument value validation if ValueArgument === arg && arg.validation && val case arg.validation when Regexp [val].flatten.each do |v| add_value_error(arg, val) unless v =~ arg.validation end when Array [val].flatten.each do |v| add_value_error(arg, val) unless arg.validation.include?(v) end when Proc begin arg.validation.call(val, arg, hsh) rescue StandardError => ex self.errors << "An error occurred in the validation handler for argument '#{arg}': #{ex}" return end else raise "Unknown validation type: #{arg.validation.class.name}" end end # TODO: Argument value coercion # Call any registered on_parse handler begin val = arg.on_parse.call(val, arg, hsh) if val && arg.on_parse rescue StandardError => ex self.errors << "An error occurred in the on_parse handler for argument '#{arg}': #{ex}" return end # Return result val end
[ "def", "process_arg_val", "(", "arg", ",", "val", ",", "hsh", ",", "is_default", "=", "false", ")", "if", "is_default", "&&", "arg", ".", "required?", "&&", "(", "val", ".", "nil?", "||", "val", ".", "empty?", ")", "self", ".", "errors", "<<", "\"No value was specified for required argument '#{arg}'\"", "return", "end", "if", "!", "is_default", "&&", "val", ".", "nil?", "&&", "KeywordArgument", "===", "arg", "if", "arg", ".", "value_optional?", "val", "=", "arg", ".", "value_optional", "else", "self", ".", "errors", "<<", "\"No value was specified for keyword argument '#{arg}'\"", "return", "end", "end", "if", "ValueArgument", "===", "arg", "&&", "arg", ".", "validation", "&&", "val", "case", "arg", ".", "validation", "when", "Regexp", "[", "val", "]", ".", "flatten", ".", "each", "do", "|", "v", "|", "add_value_error", "(", "arg", ",", "val", ")", "unless", "v", "=~", "arg", ".", "validation", "end", "when", "Array", "[", "val", "]", ".", "flatten", ".", "each", "do", "|", "v", "|", "add_value_error", "(", "arg", ",", "val", ")", "unless", "arg", ".", "validation", ".", "include?", "(", "v", ")", "end", "when", "Proc", "begin", "arg", ".", "validation", ".", "call", "(", "val", ",", "arg", ",", "hsh", ")", "rescue", "StandardError", "=>", "ex", "self", ".", "errors", "<<", "\"An error occurred in the validation handler for argument '#{arg}': #{ex}\"", "return", "end", "else", "raise", "\"Unknown validation type: #{arg.validation.class.name}\"", "end", "end", "begin", "val", "=", "arg", ".", "on_parse", ".", "call", "(", "val", ",", "arg", ",", "hsh", ")", "if", "val", "&&", "arg", ".", "on_parse", "rescue", "StandardError", "=>", "ex", "self", ".", "errors", "<<", "\"An error occurred in the on_parse handler for argument '#{arg}': #{ex}\"", "return", "end", "val", "end" ]
Process a single argument value
[ "Process", "a", "single", "argument", "value" ]
43c04fb7af45ef4f00bc52253780152a38aeb257
https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/parser.rb#L200-L249
train
jamesruston/postcodes_io
lib/postcodes_io/base.rb
Postcodes.Base.method_missing
def method_missing(name, *args, &block) return @info[name.to_s] if @info.key? name.to_s return @info[name] if @info.key? name super.method_missing name end
ruby
def method_missing(name, *args, &block) return @info[name.to_s] if @info.key? name.to_s return @info[name] if @info.key? name super.method_missing name end
[ "def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "return", "@info", "[", "name", ".", "to_s", "]", "if", "@info", ".", "key?", "name", ".", "to_s", "return", "@info", "[", "name", "]", "if", "@info", ".", "key?", "name", "super", ".", "method_missing", "name", "end" ]
allow accessing info values with dot notation
[ "allow", "accessing", "info", "values", "with", "dot", "notation" ]
29283c42ef3b441578177dd4b2606243617e4250
https://github.com/jamesruston/postcodes_io/blob/29283c42ef3b441578177dd4b2606243617e4250/lib/postcodes_io/base.rb#L4-L8
train
kares/jruby-rack-worker
src/main/ruby/resque/jruby_worker.rb
Resque.JRubyWorker.prune_dead_workers
def prune_dead_workers all_workers = self.class.all return if all_workers.empty? known_workers = JRUBY ? worker_thread_ids : [] pids = nil, hostname = self.hostname all_workers.each do |worker| host, pid, thread, queues = self.class.split_id(worker.id) next if host != hostname next if known_workers.include?(thread) && pid == self.pid.to_s # NOTE: allow flexibility of running workers : # 1. worker might run in another JVM instance # 2. worker might run as a process (with MRI) next if (pids ||= system_pids).include?(pid) log! "Pruning dead worker: #{worker}" if worker.respond_to?(:unregister_worker) worker.unregister_worker else # Resque 2.x Registry.for(worker).unregister end end end
ruby
def prune_dead_workers all_workers = self.class.all return if all_workers.empty? known_workers = JRUBY ? worker_thread_ids : [] pids = nil, hostname = self.hostname all_workers.each do |worker| host, pid, thread, queues = self.class.split_id(worker.id) next if host != hostname next if known_workers.include?(thread) && pid == self.pid.to_s # NOTE: allow flexibility of running workers : # 1. worker might run in another JVM instance # 2. worker might run as a process (with MRI) next if (pids ||= system_pids).include?(pid) log! "Pruning dead worker: #{worker}" if worker.respond_to?(:unregister_worker) worker.unregister_worker else # Resque 2.x Registry.for(worker).unregister end end end
[ "def", "prune_dead_workers", "all_workers", "=", "self", ".", "class", ".", "all", "return", "if", "all_workers", ".", "empty?", "known_workers", "=", "JRUBY", "?", "worker_thread_ids", ":", "[", "]", "pids", "=", "nil", ",", "hostname", "=", "self", ".", "hostname", "all_workers", ".", "each", "do", "|", "worker", "|", "host", ",", "pid", ",", "thread", ",", "queues", "=", "self", ".", "class", ".", "split_id", "(", "worker", ".", "id", ")", "next", "if", "host", "!=", "hostname", "next", "if", "known_workers", ".", "include?", "(", "thread", ")", "&&", "pid", "==", "self", ".", "pid", ".", "to_s", "next", "if", "(", "pids", "||=", "system_pids", ")", ".", "include?", "(", "pid", ")", "log!", "\"Pruning dead worker: #{worker}\"", "if", "worker", ".", "respond_to?", "(", ":unregister_worker", ")", "worker", ".", "unregister_worker", "else", "Registry", ".", "for", "(", "worker", ")", ".", "unregister", "end", "end", "end" ]
similar to the original pruning but accounts for thread-based workers @see Resque::Worker#prune_dead_workers
[ "similar", "to", "the", "original", "pruning", "but", "accounts", "for", "thread", "-", "based", "workers" ]
d6bb51b063d8da6e1c5aedf74f62d7c70ea0aa4d
https://github.com/kares/jruby-rack-worker/blob/d6bb51b063d8da6e1c5aedf74f62d7c70ea0aa4d/src/main/ruby/resque/jruby_worker.rb#L188-L208
train
kares/jruby-rack-worker
src/main/ruby/resque/jruby_worker.rb
Resque.JRubyWorker.worker_thread_ids
def worker_thread_ids thread_group = java.lang.Thread.currentThread.getThreadGroup threads = java.lang.reflect.Array.newInstance( java.lang.Thread.java_class, thread_group.activeCount) thread_group.enumerate(threads) # NOTE: we shall check the name from $servlet_context.getServletContextName # but that's an implementation detail of the factory currently that threads # are named including their context name. thread grouping should be fine ! threads.map do |thread| # a convention is to name threads as "worker" : thread && thread.getName.index(WORKER_THREAD_ID) ? thread.getName : nil end.compact end
ruby
def worker_thread_ids thread_group = java.lang.Thread.currentThread.getThreadGroup threads = java.lang.reflect.Array.newInstance( java.lang.Thread.java_class, thread_group.activeCount) thread_group.enumerate(threads) # NOTE: we shall check the name from $servlet_context.getServletContextName # but that's an implementation detail of the factory currently that threads # are named including their context name. thread grouping should be fine ! threads.map do |thread| # a convention is to name threads as "worker" : thread && thread.getName.index(WORKER_THREAD_ID) ? thread.getName : nil end.compact end
[ "def", "worker_thread_ids", "thread_group", "=", "java", ".", "lang", ".", "Thread", ".", "currentThread", ".", "getThreadGroup", "threads", "=", "java", ".", "lang", ".", "reflect", ".", "Array", ".", "newInstance", "(", "java", ".", "lang", ".", "Thread", ".", "java_class", ",", "thread_group", ".", "activeCount", ")", "thread_group", ".", "enumerate", "(", "threads", ")", "threads", ".", "map", "do", "|", "thread", "|", "thread", "&&", "thread", ".", "getName", ".", "index", "(", "WORKER_THREAD_ID", ")", "?", "thread", ".", "getName", ":", "nil", "end", ".", "compact", "end" ]
returns worker thread names that supposely belong to the current application
[ "returns", "worker", "thread", "names", "that", "supposely", "belong", "to", "the", "current", "application" ]
d6bb51b063d8da6e1c5aedf74f62d7c70ea0aa4d
https://github.com/kares/jruby-rack-worker/blob/d6bb51b063d8da6e1c5aedf74f62d7c70ea0aa4d/src/main/ruby/resque/jruby_worker.rb#L215-L226
train
kares/jruby-rack-worker
src/main/ruby/resque/jruby_worker.rb
Resque.JRubyWorker.update_native_thread_name
def update_native_thread_name thread = JRuby.reference(Thread.current) set_thread_name = Proc.new do |prefix, suffix| self.class.with_global_lock do count = self.class.system_registered_workers.size thread.native_thread.name = "#{prefix}##{count}#{suffix}" end end if ! name = thread.native_thread.name # "#{THREAD_ID}##{count}" : set_thread_name.call(WORKER_THREAD_ID, nil) elsif ! name.index(WORKER_THREAD_ID) # "#{name}(#{THREAD_ID}##{count})" : set_thread_name.call("#{name} (#{WORKER_THREAD_ID}", ')') end end
ruby
def update_native_thread_name thread = JRuby.reference(Thread.current) set_thread_name = Proc.new do |prefix, suffix| self.class.with_global_lock do count = self.class.system_registered_workers.size thread.native_thread.name = "#{prefix}##{count}#{suffix}" end end if ! name = thread.native_thread.name # "#{THREAD_ID}##{count}" : set_thread_name.call(WORKER_THREAD_ID, nil) elsif ! name.index(WORKER_THREAD_ID) # "#{name}(#{THREAD_ID}##{count})" : set_thread_name.call("#{name} (#{WORKER_THREAD_ID}", ')') end end
[ "def", "update_native_thread_name", "thread", "=", "JRuby", ".", "reference", "(", "Thread", ".", "current", ")", "set_thread_name", "=", "Proc", ".", "new", "do", "|", "prefix", ",", "suffix", "|", "self", ".", "class", ".", "with_global_lock", "do", "count", "=", "self", ".", "class", ".", "system_registered_workers", ".", "size", "thread", ".", "native_thread", ".", "name", "=", "\"#{prefix}##{count}#{suffix}\"", "end", "end", "if", "!", "name", "=", "thread", ".", "native_thread", ".", "name", "set_thread_name", ".", "call", "(", "WORKER_THREAD_ID", ",", "nil", ")", "elsif", "!", "name", ".", "index", "(", "WORKER_THREAD_ID", ")", "set_thread_name", ".", "call", "(", "\"#{name} (#{WORKER_THREAD_ID}\"", ",", "')'", ")", "end", "end" ]
so that we can later identify a "live" worker thread
[ "so", "that", "we", "can", "later", "identify", "a", "live", "worker", "thread" ]
d6bb51b063d8da6e1c5aedf74f62d7c70ea0aa4d
https://github.com/kares/jruby-rack-worker/blob/d6bb51b063d8da6e1c5aedf74f62d7c70ea0aa4d/src/main/ruby/resque/jruby_worker.rb#L398-L413
train
kares/jruby-rack-worker
src/main/ruby/resque/jruby_worker.rb
Resque.JRubyWorker.system_unregister_worker
def system_unregister_worker # :nodoc self.class.with_global_lock do workers = self.class.system_registered_workers workers.delete(self.id) self.class.store_global_property(WORKERS_KEY, workers.join(',')) end end
ruby
def system_unregister_worker # :nodoc self.class.with_global_lock do workers = self.class.system_registered_workers workers.delete(self.id) self.class.store_global_property(WORKERS_KEY, workers.join(',')) end end
[ "def", "system_unregister_worker", "self", ".", "class", ".", "with_global_lock", "do", "workers", "=", "self", ".", "class", ".", "system_registered_workers", "workers", ".", "delete", "(", "self", ".", "id", ")", "self", ".", "class", ".", "store_global_property", "(", "WORKERS_KEY", ",", "workers", ".", "join", "(", "','", ")", ")", "end", "end" ]
unregister a worked id globally
[ "unregister", "a", "worked", "id", "globally" ]
d6bb51b063d8da6e1c5aedf74f62d7c70ea0aa4d
https://github.com/kares/jruby-rack-worker/blob/d6bb51b063d8da6e1c5aedf74f62d7c70ea0aa4d/src/main/ruby/resque/jruby_worker.rb#L426-L432
train
kikonen/ngannotate-rails
lib/ngannotate/processor_common.rb
Ngannotate.ProcessorCommon.parse_ngannotate_options
def parse_ngannotate_options opt = config.options.clone if ENV['NG_OPT'] opt_str = ENV['NG_OPT'] if opt_str opt = Hash[opt_str.split(',').map { |e| e.split('=') }] opt.symbolize_keys! end end regexp = ENV['NG_REGEXP'] if regexp opt[:regexp] = regexp end opt end
ruby
def parse_ngannotate_options opt = config.options.clone if ENV['NG_OPT'] opt_str = ENV['NG_OPT'] if opt_str opt = Hash[opt_str.split(',').map { |e| e.split('=') }] opt.symbolize_keys! end end regexp = ENV['NG_REGEXP'] if regexp opt[:regexp] = regexp end opt end
[ "def", "parse_ngannotate_options", "opt", "=", "config", ".", "options", ".", "clone", "if", "ENV", "[", "'NG_OPT'", "]", "opt_str", "=", "ENV", "[", "'NG_OPT'", "]", "if", "opt_str", "opt", "=", "Hash", "[", "opt_str", ".", "split", "(", "','", ")", ".", "map", "{", "|", "e", "|", "e", ".", "split", "(", "'='", ")", "}", "]", "opt", ".", "symbolize_keys!", "end", "end", "regexp", "=", "ENV", "[", "'NG_REGEXP'", "]", "if", "regexp", "opt", "[", ":regexp", "]", "=", "regexp", "end", "opt", "end" ]
Parse extra options for ngannotate
[ "Parse", "extra", "options", "for", "ngannotate" ]
5297556590b73be868e7e30fcb866a681067b80d
https://github.com/kikonen/ngannotate-rails/blob/5297556590b73be868e7e30fcb866a681067b80d/lib/ngannotate/processor_common.rb#L94-L111
train
mattray/spiceweasel
lib/spiceweasel/knife.rb
Spiceweasel.Knife.validate
def validate(command, allknifes) return if allknifes.index { |x| x.start_with?("knife #{command}") } STDERR.puts "ERROR: 'knife #{command}' is not a currently supported command for knife." exit(-1) end
ruby
def validate(command, allknifes) return if allknifes.index { |x| x.start_with?("knife #{command}") } STDERR.puts "ERROR: 'knife #{command}' is not a currently supported command for knife." exit(-1) end
[ "def", "validate", "(", "command", ",", "allknifes", ")", "return", "if", "allknifes", ".", "index", "{", "|", "x", "|", "x", ".", "start_with?", "(", "\"knife #{command}\"", ")", "}", "STDERR", ".", "puts", "\"ERROR: 'knife #{command}' is not a currently supported command for knife.\"", "exit", "(", "-", "1", ")", "end" ]
test that the knife command exists
[ "test", "that", "the", "knife", "command", "exists" ]
c7f01a127a542989f8525486890cf12249b6db44
https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/knife.rb#L48-L53
train
arangodb-helper/guacamole
lib/guacamole/document_model_mapper.rb
Guacamole.DocumentModelMapper.document_to_model
def document_to_model(document) identity_map.retrieve_or_store model_class, document.key do model = model_class.new(document.to_h) model.key = document.key model.rev = document.revision handle_related_documents(model) model end end
ruby
def document_to_model(document) identity_map.retrieve_or_store model_class, document.key do model = model_class.new(document.to_h) model.key = document.key model.rev = document.revision handle_related_documents(model) model end end
[ "def", "document_to_model", "(", "document", ")", "identity_map", ".", "retrieve_or_store", "model_class", ",", "document", ".", "key", "do", "model", "=", "model_class", ".", "new", "(", "document", ".", "to_h", ")", "model", ".", "key", "=", "document", ".", "key", "model", ".", "rev", "=", "document", ".", "revision", "handle_related_documents", "(", "model", ")", "model", "end", "end" ]
Map a document to a model Sets the revision, key and all attributes on the model @param [Ashikawa::Core::Document] document @return [Model] the resulting model with the given Model class
[ "Map", "a", "document", "to", "a", "model" ]
90505fc0276ea529073c0e8d1087f51f193840b6
https://github.com/arangodb-helper/guacamole/blob/90505fc0276ea529073c0e8d1087f51f193840b6/lib/guacamole/document_model_mapper.rb#L152-L163
train
arangodb-helper/guacamole
lib/guacamole/document_model_mapper.rb
Guacamole.DocumentModelMapper.model_to_document
def model_to_document(model) document = model.attributes.dup.except(:key, :rev) handle_embedded_models(model, document) handle_related_models(document) document end
ruby
def model_to_document(model) document = model.attributes.dup.except(:key, :rev) handle_embedded_models(model, document) handle_related_models(document) document end
[ "def", "model_to_document", "(", "model", ")", "document", "=", "model", ".", "attributes", ".", "dup", ".", "except", "(", ":key", ",", ":rev", ")", "handle_embedded_models", "(", "model", ",", "document", ")", "handle_related_models", "(", "document", ")", "document", "end" ]
Map a model to a document This will include all embedded models @param [Model] model @return [Ashikawa::Core::Document] the resulting document
[ "Map", "a", "model", "to", "a", "document" ]
90505fc0276ea529073c0e8d1087f51f193840b6
https://github.com/arangodb-helper/guacamole/blob/90505fc0276ea529073c0e8d1087f51f193840b6/lib/guacamole/document_model_mapper.rb#L171-L178
train
pgharts/trusty-cms
lib/trusty_cms/initializer.rb
TrustyCms.Initializer.initialize_metal
def initialize_metal Rails::Rack::Metal.requested_metals = configuration.metals Rails::Rack::Metal.metal_paths = ["#{TRUSTY_CMS_ROOT}/app/metal"] # reset Rails default to TRUSTY_CMS_ROOT Rails::Rack::Metal.metal_paths += plugin_loader.engine_metal_paths Rails::Rack::Metal.metal_paths += extension_loader.paths(:metal) Rails::Rack::Metal.metal_paths.uniq! configuration.middleware.insert_before( :"ActionController::ParamsParser", Rails::Rack::Metal, :if => Rails::Rack::Metal.metals.any?) end
ruby
def initialize_metal Rails::Rack::Metal.requested_metals = configuration.metals Rails::Rack::Metal.metal_paths = ["#{TRUSTY_CMS_ROOT}/app/metal"] # reset Rails default to TRUSTY_CMS_ROOT Rails::Rack::Metal.metal_paths += plugin_loader.engine_metal_paths Rails::Rack::Metal.metal_paths += extension_loader.paths(:metal) Rails::Rack::Metal.metal_paths.uniq! configuration.middleware.insert_before( :"ActionController::ParamsParser", Rails::Rack::Metal, :if => Rails::Rack::Metal.metals.any?) end
[ "def", "initialize_metal", "Rails", "::", "Rack", "::", "Metal", ".", "requested_metals", "=", "configuration", ".", "metals", "Rails", "::", "Rack", "::", "Metal", ".", "metal_paths", "=", "[", "\"#{TRUSTY_CMS_ROOT}/app/metal\"", "]", "Rails", "::", "Rack", "::", "Metal", ".", "metal_paths", "+=", "plugin_loader", ".", "engine_metal_paths", "Rails", "::", "Rack", "::", "Metal", ".", "metal_paths", "+=", "extension_loader", ".", "paths", "(", ":metal", ")", "Rails", "::", "Rack", "::", "Metal", ".", "metal_paths", ".", "uniq!", "configuration", ".", "middleware", ".", "insert_before", "(", ":\"", "\"", ",", "Rails", "::", "Rack", "::", "Metal", ",", ":if", "=>", "Rails", "::", "Rack", "::", "Metal", ".", "metals", ".", "any?", ")", "end" ]
Overrides the Rails initializer to load metal from TRUSTY_CMS_ROOT and from radiant extensions.
[ "Overrides", "the", "Rails", "initializer", "to", "load", "metal", "from", "TRUSTY_CMS_ROOT", "and", "from", "radiant", "extensions", "." ]
444ad7010c28a8aa5194cc13dd4a376a6bddd1fd
https://github.com/pgharts/trusty-cms/blob/444ad7010c28a8aa5194cc13dd4a376a6bddd1fd/lib/trusty_cms/initializer.rb#L48-L58
train
pgharts/trusty-cms
lib/trusty_cms/initializer.rb
TrustyCms.Initializer.initialize_i18n
def initialize_i18n radiant_locale_paths = Dir[File.join(TRUSTY_CMS_ROOT, 'config', 'locales', '*.{rb,yml}')] configuration.i18n.load_path = radiant_locale_paths + extension_loader.paths(:locale) super end
ruby
def initialize_i18n radiant_locale_paths = Dir[File.join(TRUSTY_CMS_ROOT, 'config', 'locales', '*.{rb,yml}')] configuration.i18n.load_path = radiant_locale_paths + extension_loader.paths(:locale) super end
[ "def", "initialize_i18n", "radiant_locale_paths", "=", "Dir", "[", "File", ".", "join", "(", "TRUSTY_CMS_ROOT", ",", "'config'", ",", "'locales'", ",", "'*.{rb,yml}'", ")", "]", "configuration", ".", "i18n", ".", "load_path", "=", "radiant_locale_paths", "+", "extension_loader", ".", "paths", "(", ":locale", ")", "super", "end" ]
Extends the Rails initializer to add locale paths from TRUSTY_CMS_ROOT and from radiant extensions.
[ "Extends", "the", "Rails", "initializer", "to", "add", "locale", "paths", "from", "TRUSTY_CMS_ROOT", "and", "from", "radiant", "extensions", "." ]
444ad7010c28a8aa5194cc13dd4a376a6bddd1fd
https://github.com/pgharts/trusty-cms/blob/444ad7010c28a8aa5194cc13dd4a376a6bddd1fd/lib/trusty_cms/initializer.rb#L62-L66
train
mattray/spiceweasel
lib/spiceweasel/nodes.rb
Spiceweasel.Nodes.validate_run_list
def validate_run_list(node, run_list, cookbooks, roles) run_list.split(",").each do |item| if item.start_with?("recipe[") # recipe[foo] or recipe[foo::bar] cb = item.split(/\[|\]/)[1].split(":")[0] unless cookbooks.member?(cb) STDERR.puts "ERROR: '#{node}' run list cookbook '#{cb}' is missing from the list of cookbooks in the manifest." exit(-1) end elsif item.start_with?("role[") # role[blah] role = item.split(/\[|\]/)[1] unless roles.member?(role) STDERR.puts "ERROR: '#{node}' run list role '#{role}' is missing from the list of roles in the manifest." exit(-1) end else STDERR.puts "ERROR: '#{node}' run list '#{item}' is an invalid run list entry in the manifest." exit(-1) end end end
ruby
def validate_run_list(node, run_list, cookbooks, roles) run_list.split(",").each do |item| if item.start_with?("recipe[") # recipe[foo] or recipe[foo::bar] cb = item.split(/\[|\]/)[1].split(":")[0] unless cookbooks.member?(cb) STDERR.puts "ERROR: '#{node}' run list cookbook '#{cb}' is missing from the list of cookbooks in the manifest." exit(-1) end elsif item.start_with?("role[") # role[blah] role = item.split(/\[|\]/)[1] unless roles.member?(role) STDERR.puts "ERROR: '#{node}' run list role '#{role}' is missing from the list of roles in the manifest." exit(-1) end else STDERR.puts "ERROR: '#{node}' run list '#{item}' is an invalid run list entry in the manifest." exit(-1) end end end
[ "def", "validate_run_list", "(", "node", ",", "run_list", ",", "cookbooks", ",", "roles", ")", "run_list", ".", "split", "(", "\",\"", ")", ".", "each", "do", "|", "item", "|", "if", "item", ".", "start_with?", "(", "\"recipe[\"", ")", "cb", "=", "item", ".", "split", "(", "/", "\\[", "\\]", "/", ")", "[", "1", "]", ".", "split", "(", "\":\"", ")", "[", "0", "]", "unless", "cookbooks", ".", "member?", "(", "cb", ")", "STDERR", ".", "puts", "\"ERROR: '#{node}' run list cookbook '#{cb}' is missing from the list of cookbooks in the manifest.\"", "exit", "(", "-", "1", ")", "end", "elsif", "item", ".", "start_with?", "(", "\"role[\"", ")", "role", "=", "item", ".", "split", "(", "/", "\\[", "\\]", "/", ")", "[", "1", "]", "unless", "roles", ".", "member?", "(", "role", ")", "STDERR", ".", "puts", "\"ERROR: '#{node}' run list role '#{role}' is missing from the list of roles in the manifest.\"", "exit", "(", "-", "1", ")", "end", "else", "STDERR", ".", "puts", "\"ERROR: '#{node}' run list '#{item}' is an invalid run list entry in the manifest.\"", "exit", "(", "-", "1", ")", "end", "end", "end" ]
ensure run_list contents are listed previously.
[ "ensure", "run_list", "contents", "are", "listed", "previously", "." ]
c7f01a127a542989f8525486890cf12249b6db44
https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/nodes.rb#L102-L123
train
mattray/spiceweasel
lib/spiceweasel/nodes.rb
Spiceweasel.Nodes.validate_options
def validate_options(node, options, environments) if options =~ /-E/ # check for environments env = options.split("-E")[1].split[0] unless environments.member?(env) STDERR.puts "ERROR: '#{node}' environment '#{env}' is missing from the list of environments in the manifest." exit(-1) end end end
ruby
def validate_options(node, options, environments) if options =~ /-E/ # check for environments env = options.split("-E")[1].split[0] unless environments.member?(env) STDERR.puts "ERROR: '#{node}' environment '#{env}' is missing from the list of environments in the manifest." exit(-1) end end end
[ "def", "validate_options", "(", "node", ",", "options", ",", "environments", ")", "if", "options", "=~", "/", "/", "env", "=", "options", ".", "split", "(", "\"-E\"", ")", "[", "1", "]", ".", "split", "[", "0", "]", "unless", "environments", ".", "member?", "(", "env", ")", "STDERR", ".", "puts", "\"ERROR: '#{node}' environment '#{env}' is missing from the list of environments in the manifest.\"", "exit", "(", "-", "1", ")", "end", "end", "end" ]
for now, just check that -E is legit
[ "for", "now", "just", "check", "that", "-", "E", "is", "legit" ]
c7f01a127a542989f8525486890cf12249b6db44
https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/nodes.rb#L126-L134
train
mattray/spiceweasel
lib/spiceweasel/nodes.rb
Spiceweasel.Nodes.validate_node_file
def validate_node_file(name) # read in the file node = Chef::JSONCompat.from_json(IO.read("nodes/#{name}.json")) # check the node name vs. contents of the file return unless node["name"] != name STDERR.puts "ERROR: Node '#{name}' listed in the manifest does not match the name '#{node['name']}' within the nodes/#{name}.json file." exit(-1) end
ruby
def validate_node_file(name) # read in the file node = Chef::JSONCompat.from_json(IO.read("nodes/#{name}.json")) # check the node name vs. contents of the file return unless node["name"] != name STDERR.puts "ERROR: Node '#{name}' listed in the manifest does not match the name '#{node['name']}' within the nodes/#{name}.json file." exit(-1) end
[ "def", "validate_node_file", "(", "name", ")", "node", "=", "Chef", "::", "JSONCompat", ".", "from_json", "(", "IO", ".", "read", "(", "\"nodes/#{name}.json\"", ")", ")", "return", "unless", "node", "[", "\"name\"", "]", "!=", "name", "STDERR", ".", "puts", "\"ERROR: Node '#{name}' listed in the manifest does not match the name '#{node['name']}' within the nodes/#{name}.json file.\"", "exit", "(", "-", "1", ")", "end" ]
validate individual node files
[ "validate", "individual", "node", "files" ]
c7f01a127a542989f8525486890cf12249b6db44
https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/nodes.rb#L184-L193
train
mattray/spiceweasel
lib/spiceweasel/nodes.rb
Spiceweasel.Nodes.process_providers
def process_providers(names, count, name, options, run_list, create_command_options, knifecommands) # rubocop:disable CyclomaticComplexity provider = names[0] validate_provider(provider, names, count, options, knifecommands) unless Spiceweasel::Config[:novalidation] provided_names = [] if name.nil? && options.split.index("-N") # pull this out for deletes name = options.split[options.split.index("-N") + 1] count.to_i.times { |i| provided_names << node_numerate(name, i + 1, count) } if name end # google can have names or numbers if provider.eql?("google") && names[1].to_i == 0 do_google_numeric_provider(create_command_options, names, options, provided_names, run_list) elsif Spiceweasel::Config[:parallel] process_parallel(count, create_command_options, name, options, provider, run_list) else determine_cloud_provider(count, create_command_options, name, options, provider, run_list) end if Spiceweasel::Config[:bulkdelete] && provided_names.empty? do_bulk_delete(provider) else provided_names.each do |p_name| do_provided_names(p_name, provider) end end end
ruby
def process_providers(names, count, name, options, run_list, create_command_options, knifecommands) # rubocop:disable CyclomaticComplexity provider = names[0] validate_provider(provider, names, count, options, knifecommands) unless Spiceweasel::Config[:novalidation] provided_names = [] if name.nil? && options.split.index("-N") # pull this out for deletes name = options.split[options.split.index("-N") + 1] count.to_i.times { |i| provided_names << node_numerate(name, i + 1, count) } if name end # google can have names or numbers if provider.eql?("google") && names[1].to_i == 0 do_google_numeric_provider(create_command_options, names, options, provided_names, run_list) elsif Spiceweasel::Config[:parallel] process_parallel(count, create_command_options, name, options, provider, run_list) else determine_cloud_provider(count, create_command_options, name, options, provider, run_list) end if Spiceweasel::Config[:bulkdelete] && provided_names.empty? do_bulk_delete(provider) else provided_names.each do |p_name| do_provided_names(p_name, provider) end end end
[ "def", "process_providers", "(", "names", ",", "count", ",", "name", ",", "options", ",", "run_list", ",", "create_command_options", ",", "knifecommands", ")", "provider", "=", "names", "[", "0", "]", "validate_provider", "(", "provider", ",", "names", ",", "count", ",", "options", ",", "knifecommands", ")", "unless", "Spiceweasel", "::", "Config", "[", ":novalidation", "]", "provided_names", "=", "[", "]", "if", "name", ".", "nil?", "&&", "options", ".", "split", ".", "index", "(", "\"-N\"", ")", "name", "=", "options", ".", "split", "[", "options", ".", "split", ".", "index", "(", "\"-N\"", ")", "+", "1", "]", "count", ".", "to_i", ".", "times", "{", "|", "i", "|", "provided_names", "<<", "node_numerate", "(", "name", ",", "i", "+", "1", ",", "count", ")", "}", "if", "name", "end", "if", "provider", ".", "eql?", "(", "\"google\"", ")", "&&", "names", "[", "1", "]", ".", "to_i", "==", "0", "do_google_numeric_provider", "(", "create_command_options", ",", "names", ",", "options", ",", "provided_names", ",", "run_list", ")", "elsif", "Spiceweasel", "::", "Config", "[", ":parallel", "]", "process_parallel", "(", "count", ",", "create_command_options", ",", "name", ",", "options", ",", "provider", ",", "run_list", ")", "else", "determine_cloud_provider", "(", "count", ",", "create_command_options", ",", "name", ",", "options", ",", "provider", ",", "run_list", ")", "end", "if", "Spiceweasel", "::", "Config", "[", ":bulkdelete", "]", "&&", "provided_names", ".", "empty?", "do_bulk_delete", "(", "provider", ")", "else", "provided_names", ".", "each", "do", "|", "p_name", "|", "do_provided_names", "(", "p_name", ",", "provider", ")", "end", "end", "end" ]
manage all the provider logic
[ "manage", "all", "the", "provider", "logic" ]
c7f01a127a542989f8525486890cf12249b6db44
https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/nodes.rb#L196-L220
train
mattray/spiceweasel
lib/spiceweasel/nodes.rb
Spiceweasel.Nodes.validate_provider
def validate_provider(provider, names, _count, options, knifecommands) unless knifecommands.index { |x| x.start_with?("knife #{provider}") } STDERR.puts "ERROR: 'knife #{provider}' is not a currently installed plugin for knife." exit(-1) end return unless provider.eql?("google") return unless names[1].to_i != 0 && !options.split.member?("-N") STDERR.puts "ERROR: 'knife google' currently requires providing a name. Please use -N within the options." exit(-1) end
ruby
def validate_provider(provider, names, _count, options, knifecommands) unless knifecommands.index { |x| x.start_with?("knife #{provider}") } STDERR.puts "ERROR: 'knife #{provider}' is not a currently installed plugin for knife." exit(-1) end return unless provider.eql?("google") return unless names[1].to_i != 0 && !options.split.member?("-N") STDERR.puts "ERROR: 'knife google' currently requires providing a name. Please use -N within the options." exit(-1) end
[ "def", "validate_provider", "(", "provider", ",", "names", ",", "_count", ",", "options", ",", "knifecommands", ")", "unless", "knifecommands", ".", "index", "{", "|", "x", "|", "x", ".", "start_with?", "(", "\"knife #{provider}\"", ")", "}", "STDERR", ".", "puts", "\"ERROR: 'knife #{provider}' is not a currently installed plugin for knife.\"", "exit", "(", "-", "1", ")", "end", "return", "unless", "provider", ".", "eql?", "(", "\"google\"", ")", "return", "unless", "names", "[", "1", "]", ".", "to_i", "!=", "0", "&&", "!", "options", ".", "split", ".", "member?", "(", "\"-N\"", ")", "STDERR", ".", "puts", "\"ERROR: 'knife google' currently requires providing a name. Please use -N within the options.\"", "exit", "(", "-", "1", ")", "end" ]
check that the knife plugin is installed
[ "check", "that", "the", "knife", "plugin", "is", "installed" ]
c7f01a127a542989f8525486890cf12249b6db44
https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/nodes.rb#L321-L333
train
mattray/spiceweasel
lib/spiceweasel/nodes.rb
Spiceweasel.Nodes.chef_client_search
def chef_client_search(name, run_list, environment) search = [] search.push("name:#{name}") if name search.push("chef_environment:#{environment}") if environment run_list.split(",").each do |item| item.sub!(/\[/, ":") item.chop! item.sub!(/::/, '\:\:') search.push(item) end "#{search.join(' AND ')}" end
ruby
def chef_client_search(name, run_list, environment) search = [] search.push("name:#{name}") if name search.push("chef_environment:#{environment}") if environment run_list.split(",").each do |item| item.sub!(/\[/, ":") item.chop! item.sub!(/::/, '\:\:') search.push(item) end "#{search.join(' AND ')}" end
[ "def", "chef_client_search", "(", "name", ",", "run_list", ",", "environment", ")", "search", "=", "[", "]", "search", ".", "push", "(", "\"name:#{name}\"", ")", "if", "name", "search", ".", "push", "(", "\"chef_environment:#{environment}\"", ")", "if", "environment", "run_list", ".", "split", "(", "\",\"", ")", ".", "each", "do", "|", "item", "|", "item", ".", "sub!", "(", "/", "\\[", "/", ",", "\":\"", ")", "item", ".", "chop!", "item", ".", "sub!", "(", "/", "/", ",", "'\\:\\:'", ")", "search", ".", "push", "(", "item", ")", "end", "\"#{search.join(' AND ')}\"", "end" ]
create the knife ssh chef-client search pattern
[ "create", "the", "knife", "ssh", "chef", "-", "client", "search", "pattern" ]
c7f01a127a542989f8525486890cf12249b6db44
https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/nodes.rb#L474-L485
train
mattray/spiceweasel
lib/spiceweasel/cookbooks.rb
Spiceweasel.Cookbooks.validate_metadata
def validate_metadata(cookbook, version) # check metadata.rb for requested version metadata = @loader.cookbooks_by_name[cookbook].metadata Spiceweasel::Log.debug("validate_metadata: #{cookbook} #{metadata.name} #{metadata.version}") # Should the cookbook directory match the name in the metadata? if metadata.name.empty? Spiceweasel::Log.warn("No cookbook name in the #{cookbook} metadata.rb.") elsif cookbook != metadata.name STDERR.puts "ERROR: Cookbook '#{cookbook}' does not match the name '#{metadata.name}' in #{cookbook}/metadata.rb." exit(-1) end if version && metadata.version != version STDERR.puts "ERROR: Invalid version '#{version}' of '#{cookbook}' requested, '#{metadata.version}' is already in the cookbooks directory." exit(-1) end metadata.dependencies.each do |dependency| Spiceweasel::Log.debug("cookbook #{cookbook} metadata dependency: #{dependency}") @dependencies.push(dependency[0]) end end
ruby
def validate_metadata(cookbook, version) # check metadata.rb for requested version metadata = @loader.cookbooks_by_name[cookbook].metadata Spiceweasel::Log.debug("validate_metadata: #{cookbook} #{metadata.name} #{metadata.version}") # Should the cookbook directory match the name in the metadata? if metadata.name.empty? Spiceweasel::Log.warn("No cookbook name in the #{cookbook} metadata.rb.") elsif cookbook != metadata.name STDERR.puts "ERROR: Cookbook '#{cookbook}' does not match the name '#{metadata.name}' in #{cookbook}/metadata.rb." exit(-1) end if version && metadata.version != version STDERR.puts "ERROR: Invalid version '#{version}' of '#{cookbook}' requested, '#{metadata.version}' is already in the cookbooks directory." exit(-1) end metadata.dependencies.each do |dependency| Spiceweasel::Log.debug("cookbook #{cookbook} metadata dependency: #{dependency}") @dependencies.push(dependency[0]) end end
[ "def", "validate_metadata", "(", "cookbook", ",", "version", ")", "metadata", "=", "@loader", ".", "cookbooks_by_name", "[", "cookbook", "]", ".", "metadata", "Spiceweasel", "::", "Log", ".", "debug", "(", "\"validate_metadata: #{cookbook} #{metadata.name} #{metadata.version}\"", ")", "if", "metadata", ".", "name", ".", "empty?", "Spiceweasel", "::", "Log", ".", "warn", "(", "\"No cookbook name in the #{cookbook} metadata.rb.\"", ")", "elsif", "cookbook", "!=", "metadata", ".", "name", "STDERR", ".", "puts", "\"ERROR: Cookbook '#{cookbook}' does not match the name '#{metadata.name}' in #{cookbook}/metadata.rb.\"", "exit", "(", "-", "1", ")", "end", "if", "version", "&&", "metadata", ".", "version", "!=", "version", "STDERR", ".", "puts", "\"ERROR: Invalid version '#{version}' of '#{cookbook}' requested, '#{metadata.version}' is already in the cookbooks directory.\"", "exit", "(", "-", "1", ")", "end", "metadata", ".", "dependencies", ".", "each", "do", "|", "dependency", "|", "Spiceweasel", "::", "Log", ".", "debug", "(", "\"cookbook #{cookbook} metadata dependency: #{dependency}\"", ")", "@dependencies", ".", "push", "(", "dependency", "[", "0", "]", ")", "end", "end" ]
check the metadata for versions and gather deps
[ "check", "the", "metadata", "for", "versions", "and", "gather", "deps" ]
c7f01a127a542989f8525486890cf12249b6db44
https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/cookbooks.rb#L105-L124
train
mattray/spiceweasel
lib/spiceweasel/cookbooks.rb
Spiceweasel.Cookbooks.validate_dependencies
def validate_dependencies Spiceweasel::Log.debug("cookbook validate_dependencies: '#{@dependencies}'") @dependencies.each do |dep| unless member?(dep) STDERR.puts "ERROR: Cookbook dependency '#{dep}' is missing from the list of cookbooks in the manifest." exit(-1) end end end
ruby
def validate_dependencies Spiceweasel::Log.debug("cookbook validate_dependencies: '#{@dependencies}'") @dependencies.each do |dep| unless member?(dep) STDERR.puts "ERROR: Cookbook dependency '#{dep}' is missing from the list of cookbooks in the manifest." exit(-1) end end end
[ "def", "validate_dependencies", "Spiceweasel", "::", "Log", ".", "debug", "(", "\"cookbook validate_dependencies: '#{@dependencies}'\"", ")", "@dependencies", ".", "each", "do", "|", "dep", "|", "unless", "member?", "(", "dep", ")", "STDERR", ".", "puts", "\"ERROR: Cookbook dependency '#{dep}' is missing from the list of cookbooks in the manifest.\"", "exit", "(", "-", "1", ")", "end", "end", "end" ]
compare the list of cookbook deps with those specified
[ "compare", "the", "list", "of", "cookbook", "deps", "with", "those", "specified" ]
c7f01a127a542989f8525486890cf12249b6db44
https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/cookbooks.rb#L127-L135
train
DDAZZA/renogen
lib/renogen/generator.rb
Renogen.Generator.generate!
def generate! changelog = extraction_stratagy.extract changelog.version = version changelog.date = options['release_date'] writer.write!(changelog) end
ruby
def generate! changelog = extraction_stratagy.extract changelog.version = version changelog.date = options['release_date'] writer.write!(changelog) end
[ "def", "generate!", "changelog", "=", "extraction_stratagy", ".", "extract", "changelog", ".", "version", "=", "version", "changelog", ".", "date", "=", "options", "[", "'release_date'", "]", "writer", ".", "write!", "(", "changelog", ")", "end" ]
Create the change log
[ "Create", "the", "change", "log" ]
4c9b3db56b1e56c95f457c1a92e43f411c18a4f7
https://github.com/DDAZZA/renogen/blob/4c9b3db56b1e56c95f457c1a92e43f411c18a4f7/lib/renogen/generator.rb#L14-L20
train
arangodb-helper/guacamole
lib/guacamole/aql_query.rb
Guacamole.AqlQuery.perfom_query
def perfom_query(iterator_with_mapping, &block) iterator = perform_mapping? ? iterator_with_mapping : iterator_without_mapping(&block) connection.execute(aql_string, options).each(&iterator) end
ruby
def perfom_query(iterator_with_mapping, &block) iterator = perform_mapping? ? iterator_with_mapping : iterator_without_mapping(&block) connection.execute(aql_string, options).each(&iterator) end
[ "def", "perfom_query", "(", "iterator_with_mapping", ",", "&", "block", ")", "iterator", "=", "perform_mapping?", "?", "iterator_with_mapping", ":", "iterator_without_mapping", "(", "&", "block", ")", "connection", ".", "execute", "(", "aql_string", ",", "options", ")", ".", "each", "(", "&", "iterator", ")", "end" ]
Executes an AQL query with bind parameters @see Query#perfom_query
[ "Executes", "an", "AQL", "query", "with", "bind", "parameters" ]
90505fc0276ea529073c0e8d1087f51f193840b6
https://github.com/arangodb-helper/guacamole/blob/90505fc0276ea529073c0e8d1087f51f193840b6/lib/guacamole/aql_query.rb#L96-L99
train
mattray/spiceweasel
lib/spiceweasel/clusters.rb
Spiceweasel.Clusters.cluster_process_nodes
def cluster_process_nodes(cluster, environment, cookbooks, environments, roles, knifecommands, rootoptions) Spiceweasel::Log.debug("cluster::cluster_process_nodes '#{environment}' '#{cluster[environment]}'") cluster[environment].each do |node| node_name = node.keys.first options = node[node_name]["options"] || "" validate_environment(options, environment, environments) unless Spiceweasel::Config[:novalidation] # push the Environment back on the options node[node_name]["options"] = options + " -E #{environment}" end # let's reuse the Nodes logic nodes = Spiceweasel::Nodes.new(cluster[environment], cookbooks, environments, roles, knifecommands, rootoptions) @create.concat(nodes.create) # what about providers?? nodes.delete.each do |del| @delete.push(del) unless del.to_s =~ /^knife client|^knife node/ end if bundler? @delete.push(Command.new("for N in $(bundle exec knife node list -E #{environment}); do bundle exec knife client delete $N -y; bundle exec knife node delete $N -y; done")) else @delete.push(Command.new("for N in $(knife node list -E #{environment}); do knife client delete $N -y; knife node delete $N -y; done")) end end
ruby
def cluster_process_nodes(cluster, environment, cookbooks, environments, roles, knifecommands, rootoptions) Spiceweasel::Log.debug("cluster::cluster_process_nodes '#{environment}' '#{cluster[environment]}'") cluster[environment].each do |node| node_name = node.keys.first options = node[node_name]["options"] || "" validate_environment(options, environment, environments) unless Spiceweasel::Config[:novalidation] # push the Environment back on the options node[node_name]["options"] = options + " -E #{environment}" end # let's reuse the Nodes logic nodes = Spiceweasel::Nodes.new(cluster[environment], cookbooks, environments, roles, knifecommands, rootoptions) @create.concat(nodes.create) # what about providers?? nodes.delete.each do |del| @delete.push(del) unless del.to_s =~ /^knife client|^knife node/ end if bundler? @delete.push(Command.new("for N in $(bundle exec knife node list -E #{environment}); do bundle exec knife client delete $N -y; bundle exec knife node delete $N -y; done")) else @delete.push(Command.new("for N in $(knife node list -E #{environment}); do knife client delete $N -y; knife node delete $N -y; done")) end end
[ "def", "cluster_process_nodes", "(", "cluster", ",", "environment", ",", "cookbooks", ",", "environments", ",", "roles", ",", "knifecommands", ",", "rootoptions", ")", "Spiceweasel", "::", "Log", ".", "debug", "(", "\"cluster::cluster_process_nodes '#{environment}' '#{cluster[environment]}'\"", ")", "cluster", "[", "environment", "]", ".", "each", "do", "|", "node", "|", "node_name", "=", "node", ".", "keys", ".", "first", "options", "=", "node", "[", "node_name", "]", "[", "\"options\"", "]", "||", "\"\"", "validate_environment", "(", "options", ",", "environment", ",", "environments", ")", "unless", "Spiceweasel", "::", "Config", "[", ":novalidation", "]", "node", "[", "node_name", "]", "[", "\"options\"", "]", "=", "options", "+", "\" -E #{environment}\"", "end", "nodes", "=", "Spiceweasel", "::", "Nodes", ".", "new", "(", "cluster", "[", "environment", "]", ",", "cookbooks", ",", "environments", ",", "roles", ",", "knifecommands", ",", "rootoptions", ")", "@create", ".", "concat", "(", "nodes", ".", "create", ")", "nodes", ".", "delete", ".", "each", "do", "|", "del", "|", "@delete", ".", "push", "(", "del", ")", "unless", "del", ".", "to_s", "=~", "/", "/", "end", "if", "bundler?", "@delete", ".", "push", "(", "Command", ".", "new", "(", "\"for N in $(bundle exec knife node list -E #{environment}); do bundle exec knife client delete $N -y; bundle exec knife node delete $N -y; done\"", ")", ")", "else", "@delete", ".", "push", "(", "Command", ".", "new", "(", "\"for N in $(knife node list -E #{environment}); do knife client delete $N -y; knife node delete $N -y; done\"", ")", ")", "end", "end" ]
configure the individual nodes within the cluster
[ "configure", "the", "individual", "nodes", "within", "the", "cluster" ]
c7f01a127a542989f8525486890cf12249b6db44
https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/clusters.rb#L37-L58
train
pgharts/trusty-cms
lib/trusty_cms/extension_loader.rb
TrustyCms.ExtensionLoader.activate_extensions
def activate_extensions initializer.initialize_views ordered_extensions = [] configuration = TrustyCms::Application.config if configuration.extensions.first == :all ordered_extensions = extensions else configuration.extensions.each {|name| ordered_extensions << select_extension(name) } end ordered_extensions.flatten.each(&:activate) Page.load_subclasses end
ruby
def activate_extensions initializer.initialize_views ordered_extensions = [] configuration = TrustyCms::Application.config if configuration.extensions.first == :all ordered_extensions = extensions else configuration.extensions.each {|name| ordered_extensions << select_extension(name) } end ordered_extensions.flatten.each(&:activate) Page.load_subclasses end
[ "def", "activate_extensions", "initializer", ".", "initialize_views", "ordered_extensions", "=", "[", "]", "configuration", "=", "TrustyCms", "::", "Application", ".", "config", "if", "configuration", ".", "extensions", ".", "first", "==", ":all", "ordered_extensions", "=", "extensions", "else", "configuration", ".", "extensions", ".", "each", "{", "|", "name", "|", "ordered_extensions", "<<", "select_extension", "(", "name", ")", "}", "end", "ordered_extensions", ".", "flatten", ".", "each", "(", "&", ":activate", ")", "Page", ".", "load_subclasses", "end" ]
Activates all enabled extensions and makes sure that any newly declared subclasses of Page are recognised. The admin UI and views have to be reinitialized each time to pick up changes and avoid duplicates.
[ "Activates", "all", "enabled", "extensions", "and", "makes", "sure", "that", "any", "newly", "declared", "subclasses", "of", "Page", "are", "recognised", ".", "The", "admin", "UI", "and", "views", "have", "to", "be", "reinitialized", "each", "time", "to", "pick", "up", "changes", "and", "avoid", "duplicates", "." ]
444ad7010c28a8aa5194cc13dd4a376a6bddd1fd
https://github.com/pgharts/trusty-cms/blob/444ad7010c28a8aa5194cc13dd4a376a6bddd1fd/lib/trusty_cms/extension_loader.rb#L100-L111
train
jamesramsay/jekyll-app-engine
lib/jekyll-app-engine.rb
Jekyll.JekyllAppEngine.source_partial_exists?
def source_partial_exists? if @site.respond_to?(:in_source_dir) File.exists? @site.in_source_dir("_app.yaml") else File.exists? Jekyll.sanitized_path(@site.source, "_app.yaml") end end
ruby
def source_partial_exists? if @site.respond_to?(:in_source_dir) File.exists? @site.in_source_dir("_app.yaml") else File.exists? Jekyll.sanitized_path(@site.source, "_app.yaml") end end
[ "def", "source_partial_exists?", "if", "@site", ".", "respond_to?", "(", ":in_source_dir", ")", "File", ".", "exists?", "@site", ".", "in_source_dir", "(", "\"_app.yaml\"", ")", "else", "File", ".", "exists?", "Jekyll", ".", "sanitized_path", "(", "@site", ".", "source", ",", "\"_app.yaml\"", ")", "end", "end" ]
Checks if a optional _app.yaml partial already exists
[ "Checks", "if", "a", "optional", "_app", ".", "yaml", "partial", "already", "exists" ]
e562baf54ebb4496bdd77183b2bd4b83d015d843
https://github.com/jamesramsay/jekyll-app-engine/blob/e562baf54ebb4496bdd77183b2bd4b83d015d843/lib/jekyll-app-engine.rb#L50-L56
train
jamesramsay/jekyll-app-engine
lib/jekyll-app-engine.rb
Jekyll.JekyllAppEngine.document_overrides
def document_overrides(document) if document.respond_to?(:data) and document.data.has_key?("app_engine") document.data.fetch("app_engine") else {} end end
ruby
def document_overrides(document) if document.respond_to?(:data) and document.data.has_key?("app_engine") document.data.fetch("app_engine") else {} end end
[ "def", "document_overrides", "(", "document", ")", "if", "document", ".", "respond_to?", "(", ":data", ")", "and", "document", ".", "data", ".", "has_key?", "(", "\"app_engine\"", ")", "document", ".", "data", ".", "fetch", "(", "\"app_engine\"", ")", "else", "{", "}", "end", "end" ]
Document specific app.yaml configuration provided in yaml frontmatter
[ "Document", "specific", "app", ".", "yaml", "configuration", "provided", "in", "yaml", "frontmatter" ]
e562baf54ebb4496bdd77183b2bd4b83d015d843
https://github.com/jamesramsay/jekyll-app-engine/blob/e562baf54ebb4496bdd77183b2bd4b83d015d843/lib/jekyll-app-engine.rb#L161-L167
train
jamesramsay/jekyll-app-engine
lib/jekyll-app-engine.rb
Jekyll.JekyllAppEngine.app_yaml_exists?
def app_yaml_exists? if @site.respond_to?(:in_source_dir) File.exists? @site.in_source_dir("app.yaml") else File.exists? Jekyll.sanitized_path(@site.source, "app.yaml") end end
ruby
def app_yaml_exists? if @site.respond_to?(:in_source_dir) File.exists? @site.in_source_dir("app.yaml") else File.exists? Jekyll.sanitized_path(@site.source, "app.yaml") end end
[ "def", "app_yaml_exists?", "if", "@site", ".", "respond_to?", "(", ":in_source_dir", ")", "File", ".", "exists?", "@site", ".", "in_source_dir", "(", "\"app.yaml\"", ")", "else", "File", ".", "exists?", "Jekyll", ".", "sanitized_path", "(", "@site", ".", "source", ",", "\"app.yaml\"", ")", "end", "end" ]
Checks if a app.yaml already exists in the site source
[ "Checks", "if", "a", "app", ".", "yaml", "already", "exists", "in", "the", "site", "source" ]
e562baf54ebb4496bdd77183b2bd4b83d015d843
https://github.com/jamesramsay/jekyll-app-engine/blob/e562baf54ebb4496bdd77183b2bd4b83d015d843/lib/jekyll-app-engine.rb#L170-L176
train
mattray/spiceweasel
lib/spiceweasel/data_bags.rb
Spiceweasel.DataBags.validate_item
def validate_item(db, item) unless File.exist?("data_bags/#{db}/#{item}.json") STDERR.puts "ERROR: data bag '#{db}' item '#{item}' file 'data_bags/#{db}/#{item}.json' does not exist" exit(-1) end f = File.read("data_bags/#{db}/#{item}.json") begin itemfile = JSON.parse(f) rescue JSON::ParserError => e # invalid JSON STDERR.puts "ERROR: data bag '#{db} item '#{item}' has JSON errors." STDERR.puts e.message exit(-1) end # validate the id matches the file name item = item.split("/").last if item =~ /\// # pull out directories return if item.eql?(itemfile["id"]) STDERR.puts "ERROR: data bag '#{db}' item '#{item}' listed in the manifest does not match the id '#{itemfile['id']}' within the 'data_bags/#{db}/#{item}.json' file." exit(-1) end
ruby
def validate_item(db, item) unless File.exist?("data_bags/#{db}/#{item}.json") STDERR.puts "ERROR: data bag '#{db}' item '#{item}' file 'data_bags/#{db}/#{item}.json' does not exist" exit(-1) end f = File.read("data_bags/#{db}/#{item}.json") begin itemfile = JSON.parse(f) rescue JSON::ParserError => e # invalid JSON STDERR.puts "ERROR: data bag '#{db} item '#{item}' has JSON errors." STDERR.puts e.message exit(-1) end # validate the id matches the file name item = item.split("/").last if item =~ /\// # pull out directories return if item.eql?(itemfile["id"]) STDERR.puts "ERROR: data bag '#{db}' item '#{item}' listed in the manifest does not match the id '#{itemfile['id']}' within the 'data_bags/#{db}/#{item}.json' file." exit(-1) end
[ "def", "validate_item", "(", "db", ",", "item", ")", "unless", "File", ".", "exist?", "(", "\"data_bags/#{db}/#{item}.json\"", ")", "STDERR", ".", "puts", "\"ERROR: data bag '#{db}' item '#{item}' file 'data_bags/#{db}/#{item}.json' does not exist\"", "exit", "(", "-", "1", ")", "end", "f", "=", "File", ".", "read", "(", "\"data_bags/#{db}/#{item}.json\"", ")", "begin", "itemfile", "=", "JSON", ".", "parse", "(", "f", ")", "rescue", "JSON", "::", "ParserError", "=>", "e", "STDERR", ".", "puts", "\"ERROR: data bag '#{db} item '#{item}' has JSON errors.\"", "STDERR", ".", "puts", "e", ".", "message", "exit", "(", "-", "1", ")", "end", "item", "=", "item", ".", "split", "(", "\"/\"", ")", ".", "last", "if", "item", "=~", "/", "\\/", "/", "return", "if", "item", ".", "eql?", "(", "itemfile", "[", "\"id\"", "]", ")", "STDERR", ".", "puts", "\"ERROR: data bag '#{db}' item '#{item}' listed in the manifest does not match the id '#{itemfile['id']}' within the 'data_bags/#{db}/#{item}.json' file.\"", "exit", "(", "-", "1", ")", "end" ]
validate the item to be loaded
[ "validate", "the", "item", "to", "be", "loaded" ]
c7f01a127a542989f8525486890cf12249b6db44
https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/data_bags.rb#L114-L134
train
solnic/coercible
lib/coercible/coercer.rb
Coercible.Coercer.initialize_coercer
def initialize_coercer(klass) coercers[klass] = begin coercer = Coercer::Object.determine_type(klass) || Coercer::Object args = [ self ] args << config_for(coercer) if coercer.respond_to?(:config_name) coercer.new(*args) end end
ruby
def initialize_coercer(klass) coercers[klass] = begin coercer = Coercer::Object.determine_type(klass) || Coercer::Object args = [ self ] args << config_for(coercer) if coercer.respond_to?(:config_name) coercer.new(*args) end end
[ "def", "initialize_coercer", "(", "klass", ")", "coercers", "[", "klass", "]", "=", "begin", "coercer", "=", "Coercer", "::", "Object", ".", "determine_type", "(", "klass", ")", "||", "Coercer", "::", "Object", "args", "=", "[", "self", "]", "args", "<<", "config_for", "(", "coercer", ")", "if", "coercer", ".", "respond_to?", "(", ":config_name", ")", "coercer", ".", "new", "(", "*", "args", ")", "end", "end" ]
Initialize a new coercer instance for the given type If a coercer class supports configuration it will receive it from the global configuration object @return [Coercer::Object] @api private
[ "Initialize", "a", "new", "coercer", "instance", "for", "the", "given", "type" ]
c076869838531abb5783280da108aa3cbddbd61a
https://github.com/solnic/coercible/blob/c076869838531abb5783280da108aa3cbddbd61a/lib/coercible/coercer.rb#L115-L123
train
arangodb-helper/guacamole
lib/guacamole/transaction.rb
Guacamole.Transaction.write_collections
def write_collections edge_collections.flat_map do |target_state| [target_state.edge_collection_name] + (target_state.from_vertices + target_state.to_vertices).map(&:collection) end.uniq.compact end
ruby
def write_collections edge_collections.flat_map do |target_state| [target_state.edge_collection_name] + (target_state.from_vertices + target_state.to_vertices).map(&:collection) end.uniq.compact end
[ "def", "write_collections", "edge_collections", ".", "flat_map", "do", "|", "target_state", "|", "[", "target_state", ".", "edge_collection_name", "]", "+", "(", "target_state", ".", "from_vertices", "+", "target_state", ".", "to_vertices", ")", ".", "map", "(", "&", ":collection", ")", "end", ".", "uniq", ".", "compact", "end" ]
A list of collections we will write to @return [Array<String>] A list of the collection names we will write to
[ "A", "list", "of", "collections", "we", "will", "write", "to" ]
90505fc0276ea529073c0e8d1087f51f193840b6
https://github.com/arangodb-helper/guacamole/blob/90505fc0276ea529073c0e8d1087f51f193840b6/lib/guacamole/transaction.rb#L308-L313
train
arangodb-helper/guacamole
lib/guacamole/transaction.rb
Guacamole.Transaction.transaction
def transaction transaction = database.create_transaction(transaction_code, write: write_collections, read: read_collections) transaction.wait_for_sync = true transaction end
ruby
def transaction transaction = database.create_transaction(transaction_code, write: write_collections, read: read_collections) transaction.wait_for_sync = true transaction end
[ "def", "transaction", "transaction", "=", "database", ".", "create_transaction", "(", "transaction_code", ",", "write", ":", "write_collections", ",", "read", ":", "read_collections", ")", "transaction", ".", "wait_for_sync", "=", "true", "transaction", "end" ]
A transaction instance from the database return [Ashikawa::Core::Transaction] A raw transaction to execute the Transaction on the database @api private
[ "A", "transaction", "instance", "from", "the", "database" ]
90505fc0276ea529073c0e8d1087f51f193840b6
https://github.com/arangodb-helper/guacamole/blob/90505fc0276ea529073c0e8d1087f51f193840b6/lib/guacamole/transaction.rb#L352-L359
train
tulak/pdu_tools
lib/pdu_tools/helpers.rb
PDUTools.Helpers.decode16bit
def decode16bit data, length data.split('').in_groups_of(4).collect() double_octets = data.split('').in_groups_of(4).map(&:join).map{|x| x.to_i(16) }[0, length / 2] # integer values double_octets.collect do |o| [o].pack('S') end.join.force_encoding('utf-16le').encode('utf-8') end
ruby
def decode16bit data, length data.split('').in_groups_of(4).collect() double_octets = data.split('').in_groups_of(4).map(&:join).map{|x| x.to_i(16) }[0, length / 2] # integer values double_octets.collect do |o| [o].pack('S') end.join.force_encoding('utf-16le').encode('utf-8') end
[ "def", "decode16bit", "data", ",", "length", "data", ".", "split", "(", "''", ")", ".", "in_groups_of", "(", "4", ")", ".", "collect", "(", ")", "double_octets", "=", "data", ".", "split", "(", "''", ")", ".", "in_groups_of", "(", "4", ")", ".", "map", "(", "&", ":join", ")", ".", "map", "{", "|", "x", "|", "x", ".", "to_i", "(", "16", ")", "}", "[", "0", ",", "length", "/", "2", "]", "double_octets", ".", "collect", "do", "|", "o", "|", "[", "o", "]", ".", "pack", "(", "'S'", ")", "end", ".", "join", ".", "force_encoding", "(", "'utf-16le'", ")", ".", "encode", "(", "'utf-8'", ")", "end" ]
Decodes 16bit UTF-16 string into UTF-8 string
[ "Decodes", "16bit", "UTF", "-", "16", "string", "into", "UTF", "-", "8", "string" ]
dd542ac0c30a32246d31613a7fb5d7e8a93dc847
https://github.com/tulak/pdu_tools/blob/dd542ac0c30a32246d31613a7fb5d7e8a93dc847/lib/pdu_tools/helpers.rb#L118-L124
train
arangodb-helper/guacamole
lib/guacamole/query.rb
Guacamole.Query.each
def each(&block) return to_enum(__callee__) unless block_given? perfom_query ->(document) { block.call mapper.document_to_model(document) }, &block end
ruby
def each(&block) return to_enum(__callee__) unless block_given? perfom_query ->(document) { block.call mapper.document_to_model(document) }, &block end
[ "def", "each", "(", "&", "block", ")", "return", "to_enum", "(", "__callee__", ")", "unless", "block_given?", "perfom_query", "->", "(", "document", ")", "{", "block", ".", "call", "mapper", ".", "document_to_model", "(", "document", ")", "}", ",", "&", "block", "end" ]
Create a new Query @param [Ashikawa::Core::Collection] connection The collection to use to talk to the database @param [Class] mapper the class of the mapper to use Iterate over the result of the query This will execute the query you have build
[ "Create", "a", "new", "Query" ]
90505fc0276ea529073c0e8d1087f51f193840b6
https://github.com/arangodb-helper/guacamole/blob/90505fc0276ea529073c0e8d1087f51f193840b6/lib/guacamole/query.rb#L41-L45
train
arangodb-helper/guacamole
lib/guacamole/query.rb
Guacamole.Query.perfom_query
def perfom_query(iterator, &block) if example connection.by_example(example, options).each(&iterator) else connection.all(options).each(&iterator) end end
ruby
def perfom_query(iterator, &block) if example connection.by_example(example, options).each(&iterator) else connection.all(options).each(&iterator) end end
[ "def", "perfom_query", "(", "iterator", ",", "&", "block", ")", "if", "example", "connection", ".", "by_example", "(", "example", ",", "options", ")", ".", "each", "(", "&", "iterator", ")", "else", "connection", ".", "all", "(", "options", ")", ".", "each", "(", "&", "iterator", ")", "end", "end" ]
Performs the query against the database connection. This can be changed by subclasses to implement other types of queries, such as AQL queries. @param [Lambda] iterator To be called on each document returned from the database
[ "Performs", "the", "query", "against", "the", "database", "connection", "." ]
90505fc0276ea529073c0e8d1087f51f193840b6
https://github.com/arangodb-helper/guacamole/blob/90505fc0276ea529073c0e8d1087f51f193840b6/lib/guacamole/query.rb#L85-L91
train
mapnik/Ruby-Mapnik
lib/ruby_mapnik/mapnik/map.rb
Mapnik.Map.style
def style(name) style = Mapnik::Style.new yield style styles[name] = style end
ruby
def style(name) style = Mapnik::Style.new yield style styles[name] = style end
[ "def", "style", "(", "name", ")", "style", "=", "Mapnik", "::", "Style", ".", "new", "yield", "style", "styles", "[", "name", "]", "=", "style", "end" ]
Creates and yeilds a new style object, then adds that style to the map's collection of styles, under the name passed in. Makes no effort to de-dupe style name collisions. @return [Mapnik::Style]
[ "Creates", "and", "yeilds", "a", "new", "style", "object", "then", "adds", "that", "style", "to", "the", "map", "s", "collection", "of", "styles", "under", "the", "name", "passed", "in", ".", "Makes", "no", "effort", "to", "de", "-", "dupe", "style", "name", "collisions", "." ]
39e76e0f786fbc1e322bc115fbbaeb49c84d3bd0
https://github.com/mapnik/Ruby-Mapnik/blob/39e76e0f786fbc1e322bc115fbbaeb49c84d3bd0/lib/ruby_mapnik/mapnik/map.rb#L117-L121
train
mapnik/Ruby-Mapnik
lib/ruby_mapnik/mapnik/map.rb
Mapnik.Map.layer
def layer(name, srs = nil) layer = Mapnik::Layer.new(name, srs) layer.map = self yield layer layers << layer end
ruby
def layer(name, srs = nil) layer = Mapnik::Layer.new(name, srs) layer.map = self yield layer layers << layer end
[ "def", "layer", "(", "name", ",", "srs", "=", "nil", ")", "layer", "=", "Mapnik", "::", "Layer", ".", "new", "(", "name", ",", "srs", ")", "layer", ".", "map", "=", "self", "yield", "layer", "layers", "<<", "layer", "end" ]
Creates and yields a new layer object, then adds that layer to the map's collection of layers. If the srs is not provided in the initial call, it will need to be provided in the block. @return [Mapnik::Layer]
[ "Creates", "and", "yields", "a", "new", "layer", "object", "then", "adds", "that", "layer", "to", "the", "map", "s", "collection", "of", "layers", ".", "If", "the", "srs", "is", "not", "provided", "in", "the", "initial", "call", "it", "will", "need", "to", "be", "provided", "in", "the", "block", "." ]
39e76e0f786fbc1e322bc115fbbaeb49c84d3bd0
https://github.com/mapnik/Ruby-Mapnik/blob/39e76e0f786fbc1e322bc115fbbaeb49c84d3bd0/lib/ruby_mapnik/mapnik/map.rb#L135-L140
train
mapnik/Ruby-Mapnik
lib/ruby_mapnik/mapnik/map.rb
Mapnik.Map.render_to_file
def render_to_file(filename, format = nil) if format __render_to_file_with_format__(filename, format) else __render_to_file__(filename) end return File.exists?(filename) end
ruby
def render_to_file(filename, format = nil) if format __render_to_file_with_format__(filename, format) else __render_to_file__(filename) end return File.exists?(filename) end
[ "def", "render_to_file", "(", "filename", ",", "format", "=", "nil", ")", "if", "format", "__render_to_file_with_format__", "(", "filename", ",", "format", ")", "else", "__render_to_file__", "(", "filename", ")", "end", "return", "File", ".", "exists?", "(", "filename", ")", "end" ]
Renders the map to a file. Returns true or false depending if the render was successful. The image type is inferred from the filename. @param [String] filename Should end in one of "png", "jpg", or "tiff" if format not specified @param [String] format Should be one of formats supported by Mapnik or nil (to be guessed from filename) @return [Boolean]
[ "Renders", "the", "map", "to", "a", "file", ".", "Returns", "true", "or", "false", "depending", "if", "the", "render", "was", "successful", ".", "The", "image", "type", "is", "inferred", "from", "the", "filename", "." ]
39e76e0f786fbc1e322bc115fbbaeb49c84d3bd0
https://github.com/mapnik/Ruby-Mapnik/blob/39e76e0f786fbc1e322bc115fbbaeb49c84d3bd0/lib/ruby_mapnik/mapnik/map.rb#L155-L162
train
lardawge/rfm
lib/rfm/error.rb
Rfm.Error.getError
def getError(code, message=nil) klass = find_by_code(code) message = build_message(klass, code, message) error = klass.new(code, message) error end
ruby
def getError(code, message=nil) klass = find_by_code(code) message = build_message(klass, code, message) error = klass.new(code, message) error end
[ "def", "getError", "(", "code", ",", "message", "=", "nil", ")", "klass", "=", "find_by_code", "(", "code", ")", "message", "=", "build_message", "(", "klass", ",", "code", ",", "message", ")", "error", "=", "klass", ".", "new", "(", "code", ",", "message", ")", "error", "end" ]
This method returns the appropriate FileMaker object depending on the error code passed to it. It also accepts an optional message.
[ "This", "method", "returns", "the", "appropriate", "FileMaker", "object", "depending", "on", "the", "error", "code", "passed", "to", "it", ".", "It", "also", "accepts", "an", "optional", "message", "." ]
f52601d3a6e685428be99a48397f50f3db53ae4f
https://github.com/lardawge/rfm/blob/f52601d3a6e685428be99a48397f50f3db53ae4f/lib/rfm/error.rb#L126-L131
train
monzo/mondo-ruby
lib/mondo/client.rb
Mondo.Client.request
def request(method, path, opts = {}) raise ClientError, 'Access token missing' unless @access_token opts[:headers] = {} if opts[:headers].nil? opts[:headers]['Accept'] = 'application/json' opts[:headers]['Content-Type'] = 'application/json' unless method == :get opts[:headers]['User-Agent'] = user_agent opts[:headers]['Authorization'] = "Bearer #{@access_token}" if !opts[:data].nil? opts[:body] = opts[:data].to_param puts "SETTING BODY #{opts[:body]}" opts[:headers]['Content-Type'] = 'application/x-www-form-urlencoded' # sob sob end path = URI.encode(path) resp = connection.run_request(method, path, opts[:body], opts[:headers]) do |req| req.params = opts[:params] if !opts[:params].nil? end response = Response.new(resp) case response.status when 301, 302, 303, 307 # TODO when 200..299, 300..399 # on non-redirecting 3xx statuses, just return the response response when 400..599 error = ApiError.new(response) raise(error, "Status code #{response.status}") else error = ApiError.new(response) raise(error, "Unhandled status code value of #{response.status}") end end
ruby
def request(method, path, opts = {}) raise ClientError, 'Access token missing' unless @access_token opts[:headers] = {} if opts[:headers].nil? opts[:headers]['Accept'] = 'application/json' opts[:headers]['Content-Type'] = 'application/json' unless method == :get opts[:headers]['User-Agent'] = user_agent opts[:headers]['Authorization'] = "Bearer #{@access_token}" if !opts[:data].nil? opts[:body] = opts[:data].to_param puts "SETTING BODY #{opts[:body]}" opts[:headers]['Content-Type'] = 'application/x-www-form-urlencoded' # sob sob end path = URI.encode(path) resp = connection.run_request(method, path, opts[:body], opts[:headers]) do |req| req.params = opts[:params] if !opts[:params].nil? end response = Response.new(resp) case response.status when 301, 302, 303, 307 # TODO when 200..299, 300..399 # on non-redirecting 3xx statuses, just return the response response when 400..599 error = ApiError.new(response) raise(error, "Status code #{response.status}") else error = ApiError.new(response) raise(error, "Unhandled status code value of #{response.status}") end end
[ "def", "request", "(", "method", ",", "path", ",", "opts", "=", "{", "}", ")", "raise", "ClientError", ",", "'Access token missing'", "unless", "@access_token", "opts", "[", ":headers", "]", "=", "{", "}", "if", "opts", "[", ":headers", "]", ".", "nil?", "opts", "[", ":headers", "]", "[", "'Accept'", "]", "=", "'application/json'", "opts", "[", ":headers", "]", "[", "'Content-Type'", "]", "=", "'application/json'", "unless", "method", "==", ":get", "opts", "[", ":headers", "]", "[", "'User-Agent'", "]", "=", "user_agent", "opts", "[", ":headers", "]", "[", "'Authorization'", "]", "=", "\"Bearer #{@access_token}\"", "if", "!", "opts", "[", ":data", "]", ".", "nil?", "opts", "[", ":body", "]", "=", "opts", "[", ":data", "]", ".", "to_param", "puts", "\"SETTING BODY #{opts[:body]}\"", "opts", "[", ":headers", "]", "[", "'Content-Type'", "]", "=", "'application/x-www-form-urlencoded'", "end", "path", "=", "URI", ".", "encode", "(", "path", ")", "resp", "=", "connection", ".", "run_request", "(", "method", ",", "path", ",", "opts", "[", ":body", "]", ",", "opts", "[", ":headers", "]", ")", "do", "|", "req", "|", "req", ".", "params", "=", "opts", "[", ":params", "]", "if", "!", "opts", "[", ":params", "]", ".", "nil?", "end", "response", "=", "Response", ".", "new", "(", "resp", ")", "case", "response", ".", "status", "when", "301", ",", "302", ",", "303", ",", "307", "when", "200", "..", "299", ",", "300", "..", "399", "response", "when", "400", "..", "599", "error", "=", "ApiError", ".", "new", "(", "response", ")", "raise", "(", "error", ",", "\"Status code #{response.status}\"", ")", "else", "error", "=", "ApiError", ".", "new", "(", "response", ")", "raise", "(", "error", ",", "\"Unhandled status code value of #{response.status}\"", ")", "end", "end" ]
Send a request to the Mondo API servers @param [Symbol] method the HTTP method to use (e.g. +:get+, +:post+) @param [String] path the path fragment of the URL @option [Hash] opts query string parameters, headers
[ "Send", "a", "request", "to", "the", "Mondo", "API", "servers" ]
74d52e050d2cf7ccf5dd35a00795aef9e13a7fe9
https://github.com/monzo/mondo-ruby/blob/74d52e050d2cf7ccf5dd35a00795aef9e13a7fe9/lib/mondo/client.rb#L191-L229
train
lardawge/rfm
lib/rfm/server.rb
Rfm.Server.connect
def connect(action, args, options = {}) post = args.merge(expand_options(options)).merge({action => ''}) http_fetch("/fmi/xml/fmresultset.xml", post) end
ruby
def connect(action, args, options = {}) post = args.merge(expand_options(options)).merge({action => ''}) http_fetch("/fmi/xml/fmresultset.xml", post) end
[ "def", "connect", "(", "action", ",", "args", ",", "options", "=", "{", "}", ")", "post", "=", "args", ".", "merge", "(", "expand_options", "(", "options", ")", ")", ".", "merge", "(", "{", "action", "=>", "''", "}", ")", "http_fetch", "(", "\"/fmi/xml/fmresultset.xml\"", ",", "post", ")", "end" ]
Performs a raw FileMaker action. You will generally not call this method directly, but it is exposed in case you need to do something "under the hood." The +action+ parameter is any valid FileMaker web url action. For example, +-find+, +-finadny+ etc. The +args+ parameter is a hash of arguments to be included in the action url. It will be serialized and url-encoded appropriately. The +options+ parameter is a hash of RFM-specific options, which correspond to the more esoteric FileMaker URL parameters. They are exposed separately because they can also be passed into various methods on the Layout object, which is a much more typical way of sending an action to FileMaker. This method returns the Net::HTTP response object representing the response from FileMaker. For example, if you wanted to send a raw command to FileMaker to find the first 20 people in the "Customers" database whose first name is "Bill" you might do this: response = myServer.connect( '-find', { "-db" => "Customers", "-lay" => "Details", "First Name" => "Bill" }, { :max_records => 20 } )
[ "Performs", "a", "raw", "FileMaker", "action", ".", "You", "will", "generally", "not", "call", "this", "method", "directly", "but", "it", "is", "exposed", "in", "case", "you", "need", "to", "do", "something", "under", "the", "hood", "." ]
f52601d3a6e685428be99a48397f50f3db53ae4f
https://github.com/lardawge/rfm/blob/f52601d3a6e685428be99a48397f50f3db53ae4f/lib/rfm/server.rb#L262-L265
train
copycopter/copycopter-ruby-client
lib/copycopter_client/i18n_backend.rb
CopycopterClient.I18nBackend.available_locales
def available_locales cached_locales = cache.keys.map { |key| key.split('.').first } (cached_locales + super).uniq.map { |locale| locale.to_sym } end
ruby
def available_locales cached_locales = cache.keys.map { |key| key.split('.').first } (cached_locales + super).uniq.map { |locale| locale.to_sym } end
[ "def", "available_locales", "cached_locales", "=", "cache", ".", "keys", ".", "map", "{", "|", "key", "|", "key", ".", "split", "(", "'.'", ")", ".", "first", "}", "(", "cached_locales", "+", "super", ")", ".", "uniq", ".", "map", "{", "|", "locale", "|", "locale", ".", "to_sym", "}", "end" ]
Returns locales availabile for this Copycopter project. @return [Array<String>] available locales
[ "Returns", "locales", "availabile", "for", "this", "Copycopter", "project", "." ]
9996c7fa323f7251e0668e6a47dc26dd35fed391
https://github.com/copycopter/copycopter-ruby-client/blob/9996c7fa323f7251e0668e6a47dc26dd35fed391/lib/copycopter_client/i18n_backend.rb#L36-L39
train
mkroman/rar
library/rar/archive.rb
RAR.Archive.create!
def create! rar_process = IO.popen command_line # Wait for the child rar process to finish. _, status = Process.wait2 rar_process.pid if status.exitstatus > 1 if message = ExitCodeMessages[status.exitstatus] raise CommandLineError, message else raise CommandLineError, "Unknown exit status: #{status}" end else true end end
ruby
def create! rar_process = IO.popen command_line # Wait for the child rar process to finish. _, status = Process.wait2 rar_process.pid if status.exitstatus > 1 if message = ExitCodeMessages[status.exitstatus] raise CommandLineError, message else raise CommandLineError, "Unknown exit status: #{status}" end else true end end
[ "def", "create!", "rar_process", "=", "IO", ".", "popen", "command_line", "_", ",", "status", "=", "Process", ".", "wait2", "rar_process", ".", "pid", "if", "status", ".", "exitstatus", ">", "1", "if", "message", "=", "ExitCodeMessages", "[", "status", ".", "exitstatus", "]", "raise", "CommandLineError", ",", "message", "else", "raise", "CommandLineError", ",", "\"Unknown exit status: #{status}\"", "end", "else", "true", "end", "end" ]
Create the final archive. @return true if the command executes without a hitch. @raise CommandLineError if the exit code indicates an error.
[ "Create", "the", "final", "archive", "." ]
aac4f055493bacf78b8a16602d8121934f7db347
https://github.com/mkroman/rar/blob/aac4f055493bacf78b8a16602d8121934f7db347/library/rar/archive.rb#L52-L67
train
copycopter/copycopter-ruby-client
lib/copycopter_client/client.rb
CopycopterClient.Client.upload
def upload(data) connect do |http| response = http.post(uri('draft_blurbs'), data.to_json, 'Content-Type' => 'application/json') check response log 'Uploaded missing translations' end end
ruby
def upload(data) connect do |http| response = http.post(uri('draft_blurbs'), data.to_json, 'Content-Type' => 'application/json') check response log 'Uploaded missing translations' end end
[ "def", "upload", "(", "data", ")", "connect", "do", "|", "http", "|", "response", "=", "http", ".", "post", "(", "uri", "(", "'draft_blurbs'", ")", ",", "data", ".", "to_json", ",", "'Content-Type'", "=>", "'application/json'", ")", "check", "response", "log", "'Uploaded missing translations'", "end", "end" ]
Uploads the given hash of blurbs as draft content. @param data [Hash] the blurbs to upload @raise [ConnectionError] if the connection fails
[ "Uploads", "the", "given", "hash", "of", "blurbs", "as", "draft", "content", "." ]
9996c7fa323f7251e0668e6a47dc26dd35fed391
https://github.com/copycopter/copycopter-ruby-client/blob/9996c7fa323f7251e0668e6a47dc26dd35fed391/lib/copycopter_client/client.rb#L65-L71
train
copycopter/copycopter-ruby-client
lib/copycopter_client/client.rb
CopycopterClient.Client.deploy
def deploy connect do |http| response = http.post(uri('deploys'), '') check response log 'Deployed' end end
ruby
def deploy connect do |http| response = http.post(uri('deploys'), '') check response log 'Deployed' end end
[ "def", "deploy", "connect", "do", "|", "http", "|", "response", "=", "http", ".", "post", "(", "uri", "(", "'deploys'", ")", ",", "''", ")", "check", "response", "log", "'Deployed'", "end", "end" ]
Issues a deploy, marking all draft content as published for this project. @raise [ConnectionError] if the connection fails
[ "Issues", "a", "deploy", "marking", "all", "draft", "content", "as", "published", "for", "this", "project", "." ]
9996c7fa323f7251e0668e6a47dc26dd35fed391
https://github.com/copycopter/copycopter-ruby-client/blob/9996c7fa323f7251e0668e6a47dc26dd35fed391/lib/copycopter_client/client.rb#L75-L81
train
nofxx/hooray
lib/hooray/seek.rb
Hooray.Seek.nodes
def nodes return @nodes if @nodes @nodes = sweep.map do |k, v| Node.new(ip: k, mac: Hooray::Local.arp_table[k.to_s], ports: v) end # .reject { |n| n.mac.nil? } # remove those without mac end
ruby
def nodes return @nodes if @nodes @nodes = sweep.map do |k, v| Node.new(ip: k, mac: Hooray::Local.arp_table[k.to_s], ports: v) end # .reject { |n| n.mac.nil? } # remove those without mac end
[ "def", "nodes", "return", "@nodes", "if", "@nodes", "@nodes", "=", "sweep", ".", "map", "do", "|", "k", ",", "v", "|", "Node", ".", "new", "(", "ip", ":", "k", ",", "mac", ":", "Hooray", "::", "Local", ".", "arp_table", "[", "k", ".", "to_s", "]", ",", "ports", ":", "v", ")", "end", "end" ]
Map results to @nodes << Node.new()
[ "Map", "results", "to" ]
31243bfbb0d69c8139e52ead5358f1c9ca3d07e3
https://github.com/nofxx/hooray/blob/31243bfbb0d69c8139e52ead5358f1c9ca3d07e3/lib/hooray/seek.rb#L38-L43
train
nofxx/hooray
lib/hooray/seek.rb
Hooray.Seek.ping_class
def ping_class return Net::Ping::External unless ports return Net::Ping::TCP unless @protocol =~ /tcp|udp|http|wmi/ Net::Ping.const_get(@protocol.upcase) end
ruby
def ping_class return Net::Ping::External unless ports return Net::Ping::TCP unless @protocol =~ /tcp|udp|http|wmi/ Net::Ping.const_get(@protocol.upcase) end
[ "def", "ping_class", "return", "Net", "::", "Ping", "::", "External", "unless", "ports", "return", "Net", "::", "Ping", "::", "TCP", "unless", "@protocol", "=~", "/", "/", "Net", "::", "Ping", ".", "const_get", "(", "@protocol", ".", "upcase", ")", "end" ]
Decide how to ping
[ "Decide", "how", "to", "ping" ]
31243bfbb0d69c8139e52ead5358f1c9ca3d07e3
https://github.com/nofxx/hooray/blob/31243bfbb0d69c8139e52ead5358f1c9ca3d07e3/lib/hooray/seek.rb#L48-L52
train
nofxx/hooray
lib/hooray/seek.rb
Hooray.Seek.scan_bot
def scan_bot(ip) (ports || [nil]).each do |port| Thread.new do if ping_class.new(ip.to_s, port, TIMEOUT).ping? @scan[ip] << port print '.' end end end end
ruby
def scan_bot(ip) (ports || [nil]).each do |port| Thread.new do if ping_class.new(ip.to_s, port, TIMEOUT).ping? @scan[ip] << port print '.' end end end end
[ "def", "scan_bot", "(", "ip", ")", "(", "ports", "||", "[", "nil", "]", ")", ".", "each", "do", "|", "port", "|", "Thread", ".", "new", "do", "if", "ping_class", ".", "new", "(", "ip", ".", "to_s", ",", "port", ",", "TIMEOUT", ")", ".", "ping?", "@scan", "[", "ip", "]", "<<", "port", "print", "'.'", "end", "end", "end", "end" ]
Creates a bot per port on IP
[ "Creates", "a", "bot", "per", "port", "on", "IP" ]
31243bfbb0d69c8139e52ead5358f1c9ca3d07e3
https://github.com/nofxx/hooray/blob/31243bfbb0d69c8139e52ead5358f1c9ca3d07e3/lib/hooray/seek.rb#L56-L65
train
nofxx/hooray
lib/hooray/seek.rb
Hooray.Seek.sweep
def sweep network.to_range.each do |ip| @scan[ip] = [] scan_bot(ip) end Thread.list.reject { |t| t == Thread.current }.each(&:join) @scan.reject! { |_k, v| v.empty? } end
ruby
def sweep network.to_range.each do |ip| @scan[ip] = [] scan_bot(ip) end Thread.list.reject { |t| t == Thread.current }.each(&:join) @scan.reject! { |_k, v| v.empty? } end
[ "def", "sweep", "network", ".", "to_range", ".", "each", "do", "|", "ip", "|", "@scan", "[", "ip", "]", "=", "[", "]", "scan_bot", "(", "ip", ")", "end", "Thread", ".", "list", ".", "reject", "{", "|", "t", "|", "t", "==", "Thread", ".", "current", "}", ".", "each", "(", "&", ":join", ")", "@scan", ".", "reject!", "{", "|", "_k", ",", "v", "|", "v", ".", "empty?", "}", "end" ]
fast -> -sn -PA
[ "fast", "-", ">", "-", "sn", "-", "PA" ]
31243bfbb0d69c8139e52ead5358f1c9ca3d07e3
https://github.com/nofxx/hooray/blob/31243bfbb0d69c8139e52ead5358f1c9ca3d07e3/lib/hooray/seek.rb#L70-L77
train
copycopter/copycopter-ruby-client
lib/copycopter_client/cache.rb
CopycopterClient.Cache.export
def export keys = {} lock do @blurbs.sort.each do |(blurb_key, value)| current = keys yaml_keys = blurb_key.split('.') 0.upto(yaml_keys.size - 2) do |i| key = yaml_keys[i] # Overwrite en.key with en.sub.key unless current[key].class == Hash current[key] = {} end current = current[key] end current[yaml_keys.last] = value end end unless keys.size < 1 keys.to_yaml end end
ruby
def export keys = {} lock do @blurbs.sort.each do |(blurb_key, value)| current = keys yaml_keys = blurb_key.split('.') 0.upto(yaml_keys.size - 2) do |i| key = yaml_keys[i] # Overwrite en.key with en.sub.key unless current[key].class == Hash current[key] = {} end current = current[key] end current[yaml_keys.last] = value end end unless keys.size < 1 keys.to_yaml end end
[ "def", "export", "keys", "=", "{", "}", "lock", "do", "@blurbs", ".", "sort", ".", "each", "do", "|", "(", "blurb_key", ",", "value", ")", "|", "current", "=", "keys", "yaml_keys", "=", "blurb_key", ".", "split", "(", "'.'", ")", "0", ".", "upto", "(", "yaml_keys", ".", "size", "-", "2", ")", "do", "|", "i", "|", "key", "=", "yaml_keys", "[", "i", "]", "unless", "current", "[", "key", "]", ".", "class", "==", "Hash", "current", "[", "key", "]", "=", "{", "}", "end", "current", "=", "current", "[", "key", "]", "end", "current", "[", "yaml_keys", ".", "last", "]", "=", "value", "end", "end", "unless", "keys", ".", "size", "<", "1", "keys", ".", "to_yaml", "end", "end" ]
Yaml representation of all blurbs @return [String] yaml
[ "Yaml", "representation", "of", "all", "blurbs" ]
9996c7fa323f7251e0668e6a47dc26dd35fed391
https://github.com/copycopter/copycopter-ruby-client/blob/9996c7fa323f7251e0668e6a47dc26dd35fed391/lib/copycopter_client/cache.rb#L48-L73
train
copycopter/copycopter-ruby-client
lib/copycopter_client/cache.rb
CopycopterClient.Cache.wait_for_download
def wait_for_download if pending? logger.info 'Waiting for first download' if logger.respond_to? :flush logger.flush end while pending? sleep 0.1 end end end
ruby
def wait_for_download if pending? logger.info 'Waiting for first download' if logger.respond_to? :flush logger.flush end while pending? sleep 0.1 end end end
[ "def", "wait_for_download", "if", "pending?", "logger", ".", "info", "'Waiting for first download'", "if", "logger", ".", "respond_to?", ":flush", "logger", ".", "flush", "end", "while", "pending?", "sleep", "0.1", "end", "end", "end" ]
Waits until the first download has finished.
[ "Waits", "until", "the", "first", "download", "has", "finished", "." ]
9996c7fa323f7251e0668e6a47dc26dd35fed391
https://github.com/copycopter/copycopter-ruby-client/blob/9996c7fa323f7251e0668e6a47dc26dd35fed391/lib/copycopter_client/cache.rb#L76-L88
train
ryantate/rturk
lib/rturk/operations/register_hit_type.rb
RTurk.RegisterHITType.validate
def validate missing_parameters = [] required_fields.each do |param| missing_parameters << param.to_s unless self.send(param) end raise RTurk::MissingParameters, "Parameters: '#{missing_parameters.join(', ')}'" unless missing_parameters.empty? end
ruby
def validate missing_parameters = [] required_fields.each do |param| missing_parameters << param.to_s unless self.send(param) end raise RTurk::MissingParameters, "Parameters: '#{missing_parameters.join(', ')}'" unless missing_parameters.empty? end
[ "def", "validate", "missing_parameters", "=", "[", "]", "required_fields", ".", "each", "do", "|", "param", "|", "missing_parameters", "<<", "param", ".", "to_s", "unless", "self", ".", "send", "(", "param", ")", "end", "raise", "RTurk", "::", "MissingParameters", ",", "\"Parameters: '#{missing_parameters.join(', ')}'\"", "unless", "missing_parameters", ".", "empty?", "end" ]
More complicated validation run before request
[ "More", "complicated", "validation", "run", "before", "request" ]
d98daab65a0049472d632ffda45e350f5845938d
https://github.com/ryantate/rturk/blob/d98daab65a0049472d632ffda45e350f5845938d/lib/rturk/operations/register_hit_type.rb#L32-L38
train
pluginaweek/table_helper
lib/table_helper/collection_table.rb
TableHelper.CollectionTable.default_class
def default_class if collection.respond_to?(:proxy_reflection) collection.proxy_reflection.klass elsif !collection.empty? collection.first.class end end
ruby
def default_class if collection.respond_to?(:proxy_reflection) collection.proxy_reflection.klass elsif !collection.empty? collection.first.class end end
[ "def", "default_class", "if", "collection", ".", "respond_to?", "(", ":proxy_reflection", ")", "collection", ".", "proxy_reflection", ".", "klass", "elsif", "!", "collection", ".", "empty?", "collection", ".", "first", ".", "class", "end", "end" ]
Finds the class representing the objects within the collection
[ "Finds", "the", "class", "representing", "the", "objects", "within", "the", "collection" ]
8456c014f919b344b4bf6261b7eab055d888d945
https://github.com/pluginaweek/table_helper/blob/8456c014f919b344b4bf6261b7eab055d888d945/lib/table_helper/collection_table.rb#L118-L124
train
pluginaweek/table_helper
lib/table_helper/row.rb
TableHelper.RowBuilder.undef_cell
def undef_cell(name) method_name = name.gsub('-', '_') klass = class << self; self; end klass.class_eval do remove_method(method_name) end end
ruby
def undef_cell(name) method_name = name.gsub('-', '_') klass = class << self; self; end klass.class_eval do remove_method(method_name) end end
[ "def", "undef_cell", "(", "name", ")", "method_name", "=", "name", ".", "gsub", "(", "'-'", ",", "'_'", ")", "klass", "=", "class", "<<", "self", ";", "self", ";", "end", "klass", ".", "class_eval", "do", "remove_method", "(", "method_name", ")", "end", "end" ]
Removes the definition for the given cell
[ "Removes", "the", "definition", "for", "the", "given", "cell" ]
8456c014f919b344b4bf6261b7eab055d888d945
https://github.com/pluginaweek/table_helper/blob/8456c014f919b344b4bf6261b7eab055d888d945/lib/table_helper/row.rb#L40-L47
train
pluginaweek/table_helper
lib/table_helper/row.rb
TableHelper.Row.cell
def cell(name, *args) name = name.to_s if name options = args.last.is_a?(Hash) ? args.pop : {} options[:namespace] = table.object_name args << options cell = Cell.new(name, *args) cells[name] = cell builder.define_cell(name) if name cell end
ruby
def cell(name, *args) name = name.to_s if name options = args.last.is_a?(Hash) ? args.pop : {} options[:namespace] = table.object_name args << options cell = Cell.new(name, *args) cells[name] = cell builder.define_cell(name) if name cell end
[ "def", "cell", "(", "name", ",", "*", "args", ")", "name", "=", "name", ".", "to_s", "if", "name", "options", "=", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "options", "[", ":namespace", "]", "=", "table", ".", "object_name", "args", "<<", "options", "cell", "=", "Cell", ".", "new", "(", "name", ",", "*", "args", ")", "cells", "[", "name", "]", "=", "cell", "builder", ".", "define_cell", "(", "name", ")", "if", "name", "cell", "end" ]
Creates a new cell with the given name and generates shortcut accessors for the method.
[ "Creates", "a", "new", "cell", "with", "the", "given", "name", "and", "generates", "shortcut", "accessors", "for", "the", "method", "." ]
8456c014f919b344b4bf6261b7eab055d888d945
https://github.com/pluginaweek/table_helper/blob/8456c014f919b344b4bf6261b7eab055d888d945/lib/table_helper/row.rb#L75-L87
train
pluginaweek/table_helper
lib/table_helper/header.rb
TableHelper.Header.column
def column(*names) # Clear the header row if this is being customized by the user unless @customized @customized = true clear end # Extract configuration options = names.last.is_a?(Hash) ? names.pop : {} content = names.last.is_a?(String) ? names.pop : nil args = [content, options].compact names.collect! do |name| column = row.cell(name, *args) column.content_type = :header column[:scope] ||= 'col' column end names.length == 1 ? names.first : names end
ruby
def column(*names) # Clear the header row if this is being customized by the user unless @customized @customized = true clear end # Extract configuration options = names.last.is_a?(Hash) ? names.pop : {} content = names.last.is_a?(String) ? names.pop : nil args = [content, options].compact names.collect! do |name| column = row.cell(name, *args) column.content_type = :header column[:scope] ||= 'col' column end names.length == 1 ? names.first : names end
[ "def", "column", "(", "*", "names", ")", "unless", "@customized", "@customized", "=", "true", "clear", "end", "options", "=", "names", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "names", ".", "pop", ":", "{", "}", "content", "=", "names", ".", "last", ".", "is_a?", "(", "String", ")", "?", "names", ".", "pop", ":", "nil", "args", "=", "[", "content", ",", "options", "]", ".", "compact", "names", ".", "collect!", "do", "|", "name", "|", "column", "=", "row", ".", "cell", "(", "name", ",", "*", "args", ")", "column", ".", "content_type", "=", ":header", "column", "[", ":scope", "]", "||=", "'col'", "column", "end", "names", ".", "length", "==", "1", "?", "names", ".", "first", ":", "names", "end" ]
Creates one or more to columns in the header. This will clear any pre-existing columns if it is being customized for the first time after it was initially created.
[ "Creates", "one", "or", "more", "to", "columns", "in", "the", "header", ".", "This", "will", "clear", "any", "pre", "-", "existing", "columns", "if", "it", "is", "being", "customized", "for", "the", "first", "time", "after", "it", "was", "initially", "created", "." ]
8456c014f919b344b4bf6261b7eab055d888d945
https://github.com/pluginaweek/table_helper/blob/8456c014f919b344b4bf6261b7eab055d888d945/lib/table_helper/header.rb#L70-L90
train
pluginaweek/table_helper
lib/table_helper/header.rb
TableHelper.Header.html
def html html_options = @html_options.dup html_options[:style] = 'display: none;' if table.empty? && hide_when_empty content_tag(tag_name, content, html_options) end
ruby
def html html_options = @html_options.dup html_options[:style] = 'display: none;' if table.empty? && hide_when_empty content_tag(tag_name, content, html_options) end
[ "def", "html", "html_options", "=", "@html_options", ".", "dup", "html_options", "[", ":style", "]", "=", "'display: none;'", "if", "table", ".", "empty?", "&&", "hide_when_empty", "content_tag", "(", "tag_name", ",", "content", ",", "html_options", ")", "end" ]
Creates and returns the generated html for the header
[ "Creates", "and", "returns", "the", "generated", "html", "for", "the", "header" ]
8456c014f919b344b4bf6261b7eab055d888d945
https://github.com/pluginaweek/table_helper/blob/8456c014f919b344b4bf6261b7eab055d888d945/lib/table_helper/header.rb#L93-L98
train
Lax/aliyun
lib/aliyun/common.rb
Aliyun.Service.gen_request_parameters
def gen_request_parameters method, params #add common parameters params.merge! self.service.default_parameters params.merge! self.options params[:Action] = method.to_s params[:Timestamp] = Time.now.utc.iso8601 params[:SignatureNonce] = SecureRandom.uuid params[:Signature] = compute_signature params params end
ruby
def gen_request_parameters method, params #add common parameters params.merge! self.service.default_parameters params.merge! self.options params[:Action] = method.to_s params[:Timestamp] = Time.now.utc.iso8601 params[:SignatureNonce] = SecureRandom.uuid params[:Signature] = compute_signature params params end
[ "def", "gen_request_parameters", "method", ",", "params", "params", ".", "merge!", "self", ".", "service", ".", "default_parameters", "params", ".", "merge!", "self", ".", "options", "params", "[", ":Action", "]", "=", "method", ".", "to_s", "params", "[", ":Timestamp", "]", "=", "Time", ".", "now", ".", "utc", ".", "iso8601", "params", "[", ":SignatureNonce", "]", "=", "SecureRandom", ".", "uuid", "params", "[", ":Signature", "]", "=", "compute_signature", "params", "params", "end" ]
generate the parameters
[ "generate", "the", "parameters" ]
abbc3dd3a3ca5e1514d5994965d87d590b714301
https://github.com/Lax/aliyun/blob/abbc3dd3a3ca5e1514d5994965d87d590b714301/lib/aliyun/common.rb#L65-L77
train
Lax/aliyun
lib/aliyun/common.rb
Aliyun.Service.compute_signature
def compute_signature params if $DEBUG puts "keys before sorted: #{params.keys}" end sorted_keys = params.keys.sort if $DEBUG puts "keys after sorted: #{sorted_keys}" end canonicalized_query_string = "" canonicalized_query_string = sorted_keys.map {|key| "%s=%s" % [safe_encode(key.to_s), safe_encode(params[key])] }.join(self.service.separator) length = canonicalized_query_string.length string_to_sign = self.service.http_method + self.service.separator + safe_encode('/') + self.service.separator + safe_encode(canonicalized_query_string) if $DEBUG puts "string_to_sign is #{string_to_sign}" end signature = calculate_signature access_key_secret+"&", string_to_sign end
ruby
def compute_signature params if $DEBUG puts "keys before sorted: #{params.keys}" end sorted_keys = params.keys.sort if $DEBUG puts "keys after sorted: #{sorted_keys}" end canonicalized_query_string = "" canonicalized_query_string = sorted_keys.map {|key| "%s=%s" % [safe_encode(key.to_s), safe_encode(params[key])] }.join(self.service.separator) length = canonicalized_query_string.length string_to_sign = self.service.http_method + self.service.separator + safe_encode('/') + self.service.separator + safe_encode(canonicalized_query_string) if $DEBUG puts "string_to_sign is #{string_to_sign}" end signature = calculate_signature access_key_secret+"&", string_to_sign end
[ "def", "compute_signature", "params", "if", "$DEBUG", "puts", "\"keys before sorted: #{params.keys}\"", "end", "sorted_keys", "=", "params", ".", "keys", ".", "sort", "if", "$DEBUG", "puts", "\"keys after sorted: #{sorted_keys}\"", "end", "canonicalized_query_string", "=", "\"\"", "canonicalized_query_string", "=", "sorted_keys", ".", "map", "{", "|", "key", "|", "\"%s=%s\"", "%", "[", "safe_encode", "(", "key", ".", "to_s", ")", ",", "safe_encode", "(", "params", "[", "key", "]", ")", "]", "}", ".", "join", "(", "self", ".", "service", ".", "separator", ")", "length", "=", "canonicalized_query_string", ".", "length", "string_to_sign", "=", "self", ".", "service", ".", "http_method", "+", "self", ".", "service", ".", "separator", "+", "safe_encode", "(", "'/'", ")", "+", "self", ".", "service", ".", "separator", "+", "safe_encode", "(", "canonicalized_query_string", ")", "if", "$DEBUG", "puts", "\"string_to_sign is #{string_to_sign}\"", "end", "signature", "=", "calculate_signature", "access_key_secret", "+", "\"&\"", ",", "string_to_sign", "end" ]
compute the signature of the parameters String
[ "compute", "the", "signature", "of", "the", "parameters", "String" ]
abbc3dd3a3ca5e1514d5994965d87d590b714301
https://github.com/Lax/aliyun/blob/abbc3dd3a3ca5e1514d5994965d87d590b714301/lib/aliyun/common.rb#L80-L106
train
Lax/aliyun
lib/aliyun/common.rb
Aliyun.Service.calculate_signature
def calculate_signature key, string_to_sign hmac = HMAC::SHA1.new(key) hmac.update(string_to_sign) signature = Base64.encode64(hmac.digest).gsub("\n", '') if $DEBUG puts "Signature #{signature}" end signature end
ruby
def calculate_signature key, string_to_sign hmac = HMAC::SHA1.new(key) hmac.update(string_to_sign) signature = Base64.encode64(hmac.digest).gsub("\n", '') if $DEBUG puts "Signature #{signature}" end signature end
[ "def", "calculate_signature", "key", ",", "string_to_sign", "hmac", "=", "HMAC", "::", "SHA1", ".", "new", "(", "key", ")", "hmac", ".", "update", "(", "string_to_sign", ")", "signature", "=", "Base64", ".", "encode64", "(", "hmac", ".", "digest", ")", ".", "gsub", "(", "\"\\n\"", ",", "''", ")", "if", "$DEBUG", "puts", "\"Signature #{signature}\"", "end", "signature", "end" ]
calculate the signature
[ "calculate", "the", "signature" ]
abbc3dd3a3ca5e1514d5994965d87d590b714301
https://github.com/Lax/aliyun/blob/abbc3dd3a3ca5e1514d5994965d87d590b714301/lib/aliyun/common.rb#L109-L117
train
nofxx/subtitle_it
lib/subtitle_it/subtitle.rb
SubtitleIt.Subtitle.encode_dump
def encode_dump(dump) dump = dump.read unless dump.is_a?(String) enc = CharlockHolmes::EncodingDetector.detect(dump) if enc[:encoding] != 'UTF-8' puts "Converting `#{enc[:encoding]}` to `UTF-8`".yellow dump = CharlockHolmes::Converter.convert dump, enc[:encoding], 'UTF-8' end dump end
ruby
def encode_dump(dump) dump = dump.read unless dump.is_a?(String) enc = CharlockHolmes::EncodingDetector.detect(dump) if enc[:encoding] != 'UTF-8' puts "Converting `#{enc[:encoding]}` to `UTF-8`".yellow dump = CharlockHolmes::Converter.convert dump, enc[:encoding], 'UTF-8' end dump end
[ "def", "encode_dump", "(", "dump", ")", "dump", "=", "dump", ".", "read", "unless", "dump", ".", "is_a?", "(", "String", ")", "enc", "=", "CharlockHolmes", "::", "EncodingDetector", ".", "detect", "(", "dump", ")", "if", "enc", "[", ":encoding", "]", "!=", "'UTF-8'", "puts", "\"Converting `#{enc[:encoding]}` to `UTF-8`\"", ".", "yellow", "dump", "=", "CharlockHolmes", "::", "Converter", ".", "convert", "dump", ",", "enc", "[", ":encoding", "]", ",", "'UTF-8'", "end", "dump", "end" ]
Force subtitles to be UTF-8
[ "Force", "subtitles", "to", "be", "UTF", "-", "8" ]
21ba59f4ebd860b1c9127f60eed9e0d3077f1bca
https://github.com/nofxx/subtitle_it/blob/21ba59f4ebd860b1c9127f60eed9e0d3077f1bca/lib/subtitle_it/subtitle.rb#L66-L75
train
BlockScore/blockscore-ruby
lib/blockscore/collection.rb
BlockScore.Collection.create
def create(params = {}) fail Error, 'Create parent first' unless parent.id assoc_params = default_params.merge(params) add_instance(member_class.create(assoc_params)) end
ruby
def create(params = {}) fail Error, 'Create parent first' unless parent.id assoc_params = default_params.merge(params) add_instance(member_class.create(assoc_params)) end
[ "def", "create", "(", "params", "=", "{", "}", ")", "fail", "Error", ",", "'Create parent first'", "unless", "parent", ".", "id", "assoc_params", "=", "default_params", ".", "merge", "(", "params", ")", "add_instance", "(", "member_class", ".", "create", "(", "assoc_params", ")", ")", "end" ]
Initialize a collection member and save it @example >> person.question_sets.create => #<BlockScore::QuestionSet:0x3fc67a6007f4 JSON:{ "object": "question_set", "id": "55ef5d5b62386200030001b3", "created_at": 1441750363, ... } @param params [Hash] params @return new saved instance of {member_class} @api public
[ "Initialize", "a", "collection", "member", "and", "save", "it" ]
3f837729f9997d92468966e4478ea2f4aaea0156
https://github.com/BlockScore/blockscore-ruby/blob/3f837729f9997d92468966e4478ea2f4aaea0156/lib/blockscore/collection.rb#L113-L118
train
BlockScore/blockscore-ruby
lib/blockscore/collection.rb
BlockScore.Collection.retrieve
def retrieve(id) each do |item| return item if item.id.eql?(id) end add_instance(member_class.retrieve(id)) end
ruby
def retrieve(id) each do |item| return item if item.id.eql?(id) end add_instance(member_class.retrieve(id)) end
[ "def", "retrieve", "(", "id", ")", "each", "do", "|", "item", "|", "return", "item", "if", "item", ".", "id", ".", "eql?", "(", "id", ")", "end", "add_instance", "(", "member_class", ".", "retrieve", "(", "id", ")", ")", "end" ]
Retrieve a collection member by its id @example usage person.question_sets.retrieve('55ef5b4e3532630003000178') => instance of QuestionSet @param id [String] resource id @return instance of {member_class} if found @raise [BlockScore::NotFoundError] otherwise @api public
[ "Retrieve", "a", "collection", "member", "by", "its", "id" ]
3f837729f9997d92468966e4478ea2f4aaea0156
https://github.com/BlockScore/blockscore-ruby/blob/3f837729f9997d92468966e4478ea2f4aaea0156/lib/blockscore/collection.rb#L132-L138
train
BlockScore/blockscore-ruby
lib/blockscore/collection.rb
BlockScore.Collection.parent_id?
def parent_id?(item) parent.id && item.send(foreign_key).eql?(parent.id) end
ruby
def parent_id?(item) parent.id && item.send(foreign_key).eql?(parent.id) end
[ "def", "parent_id?", "(", "item", ")", "parent", ".", "id", "&&", "item", ".", "send", "(", "foreign_key", ")", ".", "eql?", "(", "parent", ".", "id", ")", "end" ]
Check if `parent_id` is defined on `item` @param item [BlockScore::Base] any resource @return [Boolean] @api private
[ "Check", "if", "parent_id", "is", "defined", "on", "item" ]
3f837729f9997d92468966e4478ea2f4aaea0156
https://github.com/BlockScore/blockscore-ruby/blob/3f837729f9997d92468966e4478ea2f4aaea0156/lib/blockscore/collection.rb#L194-L196
train