_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3
values | text stringlengths 66 10.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q23300 | Humidifier.Stack.add | train | def add(name, resource, attributes = {})
resources[name] = resource
resource.update_attributes(attributes) if attributes.any?
resource
end | ruby | {
"resource": ""
} |
q23301 | Humidifier.Stack.to_cf | train | def to_cf(serializer = :json)
resources = static_resources.merge(enumerable_resources)
case serializer
when :json then JSON.pretty_generate(resources)
when :yaml then YAML.dump(resources)
end
end | ruby | {
"resource": ""
} |
q23302 | CukeSlicer.Slicer.slice | train | def slice(target, filters = {}, format, &block)
validate_target(target)
validate_filters(filters)
validate_format(format)
begin
target = File.directory?(target) ? CukeModeler::Directory.new(target) : CukeModeler::FeatureFile.new(target)
rescue => e
if e.message =~ /lexing|... | ruby | {
"resource": ""
} |
q23303 | IIIF.OrderedHash.insert | train | def insert(index, key, value)
tmp = IIIF::OrderedHash.new
index = self.length + 1 + index if index < 0
if index < 0
m = "Index #{index} is too small for current length (#{length})"
raise IndexError, m
end
if index > 0
i=0
self.each do |k,v|
tmp[k] ... | ruby | {
"resource": ""
} |
q23304 | IIIF.OrderedHash.remove_empties | train | def remove_empties
self.keys.each do |key|
if (self[key].kind_of?(Array) && self[key].empty?) || self[key].nil?
self.delete(key)
end
end
end | ruby | {
"resource": ""
} |
q23305 | IIIF.OrderedHash.camelize_keys | train | def camelize_keys
self.keys.each_with_index do |key, i|
if key != key.camelize(:lower)
self.insert(i, key.camelize(:lower), self[key])
self.delete(key)
end
end
self
end | ruby | {
"resource": ""
} |
q23306 | IIIF.OrderedHash.snakeize_keys | train | def snakeize_keys
self.keys.each_with_index do |key, i|
if key != key.underscore
self.insert(i, key.underscore, self[key])
self.delete(key)
end
end
self
end | ruby | {
"resource": ""
} |
q23307 | KingDta.Dtazv.add_z | train | def add_z(bookings)
data3 = '0256'
data3 += 'Z'
sum = 0
bookings.each do |b|
sum += b.value.divmod(100)[0]
end
data3 += '%015i' % sum
data3 += '%015i' % bookings.count
data3 += '%0221s' % ''
raise "DTAUS: Längenfehler Z (#{data3.size} <> 256)\n" if dat... | ruby | {
"resource": ""
} |
q23308 | IIIF.HashBehaviours.select | train | def select
new_instance = self.class.new
if block_given?
@data.each { |k,v| new_instance.data[k] = v if yield(k,v) }
end
return new_instance
end | ruby | {
"resource": ""
} |
q23309 | KingDta.Account.bank_account_number= | train | def bank_account_number=(number)
raise ArgumentError.new('Bank account number cannot be nil') if number.nil?
nr_str = "#{number}".gsub(/\s/,'')
raise ArgumentError.new('Bank account number too long, max 10 allowed') if nr_str.length > 10
raise ArgumentError.new('Bank account number cannot be 0')... | ruby | {
"resource": ""
} |
q23310 | Scheduler.Base.time | train | def time
if Time.respond_to?(:zone) && Time.zone
self.class.send(:define_method, :time) { Time.zone.now.to_s }
else
self.class.send(:define_method, :time) { Time.now.to_s }
end
time
end | ruby | {
"resource": ""
} |
q23311 | Bandit.RedisStorage.init | train | def init(key, value)
with_failure_grace(value) {
@redis.set(key, value) if get(key, nil).nil?
}
end | ruby | {
"resource": ""
} |
q23312 | Bandit.RedisStorage.get | train | def get(key, default=0)
with_failure_grace(default) {
val = @redis.get(key)
return default if val.nil?
val.numeric? ? val.to_i : val
}
end | ruby | {
"resource": ""
} |
q23313 | Bandit.ViewConcerns.bandit_session_choose | train | def bandit_session_choose(exp)
name = "bandit_#{exp}".intern
# choose url param with preference
value = params[name].nil? ? cookies.signed[name] : params[name]
# choose with default, and set cookie
cookies.signed[name] = Bandit.get_experiment(exp).choose(value)
end | ruby | {
"resource": ""
} |
q23314 | Bandit.ViewConcerns.bandit_sticky_choose | train | def bandit_sticky_choose(exp)
name = "bandit_#{exp}".intern
# choose url param with preference
value = params[name].nil? ? cookies.signed[name] : params[name]
# sticky choice may outlast a given alternative
alternative = if Bandit.get_experiment(exp).alternatives.include?(value)
... | ruby | {
"resource": ""
} |
q23315 | RubyAem.Aem.sanitise_conf | train | def sanitise_conf(conf)
conf[:username] ||= 'admin'
conf[:password] ||= 'admin'
conf[:protocol] ||= 'http'
conf[:host] ||= 'localhost'
conf[:port] ||= 4502
conf[:timeout] ||= 300
# handle custom configuration value being passed as a String
# e.g. when the values are passe... | ruby | {
"resource": ""
} |
q23316 | RubyAem.Aem.config_property | train | def config_property(name, type, value)
RubyAem::Resources::ConfigProperty.new(@client, name, type, value)
end | ruby | {
"resource": ""
} |
q23317 | RubyAem.Aem.package | train | def package(group_name, package_name, package_version)
RubyAem::Resources::Package.new(@client, group_name, package_name, package_version)
end | ruby | {
"resource": ""
} |
q23318 | Bandit.BaseStorage.part_key | train | def part_key(exp, alt, date_hour=nil)
parts = [ "participants", exp.name, alt ]
parts += [ date_hour.date, date_hour.hour ] unless date_hour.nil?
make_key parts
end | ruby | {
"resource": ""
} |
q23319 | OAuthenticator.RackAuthenticator.unauthenticated_response | train | def unauthenticated_response(errors)
# default to a blank realm, I suppose
realm = @options[:realm] || ''
response_headers = {"WWW-Authenticate" => %Q(OAuth realm="#{realm}"), 'Content-Type' => 'application/json'}
body = {'errors' => errors}
error_message = begin
error_values = er... | ruby | {
"resource": ""
} |
q23320 | Bandit.ControllerConcerns.bandit_simple_convert! | train | def bandit_simple_convert!(exp, alt, count=1)
Bandit.get_experiment(exp).convert!(alt, count)
end | ruby | {
"resource": ""
} |
q23321 | Bandit.ControllerConcerns.bandit_session_convert! | train | def bandit_session_convert!(exp, alt=nil, count=1)
cookiename = "bandit_#{exp}".intern
cookiename_converted = "bandit_#{exp}_converted".intern
alt ||= cookies.signed[cookiename]
unless alt.nil? or cookies.signed[cookiename_converted]
Bandit.get_experiment(exp).convert!(alt, count)
... | ruby | {
"resource": ""
} |
q23322 | Bandit.ControllerConcerns.bandit_sticky_convert! | train | def bandit_sticky_convert!(exp, alt=nil, count=1)
cookiename = "bandit_#{exp}".intern
cookiename_converted = "bandit_#{exp}_converted".intern
alt ||= cookies.signed[cookiename]
unless alt.nil? or cookies.signed[cookiename_converted]
cookies.permanent.signed[cookiename_converted] = "true"... | ruby | {
"resource": ""
} |
q23323 | ELFTools.Dynamic.each_tags | train | def each_tags(&block)
return enum_for(:each_tags) unless block_given?
arr = []
0.step do |i|
tag = tag_at(i).tap(&block)
arr << tag
break if tag.header.d_tag == ELFTools::Constants::DT_NULL
end
arr
end | ruby | {
"resource": ""
} |
q23324 | ELFTools.Dynamic.tag_at | train | def tag_at(n)
return if n < 0
@tag_at_map ||= {}
return @tag_at_map[n] if @tag_at_map[n]
dyn = Structs::ELF_Dyn.new(endian: endian)
dyn.elf_class = header.elf_class
stream.pos = tag_start + n * dyn.num_bytes
dyn.offset = stream.pos
@tag_at_map[n] = Tag.new(dyn.read(stre... | ruby | {
"resource": ""
} |
q23325 | ELFTools.ELFFile.build_id | train | def build_id
section = section_by_name('.note.gnu.build-id')
return nil if section.nil?
note = section.notes.first
return nil if note.nil?
note.desc.unpack('H*').first
end | ruby | {
"resource": ""
} |
q23326 | ELFTools.ELFFile.each_sections | train | def each_sections(&block)
return enum_for(:each_sections) unless block_given?
Array.new(num_sections) do |i|
section_at(i).tap(&block)
end
end | ruby | {
"resource": ""
} |
q23327 | ELFTools.ELFFile.sections_by_type | train | def sections_by_type(type, &block)
type = Util.to_constant(Constants::SHT, type)
Util.select_by_type(each_sections, type, &block)
end | ruby | {
"resource": ""
} |
q23328 | ELFTools.ELFFile.each_segments | train | def each_segments(&block)
return enum_for(:each_segments) unless block_given?
Array.new(num_segments) do |i|
segment_at(i).tap(&block)
end
end | ruby | {
"resource": ""
} |
q23329 | ELFTools.ELFFile.segments_by_type | train | def segments_by_type(type, &block)
type = Util.to_constant(Constants::PT, type)
Util.select_by_type(each_segments, type, &block)
end | ruby | {
"resource": ""
} |
q23330 | ELFTools.ELFFile.offset_from_vma | train | def offset_from_vma(vma, size = 0)
segments_by_type(:load) do |seg|
return seg.vma_to_offset(vma) if seg.vma_in?(vma, size)
end
end | ruby | {
"resource": ""
} |
q23331 | ELFTools.ELFFile.patches | train | def patches
patch = {}
loaded_headers.each do |header|
header.patches.each do |key, val|
patch[key + header.offset] = val
end
end
patch
end | ruby | {
"resource": ""
} |
q23332 | ELFTools.ELFFile.save | train | def save(filename)
stream.pos = 0
all = stream.read.force_encoding('ascii-8bit')
patches.each do |pos, val|
all[pos, val.size] = val
end
IO.binwrite(filename, all)
end | ruby | {
"resource": ""
} |
q23333 | ELFTools.ELFFile.loaded_headers | train | def loaded_headers
explore = lambda do |obj|
return obj if obj.is_a?(::ELFTools::Structs::ELFStruct)
return obj.map(&explore) if obj.is_a?(Array)
obj.instance_variables.map do |s|
explore.call(obj.instance_variable_get(s))
end
end
explore.call(self).flatten
... | ruby | {
"resource": ""
} |
q23334 | HttpParser.Parser.parse | train | def parse(inst, data)
::HttpParser.http_parser_execute(inst, @settings, data, data.length)
return inst.error?
end | ruby | {
"resource": ""
} |
q23335 | RubyAem.Client.call | train | def call(clazz, action, call_params)
resource_name = clazz.name.downcase.sub('rubyaem::resources::', '')
resource = @spec[resource_name]
action_spec = resource['actions'][action]
api = @apis[action_spec['api'].to_sym]
operation = action_spec['operation']
params = []
required_... | ruby | {
"resource": ""
} |
q23336 | RubyAem.Client.add_optional_param | train | def add_optional_param(key, value, params, call_params)
# if there is no value in optional param spec,
# then only add optional param that is set in call parameters
if !value
params[-1][key.to_sym] = call_params[key.to_sym] if call_params.key? key.to_sym
# if value is provided in optiona... | ruby | {
"resource": ""
} |
q23337 | RubyAem.Client.handle | train | def handle(response, responses_spec, call_params)
if responses_spec.key?(response.status_code)
response_spec = responses_spec[response.status_code]
handler = response_spec['handler']
Handlers.send(handler, response, response_spec, call_params)
else
message = "Unexpected respo... | ruby | {
"resource": ""
} |
q23338 | Evercookie.EvercookieController.save | train | def save
if data = session[Evercookie.hash_name_for_get]
if data[:key] && cookies[data[:key]]
session[Evercookie.hash_name_for_saved] =
{ data[:key] => cookies[data[:key]] }
end
end
render nothing: true
end | ruby | {
"resource": ""
} |
q23339 | Evercookie.EvercookieController.ec_png | train | def ec_png
if not cookies[Evercookie.cookie_png].present?
render :nothing => true, :status => 304
return true
end
response.headers["Content-Type"] = "image/png"
response.headers["Last-Modified"] = "Wed, 30 Jun 2010 21:36:48 GMT"
response.headers["Expires"] = "Tue, 31 Dec 2... | ruby | {
"resource": ""
} |
q23340 | Evercookie.EvercookieController.ec_etag | train | def ec_etag
if not cookies[Evercookie.cookie_etag].present?
render :text => request.headers['If-None-Match'] || '', :status => 304
return true
end
puts "cache value (#{Evercookie.cookie_etag}): #{cookies[Evercookie.cookie_etag]}"
response.headers["Etag"] = cookies[Evercookie.co... | ruby | {
"resource": ""
} |
q23341 | Evercookie.EvercookieController.ec_cache | train | def ec_cache
if not cookies[Evercookie.cookie_cache].present?
render :nothing => true, :status => 304
return true
end
puts "cache value (#{Evercookie.cookie_cache}): #{cookies[Evercookie.cookie_cache]}"
response.headers["Content-Type"] = "text/html"
response.headers["Last... | ruby | {
"resource": ""
} |
q23342 | ELFTools.Note.each_notes | train | def each_notes
return enum_for(:each_notes) unless block_given?
@notes_offset_map ||= {}
cur = note_start
notes = []
while cur < note_start + note_total_size
stream.pos = cur
@notes_offset_map[cur] ||= create_note(cur)
note = @notes_offset_map[cur]
# name a... | ruby | {
"resource": ""
} |
q23343 | OAuthenticator.SignedRequest.config_method_not_implemented | train | def config_method_not_implemented
caller_name = caller[0].match(%r(in `(.*?)'))[1]
using_middleware = caller.any? { |l| l =~ %r(oauthenticator/rack_authenticator.rb:.*`call') }
message = "method \##{caller_name} must be implemented on a module of oauth config methods, which is " + begin
if usi... | ruby | {
"resource": ""
} |
q23344 | HttpParser.Instance.error | train | def error
error = (self[:error_upgrade] & 0b1111111)
return nil if error == 0
err = ::HttpParser.err_name(error)[4..-1] # HPE_ is at the start of all these errors
klass = ERRORS[err.to_sym]
err = "#{::HttpParser.err_desc(error)} (#{err})"
return k... | ruby | {
"resource": ""
} |
q23345 | OAuthenticator.FaradaySigner.call | train | def call(request_env)
media_type = Rack::Request.new('CONTENT_TYPE' => request_env[:request_headers]['Content-Type']).media_type
request_attributes = {
:request_method => request_env[:method],
:uri => request_env[:url],
:media_type => media_type,
:body => request_env[:body]
... | ruby | {
"resource": ""
} |
q23346 | OAuthenticator.SignableRequest.signature_base | train | def signature_base
parts = [normalized_request_method, base_string_uri, normalized_request_params_string]
parts.map { |v| OAuthenticator.escape(v) }.join('&')
end | ruby | {
"resource": ""
} |
q23347 | OAuthenticator.SignableRequest.base_string_uri | train | def base_string_uri
Addressable::URI.parse(@attributes['uri'].to_s).tap do |uri|
uri.scheme = uri.scheme.downcase if uri.scheme
uri.host = uri.host.downcase if uri.host
uri.normalize!
uri.fragment = nil
uri.query = nil
end.to_s
end | ruby | {
"resource": ""
} |
q23348 | OAuthenticator.SignableRequest.normalized_request_params_string | train | def normalized_request_params_string
normalized_request_params.map { |kv| kv.map { |v| OAuthenticator.escape(v) } }.sort.map { |p| p.join('=') }.join('&')
end | ruby | {
"resource": ""
} |
q23349 | OAuthenticator.SignableRequest.normalized_request_params | train | def normalized_request_params
query_params + protocol_params.reject { |k,v| %w(realm oauth_signature).include?(k) }.to_a + entity_params
end | ruby | {
"resource": ""
} |
q23350 | OAuthenticator.SignableRequest.parse_form_encoded | train | def parse_form_encoded(data)
data.split(/[&;]/).map do |pair|
key, value = pair.split('=', 2).map { |v| CGI::unescape(v) }
[key, value] unless [nil, ''].include?(key)
end.compact
end | ruby | {
"resource": ""
} |
q23351 | OAuthenticator.SignableRequest.read_body | train | def read_body
body = @attributes['body']
if body.nil?
''
elsif body.is_a?(String)
body
elsif body.respond_to?(:read) && body.respond_to?(:rewind)
body.rewind
body.read.tap do
body.rewind
end
else
raise TypeError, "Body must be a Str... | ruby | {
"resource": ""
} |
q23352 | OAuthenticator.SignableRequest.rsa_sha1_signature | train | def rsa_sha1_signature
private_key = OpenSSL::PKey::RSA.new(@attributes['consumer_secret'])
Base64.encode64(private_key.sign(OpenSSL::Digest::SHA1.new, signature_base)).gsub(/\n/, '')
end | ruby | {
"resource": ""
} |
q23353 | OAuthenticator.SignableRequest.hmac_sha1_signature | train | def hmac_sha1_signature
# hmac secret is same as plaintext signature
secret = plaintext_signature
Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest::SHA1.new, secret, signature_base)).gsub(/\n/, '')
end | ruby | {
"resource": ""
} |
q23354 | Tetra.Bash.bash | train | def bash(command = nil)
Tempfile.open("tetra-history") do |history_file|
Tempfile.open("tetra-bashrc") do |bashrc_file|
kit = Tetra::Kit.new(@project)
ant_path = kit.find_executable("ant")
ant_in_kit = ant_path != nil
ant_commandline = Tetra::Ant.commandline(@projec... | ruby | {
"resource": ""
} |
q23355 | Serverspec.Type.bitlbee | train | def bitlbee(port, nick, password, use_ssl=false)
Bitlbee.new(port, nick, password, use_ssl)
end | ruby | {
"resource": ""
} |
q23356 | Tetra.Git.commit_directories | train | def commit_directories(directories, message)
log.debug "committing with message: #{message}"
Dir.chdir(@directory) do
directories.each do |directory|
run("git rm -r --cached --ignore-unmatch #{directory}")
run("git add #{directory}")
end
run("git commit --allow-e... | ruby | {
"resource": ""
} |
q23357 | Tetra.Git.commit_file | train | def commit_file(path, message)
Dir.chdir(@directory) do
log.debug "committing path #{path} with message: #{message}"
run("git add #{path}")
run("git commit --allow-empty -F -", false, message)
end
end | ruby | {
"resource": ""
} |
q23358 | Tetra.Git.revert_directories | train | def revert_directories(directories, id)
Dir.chdir(@directory) do
directories.each do |directory|
# reverts added and modified files, both in index and working tree
run("git checkout -f #{id} -- #{directory}")
# compute the list of deleted files
files_in_commit = ru... | ruby | {
"resource": ""
} |
q23359 | Tetra.Git.disable_special_files | train | def disable_special_files(path)
Dir.chdir(File.join(@directory, path)) do
Find.find(".") do |file|
next unless file =~ /\.git(ignore)?$/
FileUtils.mv(file, "#{file}_disabled_by_tetra")
end
end
end | ruby | {
"resource": ""
} |
q23360 | Tetra.Git.merge_with_id | train | def merge_with_id(path, new_path, id)
Dir.chdir(@directory) do
run("git show #{id}:#{path} > #{path}.old_version")
conflict_count = 0
begin
run("git merge-file #{path} #{path}.old_version #{new_path} \
-L \"newly generated\" \
-L \"previously gene... | ruby | {
"resource": ""
} |
q23361 | Tetra.Git.changed_files | train | def changed_files(directory, id)
Dir.chdir(@directory) do
tracked_files = []
begin
tracked_files += run("git diff-index --name-only #{id} -- #{directory}").split
rescue ExecutionFailed => e
raise e if e.status != 1 # status 1 is normal
end
untracked_fil... | ruby | {
"resource": ""
} |
q23362 | Tetra.Git.archive | train | def archive(directory, id, destination_path)
Dir.chdir(@directory) do
FileUtils.mkdir_p(File.dirname(destination_path))
run("git archive --format=tar #{id} -- #{directory} | xz -9e > #{destination_path}")
end
destination_path
end | ruby | {
"resource": ""
} |
q23363 | Tetra.Subcommand.configure_log_level | train | def configure_log_level(v, vv, vvv)
if vvv
log.level = ::Logger::DEBUG
elsif vv
log.level = ::Logger::INFO
elsif v
log.level = ::Logger::WARN
else
log.level = ::Logger::ERROR
end
end | ruby | {
"resource": ""
} |
q23364 | Tetra.Subcommand.bypass_parsing | train | def bypass_parsing(args)
log.level = ::Logger::WARN if args.delete "--verbose"
log.level = ::Logger::INFO if args.delete "--very-verbose"
log.level = ::Logger::DEBUG if args.delete "--very-very-verbose"
@options = args
end | ruby | {
"resource": ""
} |
q23365 | Tetra.Subcommand.format_path | train | def format_path(path, project)
full_path = (
if Pathname.new(path).relative?
File.join(project.full_path, path)
else
path
end
)
Pathname.new(full_path).relative_path_from(Pathname.new(Dir.pwd))
end | ruby | {
"resource": ""
} |
q23366 | Tetra.Subcommand.checking_exceptions | train | def checking_exceptions
yield
rescue Errno::EACCES => e
$stderr.puts e
rescue Errno::ENOENT => e
$stderr.puts e
rescue Errno::EEXIST => e
$stderr.puts e
rescue NoProjectDirectoryError => e
$stderr.puts "#{e.directory} is not a tetra project directory, see \"tetra init\""
... | ruby | {
"resource": ""
} |
q23367 | Buildbox.Canceler.process_map | train | def process_map
output = `ps -eo ppid,pid`
processes = {}
output.split("\n").each do |line|
if result = line.match(/(\d+)\s(\d+)/)
parent = result[1].to_i
child = result[2].to_i
processes[parent] ||= []
processes[parent] << child
end
... | ruby | {
"resource": ""
} |
q23368 | Buildbox.Command.read_io | train | def read_io(io)
data = ""
while true
begin
if Platform.windows?
# Windows doesn't support non-blocking reads on
# file descriptors or pipes so we have to get
# a bit more creative.
# Check if data is actually ready on this IO device.
... | ruby | {
"resource": ""
} |
q23369 | Serverspec::Type.Virtualenv.virtualenv? | train | def virtualenv?
pip_path = ::File.join(@name, 'bin', 'pip')
python_path = ::File.join(@name, 'bin', 'python')
act_path = ::File.join(@name, 'bin', 'activate')
cmd = "grep -q 'export VIRTUAL_ENV' #{act_path}"
@runner.check_file_is_executable(pip_path, 'owner') and
@runner.check_file... | ruby | {
"resource": ""
} |
q23370 | Tetra.ProcessRunner.run_interactive | train | def run_interactive(command)
log.debug "running `#{command}`"
success = system({}, command)
log.debug "`#{command}` exited with success #{success}"
fail ExecutionFailed.new(command, $CHILD_STATUS, nil, nil) unless success
end | ruby | {
"resource": ""
} |
q23371 | Tetra.Project.merge_new_content | train | def merge_new_content(new_content, path, comment, kind)
from_directory do
log.debug "merging new content to #{path} of kind #{kind}"
already_existing = File.exist?(path)
generated_comment = "tetra: generated-#{kind}"
whole_comment = [comment, generated_comment].join("\n\n")
... | ruby | {
"resource": ""
} |
q23372 | Tetra.Project.src_archive | train | def src_archive
from_directory do
Find.find(File.join("packages", name)) do |file|
if File.file?(file) && file.match(/\.(spec)|(sh)|(patch)$/).nil?
return File.basename(file)
end
end
nil
end
end | ruby | {
"resource": ""
} |
q23373 | Docker.Swarm.authenticate! | train | def authenticate!(options = {}, connection = self.connection)
creds = options.to_json
connection.post('/auth', {}, :body => creds)
@creds = creds
true
rescue Docker::Error::ServerError, Docker::Error::UnauthorizedError
raise Docker::Error::AuthenticationError
end | ruby | {
"resource": ""
} |
q23374 | Docker.Swarm.validate_version! | train | def validate_version!
Docker.info
true
rescue Docker::Error::DockerError
raise Docker::Error::VersionError, "Expected API Version: #{API_VERSION}"
end | ruby | {
"resource": ""
} |
q23375 | Tetra.Mockers.create_mock_project | train | 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 | {
"resource": ""
} |
q23376 | Tetra.Mockers.create_mock_executable | train | 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.chmo... | ruby | {
"resource": ""
} |
q23377 | Tetra.PomGetter.get_pom_from_jar | train | 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
... | ruby | {
"resource": ""
} |
q23378 | Tetra.PomGetter.get_pom_from_sha1 | train | 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") }
... | ruby | {
"resource": ""
} |
q23379 | Tetra.PomGetter.get_pom_from_heuristic | train | 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)
... | ruby | {
"resource": ""
} |
q23380 | Tetra.Scriptable._to_script | train | 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... | ruby | {
"resource": ""
} |
q23381 | Tetra.Scriptable.aliases | train | 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 = Tetr... | ruby | {
"resource": ""
} |
q23382 | Tetra.ProjectIniter.template_files | train | 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
... | ruby | {
"resource": ""
} |
q23383 | Tetra.ProjectIniter.commit_source_archive | train | 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"... | ruby | {
"resource": ""
} |
q23384 | Serverspec.Type.http_get | train | 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 | {
"resource": ""
} |
q23385 | Tetra.Generatable.generate | train | def generate(template_name, object_binding)
erb = ERB.new(File.read(File.join(template_path, template_name)), nil, "<>")
erb.result(object_binding)
end | ruby | {
"resource": ""
} |
q23386 | SumologicCloudSyslog.Logger.log | train | 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 = ... | ruby | {
"resource": ""
} |
q23387 | PoiseLanguages.Utils.shelljoin | train | 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 | {
"resource": ""
} |
q23388 | PoiseLanguages.Utils.absolute_command | train | 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?... | ruby | {
"resource": ""
} |
q23389 | WorkflowRb.StepBuilder.then | train | 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)
... | ruby | {
"resource": ""
} |
q23390 | WorkflowRb.StepBuilder.input | train | def input(step_property, &value)
mapping = IOMapping.new
mapping.property = step_property
mapping.value = value
@step.inputs << mapping
self
end | ruby | {
"resource": ""
} |
q23391 | Rijndael.Base.decrypt | train | 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 =... | ruby | {
"resource": ""
} |
q23392 | Fluent.SumologicCloudSyslogOutput.logger | train | 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 | {
"resource": ""
} |
q23393 | Royce.Methods.add_role | train | 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 | {
"resource": ""
} |
q23394 | UTF8Utils.StringExt.tidy_bytes | train | 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]
... | ruby | {
"resource": ""
} |
q23395 | SetupAndTeardownAdapter.ClassMethods.setup | train | 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 | {
"resource": ""
} |
q23396 | FakedCSV.Config.parse | train | 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 ... | ruby | {
"resource": ""
} |
q23397 | HAProxy.Parser.parse_server_attributes | train | 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 "Inv... | ruby | {
"resource": ""
} |
q23398 | HAProxy.Parser.clean_parsed_server_attributes | train | def clean_parsed_server_attributes(pairs)
pairs.each do |k, v|
pairs[k] = if v.empty?
true
else
v.join(" ")
end
end
end | ruby | {
"resource": ""
} |
q23399 | JGrep.Parser.parse | train | 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
... | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.