_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q5700
|
StatModule.Finding.categories=
|
train
|
def categories=(categories)
raise TypeException unless categories.is_a?(Array)
categories.each { |item|
raise TypeException unless Category.all.include?(item)
raise DuplicateElementException if @categories.include?(item)
@categories.push(item)
}
end
|
ruby
|
{
"resource": ""
}
|
q5701
|
StatModule.Finding.print
|
train
|
def print(formatted = false)
result = "#{rule}, #{description}"
if formatted
if failure
result = "#{FORMATTING_BALL} #{result}".colorize(:red)
else
result = "#{FORMATTING_WARNING} #{result}".colorize(:yellow)
end
end
result += "\n#{location.print}" unless location.nil?
result += "\nRECOMMENDATION: #{recommendation}" unless recommendation.nil?
result
end
|
ruby
|
{
"resource": ""
}
|
q5702
|
Wanikani.CriticalItems.critical_items
|
train
|
def critical_items(percentage = 75)
raise ArgumentError, "Percentage must be an Integer between 0 and 100" if !percentage.between?(0, 100)
response = api_response("critical-items", percentage)
return response["requested_information"]
end
|
ruby
|
{
"resource": ""
}
|
q5703
|
Trepanning.Method.find_method_with_line
|
train
|
def find_method_with_line(cm, line)
unless cm.kind_of?(Rubinius::CompiledMethod)
return nil
end
lines = lines_of_method(cm)
return cm if lines.member?(line)
scope = cm.scope
return nil unless scope and scope.current_script
cm = scope.current_script.compiled_code
lines = lines_of_method(cm)
until lines.member?(line) do
child = scope
scope = scope.parent
unless scope
# child is the top-most scope. Search down from here.
cm = child.current_script.compiled_code
pair = locate_line(line, cm)
## pair = cm.locate_line(line)
return pair ? pair[0] : nil
end
cm = scope.current_script.compiled_code
lines = lines_of_method(cm)
end
return cm
end
|
ruby
|
{
"resource": ""
}
|
q5704
|
GameOverseer.ChannelManager.register_channel
|
train
|
def register_channel(channel, service)
_channel = channel.downcase
unless @channels[_channel]
@channels[_channel] = service
GameOverseer::Console.log("ChannelManager> mapped '#{_channel}' to '#{service.class}'.")
else
raise "Could not map channel '#{_channel}' because '#{@channels[data[_channel]].class}' is already using it."
end
end
|
ruby
|
{
"resource": ""
}
|
q5705
|
Opencnam.Client.phone
|
train
|
def phone(phone_number, options = {})
# Build query string
options = {
:account_sid => account_sid,
:auth_token => auth_token,
:format => 'text',
}.merge(options)
options[:format] = options[:format].to_s.strip.downcase
# Check for supported format
unless %w(text json).include? options[:format]
raise ArgumentError.new "Unsupported format: #{options[:format]}"
end
# Send request
http = Net::HTTP.new(API_HOST, (use_ssl? ? '443' : '80'))
http.use_ssl = true if use_ssl?
query = URI.encode_www_form(options)
res = http.request_get("/v2/phone/#{phone_number.strip}?#{query}")
# Look up was unsuccessful
raise OpencnamError.new res.message unless res.kind_of? Net::HTTPOK
return res.body if options[:format] == 'text'
return parse_json(res.body) if options[:format] == 'json'
end
|
ruby
|
{
"resource": ""
}
|
q5706
|
SpellNumber.Speller.two_digit_number
|
train
|
def two_digit_number(number, combined = false)
words = combined ? simple_number_to_words_combined(number) : simple_number_to_words(number)
return words if(words != 'not_found')
rest = number % 10
format = "spell_number.formats.tens.#{rest == 0 ? 'no_rest' : 'rest'}"
first_digit = simple_number_to_words(number - rest)
second_digit = simple_number_to_words_combined(rest)
I18n.t(format, :locale => @options[:locale], :first_digit => first_digit, :second_digit => second_digit)
end
|
ruby
|
{
"resource": ""
}
|
q5707
|
SpellNumber.Speller.simple_number_to_words_combined
|
train
|
def simple_number_to_words_combined(number)
words = I18n.t("spell_number.numbers.number_#{number}_combined", :locale => @options[:locale], :default => 'not_found')
words = simple_number_to_words(number) if(words == 'not_found')
words
end
|
ruby
|
{
"resource": ""
}
|
q5708
|
FormAPI.PDFApi.combine_pdfs
|
train
|
def combine_pdfs(combine_pdfs_data, opts = {})
data, _status_code, _headers = combine_pdfs_with_http_info(combine_pdfs_data, opts)
data
end
|
ruby
|
{
"resource": ""
}
|
q5709
|
FormAPI.PDFApi.combine_submissions
|
train
|
def combine_submissions(combined_submission_data, opts = {})
data, _status_code, _headers = combine_submissions_with_http_info(combined_submission_data, opts)
data
end
|
ruby
|
{
"resource": ""
}
|
q5710
|
FormAPI.PDFApi.create_custom_file_from_upload
|
train
|
def create_custom_file_from_upload(create_custom_file_data, opts = {})
data, _status_code, _headers = create_custom_file_from_upload_with_http_info(create_custom_file_data, opts)
data
end
|
ruby
|
{
"resource": ""
}
|
q5711
|
FormAPI.PDFApi.create_data_request_token
|
train
|
def create_data_request_token(data_request_id, opts = {})
data, _status_code, _headers = create_data_request_token_with_http_info(data_request_id, opts)
data
end
|
ruby
|
{
"resource": ""
}
|
q5712
|
FormAPI.PDFApi.create_template_from_upload
|
train
|
def create_template_from_upload(create_template_data, opts = {})
data, _status_code, _headers = create_template_from_upload_with_http_info(create_template_data, opts)
data
end
|
ruby
|
{
"resource": ""
}
|
q5713
|
FormAPI.PDFApi.expire_combined_submission
|
train
|
def expire_combined_submission(combined_submission_id, opts = {})
data, _status_code, _headers = expire_combined_submission_with_http_info(combined_submission_id, opts)
data
end
|
ruby
|
{
"resource": ""
}
|
q5714
|
FormAPI.PDFApi.expire_submission
|
train
|
def expire_submission(submission_id, opts = {})
data, _status_code, _headers = expire_submission_with_http_info(submission_id, opts)
data
end
|
ruby
|
{
"resource": ""
}
|
q5715
|
FormAPI.PDFApi.generate_pdf
|
train
|
def generate_pdf(template_id, submission_data, opts = {})
data, _status_code, _headers = generate_pdf_with_http_info(template_id, submission_data, opts)
data
end
|
ruby
|
{
"resource": ""
}
|
q5716
|
FormAPI.PDFApi.get_data_request
|
train
|
def get_data_request(data_request_id, opts = {})
data, _status_code, _headers = get_data_request_with_http_info(data_request_id, opts)
data
end
|
ruby
|
{
"resource": ""
}
|
q5717
|
FormAPI.PDFApi.get_submission
|
train
|
def get_submission(submission_id, opts = {})
data, _status_code, _headers = get_submission_with_http_info(submission_id, opts)
data
end
|
ruby
|
{
"resource": ""
}
|
q5718
|
FormAPI.PDFApi.get_submission_batch
|
train
|
def get_submission_batch(submission_batch_id, opts = {})
data, _status_code, _headers = get_submission_batch_with_http_info(submission_batch_id, opts)
data
end
|
ruby
|
{
"resource": ""
}
|
q5719
|
FormAPI.PDFApi.get_template
|
train
|
def get_template(template_id, opts = {})
data, _status_code, _headers = get_template_with_http_info(template_id, opts)
data
end
|
ruby
|
{
"resource": ""
}
|
q5720
|
FormAPI.PDFApi.get_template_schema
|
train
|
def get_template_schema(template_id, opts = {})
data, _status_code, _headers = get_template_schema_with_http_info(template_id, opts)
data
end
|
ruby
|
{
"resource": ""
}
|
q5721
|
FormAPI.PDFApi.update_data_request
|
train
|
def update_data_request(data_request_id, update_submission_data_request_data, opts = {})
data, _status_code, _headers = update_data_request_with_http_info(data_request_id, update_submission_data_request_data, opts)
data
end
|
ruby
|
{
"resource": ""
}
|
q5722
|
ActsAsNestedInterval.InstanceMethods.next_root_lft
|
train
|
def next_root_lft
last_root = nested_interval_scope.roots.order( rgtp: :desc, rgtq: :desc ).first
raise Exception.new("Only one root allowed") if last_root.present? && !self.class.nested_interval.multiple_roots?
last_root.try(:right) || 0.to_r
end
|
ruby
|
{
"resource": ""
}
|
q5723
|
Fusebox.Request.report
|
train
|
def report (opts = {})
default_options = {
:user => 'all',
:group_subaccount => true,
:report_type => 'basic'
}
opts.reverse_merge! default_options
post 'report', opts, "report_#{opts[:report_type]}".to_sym
end
|
ruby
|
{
"resource": ""
}
|
q5724
|
Fusebox.Request.load_auth_from_yaml
|
train
|
def load_auth_from_yaml
self.class.auth_yaml_paths.map { |path| File.expand_path(path) }.select { |path| File.exist?(path) }.each do |path|
auth = YAML.load(File.read(path))
@username = auth['username']
@password = auth['password']
return if @username && @password
end
raise "Could not locate a fusemail authentication file in locations: #{self.class.auth_yaml_paths.inspect}"
end
|
ruby
|
{
"resource": ""
}
|
q5725
|
AppRepo.Uploader.download_manifest_only
|
train
|
def download_manifest_only
FastlaneCore::UI.message('download_manifest_only...')
rsa_key = load_rsa_key(rsa_keypath)
success = true
if !rsa_key.nil?
FastlaneCore::UI.message('Logging in with RSA key for download...')
Net::SSH.start(host, user, key_data: rsa_key, keys_only: true) do |ssh|
FastlaneCore::UI.message('Uploading UPA & Manifest...')
success = ssh_sftp_download(ssh, manifest_path)
end
else
FastlaneCore::UI.message('Logging in for download...')
Net::SSH.start(host, user, password: password) do |ssh|
FastlaneCore::UI.message('Uploading UPA & Manifest...')
success = ssh_sftp_download(ssh, manifest_path)
end
end
success
end
|
ruby
|
{
"resource": ""
}
|
q5726
|
AppRepo.Uploader.check_ipa
|
train
|
def check_ipa(local_ipa_path)
if File.exist?(local_ipa_path)
FastlaneCore::UI.important('IPA found at ' + local_ipa_path)
return true
else
FastlaneCore::UI.verbose('IPA at given path does not exist yet.')
return false
end
end
|
ruby
|
{
"resource": ""
}
|
q5727
|
AppRepo.Uploader.download_manifest
|
train
|
def download_manifest(sftp)
FastlaneCore::UI.message('Checking remote Manifest')
json = nil
remote_manifest_path = remote_manifest_path(appcode)
begin
sftp.stat!(remote_manifest_path) do |response|
if response.ok?
FastlaneCore::UI.success('Loading remote manifest:')
manifest = sftp.download!(remote_manifest_path)
json = JSON.parse(manifest)
end
end
rescue
FastlaneCore::UI.message('No previous Manifest found')
end
json
end
|
ruby
|
{
"resource": ""
}
|
q5728
|
AppRepo.Uploader.upload_ipa
|
train
|
def upload_ipa(sftp, local_ipa_path, remote_ipa_path)
msg = "[Uploading IPA] #{local_ipa_path} to #{remote_ipa_path}"
FastlaneCore::UI.message(msg)
result = sftp.upload!(local_ipa_path, remote_ipa_path) do |event, _uploader, *_args|
case event
when :open then
putc '.'
when :put then
putc '.'
$stdout.flush
when :close then
puts "\n"
when :finish then
FastlaneCore::UI.success('IPA upload successful')
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5729
|
AppRepo.Uploader.upload_manifest
|
train
|
def upload_manifest(sftp, local_path, remote_path)
msg = '[Uploading Manifest] ' + local_path + ' to ' + remote_path
FastlaneCore::UI.message(msg)
result = sftp.upload!(local_path, remote_path) do |event, _uploader, *_args|
case event
when :finish then
FastlaneCore::UI.success('Manifest upload successful')
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5730
|
AppRepo.Uploader.load_rsa_key
|
train
|
def load_rsa_key(rsa_keypath)
File.open(rsa_keypath, 'r') do |file|
rsa_key = nil
rsa_key = [file.read]
if !rsa_key.nil?
FastlaneCore::UI.success('Successfully loaded RSA key...')
else
FastlaneCore::UI.user_error!('Failed to load RSA key...')
end
rsa_key
end
end
|
ruby
|
{
"resource": ""
}
|
q5731
|
ConstructorPages.Field.check_code_name
|
train
|
def check_code_name(code_name)
[code_name.pluralize, code_name.singularize].each {|name|
%w{self_and_ancestors descendants}.each {|m|
return false if template.send(m).map(&:code_name).include?(name)}}
true
end
|
ruby
|
{
"resource": ""
}
|
q5732
|
StatModule.Location.print
|
train
|
def print
result = "in #{path}"
if !begin_line.nil? && !end_line.nil?
if begin_line != end_line
if !begin_column.nil? && !end_column.nil?
result += ", line #{begin_line}:#{begin_column} to line #{end_line}:#{end_column}"
elsif !begin_column.nil? && end_column.nil?
result += ", line #{begin_line}:#{begin_column} to line #{end_line}"
elsif begin_column.nil? && !end_column.nil?
result += ", line #{begin_line} to line #{end_line}:#{end_column}"
else
result += ", lines #{begin_line}-#{end_line}"
end
else
if begin_column.nil?
result += ", line #{begin_line}"
else
result += ", line #{begin_line}:#{begin_column}"
result += "-#{end_column}" unless end_column.nil?
end
end
end
result
end
|
ruby
|
{
"resource": ""
}
|
q5733
|
Wanikani.Level.level_items_list
|
train
|
def level_items_list(type, levels)
levels = levels.join(',') if levels.is_a?(Array)
response = api_response(type, levels)
# The vocabulary API call without specifying levels returns a Hash instead
# of an Array, so this is a hacky way of dealing with it.
if response["requested_information"].is_a?(Hash)
return response["requested_information"]["general"]
else
return response["requested_information"]
end
end
|
ruby
|
{
"resource": ""
}
|
q5734
|
Grabbers.GenericHttp.check_expired_resources
|
train
|
def check_expired_resources
net_resources = ::NetResource.expired
net_resources.each do |resource|
http = EM::HttpRequest.new(resource.url).get
http.callback{ |response|
resource.set_next_update
if resource_changed?(resource, response)
resource.body = response.response
update_changed_resource(resource, response)
notify_subscribers(resource)
end
}
http.errback {|response|
# Do something here, maybe setting the resource
# to be not checked anymore.
}
end
end
|
ruby
|
{
"resource": ""
}
|
q5735
|
Grabbers.GenericHttp.notify_subscribers
|
train
|
def notify_subscribers(resource)
resource.subscriptions.each do |subscription|
http = EM::HttpRequest.new(subscription.url).post(:body => {:data => resource.body})
http.callback{ |response|
puts "POSTed updated data for #{resource.url}, #{resource.body.length} characters"
}
http.errback {|response|
# Do something here, maybe setting the resource
# to be not checked anymore.
}
end
end
|
ruby
|
{
"resource": ""
}
|
q5736
|
Grabbers.GenericHttp.resource_changed?
|
train
|
def resource_changed?(resource, response)
changed = false
puts "checking for changes on #{resource.url}"
puts "response.response.hash: #{response.response.hash}"
puts "resource.last_modified_hash: #{resource.last_modified_hash}"
if response.response.hash != resource.last_modified_hash
puts "changed!!!!\n\n\n\n"
changed = true
end
end
|
ruby
|
{
"resource": ""
}
|
q5737
|
Grabbers.GenericHttp.update_changed_resource
|
train
|
def update_changed_resource(resource, response)
resource.last_modified_hash = response.response.hash
resource.last_updated = Time.now
resource.body = response.response
resource.save
end
|
ruby
|
{
"resource": ""
}
|
q5738
|
FalkorLib.Config.default
|
train
|
def default
res = FalkorLib::Config::DEFAULTS.clone
$LOADED_FEATURES.each do |path|
res[:git] = FalkorLib::Config::Git::DEFAULTS if path.include?('lib/falkorlib/git.rb')
res[:gitflow] = FalkorLib::Config::GitFlow::DEFAULTS if path.include?('lib/falkorlib/git.rb')
res[:versioning] = FalkorLib::Config::Versioning::DEFAULTS if path.include?('lib/falkorlib/versioning.rb')
if path.include?('lib/falkorlib/puppet.rb')
res[:puppet] = FalkorLib::Config::Puppet::DEFAULTS
res[:templates][:puppet][:modules] = FalkorLib::Config::Puppet::Modules::DEFAULTS[:metadata]
end
end
# Check the potential local customizations
[:local, :private].each do |type|
custom_cfg = File.join( res[:root], res[:config_files][type.to_sym])
if File.exist?( custom_cfg )
res.deep_merge!( load_config( custom_cfg ) )
end
end
res
end
|
ruby
|
{
"resource": ""
}
|
q5739
|
FalkorLib.Config.config_file
|
train
|
def config_file(dir = Dir.pwd, type = :local, options = {})
path = normalized_path(dir)
path = FalkorLib::Git.rootdir(path) if FalkorLib::Git.init?(path)
raise FalkorLib::Error, "Wrong FalkorLib configuration type" unless FalkorLib.config[:config_files].keys.include?( type.to_sym)
(options[:file]) ? options[:file] : File.join(path, FalkorLib.config[:config_files][type.to_sym])
end
|
ruby
|
{
"resource": ""
}
|
q5740
|
ISE.ProjectNavigator.most_recent_project_path
|
train
|
def most_recent_project_path
#Re-load the preference file, so we have the most recent project.
@preferences = PreferenceFile.load
#And retrieve the first project in the recent projects list.
project = preference(RecentProjectsPath).split(', ').first
#If the project exists, return it; otherwise, return nil.
File::exists?(project) ? project : nil
end
|
ruby
|
{
"resource": ""
}
|
q5741
|
CLIUtils.Configurator.ingest_prefs
|
train
|
def ingest_prefs(prefs)
fail 'Invaid Prefs class' unless prefs.kind_of?(Prefs)
prefs.prompts.each do |p|
section_sym = p.config_section.to_sym
add_section(section_sym) unless @data.key?(section_sym)
@data[section_sym].merge!(p.config_key.to_sym => p.answer)
end
end
|
ruby
|
{
"resource": ""
}
|
q5742
|
CLIUtils.Configurator.method_missing
|
train
|
def method_missing(name, *args, &block)
if name[-1,1] == '='
@data[name[0..-2].to_sym] = args[0]
else
@data[name.to_sym] ||= {}
end
end
|
ruby
|
{
"resource": ""
}
|
q5743
|
Cassie::Schema.VersionLoader.load
|
train
|
def load
return false unless filename
require filename
begin
# ensure the migration class is now defined
version.migration_class_name.constantize
if version.migration.is_a?(Cassie::Schema::Migration)
version
else
false
end
rescue NameError
raise NameError.new("Expected #{version.migration_class_name} to be defined in #{filename}, but it was not.")
end
end
|
ruby
|
{
"resource": ""
}
|
q5744
|
GovDelivery::TMS::InstanceResource.ClassMethods.nullable_attributes
|
train
|
def nullable_attributes(*attrs)
@nullable_attributes ||= []
if attrs.any?
@nullable_attributes.map!(&:to_sym).concat(attrs).uniq! if attrs.any?
end
@nullable_attributes
end
|
ruby
|
{
"resource": ""
}
|
q5745
|
Bullshit.ModuleFunctions.array_window
|
train
|
def array_window(array, window_size)
window_size < 1 and raise ArgumentError, "window_size = #{window_size} < 1"
window_size = window_size.to_i
window_size += 1 if window_size % 2 == 0
radius = window_size / 2
array.each_index do |i|
ws = window_size
from = i - radius
negative_from = false
if from < 0
negative_from = true
ws += from
from = 0
end
a = array[from, ws]
if (diff = window_size - a.size) > 0
mean = a.inject(0.0) { |s, x| s + x } / a.size
a = if negative_from
[ mean ] * diff + a
else
a + [ mean ] * diff
end
end
yield a
end
nil
end
|
ruby
|
{
"resource": ""
}
|
q5746
|
Bullshit.Clock.<<
|
train
|
def <<(times)
r = times.shift
@repeat += 1 if @times[:repeat].last != r
@times[:repeat] << r
TIMES.zip(times) { |t, time| @times[t] << time.to_f }
self
end
|
ruby
|
{
"resource": ""
}
|
q5747
|
Bullshit.Clock.analysis
|
train
|
def analysis
@analysis ||= Hash.new do |h, time|
time = time.to_sym
times = @times[time]
h[time] = MoreMath::Sequence.new(times)
end
end
|
ruby
|
{
"resource": ""
}
|
q5748
|
Bullshit.Clock.cover?
|
train
|
def cover?(other)
time = self.case.compare_time.to_sym
analysis[time].cover?(other.analysis[time], self.case.covering.alpha_level.abs)
end
|
ruby
|
{
"resource": ""
}
|
q5749
|
Bullshit.Clock.to_a
|
train
|
def to_a
if @repeat >= 1
(::Bullshit::Clock::ALL_COLUMNS).map do |t|
analysis[t].elements
end.transpose
else
[]
end
end
|
ruby
|
{
"resource": ""
}
|
q5750
|
Bullshit.Clock.take_time
|
train
|
def take_time
@time, times = Time.now, Process.times
user_time = times.utime + times.cutime # user time of this process and its children
system_time = times.stime + times.cstime # system time of this process and its children
total_time = user_time + system_time # total time of this process and its children
[ @time.to_f, total_time, user_time, system_time ]
end
|
ruby
|
{
"resource": ""
}
|
q5751
|
Bullshit.Clock.measure
|
train
|
def measure
before = take_time
yield
after = take_time
@repeat += 1
@times[:repeat] << @repeat
@times[:scatter] << @scatter
bs = self.case.batch_size.abs
if bs and bs > 1
TIMES.each_with_index { |t, i| @times[t] << (after[i] - before[i]) / bs }
else
TIMES.each_with_index { |t, i| @times[t] << after[i] - before[i] }
end
@analysis = nil
end
|
ruby
|
{
"resource": ""
}
|
q5752
|
Bullshit.Clock.detect_autocorrelation
|
train
|
def detect_autocorrelation(time)
analysis[time.to_sym].detect_autocorrelation(
self.case.autocorrelation.max_lags.to_i,
self.case.autocorrelation.alpha_level.abs)
end
|
ruby
|
{
"resource": ""
}
|
q5753
|
Bullshit.Clock.autocorrelation_plot
|
train
|
def autocorrelation_plot(time)
r = autocorrelation time
start = @times[:repeat].first
ende = (start + r.size)
(start...ende).to_a.zip(r)
end
|
ruby
|
{
"resource": ""
}
|
q5754
|
Bullshit.Clock.truncate_data
|
train
|
def truncate_data(offset)
for t in ALL_COLUMNS
times = @times[t]
@times[t] = @times[t][offset, times.size]
@repeat = @times[t].size
end
@analysis = nil
self
end
|
ruby
|
{
"resource": ""
}
|
q5755
|
Bullshit.Clock.find_truncation_offset
|
train
|
def find_truncation_offset
truncation = self.case.truncate_data
slope_angle = self.case.truncate_data.slope_angle.abs
time = self.case.compare_time.to_sym
ms = analysis[time].elements.reverse
offset = ms.size - 1
@slopes = []
ModuleFunctions.array_window(ms, truncation.window_size) do |data|
lr = LinearRegression.new(data)
a = lr.a
@slopes << [ offset, a ]
a.abs > slope_angle and break
offset -= 1
end
offset < 0 ? 0 : offset
end
|
ruby
|
{
"resource": ""
}
|
q5756
|
Bullshit.CaseMethod.load
|
train
|
def load(fp = file_path)
self.clock = self.case.class.clock.new self
$DEBUG and warn "Loading '#{fp}' into clock."
File.open(fp, 'r') do |f|
f.each do |line|
line.chomp!
line =~ /^\s*#/ and next
clock << line.split(/\t/)
end
end
self
rescue Errno::ENOENT
end
|
ruby
|
{
"resource": ""
}
|
q5757
|
Bullshit.Case.longest_name
|
train
|
def longest_name
bmethods.empty? and return 0
bmethods.map { |x| x.short_name.size }.max
end
|
ruby
|
{
"resource": ""
}
|
q5758
|
Bullshit.Case.pre_run
|
train
|
def pre_run(bc_method)
setup_name = bc_method.setup_name
if respond_to? setup_name
$DEBUG and warn "Calling #{setup_name}."
__send__(setup_name)
end
self.class.output.puts "#{bc_method.long_name}:"
end
|
ruby
|
{
"resource": ""
}
|
q5759
|
Bullshit.Case.run_method
|
train
|
def run_method(bc_method)
pre_run bc_method
clock = self.class.clock.__send__(self.class.clock_method, bc_method) do
__send__(bc_method.name)
end
bc_method.clock = clock
post_run bc_method
clock
end
|
ruby
|
{
"resource": ""
}
|
q5760
|
Bullshit.Case.post_run
|
train
|
def post_run(bc_method)
teardown_name = bc_method.teardown_name
if respond_to? teardown_name
$DEBUG and warn "Calling #{teardown_name}."
__send__(bc_method.teardown_name)
end
end
|
ruby
|
{
"resource": ""
}
|
q5761
|
Bullshit.Comparison.output_filename
|
train
|
def output_filename(name)
path = File.expand_path(name, output_dir)
output File.new(path, 'a+')
end
|
ruby
|
{
"resource": ""
}
|
q5762
|
Inaho.Dictionary.validate
|
train
|
def validate
errors = []
schema_path = File.expand_path("../../../vendor/AppleDictionarySchema.rng", __FILE__)
schema = Nokogiri::XML::RelaxNG(File.open(schema_path))
schema.validate(Nokogiri::XML(self.to_xml)).each do |error|
errors << error
end
if errors.size > 0
return errors
else
return true
end
end
|
ruby
|
{
"resource": ""
}
|
q5763
|
Inaho.Dictionary.to_xml
|
train
|
def to_xml
xml = ""
xml << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
xml << "<d:dictionary xmlns=\"http://www.w3.org/1999/xhtml\" "
xml << "xmlns:d=\"http://www.apple.com/DTDs/DictionaryService-1.0.rng\">\n"
@entries.each do |entry|
next if entry.to_xml.nil?
xml << entry.to_xml
end
xml << "</d:dictionary>"
return xml
end
|
ruby
|
{
"resource": ""
}
|
q5764
|
Stribog.CreateHash.return_hash
|
train
|
def return_hash(final_vector)
case digest_length
when 512
create_digest(final_vector)
when 256
create_digest(vector_from_array(final_vector[0..31]))
else
raise ArgumentError,
"digest length must be equal to 256 or 512, not #{digest_length}"
end
end
|
ruby
|
{
"resource": ""
}
|
q5765
|
RepoManager.BaseAction.parse_options
|
train
|
def parse_options(parser_configuration = {})
raise_on_invalid_option = parser_configuration.has_key?(:raise_on_invalid_option) ? parser_configuration[:raise_on_invalid_option] : true
parse_base_options = parser_configuration.has_key?(:parse_base_options) ? parser_configuration[:parse_base_options] : true
logger.debug "parsing args: #{@args.inspect}, raise_on_invalid_option: #{raise_on_invalid_option}, parse_base_options: #{parse_base_options}"
@option_parser ||= OptionParser.new
option_parser.banner = help + "\n\nOptions:"
if parse_base_options
option_parser.on("--template [NAME]", "Use a template to render output. (default=default.slim)") do |t|
options[:template] = t.nil? ? "default.slim" : t
@template = options[:template]
end
option_parser.on("--output FILENAME", "Render output directly to a file") do |f|
options[:output] = f
@output = options[:output]
end
option_parser.on("--force", "Overwrite file output without prompting") do |f|
options[:force] = f
end
option_parser.on("-r", "--repos a1,a2,a3", "--asset a1,a2,a3", "--filter a1,a2,a3", Array, "List of regex asset name filters") do |list|
options[:filter] = list
end
# NOTE: OptionParser will add short options, there is no way to stop '-m' from being the same as '--match'
option_parser.on("--match [MODE]", "Asset filter match mode. MODE=ALL (default), FIRST, EXACT, or ONE (fails if more than 1 match)") do |m|
options[:match] = m || "ALL"
options[:match].upcase!
unless ["ALL", "FIRST", "EXACT", "ONE"].include?(options[:match])
puts "invalid match mode option: #{options[:match]}"
exit 1
end
end
end
# allow decendants to add options
yield option_parser if block_given?
# reprocess args for known options, see binary wrapper for first pass
# (first pass doesn't know about action specific options), find all
# action options that may come after the action/subcommand (options
# before subcommand have already been processed) and its args
logger.debug "args before reprocessing: #{@args.inspect}"
begin
option_parser.order!(@args)
rescue OptionParser::InvalidOption => e
if raise_on_invalid_option
puts "option error: #{e}"
puts option_parser
exit 1
else
# parse and consume until we hit an unknown option (not arg), put it back so it
# can be shifted into the new array
e.recover(@args)
end
end
logger.debug "args before unknown collection: #{@args.inspect}"
unknown_args = []
while unknown_arg = @args.shift
logger.debug "unknown_arg: #{unknown_arg.inspect}"
unknown_args << unknown_arg
begin
# consume options and stop at an arg
option_parser.order!(@args)
rescue OptionParser::InvalidOption => e
if raise_on_invalid_option
puts "option error: #{e}"
puts option_parser
exit 1
else
# parse and consume until we hit an unknown option (not arg), put it back so it
# can be shifted into the new array
e.recover(@args)
end
end
end
logger.debug "args after unknown collection: #{@args.inspect}"
@args = unknown_args.dup
logger.debug "args after reprocessing: #{@args.inspect}"
logger.debug "configuration after reprocessing: #{@configuration.inspect}"
logger.debug "options after reprocessing: #{@options.inspect}"
option_parser
end
|
ruby
|
{
"resource": ""
}
|
q5766
|
RepoManager.BaseAction.asset_options
|
train
|
def asset_options
# include all base action options
result = options.deep_clone
# anything left on the command line should be filters as all options have
# been consumed, for pass through options, filters must be ignored by overwritting them
filters = args.dup
filters += result[:filter] if result[:filter]
result = result.merge(:filter => filters) unless filters.empty?
# asset type to create
type = result[:type] || asset_type
result = result.merge(:type => type)
# optional key: :assets_folder, absolute path or relative to config file if :base_folder is specified
result = result.merge(:assets_folder => configuration[:folders][:assets]) if configuration[:folders]
# optional key: :base_folder is the folder that contains the main config file
result = result.merge(:base_folder => File.dirname(configuration[:configuration_filename])) if configuration[:configuration_filename]
result
end
|
ruby
|
{
"resource": ""
}
|
q5767
|
RepoManager.BaseAction.render
|
train
|
def render(view_options=configuration)
logger.debug "rendering"
result = ""
if template
logger.debug "rendering with template : #{template}"
view = AppView.new(items, view_options)
view.template = template
result = view.render
else
items.each_with_index do |item, index|
result += "\n" unless index == 0
result += item.name.green + ":\n"
if item.respond_to?(:attributes)
attributes = item.attributes.deep_clone
result += attributes.recursively_stringify_keys!.to_conf.gsub(/\s+$/, '') # strip trailing whitespace from YAML
result += "\n"
end
end
end
result
end
|
ruby
|
{
"resource": ""
}
|
q5768
|
SiteFramework.Middleware.call
|
train
|
def call(env)
# Create a method called domain which will return the current domain
# name
Rails.application.send :define_singleton_method, 'domain_name' do
env['SERVER_NAME']
end
# Create `fetch_domain` method on `Rails.application`
# only if it didn't already define.
unless Rails.application.respond_to? :fetch_domain
Rails.application.send :define_singleton_method, 'fetch_domain' do
if defined? ActiveRecord
Domain.find_by(nam: Rails.application.domain_name)
elsif defined? Mongoid
Site.where('domains.name' => Rails.application.domain_name).domains.first
end
end
end
Rails.application.send :define_singleton_method, 'site' do
site = nil
unless Rails.application.domain.nil?
site = Rails.application.domain.site
end
site
end
Rails.application
@app.call(env)
end
|
ruby
|
{
"resource": ""
}
|
q5769
|
Ripl.Fresh.loop_eval
|
train
|
def loop_eval(input)
if input == ''
@command_mode = :system and return
end
case @command_mode
when :system # generate ruby code to execute the command
if !@result_storage
ruby_command_code = "_ = system '#{ input }'\n"
else
temp_file = "/tmp/ripl-fresh_#{ rand 12345678901234567890 }"
ruby_command_code = "_ = system '#{ input } 2>&1', :out => '#{ temp_file }'\n"
# assign result to result storage variable
case @result_operator
when '=>', '=>>'
result_literal = "[]"
formatted_result = "File.read('#{ temp_file }').split($/)"
operator = @result_operator == '=>>' ? '+=' : '='
when '~>', '~>>'
result_literal = "''"
formatted_result = "File.read('#{ temp_file }')"
operator = @result_operator == '~>>' ? '<<' : '='
end
ruby_command_code << %Q%
#{ @result_storage } ||= #{ result_literal }
#{ @result_storage } #{ operator } #{ formatted_result }
FileUtils.rm '#{ temp_file }'
%
end
# ruby_command_code << "raise( SystemCallError.new $?.exitstatus ) if !_\n" # easy auto indent
ruby_command_code << "if !_
raise( SystemCallError.new $?.exitstatus )
end;"
super @input = ruby_command_code
when :mixed # call the ruby method, but with shell style arguments TODO more shell like (e.g. "")
method_name, *args = *input.split
super @input = "#{ method_name }(*#{ args })"
else # good old :ruby
super
end
end
|
ruby
|
{
"resource": ""
}
|
q5770
|
CF.Data.to_s
|
train
|
def to_s
ptr = CF.CFDataGetBytePtr(self)
if CF::String::HAS_ENCODING
ptr.read_string(CF.CFDataGetLength(self)).force_encoding(Encoding::ASCII_8BIT)
else
ptr.read_string(CF.CFDataGetLength(self))
end
end
|
ruby
|
{
"resource": ""
}
|
q5771
|
RakeOE.Toolchain.set_build_vars
|
train
|
def set_build_vars
warning_flags = ' -W -Wall'
if 'release' == @config.release
optimization_flags = " #{@config.optimization_release} -DRELEASE"
else
optimization_flags = " #{@config.optimization_dbg} -g"
end
# we could make these also arrays of source directories ...
@settings['APP_SRC_DIR'] = 'src/app'
@settings['LIB_SRC_DIR'] = 'src/lib'
# derived settings
@settings['BUILD_DIR'] = "#{build_dir}"
@settings['LIB_OUT'] = "#{@settings['BUILD_DIR']}/libs"
@settings['APP_OUT'] = "#{@settings['BUILD_DIR']}/apps"
unless @settings['OECORE_TARGET_SYSROOT'].nil? || @settings['OECORE_TARGET_SYSROOT'].empty?
@settings['SYS_LFLAGS'] = "-L#{@settings['OECORE_TARGET_SYSROOT']}/lib -L#{@settings['OECORE_TARGET_SYSROOT']}/usr/lib"
end
# set LD_LIBRARY_PATH
@settings['LD_LIBRARY_PATH'] = @settings['LIB_OUT']
# standard settings
@settings['CXXFLAGS'] += warning_flags + optimization_flags + " #{@config.language_std_cpp}"
@settings['CFLAGS'] += warning_flags + optimization_flags + " #{@config.language_std_c}"
if @settings['PRJ_TYPE'] == 'SOLIB'
@settings['CXXFLAGS'] += ' -fPIC'
@settings['CFLAGS'] += ' -fPIC'
end
# !! don't change order of the following string components without care !!
@settings['LDFLAGS'] = @settings['LDFLAGS'] + " -L #{@settings['LIB_OUT']} #{@settings['SYS_LFLAGS']} -Wl,--no-as-needed -Wl,--start-group"
end
|
ruby
|
{
"resource": ""
}
|
q5772
|
RakeOE.Toolchain.reduce_libs_to_bare_minimum
|
train
|
def reduce_libs_to_bare_minimum(libs)
rv = libs.clone
lib_entries = RakeOE::PrjFileCache.get_lib_entries(libs)
lib_entries.each_pair do |lib, entry|
rv.delete(lib) unless RakeOE::PrjFileCache.project_entry_buildable?(entry, @target)
end
rv
end
|
ruby
|
{
"resource": ""
}
|
q5773
|
RakeOE.Toolchain.libs_for_binary
|
train
|
def libs_for_binary(a_binary, visited=[])
return [] if visited.include?(a_binary)
visited << a_binary
pre = Rake::Task[a_binary].prerequisites
rv = []
pre.each do |p|
next if (File.extname(p) != '.a') && (File.extname(p) != '.so')
next if p =~ /\-app\.a/
rv << File.basename(p).gsub(/(\.a|\.so|^lib)/, '')
rv += libs_for_binary(p, visited) # Recursive call
end
reduce_libs_to_bare_minimum(rv.uniq)
end
|
ruby
|
{
"resource": ""
}
|
q5774
|
RakeOE.Toolchain.obj
|
train
|
def obj(params = {})
extension = File.extname(params[:source])
object = params[:object]
source = params[:source]
incs = compiler_incs_for(params[:includes]) + " #{@settings['LIB_INC']}"
case
when cpp_source_extensions.include?(extension)
flags = @settings['CXXFLAGS'] + ' ' + params[:settings]['ADD_CXXFLAGS']
compiler = "#{@settings['CXX']} -x c++ "
when c_source_extensions.include?(extension)
flags = @settings['CFLAGS'] + ' ' + params[:settings]['ADD_CFLAGS']
compiler = "#{@settings['CC']} -x c "
when as_source_extensions.include?(extension)
flags = ''
compiler = "#{@settings['AS']}"
else
raise "unsupported source file extension (#{extension}) for creating object!"
end
sh "#{compiler} #{flags} #{incs} -c #{source} -o #{object}"
end
|
ruby
|
{
"resource": ""
}
|
q5775
|
RubyChem.Equation.solve_equivalent_fractions
|
train
|
def solve_equivalent_fractions
last = 0
array = Array.new
@reduced_row_echelon_form.each do |x|
array = last.gcdlcm(x.last.denominator)
last = x.last.denominator
end
array.max
end
|
ruby
|
{
"resource": ""
}
|
q5776
|
RubyChem.Equation.apply_solved_equivalent_fractions_to_fraction
|
train
|
def apply_solved_equivalent_fractions_to_fraction
int = self.solve_equivalent_fractions
answer = []
@reduced_row_echelon_form.each do |row|
answer << row.last * int
end
answer << int
count = 0
@balanced = Hash.new
@left_system_of_equations.each do |x,v|
answer[count]
@left_system_of_equations[x] = answer[count].to_i.abs unless answer[count].nil?
count += 1
end
@right_system_of_equations.each do |x,v|
answer[count]
@right_system_of_equations[x] = answer[count].to_i.abs unless answer[count].nil?
count += 1
end
answer
@balanced = {left:@left_system_of_equations,right:@right_system_of_equations}
self.balanced_string.gsub(/([\D^])1([\D$])/, '\1\2') # or (/1(?!\d)/,"")
end
|
ruby
|
{
"resource": ""
}
|
q5777
|
RubyChem.Equation.reduced_row_echelon_form
|
train
|
def reduced_row_echelon_form(ary)
lead = 0
rows = ary.size
cols = ary[0].size
rary = convert_to_rational(ary) # use rational arithmetic
catch :done do
rows.times do |r|
throw :done if cols <= lead
i = r
while rary[i][lead] == 0
i += 1
if rows == i
i = r
lead += 1
throw :done if cols == lead
end
end
# swap rows i and r
rary[i], rary[r] = rary[r], rary[i]
# normalize row r
v = rary[r][lead]
rary[r].collect! {|x| x /= v}
# reduce other rows
rows.times do |i|
next if i == r
v = rary[i][lead]
rary[i].each_index {|j| rary[i][j] -= v * rary[r][j]}
end
lead += 1
end
end
rary
end
|
ruby
|
{
"resource": ""
}
|
q5778
|
HTTPStatus.ControllerAddition.http_status_exception
|
train
|
def http_status_exception(exception)
@exception = exception
render_options = {:template => exception.template, :status => exception.status}
render_options[:layout] = exception.template_layout if exception.template_layout
render(render_options)
rescue ActionView::MissingTemplate
head(exception.status)
end
|
ruby
|
{
"resource": ""
}
|
q5779
|
Trace.EventBuffer.append
|
train
|
def append(event, frame, arg)
item = EventStruct.new(event, arg, frame)
@pos = self.succ_pos
@marks.shift if @marks[0] == @pos
@buf[@pos] = item
@size += 1 unless @maxsize && @size == @maxsize
end
|
ruby
|
{
"resource": ""
}
|
q5780
|
ConstructorPages.Template.check_code_name
|
train
|
def check_code_name(cname)
[cname.pluralize, cname.singularize].each {|name|
return false if root.descendants.map{|t| t.code_name unless t.code_name == cname}.include?(name)}
true
end
|
ruby
|
{
"resource": ""
}
|
q5781
|
ExpressTemplates.Renderer.render
|
train
|
def render context=nil, template_or_src=nil, &block
compiled_template = compile(template_or_src, &block)
context.instance_eval compiled_template
end
|
ruby
|
{
"resource": ""
}
|
q5782
|
RepoManager.Settings.configure
|
train
|
def configure(options)
# config file default options
configuration = {
:options => {
:verbose => false,
:color => 'AUTO',
:short => false,
:unmodified => 'HIDE',
:match => 'ALL',
:list => 'ALL'
},
:commands => [
'diff',
'grep',
'log',
'ls-files',
'show',
'status'
]
}
# set default config if not given on command line
config = options[:config]
if config.nil?
config = [
File.join(@working_dir, "repo.conf"),
File.join(@working_dir, ".repo.conf"),
File.join(@working_dir, "repo_manager", "repo.conf"),
File.join(@working_dir, ".repo_manager", "repo.conf"),
File.join(@working_dir, "config", "repo.conf"),
File.expand_path(File.join("~", ".repo.conf")),
File.expand_path(File.join("~", "repo.conf")),
File.expand_path(File.join("~", "repo_manager", "repo.conf")),
File.expand_path(File.join("~", ".repo_manager", "repo.conf"))
].detect { |filename| File.exists?(filename) }
end
if config && File.exists?(config)
# load options from the config file, overwriting hard-coded defaults
logger.debug "reading configuration file: #{config}"
config_contents = YAML.load(ERB.new(File.open(config, "rb").read).result)
configuration.merge!(config_contents.symbolize_keys!) if config_contents && config_contents.is_a?(Hash)
else
# user specified a config file?, no error if user did not specify config file
raise "config file not found" if options[:config]
end
# store the original full config filename for later use
configuration[:configuration_filename] = config
configuration.recursively_symbolize_keys!
# the command line options override options read from the config file
configuration[:options].merge!(options)
configuration
end
|
ruby
|
{
"resource": ""
}
|
q5783
|
Cassie::Statements::Execution.BatchedFetching.fetch_in_batches
|
train
|
def fetch_in_batches(opts={})
opts[:batch_size] ||= 1000
# spawn the new query as soon as the enumerable is created
# rather than waiting until the firt iteration is executed.
# The client could mutate the object between these moments,
# however we don't want to spawn twice if a block isn't passed.
paged_query = opts.delete(:_paged_query) || self.clone
return to_enum(:fetch_in_batches, opts.merge(_paged_query: paged_query)) unless block_given?
# use Cassandra internal paging
# but clone the query to isolate it
# and allow all paging queries
# to execute within a Cassie::Query
# for use of other features, like logging
#
# note: stateless page size is independent from limit
paged_query.stateless_page_size = opts[:batch_size]
paged_query.paging_state = nil
loop do
# done if the previous result was the last page
break if paged_query.result && paged_query.result.last_page?
raise page_size_changed_error(opts[:batch_size]) if opts[:batch_size] != paged_query.stateless_page_size
batch = paged_query.fetch
paged_query.paging_state = paged_query.result.paging_state
yield batch
end
end
|
ruby
|
{
"resource": ""
}
|
q5784
|
GuideboxWrapper.GuideboxMovie.search_for
|
train
|
def search_for(name)
url = build_query(name)
url += '/fuzzy/web'
data = @client.query(url)
sleep(1)
data["results"]
end
|
ruby
|
{
"resource": ""
}
|
q5785
|
Snapi.Argument.valid_input?
|
train
|
def valid_input?(input)
case @attributes[:type]
when :boolean
[true,false].include?(input)
when :enum
raise MissingValuesError unless @attributes[:values]
raise InvalidValuesError unless @attributes[:values].class == Array
@attributes[:values].include?(input)
when :string
format = @attributes[:format] || :anything
Validator.valid_input?(format, input)
when :number
[Integer, Fixnum].include?(input.class)
when :timestamp
# TODO timestamp pending
# raise PendingBranchError
true
else
false
end
end
|
ruby
|
{
"resource": ""
}
|
q5786
|
Cassie::Statements::Execution.Fetching.fetch
|
train
|
def fetch(args={})
args.each do |k, v|
setter = "#{k}="
send(setter, v) if respond_to? setter
end
execute
result
end
|
ruby
|
{
"resource": ""
}
|
q5787
|
CF.Base.inspect
|
train
|
def inspect
cf = CF::String.new(CF.CFCopyDescription(self))
cf.to_s.tap {cf.release}
end
|
ruby
|
{
"resource": ""
}
|
q5788
|
CF.Base.equals?
|
train
|
def equals?(other)
if other.is_a?(CF::Base)
@ptr.address == other.to_ptr.address
else
false
end
end
|
ruby
|
{
"resource": ""
}
|
q5789
|
CLIUtils.PrettyIO.color_chart
|
train
|
def color_chart
[0, 1, 4, 5, 7].each do |attr|
puts '----------------------------------------------------------------'
puts "ESC[#{attr};Foreground;Background"
30.upto(37) do |fg|
40.upto(47) do |bg|
print "\033[#{attr};#{fg};#{bg}m #{fg};#{bg} "
end
puts "\033[0m"
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5790
|
Lev.Handler.validate_paramified_params
|
train
|
def validate_paramified_params
self.class.paramify_methods.each do |method|
params = send(method)
transfer_errors_from(params, TermMapper.scope(params.group)) if !params.valid?
end
end
|
ruby
|
{
"resource": ""
}
|
q5791
|
GBDispatch.Queue.perform_after
|
train
|
def perform_after(time, block=nil)
task = Concurrent::ScheduledTask.new(time) do
block = ->(){ yield } unless block
self.async.perform_now block
end
task.execute
task
end
|
ruby
|
{
"resource": ""
}
|
q5792
|
ISE.PreferenceFile.set_by_path
|
train
|
def set_by_path(path, value, target=@ini)
#Split the path into its components.
keys = path.split('/')
#Traverse the path, creating any "folders" necessary along the way.
until keys.one?
target[keys.first] = {} unless target[keys.first].is_a?(Hash)
target = target[keys.shift]
end
#And finally, place the value into the appropriate "leaf".
target[keys.shift] = value
end
|
ruby
|
{
"resource": ""
}
|
q5793
|
ISE.PreferenceFile.get_by_path
|
train
|
def get_by_path(path, target=@ini)
#Split the path into its components...
keys = path.split('/')
#And traverse the hasn until we've fully navigated the path.
target = target[keys.shift] until keys.empty?
#Returns the final value.
target
end
|
ruby
|
{
"resource": ""
}
|
q5794
|
ISE.PreferenceFile.process_property
|
train
|
def process_property(property, value)
value.chomp!
#If either the property or value are empty (or contain invalid whitespace),
#abort.
return if property.empty? and value.empty?
return if value.sub!(%r/\\\s*\z/, '')
#Strip any leading/trailing characters.
property.strip!
value.strip!
#Raise an error if we have an invalid property name.
parse_error if property.empty?
#Parse ISE's value into a path.
set_by_path(CGI::unescape(property), unescape_value(value.dup), current_section)
#And continue processing the property and value.
property.slice!(0, property.length)
value.slice!(0, value.length)
#Return nil.
nil
end
|
ruby
|
{
"resource": ""
}
|
q5795
|
FalkorLib.Git.init?
|
train
|
def init?(path = Dir.pwd)
begin
MiniGit.new(path)
rescue Exception
return false
end
true
end
|
ruby
|
{
"resource": ""
}
|
q5796
|
FalkorLib.Git.commits?
|
train
|
def commits?(path)
res = false
Dir.chdir(path) do
_stdout, _stderr, exit_status = Open3.capture3( "git rev-parse HEAD" )
res = (exit_status.to_i.zero?)
end
res
end
|
ruby
|
{
"resource": ""
}
|
q5797
|
FalkorLib.Git.command?
|
train
|
def command?(cmd)
cg = MiniGit::Capturing.new
cmd_list = cg.help :a => true
# typical run:
# usage: git [--version] [--help] [-C <path>] [-c name=value]
# [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
# [-p|--paginate|--no-pager] [--no-replace-objects] [--bare]
# [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
# <command> [<args>]
#
# available git commands in '/usr/local/Cellar/git/1.8.5.2/libexec/git-core'
#
# add [...] \
# [...] | The part we are interested in, delimited by '\n\n' sequence
# [...] /
#
# 'git help -a' and 'git help -g' lists available subcommands and some
# concept guides. See 'git help <command>' or 'git help <concept>'
# to read about a specific subcommand or concept
l = cmd_list.split("\n\n")
l.shift # useless first part
#ap l
subl = l.each_index.select { |i| l[i] =~ /^\s\s+/ } # find sublines that starts with at least two whitespaces
#ap subl
return false if subl.empty?
subl.any? { |i| l[i].split.include?(cmd) }
end
|
ruby
|
{
"resource": ""
}
|
q5798
|
FalkorLib.Git.init
|
train
|
def init(path = Dir.pwd, _options = {})
# FIXME: for travis test: ensure the global git configurations
# 'user.email' and 'user.name' are set
[ 'user.name', 'user.email' ].each do |userconf|
next unless MiniGit[userconf].nil?
warn "The Git global configuration '#{userconf}' is not set so"
warn "you should *seriously* consider setting them by running\n\t git config --global #{userconf} 'your_#{userconf.sub(/\./, '_')}'"
default_val = ENV['USER']
default_val += '@domain.org' if userconf =~ /email/
warn "Now putting a default value '#{default_val}' you could change later on"
run %(
git config --global #{userconf} "#{default_val}"
)
#MiniGit[userconf] = default_val
end
exit_status = 1
Dir.mkdir( path ) unless Dir.exist?( path )
Dir.chdir( path ) do
execute "git init" unless FalkorLib.config.debug
exit_status = $?.to_i
end
# #puts "#init #{path}"
# Dir.chdir( "#{path}" ) do
# %x[ pwd && git init ] unless FalkorLib.config.debug
# end
exit_status
end
|
ruby
|
{
"resource": ""
}
|
q5799
|
FalkorLib.Git.create_branch
|
train
|
def create_branch(branch, path = Dir.pwd)
#ap method(__method__).parameters.map { |arg| arg[1] }
g = MiniGit.new(path)
error "not yet any commit performed -- You shall do one" unless commits?(path)
g.branch branch.to_s
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.