_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q5900
|
Numerals.Numeral.approximate!
|
train
|
def approximate!(number_of_digits = nil)
if number_of_digits.nil?
if exact? && !repeating?
@repeat = nil
end
else
expand! number_of_digits
@digits.truncate! number_of_digits
@repeat = nil
end
self
end
|
ruby
|
{
"resource": ""
}
|
q5901
|
Mova.Scope.flatten
|
train
|
def flatten(translations, current_scope = nil)
translations.each_with_object({}) do |(key, value), memo|
scope = current_scope ? join(current_scope, key) : key.to_s
if value.is_a?(Hash)
memo.merge!(flatten(value, scope))
else
memo[scope] = value
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5902
|
Mova.Scope.cross_join
|
train
|
def cross_join(locales, keys)
locales.flat_map do |locale|
keys.map { |key| join(locale, key) }
end
end
|
ruby
|
{
"resource": ""
}
|
q5903
|
Csv2Psql.Analyzer.create_column
|
train
|
def create_column(data, column)
data[:columns][column] = {}
res = data[:columns][column]
analyzers.each do |analyzer|
analyzer_class = analyzer[:class]
res[analyzer[:name]] = {
class: analyzer_class.new,
results: create_results(analyzer_class)
}
end
res
end
|
ruby
|
{
"resource": ""
}
|
q5904
|
Csv2Psql.Analyzer.update_numeric_results
|
train
|
def update_numeric_results(ac, ar, val)
cval = ac.convert(val)
ar[:min] = cval if ar[:min].nil? || cval < ar[:min]
ar[:max] = cval if ar[:max].nil? || cval > ar[:max]
end
|
ruby
|
{
"resource": ""
}
|
q5905
|
PeijiSan.ViewHelper.link_to_page
|
train
|
def link_to_page(page, paginated_set, options = {}, html_options = {})
page_parameter = peiji_san_option(:page_parameter, options)
# Sinatra/Rails differentiator
pageable_params = respond_to?(:controller) ? controller.params : self.params
url_options = (page == 1 ? pageable_params.except(page_parameter) : pageable_params.merge(page_parameter => page))
anchor = peiji_san_option(:anchor, options)
url_options[:anchor] = anchor if anchor
html_options[:class] = peiji_san_option(:current_class, options) if paginated_set.current_page?(page)
# Again a little fork here
normalized_url_options = if respond_to?(:controller) # Rails
url_for(url_options)
else # Sinatra
root_path = env['PATH_INFO'].blank? ? "/" : env["PATH_INFO"]
url_for(root_path, url_options)
end
link_to page, normalized_url_options, html_options
end
|
ruby
|
{
"resource": ""
}
|
q5906
|
PeijiSan.ViewHelper.pages_to_link_to
|
train
|
def pages_to_link_to(paginated_set, options = {})
current, last = paginated_set.current_page, paginated_set.page_count
max = peiji_san_option(:max_visible, options)
separator = peiji_san_option(:separator, options)
if last <= max
(1..last).to_a
elsif current <= ((max / 2) + 1)
(1..(max - 2)).to_a + [separator, last]
elsif current >= (last - (max / 2))
[1, separator, *((last - (max - 3))..last)]
else
offset = (max - 4) / 2
[1, separator] + ((current - offset)..(current + offset)).to_a + [separator, last]
end
end
|
ruby
|
{
"resource": ""
}
|
q5907
|
Expedition.Client.devices
|
train
|
def devices
send(:devdetails) do |body|
body[:devdetails].collect { |attrs|
attrs.delete(:devdetails)
attrs[:variant] = attrs.delete(:name).downcase
attrs
}
end
end
|
ruby
|
{
"resource": ""
}
|
q5908
|
Expedition.Client.send
|
train
|
def send(command, *parameters, &block)
socket = TCPSocket.open(host, port)
socket.puts command_json(command, *parameters)
parse(socket.gets, &block)
ensure
socket.close if socket.respond_to?(:close)
end
|
ruby
|
{
"resource": ""
}
|
q5909
|
MuckEngine.FlashErrors.output_errors
|
train
|
def output_errors(title, options = {}, fields = nil, flash_only = false)
fields = [fields] unless fields.is_a?(Array)
flash_html = render(:partial => 'shared/flash_messages')
flash.clear
css_class = "class=\"#{options[:class] || 'error'}\"" unless options[:class].nil?
field_errors = render(:partial => 'shared/field_error', :collection => fields)
if flash_only || (!flash_html.empty? && field_errors.empty?)
# Only flash. Don't render errors for any fields
render(:partial => 'shared/flash_error_box', :locals => {:flash_html => flash_html, :css_class => css_class})
elsif !field_errors.empty?
# Field errors and/or flash
render(:partial => 'shared/error_box', :locals => {:title => title,
:flash_html => flash_html,
:field_errors => field_errors,
:css_class => css_class,
:extra_html => options[:extra_html]})
else
#nothing
''
end
end
|
ruby
|
{
"resource": ""
}
|
q5910
|
MuckEngine.FlashErrors.output_admin_messages
|
train
|
def output_admin_messages(fields = nil, title = '', options = { :class => 'notify-box' }, flash_only = false)
output_errors_ajax('admin-messages', title, options, fields, flash_only)
end
|
ruby
|
{
"resource": ""
}
|
q5911
|
TableMe.TablePagination.pagination_number_list
|
train
|
def pagination_number_list
(0...page_button_count).to_a.map do |n|
link_number = n + page_number_offset
number_span(link_number)
end.join(' ')
end
|
ruby
|
{
"resource": ""
}
|
q5912
|
Garcon.CopyOnWriteObserverSet.add_observer
|
train
|
def add_observer(observer=nil, func=:update, &block)
if observer.nil? && block.nil?
raise ArgumentError, 'should pass observer as a first argument or block'
elsif observer && block
raise ArgumentError.new('cannot provide both an observer and a block')
end
if block
observer = block
func = :call
end
begin
@mutex.lock
new_observers = @observers.dup
new_observers[observer] = func
@observers = new_observers
observer
ensure
@mutex.unlock
end
end
|
ruby
|
{
"resource": ""
}
|
q5913
|
Gogcom.News.parse
|
train
|
def parse(data)
rss = SimpleRSS.parse data
news = Array.new
rss.items.each do |item|
news_item = NewsItem.new(item.title, item.link, item.description.force_encoding("UTF-8"), item.pubDate)
news.push news_item
end
unless @limit.nil?
news.take(@limit)
else
news
end
end
|
ruby
|
{
"resource": ""
}
|
q5914
|
Mortadella.Horizontal.columns_indeces_to_drop
|
train
|
def columns_indeces_to_drop columns
result = []
headers = @table[0]
headers.each_with_index do |header, i|
result << i unless columns.include? header
end
result
end
|
ruby
|
{
"resource": ""
}
|
q5915
|
Mortadella.Horizontal.dry_up
|
train
|
def dry_up row
return row unless @previous_row
row.clone.tap do |result|
row.length.times do |i|
if can_dry?(@headers[i]) && row[i] == @previous_row[i]
result[i] = ''
else
break
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5916
|
Nucleon.Config.fetch
|
train
|
def fetch(data, keys, default = nil, format = false)
if keys.is_a?(String) || keys.is_a?(Symbol)
keys = [ keys ]
end
keys = keys.flatten.compact
key = keys.shift
if data.has_key?(key)
value = data[key]
if keys.empty?
return filter(value, format)
else
return fetch(data[key], keys, default, format) if data[key].is_a?(Hash)
end
end
return filter(default, format)
end
|
ruby
|
{
"resource": ""
}
|
q5917
|
Nucleon.Config.modify
|
train
|
def modify(data, keys, value = nil, delete_nil = false, &block) # :yields: key, value, existing
if keys.is_a?(String) || keys.is_a?(Symbol)
keys = [ keys ]
end
keys = keys.flatten.compact
key = keys.shift
has_key = data.has_key?(key)
existing = {
:key => key,
:value => ( has_key ? data[key] : nil )
}
if keys.empty?
if value.nil? && delete_nil
data.delete(key) if has_key
else
value = symbol_map(value) if value.is_a?(Hash)
data[key] = block ? block.call(key, value, existing[:value]) : value
end
else
data[key] = {} unless has_key
if data[key].is_a?(Hash)
existing = modify(data[key], keys, value, delete_nil, &block)
else
existing[:value] = nil
end
end
return existing
end
|
ruby
|
{
"resource": ""
}
|
q5918
|
Nucleon.Config.get
|
train
|
def get(keys, default = nil, format = false)
return fetch(@properties, symbol_array(array(keys).flatten), default, format)
end
|
ruby
|
{
"resource": ""
}
|
q5919
|
Nucleon.Config.set
|
train
|
def set(keys, value, delete_nil = false, &code) # :yields: key, value, existing
modify(@properties, symbol_array(array(keys).flatten), value, delete_nil, &code)
return self
end
|
ruby
|
{
"resource": ""
}
|
q5920
|
Nucleon.Config.append
|
train
|
def append(keys, value)
modify(@properties, symbol_array(array(keys).flatten), value, false) do |key, processed_value, existing|
if existing.is_a?(Array)
[ existing, processed_value ].flatten
else
[ processed_value ]
end
end
return self
end
|
ruby
|
{
"resource": ""
}
|
q5921
|
Nucleon.Config.prepend
|
train
|
def prepend(keys, value, reverse = false)
modify(@properties, symbol_array(array(keys).flatten), value, false) do |key, processed_value, existing|
processed_value = processed_value.reverse if reverse && processed_value.is_a?(Array)
if existing.is_a?(Array)
[ processed_value, existing ].flatten
else
[ processed_value ]
end
end
return self
end
|
ruby
|
{
"resource": ""
}
|
q5922
|
Nucleon.Config.delete
|
train
|
def delete(keys, default = nil)
existing = modify(@properties, symbol_array(array(keys).flatten), nil, true)
return existing[:value] unless existing[:value].nil?
return default
end
|
ruby
|
{
"resource": ""
}
|
q5923
|
Nucleon.Config.defaults
|
train
|
def defaults(defaults, options = {})
config = Config.new(options).set(:import_type, :default)
return import_base(defaults, config)
end
|
ruby
|
{
"resource": ""
}
|
q5924
|
Nucleon.Config.symbol_array
|
train
|
def symbol_array(array)
result = []
array.each do |item|
result << item.to_sym unless item.nil?
end
result
end
|
ruby
|
{
"resource": ""
}
|
q5925
|
StripeLocal.InstanceDelegation.signup
|
train
|
def signup params
plan = params.delete( :plan )
lines = params.delete( :lines ) || []
_customer_ = Stripe::Customer.create( params )
lines.each do |(amount,desc)|
_customer_.add_invoice_item({currency: 'usd', amount: amount, description: desc})
end
_customer_.update_subscription({ plan: plan })
StripeLocal::Customer.create _customer_.to_hash.reverse_merge({model_id: self.id})
end
|
ruby
|
{
"resource": ""
}
|
q5926
|
Axlsx.Package.simple
|
train
|
def simple(name = nil)
workbook.add_worksheet(name: name || 'Sheet 1') do |sheet|
yield sheet, workbook.predefined_styles if block_given?
sheet.add_row
end
end
|
ruby
|
{
"resource": ""
}
|
q5927
|
Axlsx.Workbook.predefined_styles
|
train
|
def predefined_styles
@predefined_styles ||=
begin
tmp = {}
styles do |s|
tmp = {
bold: s.add_style(b: true, alignment: { vertical: :top }),
date: s.add_style(format_code: 'mm/dd/yyyy', alignment: { vertical: :top }),
float: s.add_style(format_code: '#,##0.00', alignment: { vertical: :top }),
integer: s.add_style(format_code: '#,##0', alignment: { vertical: :top }),
percent: s.add_style(num_fmt: 9, alignment: { vertical: :top }),
currency: s.add_style(num_fmt: 7, alignment: { vertical: :top }),
text: s.add_style(format_code: '@', alignment: { vertical: :top }),
wrapped: s.add_style(alignment: { wrap_text: true, vertical: :top }),
normal: s.add_style(alignment: { vertical: :top })
}
end
tmp
end
end
|
ruby
|
{
"resource": ""
}
|
q5928
|
Axlsx.Worksheet.add_combined_row
|
train
|
def add_combined_row(row_data, keys = [ :value, :style, :type ])
val_index = keys.index(:value) || keys.index('value')
style_index = keys.index(:style) || keys.index('style')
type_index = keys.index(:type) || keys.index('type')
raise ArgumentError.new('Missing :value key') unless val_index
values = row_data.map{|v| v.is_a?(Array) ? v[val_index] : v }
styles = style_index ? row_data.map{ |v| v.is_a?(Array) ? v[style_index] : nil } : []
types = type_index ? row_data.map{ |v| v.is_a?(Array) ? v[type_index] : nil } : []
# allows specifying the style as just a symbol.
styles.each_with_index do |style,index|
if style.is_a?(String) || style.is_a?(Symbol)
styles[index] = workbook.predefined_styles[style.to_sym]
end
end
add_row values, style: styles, types: types
end
|
ruby
|
{
"resource": ""
}
|
q5929
|
Jinx.JoinHelper.join
|
train
|
def join(source, target, *fields, &block)
FileUtils.rm_rf OUTPUT
sf = File.expand_path("#{source}.csv", File.dirname(__FILE__))
tf = File.expand_path("#{target}.csv", File.dirname(__FILE__))
Jinx::CsvIO.join(sf, :to => tf, :for => fields, :as => OUTPUT, &block)
if File.exists?(OUTPUT) then
File.readlines(OUTPUT).map do |line|
line.chomp.split(',').map { |s| s unless s.blank? }
end
else
Array::EMPTY_ARRAY
end
end
|
ruby
|
{
"resource": ""
}
|
q5930
|
MuckEngine.FormBuilder.state_select
|
train
|
def state_select(method, options = {}, html_options = {}, additional_state = nil)
country_id_field_name = options.delete(:country_id) || 'country_id'
country_id = get_instance_object_value(country_id_field_name)
@states = country_id.nil? ? [] : (additional_state ? [additional_state] : []) + State.find(:all, :conditions => ["country_id = ?", country_id], :order => "name asc")
self.menu_select(method, I18n.t('muck.engine.choose_state'), @states, options.merge(:prompt => I18n.t('muck.engine.select_state_prompt'), :wrapper_id => 'states-container'), html_options.merge(:id => 'states'))
end
|
ruby
|
{
"resource": ""
}
|
q5931
|
MuckEngine.FormBuilder.country_select
|
train
|
def country_select(method, options = {}, html_options = {}, additional_country = nil)
@countries ||= (additional_country ? [additional_country] : []) + Country.find(:all, :order => 'sort, name asc')
self.menu_select(method, I18n.t('muck.engine.choose_country'), @countries, options.merge(:prompt => I18n.t('muck.engine.select_country_prompt'), :wrapper_id => 'countries-container'), html_options.merge(:id => 'countries'))
end
|
ruby
|
{
"resource": ""
}
|
q5932
|
MuckEngine.FormBuilder.language_select
|
train
|
def language_select(method, options = {}, html_options = {}, additional_language = nil)
@languages ||= (additional_language ? [additional_language] : []) + Language.find(:all, :order => 'name asc')
self.menu_select(method, I18n.t('muck.engine.choose_language'), @languages, options.merge(:prompt => I18n.t('muck.engine.select_language_prompt'), :wrapper_id => 'languages-container'), html_options.merge(:id => 'languages'))
end
|
ruby
|
{
"resource": ""
}
|
q5933
|
Incline.AuthEngineBase.add_success_to
|
train
|
def add_success_to(user, message, client_ip) # :doc:
Incline::Log::info "LOGIN(#{user}) SUCCESS FROM #{client_ip}: #{message}"
purge_old_history_for user
user.login_histories.create(ip_address: client_ip, successful: true, message: message)
end
|
ruby
|
{
"resource": ""
}
|
q5934
|
Sp2db.Config.credential=
|
train
|
def credential=cr
if File.exist?(cr) && File.file?(cr)
cr = File.read cr
end
@credential = case cr
when Hash, ActiveSupport::HashWithIndifferentAccess
cr
when String
JSON.parse cr
else
raise "Invalid data type"
end
end
|
ruby
|
{
"resource": ""
}
|
q5935
|
Wingtips.Slide.method_missing
|
train
|
def method_missing(method, *args, &blk)
if app_should_handle_method? method
app.send(method, *args, &blk)
else
super
end
end
|
ruby
|
{
"resource": ""
}
|
q5936
|
Usman.AuthenticationHelper.require_super_admin
|
train
|
def require_super_admin
unless @current_user.super_admin?
text = "#{I18n.t("authentication.permission_denied.heading")}: #{I18n.t("authentication.permission_denied.message")}"
set_flash_message(text, :error, false) if defined?(flash) && flash
redirect_or_popup_to_default_sign_in_page(false)
end
end
|
ruby
|
{
"resource": ""
}
|
q5937
|
Curtain.Rendering.render
|
train
|
def render(*args)
name = get_template_name(*args)
locals = args.last.is_a?(Hash) ? args.last : {}
# TODO: Cache Template objects
template_file = self.class.find_template(name)
ext = template_file.split('.').last
orig_buffer = @output_buffer
@output_buffer = Curtain::OutputBuffer.new
case ext
when 'slim'
template = ::Slim::Template.new(template_file, :buffer => '@output_buffer', :use_html_safe => true, :disable_capture => true, :generator => Temple::Generators::RailsOutputBuffer )
when 'erb'
template = ::Curtain::ErubisTemplate.new(template_file, :buffer => '@output_buffer', :use_html_safe => true, :disable_capture => true, :generator => Temple::Generators::RailsOutputBuffer )
else
raise "Curtain cannot process .#{ext} templates"
end
template.render(self, variables.merge(locals))
@output_buffer
ensure
@output_buffer = orig_buffer
end
|
ruby
|
{
"resource": ""
}
|
q5938
|
CellularMap.Map.[]
|
train
|
def [](x, y)
if x.respond_to?(:to_i) && y.respond_to?(:to_i)
Cell.new(x, y, self)
else
Zone.new(x, y, self)
end
end
|
ruby
|
{
"resource": ""
}
|
q5939
|
CellularMap.Map.[]=
|
train
|
def []=(x, y, content)
if content.nil?
@store.delete([x, y]) && nil
else
@store[[x, y]] = content
end
end
|
ruby
|
{
"resource": ""
}
|
q5940
|
Bebox.NodeWizard.create_new_node
|
train
|
def create_new_node(project_root, environment)
# Ask the hostname for node
hostname = ask_not_existing_hostname(project_root, environment)
# Ask IP for node
ip = ask_ip(environment)
# Node creation
node = Bebox::Node.new(environment, project_root, hostname, ip)
output = node.create
ok _('wizard.node.creation_success')
return output
end
|
ruby
|
{
"resource": ""
}
|
q5941
|
Bebox.NodeWizard.remove_node
|
train
|
def remove_node(project_root, environment, hostname)
# Ask for a node to remove
nodes = Bebox::Node.list(project_root, environment, 'nodes')
if nodes.count > 0
hostname = choose_option(nodes, _('wizard.node.choose_node'))
else
error _('wizard.node.no_nodes')%{environment: environment}
return true
end
# Ask for deletion confirmation
return warn(_('wizard.no_changes')) unless confirm_action?(_('wizard.node.confirm_deletion'))
# Node deletion
node = Bebox::Node.new(environment, project_root, hostname, nil)
output = node.remove
ok _('wizard.node.deletion_success')
return output
end
|
ruby
|
{
"resource": ""
}
|
q5942
|
Bebox.NodeWizard.set_role
|
train
|
def set_role(project_root, environment)
roles = Bebox::Role.list(project_root)
nodes = Bebox::Node.list(project_root, environment, 'nodes')
node = choose_option(nodes, _('wizard.choose_node'))
role = choose_option(roles, _('wizard.choose_role'))
output = Bebox::Provision.associate_node_role(project_root, environment, node, role)
ok _('wizard.node.role_set_success')
return output
end
|
ruby
|
{
"resource": ""
}
|
q5943
|
Bebox.NodeWizard.prepare
|
train
|
def prepare(project_root, environment)
# Check already prepared nodes
nodes_to_prepare = check_nodes_to_prepare(project_root, environment)
# Output the nodes to be prepared
if nodes_to_prepare.count > 0
title _('wizard.node.prepare_title')
nodes_to_prepare.each{|node| msg(node.hostname)}
linebreak
# For all environments regenerate the deploy file
Bebox::Node.regenerate_deploy_file(project_root, environment, nodes_to_prepare)
# If environment is 'vagrant' Prepare and Up the machines
up_vagrant_machines(project_root, nodes_to_prepare) if environment == 'vagrant'
# For all the environments do the preparation
nodes_to_prepare.each do |node|
node.prepare
ok _('wizard.node.preparation_success')
end
else
warn _('wizard.node.no_prepare_nodes')
end
return true
end
|
ruby
|
{
"resource": ""
}
|
q5944
|
Bebox.NodeWizard.check_nodes_to_prepare
|
train
|
def check_nodes_to_prepare(project_root, environment)
nodes_to_prepare = []
nodes = Bebox::Node.nodes_in_environment(project_root, environment, 'nodes')
prepared_nodes = Bebox::Node.list(project_root, environment, 'prepared_nodes')
nodes.each do |node|
if prepared_nodes.include?(node.hostname)
message = _('wizard.node.confirm_preparation')%{hostname: node.hostname, start: node.checkpoint_parameter_from_file('prepared_nodes', 'started_at'), end: node.checkpoint_parameter_from_file('prepared_nodes', 'finished_at')}
nodes_to_prepare << node if confirm_action?(message)
else
nodes_to_prepare << node
end
end
nodes_to_prepare
end
|
ruby
|
{
"resource": ""
}
|
q5945
|
Bebox.NodeWizard.ask_not_existing_hostname
|
train
|
def ask_not_existing_hostname(project_root, environment)
hostname = ask_hostname(project_root, environment)
# Check if the node not exist
if node_exists?(project_root, environment, hostname)
error _('wizard.node.hostname_exist')
ask_hostname(project_root, environment)
else
return hostname
end
end
|
ruby
|
{
"resource": ""
}
|
q5946
|
Bebox.NodeWizard.ask_ip
|
train
|
def ask_ip(environment)
ip = write_input(_('wizard.node.ask_ip'), nil, /\.(.*)/, _('wizard.node.valid_ip'))
# If the environment is not vagrant don't check ip free
return ip if environment != 'vagrant'
# Check if the ip address is free
if free_ip?(ip)
return ip
else
error _('wizard.node.non_free_ip')
ask_ip(environment)
end
end
|
ruby
|
{
"resource": ""
}
|
q5947
|
Mintkit.Client.transactions
|
train
|
def transactions
raw_transactions = @agent.get("https://wwws.mint.com/transactionDownload.event?").body
transos = []
raw_transactions.split("\n").each_with_index do |line,index|
if index > 1
line_array = line.split(",")
transaction = {
:date => Date.strptime(remove_quotes(line_array[0]), '%m/%d/%Y'),
:description=>remove_quotes(line_array[1]),
:original_description=>remove_quotes(line_array[2]),
:amount=>remove_quotes(line_array[3]).to_f,
:type=>remove_quotes(line_array[4]),
:category=>remove_quotes(line_array[5]),
:account=>remove_quotes(line_array[6]),
:labels=>remove_quotes(line_array[7]),
:notes=>remove_quotes(line_array[8])
}
transos << transaction
if block_given?
yield transaction
end
end
end
transos
end
|
ruby
|
{
"resource": ""
}
|
q5948
|
WhoopsLogger.Configuration.set_with_string
|
train
|
def set_with_string(config)
if File.exists?(config)
set_with_yaml(File.read(config))
else
set_with_yaml(config)
end
end
|
ruby
|
{
"resource": ""
}
|
q5949
|
KeteTrackableItems.ListManagementControllers.remove_from_list
|
train
|
def remove_from_list
begin
matching_results_ids = session[:matching_results_ids]
matching_results_ids.delete(params[:remove_id].to_i)
session[:matching_results_ids] = matching_results_ids
render :nothing => true
rescue
render :nothing => true, :status => 500
end
end
|
ruby
|
{
"resource": ""
}
|
q5950
|
KeteTrackableItems.ListManagementControllers.restore_to_list
|
train
|
def restore_to_list
begin
matching_results_ids = session[:matching_results_ids]
session[:matching_results_ids] = matching_results_ids << params[:restore_id].to_i
render :nothing => true
rescue
render :nothing => true, :status => 500
end
end
|
ruby
|
{
"resource": ""
}
|
q5951
|
Ruta.Context.sub_context
|
train
|
def sub_context id,ref,attribs={}
@sub_contexts << ref
self.elements[id] = {
attributes: attribs,
type: :sub_context,
content: ref,
}
end
|
ruby
|
{
"resource": ""
}
|
q5952
|
Smartdict.Translator::Base.call
|
train
|
def call(word, opts)
validate_opts!(opts)
driver = Smartdict::Core::DriverManager.find(opts[:driver])
translation_model = Models::Translation.find(word, opts[:from_lang], opts[:to_lang], opts[:driver])
unless translation_model
translation = driver.translate(word, opts[:from_lang], opts[:to_lang])
translation_model = Models::Translation.create_from_struct(translation)
end
log_query(translation_model) if opts[:log]
translation_model.to_struct
end
|
ruby
|
{
"resource": ""
}
|
q5953
|
Mongoid.MultiParameterAttributes.process_attributes
|
train
|
def process_attributes(attrs = nil)
if attrs
errors = []
attributes = attrs.class.new
attributes.permit! if attrs.respond_to?(:permitted?) && attrs.permitted?
multi_parameter_attributes = {}
attrs.each_pair do |key, value|
if key =~ /\A([^\(]+)\((\d+)([if])\)$/
key, index = $1, $2.to_i
(multi_parameter_attributes[key] ||= {})[index] = value.empty? ? nil : value.send("to_#{$3}")
else
attributes[key] = value
end
end
multi_parameter_attributes.each_pair do |key, values|
begin
values = (values.keys.min..values.keys.max).map { |i| values[i] }
field = self.class.fields[database_field_name(key)]
attributes[key] = instantiate_object(field, values)
rescue => e
errors << Errors::AttributeAssignmentError.new(
"error on assignment #{values.inspect} to #{key}", e, key
)
end
end
unless errors.empty?
raise Errors::MultiparameterAssignmentErrors.new(errors),
"#{errors.size} error(s) on assignment of multiparameter attributes"
end
super(attributes)
else
super
end
end
|
ruby
|
{
"resource": ""
}
|
q5954
|
Remi.Loader::S3File.load
|
train
|
def load(data)
init_kms(@kms_opt)
@logger.info "Writing file #{data} to S3 #{@bucket_name} as #{@remote_path}"
s3.bucket(@bucket_name).object(@remote_path).upload_file(data, encrypt_args)
true
end
|
ruby
|
{
"resource": ""
}
|
q5955
|
Skeletor.Builder.build_skeleton
|
train
|
def build_skeleton(dirs,path=@path)
dirs.each{
|node|
if node.kind_of?(Hash) && !node.empty?()
node.each_pair{
|dir,content|
dir = replace_tags(dir)
puts 'Creating directory ' + File.join(path,dir)
Dir.mkdir(File.join(path,dir))
if content.kind_of?(Array) && !content.empty?()
build_skeleton(content,File.join(path,dir))
end
}
elsif node.kind_of?(Array) && !node.empty?()
node.each{
|file|
write_file(file,path)
}
end
}
end
|
ruby
|
{
"resource": ""
}
|
q5956
|
Skeletor.Builder.write_file
|
train
|
def write_file(file,path)
#if a pre-existing file is specified in the includes list, copy that, if not write a blank file
if @template.includes.has_key?(file)
begin
content = Includes.copy_include(@template.includes[file],@template.path)
file = replace_tags(file)
rescue TypeError => e
puts e.message
exit
end
else
file = replace_tags(file)
puts 'Creating blank file: ' + File.join(path,file)
content=''
end
File.open(File.join(path,file),'w'){|f| f.write(replace_tags(content))}
end
|
ruby
|
{
"resource": ""
}
|
q5957
|
Skeletor.Builder.execute_tasks
|
train
|
def execute_tasks(tasks,template_path)
if File.exists?(File.expand_path(File.join(template_path,'tasks.rb')))
load File.expand_path(File.join(template_path,'tasks.rb'))
end
tasks.each{
|task|
puts 'Running Task: ' + task
task = replace_tags(task);
options = task.split(', ')
action = options.slice!(0)
if(Tasks.respond_to?(action))
Tasks.send action, options.join(', ')
else
send action, options.join(', ')
end
}
end
|
ruby
|
{
"resource": ""
}
|
q5958
|
Hornetseye.Pointer_.assign
|
train
|
def assign( value )
if @value.respond_to? :assign
@value.assign value.simplify.get
else
@value = value.simplify.get
end
value
end
|
ruby
|
{
"resource": ""
}
|
q5959
|
Hornetseye.Pointer_.store
|
train
|
def store( value )
result = value.simplify
self.class.target.new(result.get).write @value
result
end
|
ruby
|
{
"resource": ""
}
|
q5960
|
UserInput.OptionParser.define_value
|
train
|
def define_value(short_name, long_name, description, flag, default_value, validate = nil)
short_name = short_name.to_s
long_name = long_name.to_s
if (short_name.length != 1)
raise ArgumentError, "Short name must be one character long (#{short_name})"
end
if (long_name.length < 2)
raise ArgumentError, "Long name must be more than one character long (#{long_name})"
end
info = Info.new(short_name, long_name, description, flag, default_value, nil, validate)
@options[long_name] = info
@options[short_name] = info
@order.push(info)
method_name = long_name.gsub('-','_')
method_name << "?" if (flag)
(class <<self; self; end).class_eval do
define_method(method_name.to_sym) do
return @options[long_name].value || @options[long_name].default_value
end
end
return self
end
|
ruby
|
{
"resource": ""
}
|
q5961
|
UserInput.OptionParser.argument
|
train
|
def argument(short_name, long_name, description, default_value, validate = nil, &block)
return define_value(short_name, long_name, description, false, default_value, validate || block)
end
|
ruby
|
{
"resource": ""
}
|
q5962
|
UserInput.OptionParser.flag
|
train
|
def flag(short_name, long_name, description, &block)
return define_value(short_name, long_name, description, true, false, block)
end
|
ruby
|
{
"resource": ""
}
|
q5963
|
Roroacms.SetupController.create
|
train
|
def create
# To do update this table we loop through the fields and update the key with the value.
# In order to do this we need to remove any unnecessary keys from the params hash
remove_unwanted_keys
# loop through the param fields and update the key with the value
validation = Setting.manual_validation(params)
respond_to do |format|
if validation.blank?
Setting.save_data(params)
clear_cache
format.html { redirect_to administrator_setup_index_path, notice: I18n.t("controllers.admin.setup.general.success") }
else
format.html {
# add breadcrumb and set title
@settings = params
@settings['errors'] = validation
render action: "index"
}
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5964
|
Roroacms.SetupController.create_user
|
train
|
def create_user
@admin = Admin.new(administrator_params)
@admin.access_level = 'admin'
@admin.overlord = 'Y'
respond_to do |format|
if @admin.save
Setting.save_data({setup_complete: 'Y'})
clear_cache
session[:setup_complete] = true
format.html { redirect_to admin_path, notice: I18n.t("controllers.admin.setup.general.success") }
else
format.html { render action: "administrator" }
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5965
|
CLIntegracon.FileTreeSpec.compare
|
train
|
def compare(&diff_block)
# Get a copy of the outputs before any transformations are applied
FileUtils.cp_r("#{temp_transformed_path}/.", temp_raw_path)
transform_paths!
glob_all(after_path).each do |relative_path|
expected = after_path + relative_path
next unless expected.file?
next if context.ignores?(relative_path)
block = context.preprocessors_for(relative_path).first
diff = diff_files(expected, relative_path, &block)
diff_block.call diff
end
end
|
ruby
|
{
"resource": ""
}
|
q5966
|
CLIntegracon.FileTreeSpec.check_unexpected_files
|
train
|
def check_unexpected_files(&block)
expected_files = glob_all after_path
produced_files = glob_all
unexpected_files = produced_files - expected_files
# Select only files
unexpected_files.select! { |path| path.file? }
# Filter ignored paths
unexpected_files.reject! { |path| context.ignores?(path) }
block.call unexpected_files
end
|
ruby
|
{
"resource": ""
}
|
q5967
|
CLIntegracon.FileTreeSpec.prepare!
|
train
|
def prepare!
context.prepare!
temp_path.rmtree if temp_path.exist?
temp_path.mkdir
temp_raw_path.mkdir
temp_transformed_path.mkdir
end
|
ruby
|
{
"resource": ""
}
|
q5968
|
CLIntegracon.FileTreeSpec.copy_files!
|
train
|
def copy_files!
destination = temp_transformed_path
if has_base?
FileUtils.cp_r("#{base_spec.temp_raw_path}/.", destination)
end
begin
FileUtils.cp_r("#{before_path}/.", destination)
rescue Errno::ENOENT => e
raise e unless has_base?
end
end
|
ruby
|
{
"resource": ""
}
|
q5969
|
CLIntegracon.FileTreeSpec.transform_paths!
|
train
|
def transform_paths!
glob_all.each do |path|
context.transformers_for(path).each do |transformer|
transformer.call(path) if path.exist?
end
path.rmtree if context.ignores?(path) && path.exist?
end
end
|
ruby
|
{
"resource": ""
}
|
q5970
|
CLIntegracon.FileTreeSpec.glob_all
|
train
|
def glob_all(path=nil)
Dir.chdir path || '.' do
Pathname.glob("**/*", context.include_hidden_files? ? File::FNM_DOTMATCH : 0).sort.reject do |p|
%w(. ..).include?(p.basename.to_s)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5971
|
CLIntegracon.FileTreeSpec.diff_files
|
train
|
def diff_files(expected, relative_path, &block)
produced = temp_transformed_path + relative_path
Diff.new(expected, produced, relative_path, &block)
end
|
ruby
|
{
"resource": ""
}
|
q5972
|
Ladder.Resource.klass_from_predicate
|
train
|
def klass_from_predicate(predicate)
field_name = field_from_predicate(predicate)
return unless field_name
relation = relations[field_name]
return unless relation
relation.class_name.constantize
end
|
ruby
|
{
"resource": ""
}
|
q5973
|
Ladder.Resource.field_from_predicate
|
train
|
def field_from_predicate(predicate)
defined_prop = resource_class.properties.find { |_field_name, term| term.predicate == predicate }
return unless defined_prop
defined_prop.first
end
|
ruby
|
{
"resource": ""
}
|
q5974
|
Ladder.Resource.update_relation
|
train
|
def update_relation(field_name, *obj)
# Should be an Array of RDF::Term objects
return unless obj
obj.map! { |item| item.is_a?(RDF::URI) ? Ladder::Resource.from_uri(item) : item }
relation = send(field_name)
if Mongoid::Relations::Targets::Enumerable == relation.class
obj.map { |item| relation.send(:push, item) unless relation.include? item }
else
send("#{field_name}=", obj.size > 1 ? obj : obj.first)
end
end
|
ruby
|
{
"resource": ""
}
|
q5975
|
Ladder.Resource.update_field
|
train
|
def update_field(field_name, *obj)
# Should be an Array of RDF::Term objects
return unless obj
if fields[field_name] && fields[field_name].localized?
trans = {}
obj.each do |item|
lang = item.is_a?(RDF::Literal) && item.has_language? ? item.language.to_s : I18n.locale.to_s
value = item.is_a?(RDF::URI) ? item.to_s : item.object # TODO: tidy this up
trans[lang] = trans[lang] ? [*trans[lang]] << value : value
end
send("#{field_name}_translations=", trans) unless trans.empty?
else
objects = obj.map { |item| item.is_a?(RDF::URI) ? item.to_s : item.object } # TODO: tidy this up
send("#{field_name}=", objects.size > 1 ? objects : objects.first)
end
end
|
ruby
|
{
"resource": ""
}
|
q5976
|
Ladder.Resource.cast_value
|
train
|
def cast_value(value, opts = {})
case value
when Array
value.map { |v| cast_value(v, opts) }
when String
cast_uri = RDF::URI.new(value)
cast_uri.valid? ? cast_uri : RDF::Literal.new(value, opts)
when Time
# Cast DateTimes with 00:00:00 or Date stored as Times in Mongoid to xsd:date
# FIXME: this should NOT be applied for fields that are typed as Time
value.midnight == value ? RDF::Literal.new(value.to_date) : RDF::Literal.new(value.to_datetime)
else
RDF::Literal.new(value, opts)
end
end
|
ruby
|
{
"resource": ""
}
|
q5977
|
Ladder.File.data
|
train
|
def data
@grid_file ||= self.class.grid.get(id) if persisted?
return @grid_file.data if @grid_file
file.rewind if file.respond_to? :rewind
file.read
end
|
ruby
|
{
"resource": ""
}
|
q5978
|
Incline::Extensions.Numeric.to_human
|
train
|
def to_human
Incline::Extensions::Numeric::SHORT_SCALE.each do |(num,label)|
if self >= num
# Add 0.0001 to the value before rounding it off.
# This way we're telling the system that we want it to round up instead of round to even.
s = ('%.2f' % ((self.to_f / num) + 0.0001)).gsub(/\.?0+\z/,'')
return "#{s} #{label}"
end
end
if self.is_a?(::Rational)
if self.denominator == 1
return self.numerator.to_s
end
return self.to_s
elsif self.is_a?(::Integer)
return self.to_s
end
# Again we want to add the 0.0001 to the value before rounding.
('%.2f' % (self.to_f + 0.0001)).gsub(/\.?0+\z/,'')
end
|
ruby
|
{
"resource": ""
}
|
q5979
|
SublimeSunippetter.Core.generate_sunippets
|
train
|
def generate_sunippets
sunippet_define = read_sunippetdefine
dsl = Dsl.new
dsl.instance_eval sunippet_define
output_methods(dsl)
output_requires(dsl)
end
|
ruby
|
{
"resource": ""
}
|
q5980
|
ActiveMetrics.Instrumentable.count
|
train
|
def count(event, number = 1)
ActiveMetrics::Collector.record(event, { metric: 'count', value: number })
end
|
ruby
|
{
"resource": ""
}
|
q5981
|
ActiveMetrics.Instrumentable.measure
|
train
|
def measure(event, value = 0)
if block_given?
time = Time.now
# Store the value returned by the block for future reference
value = yield
delta = Time.now - time
ActiveMetrics::Collector.record(event, { metric: 'measure', value: delta })
value
else
ActiveMetrics::Collector.record(event, { metric: 'measure', value: value })
end
end
|
ruby
|
{
"resource": ""
}
|
q5982
|
Sumac.Connection.messenger_received_message
|
train
|
def messenger_received_message(message_string)
#puts "receive|#{message_string}"
begin
message = Messages.from_json(message_string)
rescue ProtocolError
@scheduler.receive(:invalid_message)
return
end
case message
when Messages::CallRequest then @scheduler.receive(:call_request_message, message)
when Messages::CallResponse then @scheduler.receive(:call_response_message, message)
when Messages::Compatibility then @scheduler.receive(:compatibility_message, message)
when Messages::Forget then @scheduler.receive(:forget_message, message)
when Messages::Initialization then @scheduler.receive(:initialization_message, message)
when Messages::Shutdown then @scheduler.receive(:shutdown_message)
end
end
|
ruby
|
{
"resource": ""
}
|
q5983
|
WinPathUtils.Path.add
|
train
|
def add(value, options = {})
# Set defaults
options[:duplication_filter] = :do_not_add unless options.key?(:duplication_filter)
# Get path
path = get_array
# Check duplicates
if path.member?(value)
case options[:duplication_filter]
when :do_not_add, :deny
# do nothing, we already have one in the list
return
when :remove_existing
path.delete!(value)
when :none
# just pass through
else
raise WrongOptionError, "Unknown :duplication_filter!"
end
end
# Change path array
case options[:where]
when :start, :left
path.unshift value
when :end, :right
path.push value
else
raise WrongOptionError, "Unknown :where!"
end
# Save new array
set_array(path)
end
|
ruby
|
{
"resource": ""
}
|
q5984
|
WinPathUtils.Path.with_reg
|
train
|
def with_reg(access_mask = Win32::Registry::Constants::KEY_ALL_ACCESS, &block)
@hkey.open(@reg_path, access_mask, &block)
end
|
ruby
|
{
"resource": ""
}
|
q5985
|
Associates.Validations.valid_with_associates?
|
train
|
def valid_with_associates?(context = nil)
# Model validations
valid_without_associates?(context)
# Associated models validations
self.class.associates.each do |associate|
model = send(associate.name)
model.valid?(context)
model.errors.each_entry do |attribute, message|
# Do not include association presence validation errors
if associate.dependent_names.include?(attribute.to_s)
next
elsif respond_to?(attribute)
errors.add(attribute, message)
else
errors.add(:base, model.errors.full_messages_for(attribute))
end
end
end
errors.messages.values.each(&:uniq!)
errors.none?
end
|
ruby
|
{
"resource": ""
}
|
q5986
|
ARK.Log.say
|
train
|
def say(msg, sym='...', loud=false, indent=0)
return false if Conf[:quiet]
return false if loud && !Conf[:verbose]
unless msg == ''
time = ""
if Conf[:timed]
time = Timer.time.to_s.ljust(4, '0')
time = time + " "
end
indent = " " * indent
indent = " " if indent == ""
puts "#{time}#{sym}#{indent}#{msg}"
else
puts
end
end
|
ruby
|
{
"resource": ""
}
|
q5987
|
Trooper.Configuration.load_troopfile!
|
train
|
def load_troopfile!(options)
if troopfile?
eval troopfile.read
@loaded = true
load_environment!
set options
else
raise Trooper::NoConfigurationFileError, "No Configuration file (#{self[:file_name]}) can be found!"
end
end
|
ruby
|
{
"resource": ""
}
|
q5988
|
RComp.Suite.load
|
train
|
def load(pattern=nil)
tests = []
# Find all tests in the tests directory
Find.find @@conf.test_root do |path|
# recurse into all subdirectories
next if File.directory? path
# filter tests by pattern if present
if pattern
next unless rel_path(path).match(pattern)
end
# ignore dotfiles
next if File.basename(path).match(/^\..*/)
# ignore files in ignore filter
next if ignored?(path)
tests << Test.new(path)
end
return tests
end
|
ruby
|
{
"resource": ""
}
|
q5989
|
RComp.Suite.ignored?
|
train
|
def ignored?(path)
@@conf.ignore.each do |ignore|
return true if rel_path(path).match(ignore)
end
return false
end
|
ruby
|
{
"resource": ""
}
|
q5990
|
Hornetseye.Malloc.save
|
train
|
def save( value )
write value.values.pack( value.typecode.directive )
value
end
|
ruby
|
{
"resource": ""
}
|
q5991
|
Roroacms.Admin::ThemesController.create
|
train
|
def create
# the theme used is set in the settings area - this does the update of the current theme used
Setting.where("setting_name = 'theme_folder'").update_all('setting' => params[:theme])
Setting.reload_settings
respond_to do |format|
format.html { redirect_to admin_themes_path, notice: I18n.t("controllers.admin.themes.create.flash.success") }
end
end
|
ruby
|
{
"resource": ""
}
|
q5992
|
Roroacms.Admin::ThemesController.destroy
|
train
|
def destroy
# remove the directory from the directory structure
destory_theme params[:id]
respond_to do |format|
format.html { redirect_to admin_themes_path, notice: I18n.t("controllers.admin.themes.destroy.flash.success") }
end
end
|
ruby
|
{
"resource": ""
}
|
q5993
|
Faker.CustomIpsum.sentence
|
train
|
def sentence
# Determine the number of comma-separated sections and number of words in
# each section for this sentence.
sections = []
1.upto(rand(5)+1) do
sections << (words(rand(9)+3).join(" "))
end
s = sections.join(", ")
return s.capitalize + ".?!".slice(rand(3),1)
end
|
ruby
|
{
"resource": ""
}
|
q5994
|
Bebox.ProjectWizard.create_new_project
|
train
|
def create_new_project(project_name)
# Check project existence
(error(_('wizard.project.name_exist')); return false) if project_exists?(Dir.pwd, project_name)
# Setup the bebox boxes directory
bebox_boxes_setup
# Asks to choose an existing box
current_box = choose_box(get_existing_boxes)
vagrant_box_base = "#{BEBOX_BOXES_PATH}/#{get_valid_box_uri(current_box)}"
# Asks user to choose vagrant box provider
vagrant_box_provider = choose_option(%w{virtualbox vmware}, _('wizard.project.choose_box_provider'))
# Set default environments
default_environments = %w{vagrant staging production}
# Project creation
project = Bebox::Project.new(project_name, vagrant_box_base, Dir.pwd, vagrant_box_provider, default_environments)
output = project.create
ok _('wizard.project.creation_success')%{project_name: project_name}
return output
end
|
ruby
|
{
"resource": ""
}
|
q5995
|
Bebox.ProjectWizard.uri_valid?
|
train
|
def uri_valid?(vbox_uri)
require 'uri'
uri = URI.parse(vbox_uri)
%w{http https}.include?(uri.scheme) ? http_uri_valid?(uri) : file_uri_valid?(uri)
end
|
ruby
|
{
"resource": ""
}
|
q5996
|
Bebox.ProjectWizard.get_existing_boxes
|
train
|
def get_existing_boxes
# Converts the bebox boxes directory to an absolute pathname
expanded_directory = File.expand_path("#{BEBOX_BOXES_PATH}")
# Get an array of bebox boxes paths
boxes = Dir["#{expanded_directory}/*"].reject {|f| File.directory? f}
boxes.map{|box| box.split('/').last}
end
|
ruby
|
{
"resource": ""
}
|
q5997
|
Bebox.ProjectWizard.choose_box
|
train
|
def choose_box(boxes)
# Menu to choose vagrant box provider
other_box_message = _('wizard.project.download_select_box')
boxes << other_box_message
current_box = choose_option(boxes, _('wizard.project.choose_box'))
current_box = (current_box == other_box_message) ? nil : current_box
end
|
ruby
|
{
"resource": ""
}
|
q5998
|
Bebox.ProjectWizard.download_box
|
train
|
def download_box(uri)
require 'net/http'
require 'uri'
url = uri.path
# Download file to bebox boxes tmp
Net::HTTP.start(uri.host) do |http|
response = http.request_head(URI.escape(url))
write_remote_file(uri, http, response)
end
end
|
ruby
|
{
"resource": ""
}
|
q5999
|
Garcon.Executor.handle_fallback
|
train
|
def handle_fallback(*args)
case @fallback_policy
when :abort
raise RejectedExecutionError
when :discard
false
when :caller_runs
begin
yield(*args)
rescue => e
Chef::Log.debug "Caught exception => #{e}"
end
true
else
fail "Unknown fallback policy #{@fallback_policy}"
end
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.