_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q17200 | Volt.Dependency.depend | train | def depend
# If there is no @dependencies, don't depend because it has been removed
return unless @dependencies
current = Computation.current
if current
added = @dependencies.add?(current)
if added
# The first time the dependency is depended on by this computation, we call on_dep
@on_dep.call if @on_dep && @dependencies.size == 1
current.on_invalidate do
# If @dependencies is nil, this Dependency has been removed
if @dependencies
# For set, .delete returns a boolean if it was deleted
deleted = @dependencies.delete?(current)
# Call on stop dep if no more deps
@on_stop_dep.call if @on_stop_dep && deleted && @dependencies.size == 0
end
end
end
end
end | ruby | {
"resource": ""
} |
q17201 | Volt.Model.assign_attributes | train | def assign_attributes(attrs, initial_setup = false, skip_changes = false)
attrs = wrap_values(attrs)
if attrs
# When doing a mass-assign, we don't validate or save until the end.
if initial_setup || skip_changes
Model.no_change_tracking do
assign_all_attributes(attrs, skip_changes)
end
else
assign_all_attributes(attrs)
end
else
# Assign to empty
@attributes = {}
end
# Trigger and change all
@deps.changed_all!
@deps = HashDependency.new
run_initial_setup(initial_setup)
end | ruby | {
"resource": ""
} |
q17202 | Volt.Model.set | train | def set(attribute_name, value, &block)
# Assign, without the =
attribute_name = attribute_name.to_sym
check_valid_field_name(attribute_name)
old_value = @attributes[attribute_name]
new_value = wrap_value(value, [attribute_name])
if old_value != new_value
# Track the old value, skip if we are in no_validate
attribute_will_change!(attribute_name, old_value) unless Volt.in_mode?(:no_change_tracking)
# Assign the new value
@attributes[attribute_name] = new_value
@deps.changed!(attribute_name)
@size_dep.changed! if old_value.nil? || new_value.nil?
# TODO: Can we make this so it doesn't need to be handled for non store collections
# (maybe move it to persistor, though thats weird since buffers don't have a persistor)
clear_server_errors(attribute_name) if @server_errors.present?
# Save the changes
run_changed(attribute_name) unless Volt.in_mode?(:no_change_tracking)
end
new_value
end | ruby | {
"resource": ""
} |
q17203 | Volt.Model.read_new_model | train | def read_new_model(method_name)
if @persistor && @persistor.respond_to?(:read_new_model)
return @persistor.read_new_model(method_name)
else
opts = @options.merge(parent: self, path: path + [method_name])
if method_name.plural?
return new_array_model([], opts)
else
return new_model({}, opts)
end
end
end | ruby | {
"resource": ""
} |
q17204 | Volt.Model.update | train | def update(attrs)
old_attrs = @attributes.dup
Model.no_change_tracking do
assign_all_attributes(attrs, false)
validate!.then do |errs|
if errs && errs.present?
# Revert wholesale
@attributes = old_attrs
Promise.new.resolve(errs)
else
# Persist
persist_changes(nil)
end
end
end
end | ruby | {
"resource": ""
} |
q17205 | Volt.ViewScope.close_scope | train | def close_scope(pop = true)
if pop
scope = @handler.scope.pop
else
scope = @handler.last
end
fail "template path already exists: #{scope.path}" if @handler.templates[scope.path]
template = {
'html' => scope.html
}
if scope.bindings.size > 0
# Add the bindings if there are any
template['bindings'] = scope.bindings
end
@handler.templates[scope.path] = template
end | ruby | {
"resource": ""
} |
q17206 | Volt.Duration.+ | train | def +(other)
if other.is_a?(Volt::Duration)
Volt::Duration.new(value + other.value, parts + other.parts)
else
Volt::Duration.new(value + other, parts + [[:seconds, other]])
end
end | ruby | {
"resource": ""
} |
q17207 | Volt.SandlebarsParser.start_binding | train | def start_binding
binding = ''
open_count = 1
# scan until we reach a {{ or }}
loop do
binding << @html.scan_until(/(\{\{|\}\}|\n|\Z)/)
match = @html[1]
if match == '}}'
# close
open_count -= 1
break if open_count == 0
elsif match == '{{'
# open more
open_count += 1
elsif match == "\n" || @html.eos?
# Starting new tag, should be closed before this
# or end of doc before closed binding
raise_parse_error("unclosed binding: {#{binding.strip}")
else
#:nocov:
fail 'should not reach here'
#:nocov:
end
end
binding = binding[0..-3]
@handler.binding(binding) if @handler.respond_to?(:binding)
end | ruby | {
"resource": ""
} |
q17208 | Volt.HttpResource.dispatch_to_controller | train | def dispatch_to_controller(params, request)
namespace = params[:component] || 'main'
controller_name = params[:controller] + '_controller'
action = params[:action]
namespace_module = Object.const_get(namespace.camelize.to_sym)
klass = namespace_module.const_get(controller_name.camelize.to_sym)
controller = klass.new(@volt_app, params, request)
# Use the 'meta' thread local to set the user_id for Volt.current_user
meta_data = {}
user_id = request.cookies['user_id']
meta_data['user_id'] = user_id if user_id
Thread.current['meta'] = meta_data
controller.perform(action)
end | ruby | {
"resource": ""
} |
q17209 | Volt.EachBinding.update | train | def update(value)
# Since we're checking things like size, we don't want this to be re-triggered on a
# size change, so we run without tracking.
Computation.run_without_tracking do
# Adjust to the new size
values = current_values(value)
@value = values
remove_listeners
if @value.respond_to?(:on)
@added_listener = @value.on('added') { |position| item_added(position) }
@removed_listener = @value.on('removed') { |position| item_removed(position) }
end
templates_size = nil
values_size = nil
Volt.run_in_mode(:no_model_promises) do
templates_size = @templates.size
unless values.respond_to?(:size)
fail InvalidObjectForEachBinding, "Each binding's require an object that responds to size and [] methods. The binding received: #{values.inspect}"
end
values_size = values.size
end
# Start over, re-create all nodes
(templates_size - 1).downto(0) do |index|
item_removed(index)
end
0.upto(values_size - 1) do |index|
item_added(index)
end
end
end | ruby | {
"resource": ""
} |
q17210 | Volt.EachBinding.update_indexes_after | train | def update_indexes_after(start_index)
size = @templates.size
if size > 0
start_index.upto(size - 1) do |index|
@templates[index].context.locals[:_index=].call(index)
end
end
end | ruby | {
"resource": ""
} |
q17211 | Volt.EachBinding.remove | train | def remove
@computation.stop
@computation = nil
# Clear value
@value = []
@getter = nil
remove_listeners
if @templates
template_count = @templates.size
template_count.times do |index|
item_removed(template_count - index - 1)
end
# @templates.compact.each(&:remove)
@templates = nil
end
super
end | ruby | {
"resource": ""
} |
q17212 | Volt.Routes.rest | train | def rest(path, params)
endpoints = (params.delete(:only) || [:index, :show, :create, :update, :destroy]).to_a
endpoints = endpoints - params.delete(:except).to_a
endpoints.each do |endpoint|
self.send(('restful_' + endpoint.to_s).to_sym, path, params)
end
end | ruby | {
"resource": ""
} |
q17213 | Volt.Routes.params_to_url | train | def params_to_url(test_params)
# Extract the desired method from the params
method = test_params.delete(:method) || :client
method = method.to_sym
# Add in underscores
test_params = test_params.each_with_object({}) do |(k, v), obj|
obj[k.to_sym] = v
end
@param_matches[method].each do |param_matcher|
# TODO: Maybe a deep dup?
result, new_params = check_params_match(test_params.dup, param_matcher[0])
return param_matcher[1].call(new_params) if result
end
[nil, nil]
end | ruby | {
"resource": ""
} |
q17214 | Volt.Routes.url_to_params | train | def url_to_params(*args)
if args.size < 2
path = args[0]
method = :client
else
path = args[1]
method = args[0].to_sym
end
# First try a direct match
result = @direct_routes[method][path]
return result if result
# Next, split the url and walk the sections
parts = url_parts(path)
match_path(parts, parts, @indirect_routes[method])
end | ruby | {
"resource": ""
} |
q17215 | Volt.Routes.match_path | train | def match_path(original_parts, remaining_parts, node)
# Take off the top part and get the rest into a new array
# part will be nil if we are out of parts (fancy how that works out, now
# stand in wonder about how much someone thought this through, though
# really I just got lucky)
part, *parts = remaining_parts
if part.nil?
if node[part]
# We found a match, replace the bindings and return
# TODO: Handle nested
setup_bindings_in_params(original_parts, node[part])
else
false
end
else
if (new_node = node[part])
# Direct match for section, continue
result = match_path(original_parts, parts, new_node)
return result if result
end
if (new_node = node['*'])
# Match on binding single section
result = match_path(original_parts, parts, new_node)
return result if result
end
if ((params = node['**']) && params && (params = params[nil]))
# Match on binding multiple sections
result = setup_bindings_in_params(original_parts, params)
return result if result
end
return false
end
end | ruby | {
"resource": ""
} |
q17216 | Volt.Routes.setup_bindings_in_params | train | def setup_bindings_in_params(original_parts, params)
# Create a copy of the params we can modify and return
params = params.dup
params.each_pair do |key, value|
if value.is_a?(Fixnum)
# Lookup the param's value in the original url parts
params[key] = original_parts[value]
elsif value.is_a?(Range)
# When doing multiple section bindings, we lookup the parts as a range
# then join them with /
params[key] = original_parts[value].join('/')
end
end
params
end | ruby | {
"resource": ""
} |
q17217 | Volt.Routes.check_params_match | train | def check_params_match(test_params, param_matcher)
param_matcher.each_pair do |key, value|
if value.is_a?(Hash)
if test_params[key]
result = check_params_match(test_params[key], value)
if result == false
return false
else
test_params.delete(key)
end
else
# test_params did not have matching key
return false
end
elsif value.nil?
return false unless test_params.key?(key)
else
if test_params[key] == value
test_params.delete(key)
else
return false
end
end
end
[true, test_params]
end | ruby | {
"resource": ""
} |
q17218 | Volt.Associations.association_with_root_model | train | def association_with_root_model(method_name)
persistor = self.persistor || (respond_to?(:save_to) && save_to && save_to.persistor)
# Check if we are on the store collection
if persistor.is_a?(Volt::Persistors::ModelStore) ||
persistor.is_a?(Volt::Persistors::Page)
# Get the root node
root = persistor.try(:root_model)
# Yield to the block passing in the root node
yield(root)
else
# raise an error about the method not being supported on this collection
fail "#{method_name} currently only works on the store and page collection (support for other collections coming soon)"
end
end | ruby | {
"resource": ""
} |
q17219 | Volt.ForkingServer.boot_error | train | def boot_error(error)
msg = error.inspect
if error.respond_to?(:backtrace)
msg << "\n" + error.backtrace.join("\n")
end
Volt.logger.error(msg)
# Only require when needed
require 'cgi'
@rack_app = Proc.new do
path = File.join(File.dirname(__FILE__), "forking_server/boot_error.html.erb")
html = File.read(path)
error_page = ERB.new(html, nil, '-').result(binding)
[500, {"Content-Type" => "text/html"}, error_page]
end
@dispatcher = ErrorDispatcher.new
end | ruby | {
"resource": ""
} |
q17220 | Volt.AttributeScope.process_attributes | train | def process_attributes(tag_name, attributes)
new_attributes = attributes.dup
attributes.each_pair do |name, value|
if name[0..1] == 'e-'
process_event_binding(tag_name, new_attributes, name, value)
else
process_attribute(tag_name, new_attributes, name, value)
end
end
new_attributes
end | ruby | {
"resource": ""
} |
q17221 | Volt.AttributeScope.binding_parts_and_count | train | def binding_parts_and_count(value)
if value.is_a?(String)
parts = value.split(/(\{\{[^\}]+\}\})/).reject(&:blank?)
else
parts = ['']
end
binding_count = parts.count { |p| p[0] == '{' && p[1] == '{' && p[-2] == '}' && p[-1] == '}' }
[parts, binding_count]
end | ruby | {
"resource": ""
} |
q17222 | Volt.ComponentViewScope.close_scope | train | def close_scope
binding_number = @handler.scope[-2].binding_number
@handler.scope[-2].binding_number += 1
@path += "/__template/#{binding_number}"
super
@handler.html << "<!-- $#{binding_number} --><!-- $/#{binding_number} -->"
@handler.scope.last.save_binding(binding_number, "lambda { |__p, __t, __c, __id| Volt::ComponentBinding.new(__p, __t, __c, __id, #{@binding_in_path.inspect}, Proc.new { [#{@arguments}] }, #{@path.inspect}) }")
end | ruby | {
"resource": ""
} |
q17223 | Volt.AssetFiles.javascript_tags | train | def javascript_tags(volt_app)
@opal_tag_generator ||= Opal::Server::Index.new(nil, volt_app.opal_files.server)
javascript_files = []
@assets.each do |type, path|
case type
when :folder
# for a folder, we search for all .js files and return a tag for them
base_path = base(path)
javascript_files += Dir["#{path}/**/*.js"].sort.map do |folder|
# Grab the component folder/assets/js/file.js
local_path = folder[path.size..-1]
@app_url + '/' + base_path + local_path
end
when :javascript_file
# javascript_file is a cdn path to a JS file
javascript_files << path
end
end
javascript_files = javascript_files.uniq
scripts = javascript_files.map {|url| "<script src=\"#{url}\"></script>" }
# Include volt itself. Unless we are running with MAPS=all, just include
# the main file without sourcemaps.
volt_path = 'volt/volt/app'
if ENV['MAPS'] == 'all'
scripts << @opal_tag_generator.javascript_include_tag(volt_path)
else
scripts << "<script src=\"#{volt_app.app_url}/#{volt_path}.js\"></script>"
scripts << "<script>#{Opal::Processor.load_asset_code(volt_app.sprockets, volt_path)}</script>"
end
scripts << @opal_tag_generator.javascript_include_tag('components/main')
scripts.join("\n")
end | ruby | {
"resource": ""
} |
q17224 | Volt.AssetFiles.css | train | def css
css_files = []
@assets.each do |type, path|
case type
when :folder
# Don't import any css/scss files that start with an underscore, so scss partials
# aren't imported by default:
# http://sass-lang.com/guide
base_path = base(path)
css_files += Dir["#{path}/**/[^_]*.{css,scss,sass}"].sort.map do |folder|
local_path = folder[path.size..-1].gsub(/[.](scss|sass)$/, '')
css_path = @app_url + '/' + base_path + local_path
css_path += '.css' unless css_path =~ /[.]css$/
css_path
end
when :css_file
css_files << path
end
end
css_files.uniq
end | ruby | {
"resource": ""
} |
q17225 | Volt.GenericPool.lookup_without_generate | train | def lookup_without_generate(*args)
section = @pool
args.each_with_index do |arg, index|
section = section[arg]
return nil unless section
end
section
end | ruby | {
"resource": ""
} |
q17226 | Volt.Errors.merge! | train | def merge!(errors)
if errors
errors.each_pair do |field, messages|
messages.each do |message|
add(field, message)
end
end
end
end | ruby | {
"resource": ""
} |
q17227 | Volt.ViewHandler.link_asset | train | def link_asset(url, link=true)
if @sprockets_context
# Getting the asset_path also links to the context.
linked_url = @sprockets_context.asset_path(url)
else
# When compiling on the server, we don't use sprockets (atm), so the
# context won't exist. Typically compiling on the server is just used
# to test, so we simply return the url.
linked_url = url
end
last << url if link
linked_url
end | ruby | {
"resource": ""
} |
q17228 | Volt.ComponentCode.code | train | def code
# Start with config code
initializer_code = @client ? generate_config_code : ''
component_code = ''
asset_files = AssetFiles.from_cache(@volt_app.app_url, @component_name, @component_paths)
asset_files.component_paths.each do |component_path, component_name|
comp_template = ComponentTemplates.new(component_path, component_name, @client)
initializer_code << comp_template.initializer_code + "\n\n"
component_code << comp_template.component_code + "\n\n"
end
initializer_code + component_code
end | ruby | {
"resource": ""
} |
q17229 | Volt.ModelWrapper.wrap_value | train | def wrap_value(value, lookup)
if value.is_a?(Array)
new_array_model(value, @options.merge(parent: self, path: path + lookup))
elsif value.is_a?(Hash)
new_model(value, @options.merge(parent: self, path: path + lookup))
else
value
end
end | ruby | {
"resource": ""
} |
q17230 | Chroma.Harmonies.analogous | train | def analogous(options = {})
size = options[:size] || 6
slices = options[:slice_by] || 30
hsl = @color.hsl
part = 360 / slices
hsl.h = ((hsl.h - (part * size >> 1)) + 720) % 360
palette = (size - 1).times.reduce([@color]) do |arr, n|
hsl.h = (hsl.h + part) % 360
arr << Color.new(hsl, @color.format)
end
with_reformat(palette, options[:as])
end | ruby | {
"resource": ""
} |
q17231 | Chroma.Harmonies.monochromatic | train | def monochromatic(options = {})
size = options[:size] || 6
h, s, v = @color.hsv
modification = 1.0 / size
palette = size.times.map do
Color.new(ColorModes::Hsv.new(h, s, v), @color.format).tap do
v = (v + modification) % 1
end
end
with_reformat(palette, options[:as])
end | ruby | {
"resource": ""
} |
q17232 | Barbeque.MessageQueue.dequeue | train | def dequeue
loop do
return nil if @stop
message = receive_message
if message
if message.valid?
return message
else
delete_message(message)
end
end
end
end | ruby | {
"resource": ""
} |
q17233 | Rho.RHO.init_sources | train | def init_sources()
return unless defined? Rho::RhoConfig::sources
@all_models_loaded = true
uniq_sources = Rho::RhoConfig::sources.values
puts 'init_sources: ' #+ uniq_sources.inspect
uniq_sources.each do |source|
source['str_associations'] = ""
end
uniq_sources.each do |source|
partition = source['partition']
@db_partitions[partition] = nil unless @db_partitions[partition]
if source['belongs_to']
source['belongs_to'].each do |hash_pair|
attrib = hash_pair.keys[0]
src_name = hash_pair.values[0]
associationsSrc = find_src_byname(uniq_sources, src_name)
if !associationsSrc
puts "Error: belongs_to '#{source['name']}' : source name '#{src_name}' does not exist."
next
end
str_associations = associationsSrc['str_associations']
str_associations = "" unless str_associations
str_associations += ',' if str_associations.length() > 0
str_associations += source['name'] + ',' + attrib
associationsSrc['str_associations'] = str_associations
end
end
end
#user partition should alwayse exist
@db_partitions['user'] = nil unless @db_partitions['user']
hash_migrate = {}
puts "@db_partitions : #{@db_partitions}"
@db_partitions.each do |partition, db|
db = Rhom::RhomDbAdapter.new(Rho::RhoFSConnector::get_db_fullpathname(partition), partition) unless db
db.start_transaction
begin
init_db_sources(db, uniq_sources, partition,hash_migrate)
#SyncEngine.update_blob_attribs(partition, -1 )
db.commit
rescue Exception => e
trace_msg = e.backtrace.join("\n")
puts "exception when init_db_sources: #{e}; Trace:" + trace_msg
db.rollback
end
@db_partitions[partition] = db
end
puts "Migrate schema sources: #{hash_migrate}"
::Rho::RHO.init_schema_sources(hash_migrate)
::Rho::RHO.check_sources_migration(uniq_sources)
#@db_partitions.each do |partition, db|
# SyncEngine.update_blob_attribs(partition, -1 )
#end
::Rho::RHO.init_sync_source_properties(uniq_sources)
end | ruby | {
"resource": ""
} |
q17234 | URI.Generic.replace! | train | def replace!(oth)
if self.class != oth.class
raise ArgumentError, "expected #{self.class} object"
end
component.each do |c|
self.__send__("#{c}=", oth.__send__(c))
end
end | ruby | {
"resource": ""
} |
q17235 | OpenURI.Meta.charset | train | def charset
type, *parameters = content_type_parse
if pair = parameters.assoc('charset')
pair.last.downcase
elsif block_given?
yield
elsif type && %r{\Atext/} =~ type &&
@base_uri && /\Ahttp\z/i =~ @base_uri.scheme
"iso-8859-1" # RFC2616 3.7.1
else
nil
end
end | ruby | {
"resource": ""
} |
q17236 | Net.POP3.delete_all | train | def delete_all # :yield: message
mails().each do |m|
yield m if block_given?
m.delete unless m.deleted?
end
end | ruby | {
"resource": ""
} |
q17237 | Net.POPMail.pop | train | def pop( dest = '', &block ) # :yield: message_chunk
if block_given?
@command.retr(@number, &block)
nil
else
@command.retr(@number) do |chunk|
dest << chunk
end
dest
end
end | ruby | {
"resource": ""
} |
q17238 | Rake.DSL.directory | train | def directory(*args, &block)
result = file_create(*args, &block)
dir, _ = *Rake.application.resolve_args(args)
Rake.each_dir_parent(dir) do |d|
file_create d do |t|
mkdir_p t.name unless File.exist?(t.name)
end
end
result
end | ruby | {
"resource": ""
} |
q17239 | Rake.DSL.namespace | train | def namespace(name=nil, &block)
name = name.to_s if name.kind_of?(Symbol)
name = name.to_str if name.respond_to?(:to_str)
unless name.kind_of?(String) || name.nil?
raise ArgumentError, "Expected a String or Symbol for a namespace name"
end
Rake.application.in_namespace(name, &block)
end | ruby | {
"resource": ""
} |
q17240 | REXML.Element.delete_namespace | train | def delete_namespace namespace="xmlns"
namespace = "xmlns:#{namespace}" unless namespace == 'xmlns'
attribute = attributes.get_attribute(namespace)
attribute.remove unless attribute.nil?
self
end | ruby | {
"resource": ""
} |
q17241 | REXML.Attributes.each_attribute | train | def each_attribute # :yields: attribute
each_value do |val|
if val.kind_of? Attribute
yield val
else
val.each_value { |atr| yield atr }
end
end
end | ruby | {
"resource": ""
} |
q17242 | Gem.Specification.sort_obj | train | def sort_obj
[@name, installation_path == File.join(defined?(Merb) && Merb.respond_to?(:root) ? Merb.root : Dir.pwd,"gems") ? 1 : -1, @version.to_ints, @new_platform == Gem::Platform::RUBY ? -1 : 1]
end | ruby | {
"resource": ""
} |
q17243 | WEBrick.GenericServer.shutdown | train | def shutdown
stop
@listeners.each{|s|
if @logger.debug?
addr = s.addr
@logger.debug("close TCPSocket(#{addr[2]}, #{addr[1]})")
end
begin
s.shutdown
rescue Errno::ENOTCONN
# when `Errno::ENOTCONN: Socket is not connected' on some platforms,
# call #close instead of #shutdown.
# (ignore @config[:ShutdownSocketWithoutClose])
s.close
else
unless @config[:ShutdownSocketWithoutClose]
s.close
end
end
}
@listeners.clear
end | ruby | {
"resource": ""
} |
q17244 | WEBrick.BasicLog.format | train | def format(arg)
if arg.is_a?(Exception)
"#{arg.class}: #{arg.message}\n\t" <<
arg.backtrace.join("\n\t") << "\n"
elsif arg.respond_to?(:to_str)
arg.to_str
else
arg.inspect
end
end | ruby | {
"resource": ""
} |
q17245 | RestClient.Request.process_url_params | train | def process_url_params url, headers
url_params = {}
headers.delete_if do |key, value|
if 'params' == key.to_s.downcase && value.is_a?(Hash)
url_params.merge! value
true
else
false
end
end
unless url_params.empty?
query_string = url_params.collect { |k, v| "#{k.to_s}=#{CGI::escape(v.to_s)}" }.join('&')
url + "?#{query_string}"
else
url
end
end | ruby | {
"resource": ""
} |
q17246 | RestClient.Request.stringify_headers | train | def stringify_headers headers
headers.inject({}) do |result, (key, value)|
if key.is_a? Symbol
key = key.to_s.split(/_/).map { |w| w.capitalize }.join('-')
end
if 'CONTENT-TYPE' == key.upcase
target_value = value.to_s
result[key] = MIME::Types.type_for_extension target_value
elsif 'ACCEPT' == key.upcase
# Accept can be composed of several comma-separated values
if value.is_a? Array
target_values = value
else
target_values = value.to_s.split ','
end
result[key] = target_values.map { |ext| MIME::Types.type_for_extension(ext.to_s.strip) }.join(', ')
else
result[key] = value.to_s
end
result
end
end | ruby | {
"resource": ""
} |
q17247 | Extlib.SimpleSet.merge | train | def merge(arr)
super(arr.inject({}) {|s,x| s[x] = true; s })
end | ruby | {
"resource": ""
} |
q17248 | RhoDevelopment.LiveUpdateTask.execute | train | def execute
puts "Executing #{self.class.taskName} at #{Time::now}".primary
begin
self.action
rescue => e
puts "Executing #{self.class.taskName} failed".warning
puts e.inspect.to_s.info
puts e.backtrace.to_s.info
end
end | ruby | {
"resource": ""
} |
q17249 | RhoDevelopment.PlatformPartialUpdateBuildingTask.dispatchToUrl | train | def dispatchToUrl(anUri)
uri = URI.join(anUri, 'tasks/new')
Net::HTTP.post_form(uri, {'taskName' => self.class.taskName, 'platform' => @platform, 'filename' => @filename})
end | ruby | {
"resource": ""
} |
q17250 | RhoDevelopment.PartialUpdateTask.action | train | def action
updated_list_filename = File.join(Configuration::application_root, 'upgrade_package_add_files.txt')
removed_list_filename = File.join(Configuration::application_root, 'upgrade_package_remove_files.txt')
mkdir_p Configuration::development_directory
Configuration::enabled_subscriber_platforms.each { |each|
RhoDevelopment.setup(Configuration::development_directory, each)
puts "Check changes for #{each}".warning
changed = RhoDevelopment.check_changes_from_last_build(updated_list_filename, removed_list_filename)
if changed
puts "Source code for platform #{each} was changed".primary
WebServer.dispatch_task(PlatformPartialUpdateBuildingTask.new(each, @filename));
Configuration::enabled_subscribers_by_platform(each).each { |subscriber|
WebServer.dispatch_task(SubscriberPartialUpdateNotifyingTask.new(subscriber, @filename));
}
else
puts "Source code for platform #{each} wasn't changed".primary
end
}
end | ruby | {
"resource": ""
} |
q17251 | REXML.XPathParser.descendant_or_self | train | def descendant_or_self( path_stack, nodeset )
rs = []
#puts "#"*80
#puts "PATH_STACK = #{path_stack.inspect}"
#puts "NODESET = #{nodeset.collect{|n|n.inspect}.inspect}"
d_o_s( path_stack, nodeset, rs )
#puts "RS = #{rs.collect{|n|n.inspect}.inspect}"
document_order(rs.flatten.compact)
#rs.flatten.compact
end | ruby | {
"resource": ""
} |
q17252 | REXML.XPathParser.document_order | train | def document_order( array_of_nodes )
new_arry = []
array_of_nodes.each { |node|
node_idx = []
np = node.node_type == :attribute ? node.element : node
while np.parent and np.parent.node_type == :element
node_idx << np.parent.index( np )
np = np.parent
end
new_arry << [ node_idx.reverse, node ]
}
#puts "new_arry = #{new_arry.inspect}"
new_arry.sort{ |s1, s2| s1[0] <=> s2[0] }.collect{ |s| s[1] }
end | ruby | {
"resource": ""
} |
q17253 | BreakSpecs.Lambda.break_in_defining_scope | train | def break_in_defining_scope(value=true)
note :a
note lambda {
note :b
if value
break :break
else
break
end
note :c
}.call
note :d
end | ruby | {
"resource": ""
} |
q17254 | Net.SMTP.start | train | def start(helo = 'localhost',
user = nil, secret = nil, authtype = nil) # :yield: smtp
if block_given?
begin
do_start helo, user, secret, authtype
return yield(self)
ensure
do_finish
end
else
do_start helo, user, secret, authtype
return self
end
end | ruby | {
"resource": ""
} |
q17255 | Net.SMTP.data | train | def data(msgstr = nil, &block) #:yield: stream
if msgstr and block
raise ArgumentError, "message and block are exclusive"
end
unless msgstr or block
raise ArgumentError, "message or block is required"
end
res = critical {
check_continue get_response('DATA')
if msgstr
@socket.write_message msgstr
else
@socket.write_message_by_block(&block)
end
recv_response()
}
check_response res
res
end | ruby | {
"resource": ""
} |
q17256 | Templater.Discovery.discover! | train | def discover!(scope)
@scopes = {}
generator_files.each do |file|
load file
end
@scopes[scope].each { |block| block.call } if @scopes[scope]
end | ruby | {
"resource": ""
} |
q17257 | REXML.Node.each_recursive | train | def each_recursive(&block) # :yields: node
self.elements.each {|node|
block.call(node)
node.each_recursive(&block)
}
end | ruby | {
"resource": ""
} |
q17258 | WEBrick.Cookie.to_s | train | def to_s
ret = ""
ret << @name << "=" << @value
ret << "; " << "Version=" << @version.to_s if @version > 0
ret << "; " << "Domain=" << @domain if @domain
ret << "; " << "Expires=" << @expires if @expires
ret << "; " << "Max-Age=" << @max_age.to_s if @max_age
ret << "; " << "Comment=" << @comment if @comment
ret << "; " << "Path=" << @path if @path
ret << "; " << "Secure" if @secure
ret
end | ruby | {
"resource": ""
} |
q17259 | Net.IMAP.disconnect | train | def disconnect
begin
begin
# try to call SSL::SSLSocket#io.
@sock.io.shutdown
rescue NoMethodError
# @sock is not an SSL::SSLSocket.
@sock.shutdown
end
rescue Errno::ENOTCONN
# ignore `Errno::ENOTCONN: Socket is not connected' on some platforms.
rescue Exception => e
@receiver_thread.raise(e)
end
@receiver_thread.join
synchronize do
unless @sock.closed?
@sock.close
end
end
raise e if e
end | ruby | {
"resource": ""
} |
q17260 | Net.IMAP.starttls | train | def starttls(options = {}, verify = true)
send_command("STARTTLS") do |resp|
if resp.kind_of?(TaggedResponse) && resp.name == "OK"
begin
# for backward compatibility
certs = options.to_str
options = create_ssl_params(certs, verify)
rescue NoMethodError
end
start_tls_session(options)
end
end
end | ruby | {
"resource": ""
} |
q17261 | Net.IMAP.idle | train | def idle(&response_handler)
raise LocalJumpError, "no block given" unless response_handler
response = nil
synchronize do
tag = Thread.current[:net_imap_tag] = generate_tag
put_string("#{tag} IDLE#{CRLF}")
begin
add_response_handler(response_handler)
@idle_done_cond = new_cond
@idle_done_cond.wait
@idle_done_cond = nil
if @receiver_thread_terminating
raise Net::IMAP::Error, "connection closed"
end
ensure
unless @receiver_thread_terminating
remove_response_handler(response_handler)
put_string("DONE#{CRLF}")
response = get_tagged_response(tag, "IDLE")
end
end
end
return response
end | ruby | {
"resource": ""
} |
q17262 | Net.HTTP.get | train | def get(path, initheader = {}, dest = nil, &block) # :yield: +body_segment+
res = nil
request(Get.new(path, initheader)) {|r|
r.read_body dest, &block
res = r
}
res
end | ruby | {
"resource": ""
} |
q17263 | Net.HTTP.patch | train | def patch(path, data, initheader = nil, dest = nil, &block) # :yield: +body_segment+
send_entity(path, data, initheader, dest, Patch, &block)
end | ruby | {
"resource": ""
} |
q17264 | Net.HTTP.proppatch | train | def proppatch(path, body, initheader = nil)
request(Proppatch.new(path, initheader), body)
end | ruby | {
"resource": ""
} |
q17265 | Net.HTTP.lock | train | def lock(path, body, initheader = nil)
request(Lock.new(path, initheader), body)
end | ruby | {
"resource": ""
} |
q17266 | Net.HTTP.unlock | train | def unlock(path, body, initheader = nil)
request(Unlock.new(path, initheader), body)
end | ruby | {
"resource": ""
} |
q17267 | Net.HTTP.propfind | train | def propfind(path, body = nil, initheader = {'Depth' => '0'})
request(Propfind.new(path, initheader), body)
end | ruby | {
"resource": ""
} |
q17268 | Net.HTTP.mkcol | train | def mkcol(path, body = nil, initheader = nil)
request(Mkcol.new(path, initheader), body)
end | ruby | {
"resource": ""
} |
q17269 | Net.HTTP.request_post | train | def request_post(path, data, initheader = nil, &block) # :yield: +response+
request Post.new(path, initheader), data, &block
end | ruby | {
"resource": ""
} |
q17270 | Net.HTTP.request | train | def request(req, body = nil, &block) # :yield: +response+
unless started?
start {
req['connection'] ||= 'close'
return request(req, body, &block)
}
end
if proxy_user()
req.proxy_basic_auth proxy_user(), proxy_pass() unless use_ssl?
end
req.set_body_internal body
res = transport_request(req, &block)
if sspi_auth?(res)
sspi_auth(req)
res = transport_request(req, &block)
end
res
end | ruby | {
"resource": ""
} |
q17271 | Net.HTTP.send_entity | train | def send_entity(path, data, initheader, dest, type, &block)
res = nil
request(type.new(path, initheader), data) {|r|
r.read_body dest, &block
res = r
}
res
end | ruby | {
"resource": ""
} |
q17272 | OpenSSL.Config.get_value | train | def get_value(section, key)
if section.nil?
raise TypeError.new('nil not allowed')
end
section = 'default' if section.empty?
get_key_string(section, key)
end | ruby | {
"resource": ""
} |
q17273 | OpenSSL.Config.[]= | train | def []=(section, pairs)
check_modify
@data[section] ||= {}
pairs.each do |key, value|
self.add_value(section, key, value)
end
end | ruby | {
"resource": ""
} |
q17274 | OpenSSL.Config.to_s | train | def to_s
ary = []
@data.keys.sort.each do |section|
ary << "[ #{section} ]\n"
@data[section].keys.each do |key|
ary << "#{key}=#{@data[section][key]}\n"
end
ary << "\n"
end
ary.join
end | ruby | {
"resource": ""
} |
q17275 | OpenSSL.Config.each | train | def each
@data.each do |section, hash|
hash.each do |key, value|
yield [section, key, value]
end
end
end | ruby | {
"resource": ""
} |
q17276 | REXML.Parent.insert_before | train | def insert_before( child1, child2 )
if child1.kind_of? String
child1 = XPath.first( self, child1 )
child1.parent.insert_before child1, child2
else
ind = index(child1)
child2.parent.delete(child2) if child2.parent
@children[ind,0] = child2
child2.parent = self
end
self
end | ruby | {
"resource": ""
} |
q17277 | REXML.Parent.index | train | def index( child )
count = -1
@children.find { |i| count += 1 ; i.hash == child.hash }
count
end | ruby | {
"resource": ""
} |
q17278 | REXML.Parent.replace_child | train | def replace_child( to_replace, replacement )
@children.map! {|c| c.equal?( to_replace ) ? replacement : c }
to_replace.parent = nil
replacement.parent = self
end | ruby | {
"resource": ""
} |
q17279 | REXML.Parent.deep_clone | train | def deep_clone
cl = clone()
each do |child|
if child.kind_of? Parent
cl << child.deep_clone
else
cl << child.clone
end
end
cl
end | ruby | {
"resource": ""
} |
q17280 | REXML.Instruction.write | train | def write writer, indent=-1, transitive=false, ie_hack=false
Kernel.warn( "#{self.class.name}.write is deprecated" )
indent(writer, indent)
writer << START.sub(/\\/u, '')
writer << @target
writer << ' '
writer << @content
writer << STOP.sub(/\\/u, '')
end | ruby | {
"resource": ""
} |
q17281 | Templater.ArgumentDescription.valid? | train | def valid?(argument)
if argument.nil? and options[:required]
raise Templater::TooFewArgumentsError
elsif not argument.nil?
if options[:as] == :hash and not argument.is_a?(Hash)
raise Templater::MalformattedArgumentError, "Expected the argument to be a Hash, but was '#{argument.inspect}'"
elsif options[:as] == :array and not argument.is_a?(Array)
raise Templater::MalformattedArgumentError, "Expected the argument to be an Array, but was '#{argument.inspect}'"
end
invalid = catch :invalid do
block.call(argument) if block
throw :invalid, :not_invalid
end
raise Templater::ArgumentError, invalid unless invalid == :not_invalid
end
end | ruby | {
"resource": ""
} |
q17282 | Net.FTP.open_socket | train | def open_socket(host, port) # :nodoc:
return Timeout.timeout(@open_timeout, Net::OpenTimeout) {
if defined? SOCKSSocket and ENV["SOCKS_SERVER"]
@passive = true
sock = SOCKSSocket.open(host, port)
else
sock = TCPSocket.open(host, port)
end
io = BufferedSocket.new(sock)
io.read_timeout = @read_timeout
io
}
end | ruby | {
"resource": ""
} |
q17283 | Net.FTP.transfercmd | train | def transfercmd(cmd, rest_offset = nil) # :nodoc:
if @passive
host, port = makepasv
conn = open_socket(host, port)
if @resume and rest_offset
resp = sendcmd("REST " + rest_offset.to_s)
if resp[0] != ?3
raise FTPReplyError, resp
end
end
resp = sendcmd(cmd)
# skip 2XX for some ftp servers
resp = getresp if resp[0] == ?2
if resp[0] != ?1
raise FTPReplyError, resp
end
else
sock = makeport
if @resume and rest_offset
resp = sendcmd("REST " + rest_offset.to_s)
if resp[0] != ?3
raise FTPReplyError, resp
end
end
resp = sendcmd(cmd)
# skip 2XX for some ftp servers
resp = getresp if resp[0] == ?2
if resp[0] != ?1
raise FTPReplyError, resp
end
conn = BufferedSocket.new(sock.accept)
conn.read_timeout = @read_timeout
sock.shutdown(Socket::SHUT_WR) rescue nil
sock.read rescue nil
sock.close
end
return conn
end | ruby | {
"resource": ""
} |
q17284 | Net.FTP.getbinaryfile | train | def getbinaryfile(remotefile, localfile = File.basename(remotefile),
blocksize = DEFAULT_BLOCKSIZE) # :yield: data
result = nil
if localfile
if @resume
rest_offset = File.size?(localfile)
f = open(localfile, "a")
else
rest_offset = nil
f = open(localfile, "w")
end
elsif !block_given?
result = ""
end
begin
f.binmode if localfile
retrbinary("RETR " + remotefile.to_s, blocksize, rest_offset) do |data|
f.write(data) if localfile
yield(data) if block_given?
result.concat(data) if result
end
return result
ensure
f.close if localfile
end
end | ruby | {
"resource": ""
} |
q17285 | Net.FTP.nlst | train | def nlst(dir = nil)
cmd = "NLST"
if dir
cmd = cmd + " " + dir
end
files = []
retrlines(cmd) do |line|
files.push(line)
end
return files
end | ruby | {
"resource": ""
} |
q17286 | Net.FTP.rename | train | def rename(fromname, toname)
resp = sendcmd("RNFR " + fromname)
if resp[0] != ?3
raise FTPReplyError, resp
end
voidcmd("RNTO " + toname)
end | ruby | {
"resource": ""
} |
q17287 | Net.FTP.delete | train | def delete(filename)
resp = sendcmd("DELE " + filename)
if resp[0, 3] == "250"
return
elsif resp[0] == ?5
raise FTPPermError, resp
else
raise FTPReplyError, resp
end
end | ruby | {
"resource": ""
} |
q17288 | WEBrick.CGI.start | train | def start(env=ENV, stdin=$stdin, stdout=$stdout)
sock = WEBrick::CGI::Socket.new(@config, env, stdin, stdout)
req = HTTPRequest.new(@config)
res = HTTPResponse.new(@config)
unless @config[:NPH] or defined?(MOD_RUBY)
def res.setup_header
unless @header["status"]
phrase = HTTPStatus::reason_phrase(@status)
@header["status"] = "#{@status} #{phrase}"
end
super
end
def res.status_line
""
end
end
begin
req.parse(sock)
req.script_name = (env["SCRIPT_NAME"] || File.expand_path($0)).dup
req.path_info = (env["PATH_INFO"] || "").dup
req.query_string = env["QUERY_STRING"]
req.user = env["REMOTE_USER"]
res.request_method = req.request_method
res.request_uri = req.request_uri
res.request_http_version = req.http_version
res.keep_alive = req.keep_alive?
self.service(req, res)
rescue HTTPStatus::Error => ex
res.set_error(ex)
rescue HTTPStatus::Status => ex
res.status = ex.code
rescue Exception => ex
@logger.error(ex)
res.set_error(ex, true)
ensure
req.fixup
if defined?(MOD_RUBY)
res.setup_header
Apache.request.status_line = "#{res.status} #{res.reason_phrase}"
Apache.request.status = res.status
table = Apache.request.headers_out
res.header.each{|key, val|
case key
when /^content-encoding$/i
Apache::request.content_encoding = val
when /^content-type$/i
Apache::request.content_type = val
else
table[key] = val.to_s
end
}
res.cookies.each{|cookie|
table.add("Set-Cookie", cookie.to_s)
}
Apache.request.send_http_header
res.send_body(sock)
else
res.send_response(sock)
end
end
end | ruby | {
"resource": ""
} |
q17289 | Templater.Manifold.remove | train | def remove(name)
public_generators.delete(name.to_sym)
private_generators.delete(name.to_sym)
end | ruby | {
"resource": ""
} |
q17290 | Templater.Manifold.run_cli | train | def run_cli(destination_root, name, version, args)
Templater::CLI::Manifold.run(destination_root, self, name, version, args)
end | ruby | {
"resource": ""
} |
q17291 | Rhom.RhomObject.djb_hash | train | def djb_hash(str, len)
hash = 5381
for i in (0..len)
hash = ((hash << 5) + hash) + str[i].to_i
end
return hash
end | ruby | {
"resource": ""
} |
q17292 | REXML.Namespace.has_name? | train | def has_name?( other, ns=nil )
if ns
return (namespace() == ns and name() == other)
elsif other.include? ":"
return fully_expanded_name == other
else
return name == other
end
end | ruby | {
"resource": ""
} |
q17293 | WEBrick.HTTPRequest.each | train | def each
if @header
@header.each{|k, v|
value = @header[k]
yield(k, value.empty? ? nil : value.join(", "))
}
end
end | ruby | {
"resource": ""
} |
q17294 | WEBrick.HTTPRequest.fixup | train | def fixup() # :nodoc:
begin
body{|chunk| } # read remaining body
rescue HTTPStatus::Error => ex
@logger.error("HTTPRequest#fixup: #{ex.class} occurred.")
@keep_alive = false
rescue => ex
@logger.error(ex)
@keep_alive = false
end
end | ruby | {
"resource": ""
} |
q17295 | WEBrick.AccessLog.format | train | def format(format_string, params)
format_string.gsub(/\%(?:\{(.*?)\})?>?([a-zA-Z%])/){
param, spec = $1, $2
case spec[0]
when ?e, ?i, ?n, ?o
raise AccessLogError,
"parameter is required for \"#{spec}\"" unless param
(param = params[spec][param]) ? escape(param) : "-"
when ?t
params[spec].strftime(param || CLF_TIME_FORMAT)
when ?p
case param
when 'remote'
escape(params["i"].peeraddr[1].to_s)
else
escape(params["p"].to_s)
end
when ?%
"%"
else
escape(params[spec].to_s)
end
}
end | ruby | {
"resource": ""
} |
q17296 | Rake.Application.run_with_threads | train | def run_with_threads
thread_pool.gather_history if options.job_stats == :history
yield
thread_pool.join
if options.job_stats
stats = thread_pool.statistics
puts "Maximum active threads: #{stats[:max_active_threads]}"
puts "Total threads in play: #{stats[:total_threads_in_play]}"
end
ThreadHistoryDisplay.new(thread_pool.history).show if
options.job_stats == :history
end | ruby | {
"resource": ""
} |
q17297 | Rake.Application.standard_exception_handling | train | def standard_exception_handling
yield
rescue SystemExit
# Exit silently with current status
raise
rescue OptionParser::InvalidOption => ex
$stderr.puts ex.message
exit(false)
rescue Exception => ex
# Exit with error message
display_error_message(ex)
exit_because_of_exception(ex)
end | ruby | {
"resource": ""
} |
q17298 | Rake.Application.display_prerequisites | train | def display_prerequisites
tasks.each do |t|
puts "#{name} #{t.name}"
t.prerequisites.each { |pre| puts " #{pre}" }
end
end | ruby | {
"resource": ""
} |
q17299 | Templater.Generator.invocations | train | def invocations
return [] unless self.class.manifold
self.class.invocations.map do |invocation|
invocation.get(self) if match_options?(invocation.options)
end.compact
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.