_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3
values | text stringlengths 66 10.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q9700 | Oshpark.Client.add_order_item | train | def add_order_item id, project_id, quantity
post_request "orders/#{id}/add_item", {order: {project_id: project_id, quantity: quantity}}
end | ruby | {
"resource": ""
} |
q9701 | Jive.SignedRequest.sign | train | def sign(string, secret, algorithm = nil)
plain = ::Base64.decode64(secret.gsub(/\.s$/,''))
# if no override algorithm passed try and extract from string
if algorithm.nil?
paramMap = ::CGI.parse string
if !paramMap.has_key?("algorithm")
raise ArgumentError, "missing algorithm"
end
al... | ruby | {
"resource": ""
} |
q9702 | Jive.SignedRequest.authenticate | train | def authenticate(authorization_header, client_secret)
# Validate JiveEXTN part of header
if !authorization_header.match(/^JiveEXTN/)
raise ArgumentError, "Jive authorization header is not properly formatted, must start with JiveEXTN"
end
paramMap = ::CGI.parse authorization_header.gsub(/^JiveEXTN\s/,''... | ruby | {
"resource": ""
} |
q9703 | Jive.SignedRequest.validate_registration | train | def validate_registration(validationBlock, *args)
options = ((args.last.is_a?(Hash)) ? args.pop : {})
require "open-uri"
require "net/http"
require "openssl"
jive_signature_url = validationBlock[:jiveSignatureURL]
jive_signature = validationBlock[:jiveSignature]
validationBlock.delete(:jiveSigna... | ruby | {
"resource": ""
} |
q9704 | Gem::Keychain.ConfigFileExtensions.load_api_keys | train | def load_api_keys
fallback = load_file(credentials_path) if File.exists?(credentials_path)
@api_keys = Gem::Keychain::ApiKeys.new(fallback: fallback)
end | ruby | {
"resource": ""
} |
q9705 | Blueprint.CustomLayout.generate_grid_css | train | def generate_grid_css
# loads up erb template to evaluate custom widths
css = ERB::new(File.path_to_string(CustomLayout::CSS_ERB_FILE))
# bind it to this instance
css.result(binding)
end | ruby | {
"resource": ""
} |
q9706 | CommonViewHelpers.ViewHelpers.info_pair | train | def info_pair(label, value)
value = content_tag(:span, "None", :class => "blank") if value.blank?
label = content_tag(:span, "#{label}:", :class => "label")
content_tag(:span, [label, value].join(" "), :class => "info_pair")
end | ruby | {
"resource": ""
} |
q9707 | CommonViewHelpers.ViewHelpers.generate_table | train | def generate_table(collection, headers=nil, options={})
return if collection.blank?
thead = content_tag(:thead) do
content_tag(:tr) do
headers.map {|header| content_tag(:th, header)}
end
end unless headers.nil?
tbody = content_tag(:tbody) do
collection.map do |v... | ruby | {
"resource": ""
} |
q9708 | CommonViewHelpers.ViewHelpers.options_td | train | def options_td(record_or_name_or_array, hide_destroy = false)
items = []
items << link_to('Edit', edit_polymorphic_path(record_or_name_or_array))
items << link_to('Delete', polymorphic_path(record_or_name_or_array), :confirm => 'Are you sure?', :method => :delete, :class => "destructive") unless hide_... | ruby | {
"resource": ""
} |
q9709 | CommonViewHelpers.ViewHelpers.link | train | def link(name, options={}, html_options={})
link_to_unless_current(name, options, html_options) do
html_options[:class] = (html_options[:class] || "").split(" ").push("active").join(" ")
link_to(name, options, html_options)
end
end | ruby | {
"resource": ""
} |
q9710 | CommonViewHelpers.ViewHelpers.list_model_columns | train | def list_model_columns(obj)
items = obj.class.columns.map{ |col| info_pair(col.name, obj[col.name]) }
content_tag(:ul, convert_to_list_items(items), :class => "model_columns")
end | ruby | {
"resource": ""
} |
q9711 | ActiveRecord.Migrator.ddl_transaction | train | def ddl_transaction(&block)
if Base.connection.supports_ddl_transactions?
Base.transaction { block.call }
else
block.call
end
end | ruby | {
"resource": ""
} |
q9712 | StringTree.Node.add_vertical | train | def add_vertical(str, value)
node = nil
str.each_char { |c|
if (node == nil)
node = self.add_horizontal_char(c)
elsif (node.down != nil)
node = node.down.add_horizontal_char(c)
else
node.down = Node.new(c, node)
node = node.down
end
... | ruby | {
"resource": ""
} |
q9713 | StringTree.Node.find_vertical | train | def find_vertical(str, offset = 0, length = str.length-offset)
node = nil
i = offset
while (i<offset+length)
c = str[i]
if (node == nil)
node = self.find_horizontal(c)
elsif (node.down != nil)
node = node.down.find_horizontal(c)
else
return... | ruby | {
"resource": ""
} |
q9714 | StringTree.Node.balance | train | def balance
node = self
i = (node.count(:right) - node.count(:left))/2
while (i!=0)
if (i>0)
mvnode = node.right
node.right = nil
mvnode.add_horizontal node
i -= 1
else
mvnode = node.left
node.left = nil
mvnode.add_h... | ruby | {
"resource": ""
} |
q9715 | StringTree.Node.walk | train | def walk(str="", &block)
@down.walk(str+char, &block) if @down != nil
@left.walk(str, &block) if @left != nil
yield str+@char, @value if @value != nil
@right.walk(str, &block) if @right != nil
end | ruby | {
"resource": ""
} |
q9716 | StringTree.Node.to_s | train | def to_s
st = @char
node = self
while node != nil
node = node.up
break if node==nil
st = node.char+st
end
st
end | ruby | {
"resource": ""
} |
q9717 | StringTree.Node.all_partials | train | def all_partials(str = "")
list = []
@down.walk(str) { |str| list << str } unless @down.nil?
list
end | ruby | {
"resource": ""
} |
q9718 | StringTree.Node.prune | train | def prune
return true if !@down.nil? && down.prune
return true if !@left.nil? && left.prune
return true if !@right.nil? && right.prune
return true unless @value.nil?
up.down = nil if !up.nil? && left.nil? && right.nil?
false
end | ruby | {
"resource": ""
} |
q9719 | Humpyard.PagesController.index | train | def index
authorize! :manage, Humpyard::Page
@root_page = Humpyard::Page.root
@page = Humpyard::Page.find_by_id(params[:actual_page_id])
unless @page.nil?
@page = @page.content_data
end
render :partial => 'index'
end | ruby | {
"resource": ""
} |
q9720 | Humpyard.PagesController.new | train | def new
@page = Humpyard::config.page_types[params[:type]].new
unless can? :create, @page.page
render :json => {
:status => :failed
}, :status => 403
return
end
@page_type = params[:type]
@prev = Humpyard::Page.find_by_id(params[:prev_id])
... | ruby | {
"resource": ""
} |
q9721 | Humpyard.PagesController.update | train | def update
@page = Humpyard::Page.find(params[:id]).content_data
if @page
unless can? :update, @page.page
render :json => {
:status => :failed
}, :status => 403
return
end
if @page.update_attributes params[:page]
@p... | ruby | {
"resource": ""
} |
q9722 | Humpyard.PagesController.move | train | def move
@page = Humpyard::Page.find(params[:id])
if @page
unless can? :update, @page
render :json => {
:status => :failed
}, :status => 403
return
end
parent = Humpyard::Page.find_by_id(params[:parent_id])
# by defau... | ruby | {
"resource": ""
} |
q9723 | Humpyard.PagesController.show | train | def show
# No page found at the beginning
@page = nil
if params[:locale] and Humpyard.config.locales.include? params[:locale].to_sym
I18n.locale = params[:locale]
elsif session[:humpyard_locale]
I18n.locale = session[:humpyard_locale]
else
I18n.locale = Humpyard.co... | ruby | {
"resource": ""
} |
q9724 | Humpyard.PagesController.sitemap | train | def sitemap
require 'builder'
xml = ::Builder::XmlMarkup.new :indent => 2
xml.instruct!
xml.tag! :urlset, {
'xmlns'=>"http://www.sitemaps.org/schemas/sitemap/0.9",
'xmlns:xsi'=>"http://www.w3.org/2001/XMLSchema-instance",
'xsi:schemaLocation'=>"http://www.sitemaps.... | ruby | {
"resource": ""
} |
q9725 | LatoBlog.PostField.update_child_visibility | train | def update_child_visibility
return if meta_visible == meta_visible_was
post_fields.map { |pf| pf.update(meta_visible: meta_visible) }
end | ruby | {
"resource": ""
} |
q9726 | Disqussion.Posts.vote | train | def vote(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
if args.length == 2
options.merge!(:vote => args[0])
options.merge!(:post => args[1])
response = post('posts/vote', options)
else
puts "#{Kernel.caller.first}: posts.vote expects 2 arguments: vote([-1..1]),... | ruby | {
"resource": ""
} |
q9727 | DAF.YAMLDataSource.action_options | train | def action_options
# Attempt resolution to outputs of monitor
return @action_options unless @monitor_class.outputs.length > 0
action_options = @action_options.clone
@monitor_class.outputs.each do |output, _type|
action_options.each do |option_key, option_value|
action_options[o... | ruby | {
"resource": ""
} |
q9728 | PonyExpress.Mail.remove | train | def remove keys
keys = keys.map(&:to_sym)
@options.reject! {|k, v| keys.include?(k) }
end | ruby | {
"resource": ""
} |
q9729 | Ambience.Config.to_hash | train | def to_hash
config = load_base_config
config = config.deep_merge(load_env_config)
config.deep_merge(load_jvm_config)
end | ruby | {
"resource": ""
} |
q9730 | Ambience.Config.hash_from_property | train | def hash_from_property(property, value)
property.split(".").reverse.inject(value) { |value, item| { item => value } }
end | ruby | {
"resource": ""
} |
q9731 | AnagramSolver.Permutator.precompute_old | train | def precompute_old
warn "This method should not be used, please use precompute instead."
word_list.rewind.each do |line|
word = line.chomp
precomputed_list_old[word.split('').sort.join.freeze] += [word]
end
end | ruby | {
"resource": ""
} |
q9732 | Blueprint.Compressor.initialize_project_from_yaml | train | def initialize_project_from_yaml(project_name = nil)
# ensures project_name is set and settings.yml is present
return unless (project_name && File.exist?(@settings_file))
# loads yaml into hash
projects = YAML::load(File.path_to_string(@settings_file))
if (project = projects[proj... | ruby | {
"resource": ""
} |
q9733 | Derelict.Executer.execute | train | def execute(command, &block)
logger.info "Executing command '#{command}'"
reset
pid, stdin, stdout_stream, stderr_stream = Open4::popen4(command)
@pid = pid
stdin.close rescue nil
save_exit_status(pid)
forward_signals_to(pid) do
handle_streams stdout_stream, stderr_str... | ruby | {
"resource": ""
} |
q9734 | Derelict.Executer.forward_signals_to | train | def forward_signals_to(pid, signals = %w[INT])
# Set up signal handlers
logger.debug "Setting up signal handlers for #{signals.inspect}"
signal_count = 0
signals.each do |signal|
Signal.trap(signal) do
Process.kill signal, pid rescue nil
# If this is th... | ruby | {
"resource": ""
} |
q9735 | Derelict.Executer.reset_handlers_for | train | def reset_handlers_for(signals)
logger.debug "Resetting signal handlers for #{signals.inspect}"
signals.each {|signal| Signal.trap signal, "DEFAULT" }
end | ruby | {
"resource": ""
} |
q9736 | Derelict.Executer.handle_streams | train | def handle_streams(stdout_stream, stderr_stream, &block)
logger.debug "Monitoring stdout/stderr streams for output"
streams = [stdout_stream, stderr_stream]
until streams.empty?
# Find which streams are ready for reading, timeout 0.1s
selected, = select(streams, nil, nil, 0.1... | ruby | {
"resource": ""
} |
q9737 | Derelict.Executer.output | train | def output(data, stream_name = :stdout, &block)
# Pass the output to the block
if block.arity == 2
args = [nil, nil]
if stream_name == :stdout
args[0] = data
else
args[1] = data
end
block.call(*args)
else
yield d... | ruby | {
"resource": ""
} |
q9738 | DAF.Command.execute | train | def execute
@thread = Thread.new do
if Thread.current != Thread.main
loop do
@datasource.monitor.on_trigger do
@datasource.action.activate(@datasource.action_options)
end
end
end
end
end | ruby | {
"resource": ""
} |
q9739 | SycLink.LinkChecker.response_of_uri | train | def response_of_uri(uri)
begin
Net::HTTP.start(uri.host, uri.port) do |http|
http.head(uri.path.size > 0 ? uri.path : "/").code
end
rescue Exception => e
"Error"
end
end | ruby | {
"resource": ""
} |
q9740 | XS.Poller.register | train | def register sock, events = XS::POLLIN | XS::POLLOUT, fd = 0
return false if (sock.nil? && fd.zero?) || events.zero?
item = @items.get(@sockets.index(sock))
unless item
@sockets << sock
item = LibXS::PollItem.new
if sock.kind_of?(XS::Socket) || sock.kind_of?(Socket)
... | ruby | {
"resource": ""
} |
q9741 | XS.Poller.deregister | train | def deregister sock, events, fd = 0
return unless sock || !fd.zero?
item = @items.get(@sockets.index(sock))
if item && (item[:events] & events) > 0
# change the value in place
item[:events] ^= events
delete sock if item[:events].zero?
true
else
false
... | ruby | {
"resource": ""
} |
q9742 | XS.Poller.delete | train | def delete sock
unless (size = @sockets.size).zero?
@sockets.delete_if { |socket| socket.socket.address == sock.socket.address }
socket_deleted = size != @sockets.size
item_deleted = @items.delete sock
raw_deleted = @raw_to_socket.delete(sock.socket.address)
socket_delet... | ruby | {
"resource": ""
} |
q9743 | XS.Poller.update_selectables | train | def update_selectables
@readables.clear
@writables.clear
@items.each do |poll_item|
#FIXME: spec for sockets *and* file descriptors
if poll_item.readable?
@readables << (poll_item.socket.address.zero? ? poll_item.fd : @raw_to_socket[poll_item.socket.address])
end
... | ruby | {
"resource": ""
} |
q9744 | TaskMapper::Provider.Bugzilla.authorize | train | def authorize(auth = {})
@authentication ||= TaskMapper::Authenticator.new(auth)
auth = @authentication
if (auth.username.nil? || auth.url.nil? || auth.password.nil?)
raise "Please provide username, password and url"
end
url = auth.url.gsub(/\/$/,'')
unless url.split('/').las... | ruby | {
"resource": ""
} |
q9745 | Mswallet.Pass.file | train | def file(options = {})
options[:file_name] ||= 'pass.mswallet'
temp_file = Tempfile.new(options[:file_name])
temp_file.write self.stream.string
temp_file.close
temp_file
end | ruby | {
"resource": ""
} |
q9746 | EZMQ.Client.request | train | def request(message, **options)
send message, options
if block_given?
yield receive options
else
receive options
end
end | ruby | {
"resource": ""
} |
q9747 | VirtualMonkey.Frontend.get_lb_hostname_input | train | def get_lb_hostname_input
lb_hostname_input = "text:"
fe_servers.each do |fe|
timeout = 30
loopcounter = 0
begin
if fe.settings['private-dns-name'] == nil
raise "FATAL: private DNS name is empty" if loopcounter > 10
sleep(timeout)
loopcou... | ruby | {
"resource": ""
} |
q9748 | Riagent.Configuration.config_for | train | def config_for(environment=:development)
if self.config.present?
env_config = self.config[environment.to_s]
else
env_config = {
'host' => ENV['RIAK_HOST'],
'http_port' => ENV['RIAK_HTTP_PORT'],
'pb_port' => ENV['RIAK_PB_PORT']
}
end
env_confi... | ruby | {
"resource": ""
} |
q9749 | StreamBot.Handler.parse_response | train | def parse_response(object)
LOG.debug("response is #{object}")
case object
when ::Net::HTTPUnauthorized
::File.delete(ACCESS_TOKEN)
raise 'user revoked oauth connection'
when ::Net::HTTPOK then
object.body
end
end | ruby | {
"resource": ""
} |
q9750 | Schemata.Schema.addressable | train | def addressable
apply_schema :street_address_1, String
apply_schema :street_address_2, String
apply_schema :city, String
apply_schema :state, String
apply_schema :zip_code, String
apply_schema :country, String
end | ruby | {
"resource": ""
} |
q9751 | CaRuby.Persistable.merge_into_snapshot | train | def merge_into_snapshot(other)
if @snapshot.nil? then
raise ValidationError.new("Cannot merge #{other.qp} content into #{qp} snapshot, since #{qp} does not have a snapshot.")
end
# the non-domain attribute => [target value, other value] difference hash
delta = diff(other)
# the dif... | ruby | {
"resource": ""
} |
q9752 | CaRuby.Persistable.add_lazy_loader | train | def add_lazy_loader(loader, attributes=nil)
# guard against invalid call
if identifier.nil? then raise ValidationError.new("Cannot add lazy loader to an unfetched domain object: #{self}") end
# the attributes to lazy-load
attributes ||= loadable_attributes
return if attributes.empty?
... | ruby | {
"resource": ""
} |
q9753 | CaRuby.Persistable.remove_lazy_loader | train | def remove_lazy_loader(attribute=nil)
if attribute.nil? then
return self.class.domain_attributes.each { |pa| remove_lazy_loader(pa) }
end
# the modified accessor method
reader, writer = self.class.property(attribute).accessors
# remove the reader override
disable_singleton_me... | ruby | {
"resource": ""
} |
q9754 | CaRuby.Persistable.fetch_saved? | train | def fetch_saved?
# only fetch a create, not an update (note that subclasses can override this condition)
return false if identifier
# Check for an attribute with a value that might need to be changed in order to
# reflect the auto-generated database content.
ag_attrs = self.class.autogener... | ruby | {
"resource": ""
} |
q9755 | CaRuby.Persistable.inject_lazy_loader | train | def inject_lazy_loader(attribute)
# bail if there is already a value
return false if attribute_loaded?(attribute)
# the accessor methods to modify
reader, writer = self.class.property(attribute).accessors
# The singleton attribute reader method loads the reference once and thenceforth call... | ruby | {
"resource": ""
} |
q9756 | CaRuby.Persistable.load_reference | train | def load_reference(attribute)
ldr = database.lazy_loader
# bypass the singleton method and call the class instance method if the lazy loader is disabled
return transient_value(attribute) unless ldr.enabled?
# First disable lazy loading for the attribute, since the reader method is called ... | ruby | {
"resource": ""
} |
q9757 | CaRuby.Persistable.disable_singleton_method | train | def disable_singleton_method(name_or_sym)
return unless singleton_methods.include?(name_or_sym.to_s)
# dissociate the method from this instance
method = self.method(name_or_sym.to_sym)
method.unbind
# JRuby unbind doesn't work in JRuby 1.1.6. In that case, redefine the singleton method to ... | ruby | {
"resource": ""
} |
q9758 | Sinatra.MercuryHelpers.sass | train | def sass(sassfile, mediatype="all")
render_style Sass::Engine.new(open_file(find_file(sassfile, SASS))).render, mediatype
end | ruby | {
"resource": ""
} |
q9759 | Sinatra.MercuryHelpers.scss | train | def scss(scssfile, mediatype="all")
render_style Sass::Engine.new(open_file(find_file(scssfile, SCSS)), :syntax => :scss).render, mediatype
end | ruby | {
"resource": ""
} |
q9760 | Brandish.Application.call | train | def call
program_information
configure_global_option
directory_global_option
command(:initialize) { |c| InitializeCommand.define(self, c) }
command(:bench) { |c| BenchCommand.define(self, c) }
command(:build) { |c| BuildCommand.define(self, c) }
command(:serve) { |c| ServeComma... | ruby | {
"resource": ""
} |
q9761 | Brandish.Application.program_information | train | def program_information
program :name, "Brandish"
program :version, Brandish::VERSION
program :help_formatter, :compact
program :help_paging, false
program :description, "A multi-format document generator."
program :help, "Author", "Jeremy Rodi <jeremy.rodi@medcat.me>"
program ... | ruby | {
"resource": ""
} |
q9762 | Brandish.Application.progress | train | def progress(array, &block)
# rubocop:disable Style/GlobalVars
width = $terminal.terminal_size[0] - PROGRESS_WIDTH
# rubocop:enable Style/GlobalVars
options = PROGRESS_OPTIONS.merge(width: width)
super(array, options, &block)
end | ruby | {
"resource": ""
} |
q9763 | Align.NeedlemanWunsch.fill | train | def fill
@matrix[0][0] = 0
# Set up the first column on each row.
1.upto(@rows-1) {|i| @matrix[i][0] = @matrix[i-1][0] + @scoring.score_delete(@seq1[i])}
# Set up the first row
1.upto(@cols-1) {|j| @matrix[0][j] = @matrix[0][j-1] + @scoring.score_insert(@seq2[j])}
1.upto(@rows-1) d... | ruby | {
"resource": ""
} |
q9764 | Align.NeedlemanWunsch.traceback | train | def traceback
i = @rows - 1
j = @cols - 1
while (i > 0 && j > 0)
score = @matrix[i][j]
seq1_obj = @seq1[i-1]
seq2_obj = @seq2[j-1]
score_align = @matrix[i-1][j-1] + @scoring.score_align(seq1_obj, seq2_obj)
score_delete = @matrix[i-1][j] + @scoring.score_delet... | ruby | {
"resource": ""
} |
q9765 | LolitaFirstData.TransactionsController.checkout | train | def checkout
response = gateway.purchase(payment.price,
currency: payment.currency.to_s,
client_ip_addr: request.remote_ip,
description: payment.description,
language: payment.fi... | ruby | {
"resource": ""
} |
q9766 | LolitaFirstData.TransactionsController.answer | train | def answer
if trx = LolitaFirstData::Transaction.where(transaction_id: params[:trans_id]).first
response = gateway.result(params[:trans_id], client_ip_addr: request.remote_ip)
trx.process_result(response)
redirect_to trx.return_path
else
render text: I18n.t('fd.wrong_request'... | ruby | {
"resource": ""
} |
q9767 | Heart.DashboardsHelper.flot_array | train | def flot_array(metrics)
replace = false
hash = Hash.new
if metrics.nil? || metrics.first.nil? || metrics.first.movingaverage.nil?
replace = true
metrics = Metric.aggregate_daily_moving_averages(0, "WHERE fulldate > SUBDATE((SELECT fulldate FROM heart_metrics WHERE movingaverage = 0 ORD... | ruby | {
"resource": ""
} |
q9768 | Vigilem::Core::Hooks.Callback.evaluate | train | def evaluate(context, *args, &block)
self.result = if block
context.define_singleton_method(:__callback__, &self)
ret = context.send :__callback__, *args, &block
context.class_eval { send :remove_method, :__callback__ }
ret
else
context.instance_exec(*args... | ruby | {
"resource": ""
} |
q9769 | XES.AttributeAccessor.define_attribute | train | def define_attribute(name, type)
_name = name.gsub(":", "_")
define_method(_name) do
var = instance_variables.include?(:@meta) ? :@meta : :@attributes
instance_variable_get(var).find do |attribute|
attribute.key == name
end.tap{|x| return x.value if x}
end
def... | ruby | {
"resource": ""
} |
q9770 | OrderlyGarden.DSL.with_tempfile | train | def with_tempfile(fname = nil, &_block)
Tempfile.open("tmp") do |f|
yield f.path, f.path.shellescape
FileUtils.cp(f.path, fname) unless fname.nil?
end
end | ruby | {
"resource": ""
} |
q9771 | OrderlyGarden.DSL.write_file | train | def write_file(file_name, file_contents)
contents = file_contents
.flatten
.select { |line| line }
.join("\n")
File.open(file_name, "w") do |fh|
fh.write(contents)
fh.write("\n")
end
end | ruby | {
"resource": ""
} |
q9772 | Guard.Tay.munge_options | train | def munge_options(options)
keys_to_munge = [:build_directory, :tayfile]
munged = {}
options.keys.each do |key|
if keys_to_munge.include?(key)
new_key = key.to_s.gsub(/_/, '-')
end
munged[new_key || key] = options[key]
end
munged
end | ruby | {
"resource": ""
} |
q9773 | PageRecord.Attributes.read_attribute | train | def read_attribute(attribute)
if block_given?
element = yield
else
element = send("#{attribute}?")
end
tag = element.tag_name
input_field?(tag) ? element.value : element.text
end | ruby | {
"resource": ""
} |
q9774 | PageRecord.Attributes.write_attribute | train | def write_attribute(attribute, value)
element = send("#{attribute}?")
tag = element.tag_name
case tag
when 'textarea', 'input' then element.set(value)
when 'select'then element.select(value)
else raise NotInputField
end
element
end | ruby | {
"resource": ""
} |
q9775 | BlogBasic.BlogComment.request= | train | def request=(request)
self.user_ip = request.remote_ip
self.user_agent = request.env['HTTP_USER_AGENT']
self.referrer = request.env['HTTP_REFERER']
end | ruby | {
"resource": ""
} |
q9776 | Ichiban.Loader.delete_all | train | def delete_all
@loaded_constants.each do |const_name|
if Object.const_defined?(const_name)
Object.send(:remove_const, const_name)
end
end
Ichiban::HTMLCompiler::Context.clear_user_defined_helpers
end | ruby | {
"resource": ""
} |
q9777 | ActiveRecord.DynamicMatchers.expand_attribute_names_for_aggregates | train | def expand_attribute_names_for_aggregates(attribute_names)
attribute_names.map { |attribute_name|
unless (aggregation = reflect_on_aggregation(attribute_name.to_sym)).nil?
aggregate_mapping(aggregation).map do |field_attr, _|
field_attr.to_sym
end
else
att... | ruby | {
"resource": ""
} |
q9778 | Bench.Runner.build_report | train | def build_report
output "Running benchmark report..."
REQUESTS.each do |name, params, times|
self.benchmark_service(name, params, times, false)
end
output "Done running benchmark report"
end | ruby | {
"resource": ""
} |
q9779 | TaskList.Parser.parse! | train | def parse!
unless @type.nil? || VALID_TASKS.include?(@type)
raise TaskList::Exceptions::InvalidTaskTypeError.new type: @type
end
@files.each { |f| parsef! file: f }
end | ruby | {
"resource": ""
} |
q9780 | Scram::DSL.ModelConditions.method_missing | train | def method_missing(method, *args)
if method.to_s.starts_with? "*"
condition_name = method.to_s.split("*")[1].to_sym
conditions = self.class.scram_conditions
if conditions && !conditions[condition_name].nil?
return conditions[condition_name].call(self)
end
end
... | ruby | {
"resource": ""
} |
q9781 | ActionView.AssetPaths.compute_source_path | train | def compute_source_path(source, dir, ext)
source = rewrite_extension(source, dir, ext) if ext
File.join(config.assets_dir, dir, source)
end | ruby | {
"resource": ""
} |
q9782 | Jekyll.StitchPlus.cleanup | train | def cleanup(site, stitch)
files = stitch.all_files.map{ |f| File.absolute_path(f)}
files.concat stitch.deleted
if files.size > 0
site.static_files.clone.each do |sf|
if sf.kind_of?(Jekyll::StaticFile) and files.include? sf.path
site.static_files.delete(sf)
end... | ruby | {
"resource": ""
} |
q9783 | SlackBotManager.Tokens.get_id_from_token | train | def get_id_from_token(token)
storage.get_all(tokens_key).each { |id, t| return id if t == token }
false
end | ruby | {
"resource": ""
} |
q9784 | Cany.Recipe.exec | train | def exec(*args)
args.flatten!
Cany.logger.info args.join(' ')
unless system(*args)
raise CommandExecutionFailed.new args
end
end | ruby | {
"resource": ""
} |
q9785 | Wireless.Registry.factory | train | def factory(name, klass = nil, &block)
@registry[name.to_sym] = Resolver::Factory.new(block || klass)
end | ruby | {
"resource": ""
} |
q9786 | Wireless.Registry.singleton | train | def singleton(name, klass = nil, &block)
@registry[name.to_sym] = Resolver::Singleton.new(block || klass)
end | ruby | {
"resource": ""
} |
q9787 | Wireless.Registry.mixin | train | def mixin(args)
# normalize the supplied argument (array or hash) into a hash of
# { visibility => exports } pairs, where `visibility` is a symbol and
# `exports` is a hash of { dependency_name => method_name } pairs
if args.is_a?(Array)
args = { @default_visibility => args }
elsif... | ruby | {
"resource": ""
} |
q9788 | Wireless.Registry.module_for | train | def module_for(args)
registry = self
mod = Module.new
args.each do |visibility, exports|
exports.each do |dependency_name, method_name|
# equivalent to (e.g.):
#
# def foo
# registry.fetch(:foo)
# end
mod.send(:define_method,... | ruby | {
"resource": ""
} |
q9789 | Sloe.Junos.cli | train | def cli(cmd_str, attrs = { format: 'text' })
reply = rpc.command(cmd_str, attrs)
reply.respond_to?(:text) ? reply.text : reply
end | ruby | {
"resource": ""
} |
q9790 | Sloe.Junos.apply_configuration | train | def apply_configuration(config, attrs = { format: 'text' })
rpc.lock_configuration
rpc.load_configuration(config, attrs)
rpc.commit_configuration
rpc.unlock_configuration
end | ruby | {
"resource": ""
} |
q9791 | TDP.PatchSet.<< | train | def <<(patch)
known_patch = @patches[patch.name]
if known_patch.nil?
@patches[patch.name] = patch
elsif patch.content != known_patch.content
raise ContradictionError, [known_patch, patch]
end
end | ruby | {
"resource": ""
} |
q9792 | TDP.DAO.patch_signature | train | def patch_signature(name)
row = @db[:tdp_patch].select(:signature).where(name: name).first
row.nil? ? nil : row[:signature]
end | ruby | {
"resource": ""
} |
q9793 | TDP.Engine.<< | train | def <<(filename)
if File.directory?(filename)
Dir.foreach(filename) do |x|
self << File.join(filename, x) unless x.start_with?('.')
end
elsif TDP.patch_file?(filename)
@patches << Patch.new(filename)
end
end | ruby | {
"resource": ""
} |
q9794 | TDP.Engine.plan | train | def plan
ref = @dao.applied_patches
@patches.select do |patch|
signature = ref[patch.name]
next false if signature == patch.signature
next true if signature.nil? || patch.volatile?
raise MismatchError, patch
end
end | ruby | {
"resource": ""
} |
q9795 | TDP.Engine.validate_compatible | train | def validate_compatible
validate_upgradable
@patches.each do |patch|
signature = @dao.patch_signature(patch.name)
next if signature == patch.signature
raise NotAppliedError, patch if signature.nil?
raise MismatchError, patch
end
end | ruby | {
"resource": ""
} |
q9796 | VirtualMonkey.UnifiedApplication.run_unified_application_check | train | def run_unified_application_check(dns_name, port=8000)
url_base = "#{dns_name}:#{port}"
behavior(:test_http_response, "html serving succeeded", "#{url_base}/index.html", port)
behavior(:test_http_response, "configuration=succeeded", "#{url_base}/appserver/", port)
behavior(:test_http_response,... | ruby | {
"resource": ""
} |
q9797 | ADAM6050.Session.validate! | train | def validate!(sender, time: monotonic_timestamp)
key = session_key sender
last_observed = @session.fetch(key) { raise UnknownSender, sender }
raise InvalidSender, sender if expired? last_observed, time, @timeout
@session[key] = time
nil
end | ruby | {
"resource": ""
} |
q9798 | LatoBlog.Back::TagsController.new | train | def new
core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:tags_new])
@tag = LatoBlog::Tag.new
if params[:language]
set_current_language params[:language]
end
if params[:parent]
@tag_parent = LatoBlog::TagParent.find_by(id: params[:parent])
end
en... | ruby | {
"resource": ""
} |
q9799 | LatoBlog.Back::TagsController.create | train | def create
@tag = LatoBlog::Tag.new(new_tag_params)
if !@tag.save
flash[:danger] = @tag.errors.full_messages.to_sentence
redirect_to lato_blog.new_tag_path
return
end
flash[:success] = LANGUAGES[:lato_blog][:flashes][:tag_create_success]
redirect_to lato_blog.tag_... | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.