_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q27100
|
Tabletastic.TableBuilder.action_link
|
test
|
def action_link(action, prefix)
html_class = "actions #{action.to_s}_link"
block = lambda do |resource|
compound_resource = [prefix, resource].compact
compound_resource.flatten! if prefix.kind_of?(Array)
case action
when :show
@template.link_to(link_title(action), compound_resource)
when :destroy
@template.link_to(link_title(action), compound_resource,
:method => :delete, :data => { :confirm => confirmation_message })
else # edit, other resource GET actions
@template.link_to(link_title(action),
@template.polymorphic_path(compound_resource, :action => action))
end
end
self.cell(action, :heading => "", :cell_html => {:class => html_class}, &block)
end
|
ruby
|
{
"resource": ""
}
|
q27101
|
Metro.Scenes.add
|
test
|
def add(scene)
all_scenes_for(scene).each { |scene| scenes_hash[scene.scene_name] = scene.to_s }
end
|
ruby
|
{
"resource": ""
}
|
q27102
|
Metro.Scenes.apply_post_filters
|
test
|
def apply_post_filters(new_scene,options)
post_filters.inject(new_scene) {|scene,post| post.filter(scene,options) }
end
|
ruby
|
{
"resource": ""
}
|
q27103
|
Metro.Scenes.hash_with_missing_scene_default
|
test
|
def hash_with_missing_scene_default
hash = HashWithIndifferentAccess.new do |hash,key|
missing_scene = hash[:missing_scene].constantize
missing_scene.missing_scene = key.to_sym
missing_scene
end
hash[:missing_scene] = "Metro::MissingScene"
hash
end
|
ruby
|
{
"resource": ""
}
|
q27104
|
Metro.Scenes.all_scenes_for
|
test
|
def all_scenes_for(scenes)
Array(scenes).map do |scene_class_name|
scene = scene_class_name.constantize
[ scene ] + all_scenes_for(scene.scenes)
end.flatten.compact
end
|
ruby
|
{
"resource": ""
}
|
q27105
|
Metro.Scene.actor
|
test
|
def actor(actor_or_actor_name)
if actor_or_actor_name.is_a? String or actor_or_actor_name.is_a? Symbol
send(actor_or_actor_name)
else
actor_or_actor_name
end
end
|
ruby
|
{
"resource": ""
}
|
q27106
|
Metro.Scene.notification
|
test
|
def notification(event,sender=nil)
sender = sender || UnknownSender
state.fire_events_for_notification(event,sender)
end
|
ruby
|
{
"resource": ""
}
|
q27107
|
Metro.Scene.after
|
test
|
def after(ticks,&block)
tick = OnUpdateOperation.new interval: ticks, context: self
tick.on_complete(&block)
enqueue tick
end
|
ruby
|
{
"resource": ""
}
|
q27108
|
Metro.Scene.add_actors_to_scene
|
test
|
def add_actors_to_scene
self.class.actors.each do |scene_actor|
actor_instance = scene_actor.create
actor_instance.scene = self
send "#{scene_actor.name}=", actor_instance
end
end
|
ruby
|
{
"resource": ""
}
|
q27109
|
Metro.Scene.register_animations!
|
test
|
def register_animations!
self.class.animations.each do |animation|
animate animation.actor, animation.options, &animation.on_complete_block
end
end
|
ruby
|
{
"resource": ""
}
|
q27110
|
Metro.Scene.register_actor
|
test
|
def register_actor(actor_factory)
registering_actor = actor(actor_factory.name)
registering_actor.window = window
registering_actor.show
drawers.push(registering_actor)
updaters.push(registering_actor)
register_events_for_target(registering_actor,registering_actor.class.events)
end
|
ruby
|
{
"resource": ""
}
|
q27111
|
Metro.Scene.base_update
|
test
|
def base_update
updaters.each { |updater| updater.update }
update
updaters.reject! { |updater| updater.update_completed? }
end
|
ruby
|
{
"resource": ""
}
|
q27112
|
Metro.Scene.base_draw
|
test
|
def base_draw
drawers.each { |drawer| drawer.draw }
draw
drawers.reject! { |drawer| drawer.draw_completed? }
end
|
ruby
|
{
"resource": ""
}
|
q27113
|
Metro.Scene.transition_to
|
test
|
def transition_to(scene_or_scene_name,options = {})
new_scene = Scenes.generate(scene_or_scene_name,options)
_prepare_transition(new_scene)
window.scene = new_scene
end
|
ruby
|
{
"resource": ""
}
|
q27114
|
Metro.Scene._prepare_transition
|
test
|
def _prepare_transition(new_scene)
log.debug "Preparing to transition from scene #{self} to #{new_scene}"
new_scene.class.actors.find_all {|actor_factory| actor_factory.load_from_previous_scene? }.each do |actor_factory|
new_actor = new_scene.actor(actor_factory.name)
current_actor = actor(actor_factory.name)
new_actor._load current_actor._save
end
prepare_transition_to(new_scene)
new_scene.prepare_transition_from(self)
end
|
ruby
|
{
"resource": ""
}
|
q27115
|
Metro.Scene.to_hash
|
test
|
def to_hash
drawn = drawers.find_all{|draw| draw.saveable_to_view }.inject({}) do |hash,drawer|
drawer_hash = drawer.to_hash
hash.merge drawer_hash
end
drawn
end
|
ruby
|
{
"resource": ""
}
|
q27116
|
Metro.Model.create
|
test
|
def create(model_name,options={})
# @TODO: this is another path that parallels the ModelFactory
model_class = Metro::Models.find(model_name)
mc = model_class.new options
mc.scene = scene
mc.window = window
mc
end
|
ruby
|
{
"resource": ""
}
|
q27117
|
Metro.Model._load
|
test
|
def _load(options = {})
# Clean up and symbolize all the keys then merge that with the existing properties
options.keys.each do |key|
property_name = key.to_s.underscore.to_sym
if respond_to? "#{property_name}="
send("#{property_name}=",options.delete(key))
else
options[property_name] = options.delete(key)
end
end
properties.merge! options
end
|
ruby
|
{
"resource": ""
}
|
q27118
|
WithingsSDK.Client.activities
|
test
|
def activities(user_id, options = {})
perform_request(:get, '/v2/measure', WithingsSDK::Activity, 'activities', {
action: 'getactivity',
userid: user_id
}.merge(options))
end
|
ruby
|
{
"resource": ""
}
|
q27119
|
WithingsSDK.Client.body_measurements
|
test
|
def body_measurements(user_id, options = {})
perform_request(:get, '/measure', WithingsSDK::MeasurementGroup, 'measuregrps', {
action: 'getmeas',
userid: user_id
}.merge(options))
end
|
ruby
|
{
"resource": ""
}
|
q27120
|
WithingsSDK.Client.weight
|
test
|
def weight(user_id, options = {})
groups = body_measurements(user_id, options)
groups.map do |group|
group.measures.select { |m| m.is_a? WithingsSDK::Measure::Weight }.map do |m|
WithingsSDK::Measure::Weight.new(m.attrs.merge('weighed_at' => group.date))
end
end.flatten
end
|
ruby
|
{
"resource": ""
}
|
q27121
|
WithingsSDK.Client.sleep_series
|
test
|
def sleep_series(user_id, options = {})
perform_request(:get, '/v2/sleep', WithingsSDK::SleepSeries, 'series', {
action: 'get',
userid: user_id
}.merge(options))
end
|
ruby
|
{
"resource": ""
}
|
q27122
|
WithingsSDK.Client.perform_request
|
test
|
def perform_request(http_method, path, klass, key, options = {})
if @consumer_key.nil? || @consumer_secret.nil?
raise WithingsSDK::Error::ClientConfigurationError, "Missing consumer_key or consumer_secret"
end
options = WithingsSDK::Utils.normalize_date_params(options)
request = WithingsSDK::HTTP::Request.new(@access_token, { 'User-Agent' => user_agent })
response = request.send(http_method, path, options)
if key.nil?
klass.new(response)
elsif response.has_key? key
response[key].collect do |element|
klass.new(element)
end
else
[klass.new(response)]
end
end
|
ruby
|
{
"resource": ""
}
|
q27123
|
CarrierWave.Magic.set_magic_content_type
|
test
|
def set_magic_content_type(override=false)
if override || file.content_type.blank? || generic_content_type?(file.content_type)
new_content_type = ::FileMagic.new(::FileMagic::MAGIC_MIME).file( file.path ).split(';').first
if file.respond_to?(:content_type=)
file.content_type = new_content_type
else
file.instance_variable_set(:@content_type, new_content_type)
end
end
rescue ::Exception => e
raise CarrierWave::ProcessingError, I18n.translate(:"errors.messages.magic_mime_types_processing_error", e: e, default: 'Failed to process file with FileMagic, Original Error: %{e}')
end
|
ruby
|
{
"resource": ""
}
|
q27124
|
RabbitMQ.Client.send_request
|
test
|
def send_request(channel_id, method, properties={})
Util.error_check :"sending a request",
@conn.send_method(Integer(channel_id), method.to_sym, properties)
nil
end
|
ruby
|
{
"resource": ""
}
|
q27125
|
RabbitMQ.Client.fetch_response
|
test
|
def fetch_response(channel_id, method, timeout: protocol_timeout)
methods = Array(method).map(&:to_sym)
timeout = Float(timeout) if timeout
fetch_response_internal(Integer(channel_id), methods, timeout)
end
|
ruby
|
{
"resource": ""
}
|
q27126
|
RabbitMQ.Client.on_event
|
test
|
def on_event(channel_id, method, callable=nil, &block)
handler = block || callable
raise ArgumentError, "expected block or callable as the event handler" \
unless handler.respond_to?(:call)
@event_handlers[Integer(channel_id)][method.to_sym] = handler
handler
end
|
ruby
|
{
"resource": ""
}
|
q27127
|
GtfsReader.SourceUpdater.download_source
|
test
|
def download_source
Log.debug { " Reading #{@source.url.green}" }
zip = Tempfile.new('gtfs')
zip.binmode
zip << open(@source.url).read
zip.rewind
extract_to_tempfiles(zip)
Log.debug { "Finished reading #{@source.url.green}" }
rescue StandardException => e
Log.error(e.message)
raise e
ensure
zip.try(:close)
end
|
ruby
|
{
"resource": ""
}
|
q27128
|
GtfsReader.SourceUpdater.check_files
|
test
|
def check_files
@found_files = []
check_required_files
check_optional_files
# Add feed files of zip to the list of files to be processed
@source.feed_definition.files.each do |req|
@found_files << req if filenames.include?(req.filename)
end
end
|
ruby
|
{
"resource": ""
}
|
q27129
|
GtfsReader.SourceUpdater.check_columns
|
test
|
def check_columns
@found_files.each do |file|
@temp_files[file.filename].open do |data|
FileReader.new(data, file, validate: true)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q27130
|
GtfsReader.SourceUpdater.fetch_http_fallback_identifier
|
test
|
def fetch_http_fallback_identifier(head_request)
if head_request.key?('last-modified')
head_request['last-modified']
elsif head_request.key?('content-length')
head_request['content-length']
else
Time.now.to_s
end
end
|
ruby
|
{
"resource": ""
}
|
q27131
|
GtfsReader.Configuration.parameter
|
test
|
def parameter(*names)
names.each do |name|
define_singleton_method(name) do |*values|
if (value = values.first)
instance_variable_set("@#{name}", value)
else
instance_variable_get("@#{name}")
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q27132
|
GtfsReader.FileReader.find_columns
|
test
|
def find_columns(validate)
@found_columns = []
prefix = "#{filename.yellow}:"
required = @definition.required_columns
unless required.empty?
Log.info { "#{prefix} #{'required columns'.magenta}" } if validate
missing = check_columns(validate, prefix, required, :green, :red)
raise RequiredColumnsMissing, missing if validate && missing.present?
end
optional = @definition.optional_columns
unless optional.empty?
Log.info { "#{prefix} #{'optional columns'.cyan}" } if validate
check_columns(validate, prefix, optional, :cyan, :light_yellow)
end
cols = @definition.columns.collect(&:name)
headers = @csv_headers.select { |h| cols.include?(h) }
@col_names ||= @found_columns.map(&:name)
::Hash[*headers.inject([]) { |list, c| list << c << @definition[c] }]
end
|
ruby
|
{
"resource": ""
}
|
q27133
|
Nidyx.Mapper.map
|
test
|
def map(models, options)
models = models.values
case options[:platform].downcase
when "objc", "obj-c", "objective-c"
Nidyx::ObjCMapper.map(models, options)
end
end
|
ruby
|
{
"resource": ""
}
|
q27134
|
Nidyx.Parser.generate
|
test
|
def generate(path, name)
object = get_object(path)
type = object[TYPE_KEY]
if type == OBJECT_TYPE
generate_object(path, name)
elsif type == ARRAY_TYPE
generate_top_level_array(path)
elsif type.is_a?(Array)
if type.include?(OBJECT_TYPE)
raise UnsupportedSchemaError if type.include?(ARRAY_TYPE)
generate_object(path, name)
elsif type.include?(ARRAY_TYPE)
generate_top_leve_array(path)
else raise UnsupportedSchemaError; end
else raise UnsupportedSchemaError; end
end
|
ruby
|
{
"resource": ""
}
|
q27135
|
Nidyx.Parser.resolve_array_refs
|
test
|
def resolve_array_refs(obj)
items = obj[ITEMS_KEY]
case items
when Array
return resolve_items_array(items)
when Hash
# handle a nested any of key
any_of = items[ANY_OF_KEY]
return resolve_items_array(any_of) if any_of.is_a?(Array)
resolve_reference_string(items[REF_KEY])
return [class_name_from_ref(items[REF_KEY])].compact
else
return []
end
end
|
ruby
|
{
"resource": ""
}
|
q27136
|
Nidyx.Generator.run
|
test
|
def run(schema_path, options)
schema = Nidyx::Reader.read(schema_path)
raw_models = Nidyx::Parser.parse(schema, options)
models = Nidyx::Mapper.map(raw_models, options)
Nidyx::Output.write(models, options[:output_directory])
end
|
ruby
|
{
"resource": ""
}
|
q27137
|
Nidyx.Reader.read
|
test
|
def read(path)
schema = nil
begin
# TODO: validate this is legitimate JSON Schema
schema = JSON.parse(IO.read(path))
raise EmptySchemaError if empty_schema?(schema)
rescue JSON::JSONError => e
puts "Encountered an error reading JSON from #{path}"
puts e.message
exit 1
rescue EmptySchemaError
puts "Schema read from #{path} is empty"
exit 1
rescue StandardError => e
puts e.message
exit 1
end
schema
end
|
ruby
|
{
"resource": ""
}
|
q27138
|
Wxpay.Sign.sign_package
|
test
|
def sign_package params
params_str = create_sign_str params
if params_str =~ /trade_type=APP/
key = Wxpay.app_api_key
else
key = Wxpay.api_key
end
Digest::MD5.hexdigest(params_str+"&key=#{key}").upcase
end
|
ruby
|
{
"resource": ""
}
|
q27139
|
Webspicy.Scope._each_resource_file
|
test
|
def _each_resource_file(config)
folder = config.folder
folder.glob("**/*.yml").select(&to_filter_proc(config.file_filter)).each do |file|
yield file, folder
end
end
|
ruby
|
{
"resource": ""
}
|
q27140
|
Webspicy.Scope.each_resource
|
test
|
def each_resource(&bl)
return enum_for(:each_resource) unless block_given?
each_resource_file do |file, folder|
yield Webspicy.resource(file.load, file, self)
end
end
|
ruby
|
{
"resource": ""
}
|
q27141
|
Webspicy.Scope.to_real_url
|
test
|
def to_real_url(url, test_case = nil, &bl)
case config.host
when Proc
config.host.call(url, test_case)
when String
url =~ /^http/ ? url : "#{config.host}#{url}"
else
return url if url =~ /^http/
return yield(url) if block_given?
raise "Unable to resolve `#{url}` : no host resolver provided\nSee `Configuration#host="
end
end
|
ruby
|
{
"resource": ""
}
|
q27142
|
Webspicy.Scope.to_filter_proc
|
test
|
def to_filter_proc(filter)
case ff = filter
when NilClass then ->(f){ true }
when Proc then ff
when Regexp then ->(f){ ff =~ f.to_s }
else
->(f){ ff === f }
end
end
|
ruby
|
{
"resource": ""
}
|
q27143
|
Webspicy.Configuration.folder
|
test
|
def folder(folder = nil, &bl)
if folder.nil?
@folder
else
folder = folder.is_a?(String) ? @folder/folder : Path(folder)
raise "Folder `#{folder}` does not exists" unless folder.exists? && folder.directory?
raise "Folder must be a descendant" unless folder.inside?(@folder)
child = dup do |c|
c.parent = self
c.folder = folder
end
yield(child) if block_given?
@children << child
child
end
end
|
ruby
|
{
"resource": ""
}
|
q27144
|
Webspicy.Configuration.data_system
|
test
|
def data_system
schema = self.folder/"schema.fio"
if schema.file?
Finitio::DEFAULT_SYSTEM.parse(schema.read)
elsif not(self.parent.nil?)
self.parent.data_system
else
Finitio::DEFAULT_SYSTEM
end
end
|
ruby
|
{
"resource": ""
}
|
q27145
|
Exodus.Migration.run
|
test
|
def run(direction)
self.status.direction = direction
# reset the status if the job is rerunnable and has already be completed
self.status.reset! if self.class.rerunnable_safe? && completed?(direction)
self.status.execution_time = time_it { self.send(direction) }
self.status.last_succesful_completion = Time.now
end
|
ruby
|
{
"resource": ""
}
|
q27146
|
Exodus.Migration.failure=
|
test
|
def failure=(exception)
self.status.error = MigrationError.new(
:error_message => exception.message,
:error_class => exception.class,
:error_backtrace => exception.backtrace)
end
|
ruby
|
{
"resource": ""
}
|
q27147
|
Exodus.Migration.is_runnable?
|
test
|
def is_runnable?(direction)
self.class.rerunnable_safe? ||
(direction == UP && status.current_status < status_complete) ||
(direction == DOWN && status.current_status > 0)
end
|
ruby
|
{
"resource": ""
}
|
q27148
|
Exodus.Migration.completed?
|
test
|
def completed?(direction)
return false if self.status.execution_time == 0
(direction == UP && self.status.current_status == self.status_complete) ||
(direction == DOWN && self.status.current_status == 0)
end
|
ruby
|
{
"resource": ""
}
|
q27149
|
Exodus.Migration.step
|
test
|
def step(step_message = nil, step_status = 1)
unless status.status_processed?(status.direction, step_status)
self.status.message = step_message
puts "\t #{step_message}"
yield if block_given?
self.status.current_status += status.direction_to_i
end
end
|
ruby
|
{
"resource": ""
}
|
q27150
|
Exodus.Migration.time_it
|
test
|
def time_it
puts "Running #{self.class}[#{self.status.arguments}](#{self.status.direction})"
start = Time.now
yield if block_given?
end_time = Time.now - start
puts "Tasks #{self.class} executed in #{end_time} seconds. \n\n"
end_time
end
|
ruby
|
{
"resource": ""
}
|
q27151
|
Exodus.TextFormatter.super_print
|
test
|
def super_print(paragraphes, space_number = 50, title = true)
puts format_paragraph(space_number, title, *paragraphes)
end
|
ruby
|
{
"resource": ""
}
|
q27152
|
Gridify.Grid.columns_hash
|
test
|
def columns_hash
colModel.inject({}) { |h, col| h[col.name] = col; h }
end
|
ruby
|
{
"resource": ""
}
|
q27153
|
Amber.Site.render
|
test
|
def render
@page_list.each do |page|
page.render_to_file(@config.dest_dir)
putc '.'; $stdout.flush
end
@dir_list.each do |directory|
src = File.join(@config.pages_dir, directory)
dst = File.join(@config.dest_dir, directory)
Render::Asset.render_dir(src, dst)
putc '.'; $stdout.flush
end
if @config.short_paths
render_short_path_symlinks
end
Render::Apache.write_htaccess(@config, @config.pages_dir, @config.dest_dir)
puts
end
|
ruby
|
{
"resource": ""
}
|
q27154
|
Amber.Site.add_page
|
test
|
def add_page(page)
@pages_by_name[page.name] ||= page
@pages_by_path[page.path.join('/')] = page
add_aliases(I18n.default_locale, page, @pages_by_path)
page.locales.each do |locale|
next if locale == I18n.default_locale
add_aliases(locale, page, @pages_by_locale_path[locale])
end
@page_list << page
end
|
ruby
|
{
"resource": ""
}
|
q27155
|
Amber.Site.add_aliases
|
test
|
def add_aliases(locale, page, path_hash)
page.aliases(locale).each do |alias_path|
alias_path_str = alias_path.join('/')
if path_hash[alias_path_str]
Amber.logger.warn "WARNING: page `#{page.path.join('/')}` has alias `#{alias_path_str}`, but this path is already taken by `#{path_hash[alias_path_str].path.join('/')}` (locale = #{locale})."
else
path_hash[alias_path_str] = page
end
end
end
|
ruby
|
{
"resource": ""
}
|
q27156
|
Amber.StaticPage.parse_headers
|
test
|
def parse_headers(content_file)
headers = []
para1 = []
para2 = []
file_type = type_from_path(content_file)
File.open(content_file, :encoding => 'UTF-8') do |f|
while (line = f.gets) =~ /^(- |)@\w/
if line !~ /^-/
line = '- ' + line
end
headers << line
end
# eat empty lines
while line = f.gets
break unless line =~ /^\s*$/
end
# grab first two paragraphs
para1 << line
while line = f.gets
break if line =~ /^\s*$/
para1 << line
end
while line = f.gets
break if line =~ /^\s*$/
para2 << line
end
end
headers = headers.join
para1 = para1.join
para2 = para2.join
excerpt = ""
# pick the first non-heading paragraph.
# this is stupid, and chokes on nested headings.
# but is also cheap and fast :)
if file_type == :textile
if para1 =~ /^h[1-5]\. /
excerpt = para2
else
excerpt = para1
end
elsif file_type == :markdown
if para1 =~ /^#+ / || para1 =~ /^(===+|---+)\s*$/m
excerpt = para2
else
excerpt = para1
end
end
return [headers, excerpt]
end
|
ruby
|
{
"resource": ""
}
|
q27157
|
Amber.StaticPage.variable_files
|
test
|
def variable_files
if @simple_page
directory = File.dirname(@file_path)
regexp = SIMPLE_VAR_MATCH_RE.call(@name)
else
directory = @file_path
regexp = VAR_FILE_MATCH_RE
end
hsh = {}
Dir.foreach(directory) do |file|
if file && match = regexp.match(file)
locale = match['locale'] || I18n.default_locale
hsh[locale.to_sym] = File.join(directory, file)
end
end
hsh
end
|
ruby
|
{
"resource": ""
}
|
q27158
|
Amber.Menu.last_menu_at_depth
|
test
|
def last_menu_at_depth(depth)
menu = self
depth.times { menu = menu.children.last }
menu
end
|
ruby
|
{
"resource": ""
}
|
q27159
|
Amber::Render.TableOfContents.nameize
|
test
|
def nameize(str)
str = str.dup
str.gsub!(/&(\w{2,6}?|#[0-9A-Fa-f]{2,6});/,'') # remove html entitities
str.gsub!(/[^- [[:word:]]]/u, '') # remove non-word characters (using unicode definition of a word char)
str.strip!
str.downcase! # upper case characters in urls are confusing
str.gsub!(/\ +/u, '-') # spaces to dashes, preferred separator char everywhere
CGI.escape(str)
end
|
ruby
|
{
"resource": ""
}
|
q27160
|
Amber::Render.TableOfContents.strip_html_tags
|
test
|
def strip_html_tags(html)
Nokogiri::HTML::DocumentFragment.parse(html, 'UTF-8').children.collect{|child| child.inner_text}.join
end
|
ruby
|
{
"resource": ""
}
|
q27161
|
Amber::Render.TocItem.populate_node
|
test
|
def populate_node(node, options)
@children.each do |item|
li = node.document.create_element("li")
li.add_child(li.document.create_element("a", item.text, :href => "#{options[:href_base]}##{item.anchor}"))
if item.children.any?
ul = li.document.create_element(options[:tag])
item.populate_node(ul, options)
li.add_child(ul)
end
node.add_child(li)
end
end
|
ruby
|
{
"resource": ""
}
|
q27162
|
Amber::Render.TocItem.to_html
|
test
|
def to_html(options={})
html = []
tag = options[:tag]
indent = options[:indent] || 0
str = options[:indent_str] || " "
html << '%s<%s>' % [(str*indent), tag]
@children.each do |item|
html << '%s<li>' % (str*(indent+1))
html << '%s<a href="%s#%s">%s</a>' % [str*(indent+2), options[:href_base], item.anchor, item.text]
if item.children.any?
html << item.to_html({
:indent => indent+2,
:indent_str => str,
:tag => tag,
:href_base => options[:href_base]
})
end
html << '%s</li>' % (str*(indent+1))
end
html << '%s</%s>' % [(str*indent), tag]
html.join("\n")
end
|
ruby
|
{
"resource": ""
}
|
q27163
|
Amber::Render.TocItem.parent_for
|
test
|
def parent_for(heading)
heading = heading[1].to_i if heading.is_a?(String)
if children.any? && children.last.level < heading
children.last.parent_for(heading)
else
self
end
end
|
ruby
|
{
"resource": ""
}
|
q27164
|
Eve.JavascriptHelper.type_id
|
test
|
def type_id(which)
which = which.to_s.humanize unless which.kind_of?(String)
which.downcase!
case which
when 'alliance' then 16159
when 'character' then 1377
when 'corporation' then 2
when 'constellation' then 4
when 'region' then 3
when 'solar system', 'solarsystem' then 5
when 'station' then 3867
else raise ArgumentError, "Unknown type: #{which}"
end
end
|
ruby
|
{
"resource": ""
}
|
q27165
|
Eve.JavascriptHelper.link_to_info
|
test
|
def link_to_info(text, type_id, item_id = nil, *args)
function = "CCPEVE.showInfo(#{type_id.inspect}"
function.concat ", #{item_id.inspect}" if item_id
function.concat ")"
link_to_function text, function, *args
end
|
ruby
|
{
"resource": ""
}
|
q27166
|
Eve.JavascriptHelper.link_to_route
|
test
|
def link_to_route(text, destination_id, source_id = nil, *args)
function = "CCPEVE.showRouteTo(#{destination_id.inspect}"
function.concat ", #{source_id.inspect}" if source_id
function.concat ")"
link_to_function text, function, *args
end
|
ruby
|
{
"resource": ""
}
|
q27167
|
Eve.JavascriptHelper.link_to_trust_request
|
test
|
def link_to_trust_request(text, trust_url = "http://#{request.host}/", *args)
trust_url = url_for(trust_url.merge(:only_path => false)) if trust_url.kind_of?(Hash)
link_to_function text, "CCPEVE.requestTrust(#{trust_url.inspect})", *args
end
|
ruby
|
{
"resource": ""
}
|
q27168
|
Eve.JavascriptHelper.request_trust
|
test
|
def request_trust(trust_url = "http://#{request.host}/", *args)
trust_url = url_for(trust_url.merge(:only_path => false)) if trust_url.kind_of?(Hash)
javascript_tag "CCPEVE.requestTrust(#{trust_url.inspect});", *args
end
|
ruby
|
{
"resource": ""
}
|
q27169
|
Amber.StaticPage.render_to_file
|
test
|
def render_to_file(dest_dir, options={})
render_content_files(dest_dir, options)
render_assets(dest_dir)
@props.locales.each do |locale|
if aliases(locale).any?
link_page_aliases(dest_dir, aliases(locale), locale)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q27170
|
Amber.StaticPage.symlink
|
test
|
def symlink(from_path, to_path)
to_path = realpath(to_path)
target = from_path.relative_path_from(to_path).to_s.sub(/^\.\.\//, '')
if !to_path.dirname.directory?
Amber.logger.warn { "On page `#{@file_path}`, the parent directories for alias name `#{to_path}` don't exist. Skipping alias." }
return
end
if to_path.exist? && to_path.symlink?
File.unlink(to_path)
end
if !to_path.exist?
Amber.logger.debug { "Symlink #{to_path} => #{target}" }
FileUtils.ln_s(target, to_path)
end
end
|
ruby
|
{
"resource": ""
}
|
q27171
|
Amber.StaticPage.render_content_files
|
test
|
def render_content_files(dest_dir, options)
view = Render::View.new(self, @config)
@config.locales.each do |file_locale|
content_file = content_file(file_locale)
next unless content_file
dest = destination_file(dest_dir, file_locale)
unless Dir.exist?(File.dirname(dest))
FileUtils.mkdir_p(File.dirname(dest))
end
if options[:force] || !File.exist?(dest) || File.mtime(content_file) > File.mtime(dest)
File.open(dest, 'w') do |f|
layout = @props.layout || 'default'
f.write view.render({page: self, layout: layout}, {locale: file_locale})
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q27172
|
Snoo.User.friend
|
test
|
def friend name, friend_id, note = nil
friend_wrapper(api_name = name, api_container = @userid, api_note = note, api_type = "friend")
end
|
ruby
|
{
"resource": ""
}
|
q27173
|
Snoo.User.get_user_listing
|
test
|
def get_user_listing username, opts = {}
opts[:type] = 'overview' if opts[:type].nil?
url = "/user/%s%s.json" % [username, ('/' + opts[:type] if opts[:type] != 'overview')]
opts.delete :type
query = opts
get(url, query: query)
end
|
ruby
|
{
"resource": ""
}
|
q27174
|
Snoo.LinksComments.comment
|
test
|
def comment text, id
logged_in?
post('/api/comment', body: { text: text, thing_id: id, uh: @modhash, api_type: 'json'})
end
|
ruby
|
{
"resource": ""
}
|
q27175
|
Snoo.LinksComments.submit
|
test
|
def submit title, subreddit, opts = {}
logged_in?
post = {
title: title,
sr: subreddit,
uh: @modhash,
kind: (opts[:url] ? "link" : "self"),
api_type: 'json'
}
post.merge! opts
post('/api/submit', body: post)
end
|
ruby
|
{
"resource": ""
}
|
q27176
|
Snoo.LinksComments.vote
|
test
|
def vote direction, id
logged_in?
post('/api/vote', body: {id: id, dir: direction, uh: @modhash, api_type: 'json'})
end
|
ruby
|
{
"resource": ""
}
|
q27177
|
Gotcha.Base.correct?
|
test
|
def correct?(str)
str = str.is_a?(String) ? str : str.to_s
str == (@answer.is_a?(String) ? @answer : @answer.to_s) # don't change @answer type
end
|
ruby
|
{
"resource": ""
}
|
q27178
|
Gotcha.FormHelpers.gotcha
|
test
|
def gotcha(options = {})
options[:label_options] ||= {}
options[:text_field_options] ||= {}
if gotcha = Gotcha.random
field = "gotcha_response[#{gotcha.class.name.to_s}-#{Digest::MD5.hexdigest(gotcha.class.down_transform(gotcha.answer))}]"
(label_tag field, gotcha.question, options[:label_options]) + "\n" + (text_field_tag field, nil, options[:text_field_options])
else
raise "No Gotchas Installed"
end
end
|
ruby
|
{
"resource": ""
}
|
q27179
|
Snoo.Subreddit.delete_image
|
test
|
def delete_image subreddit, image_name
logged_in?
post('/api/delete_sr_image', body: {r: subreddit, img_name: image_name, uh: @modhash, api_type: 'json'})
end
|
ruby
|
{
"resource": ""
}
|
q27180
|
Snoo.Subreddit.set_stylesheet
|
test
|
def set_stylesheet stylesheet, subreddit
logged_in?
post('/api/subreddit_stylesheet', body: {op: 'save', r: subreddit, stylesheet_contents: stylesheet, uh: @modhash, api_type: 'json'})
end
|
ruby
|
{
"resource": ""
}
|
q27181
|
Snoo.Subreddit.subscribe
|
test
|
def subscribe subreddit, action = "sub"
logged_in?
post('/api/subscribe', body: {action: action, sr: subreddit, uh: @modhash, api_type: 'json'})
end
|
ruby
|
{
"resource": ""
}
|
q27182
|
Snoo.Subreddit.my_reddits
|
test
|
def my_reddits opts = {}
logged_in?
url = "/reddits/mine/%s.json" % (opts[:condition] if opts[:condition])
opts.delete :condition
query = opts
get(url, query: query)
end
|
ruby
|
{
"resource": ""
}
|
q27183
|
Snoo.Subreddit.get_reddits
|
test
|
def get_reddits opts = {}
url = "/reddits/%s.json" % (opts[:condition] if opts[:condition])
opts.delete :condition
query = opts
get(url, query: query)
end
|
ruby
|
{
"resource": ""
}
|
q27184
|
Snoo.Subreddit.add_moderator
|
test
|
def add_moderator container, user, subreddit
friend_wrapper container: container, name: user, r: subreddit, type: "moderator"
end
|
ruby
|
{
"resource": ""
}
|
q27185
|
Snoo.Subreddit.add_contributor
|
test
|
def add_contributor container, user, subreddit
friend_wrapper container: container, name: user, r: subreddit, type: "contributor"
end
|
ruby
|
{
"resource": ""
}
|
q27186
|
Snoo.Subreddit.ban_user
|
test
|
def ban_user container, user, subreddit
friend_wrapper container: container, name: user, r: subreddit, type: "banned"
end
|
ruby
|
{
"resource": ""
}
|
q27187
|
Snoo.Subreddit.remove_moderator
|
test
|
def remove_moderator container, user, subreddit
unfriend_wrapper container: container, name: user, r: subreddit, type: "moderator"
end
|
ruby
|
{
"resource": ""
}
|
q27188
|
Snoo.Subreddit.remove_contributor
|
test
|
def remove_contributor container, user, subreddit
unfriend_wrapper container: container, name: user, r: subreddit, type: "contributor"
end
|
ruby
|
{
"resource": ""
}
|
q27189
|
Snoo.Subreddit.unban_user
|
test
|
def unban_user container, user, subreddit
unfriend_wrapper container: container, name: user, r: subreddit, type: "banned"
end
|
ruby
|
{
"resource": ""
}
|
q27190
|
Snoo.Utilities.get
|
test
|
def get *args, &block
response = self.class.get *args, &block
raise WebserverError, response.code unless response.code == 200
response
end
|
ruby
|
{
"resource": ""
}
|
q27191
|
Snoo.Account.log_in
|
test
|
def log_in username, password
login = post("/api/login", :body => {user: username, passwd: password, api_type: 'json'})
errors = login['json']['errors']
raise errors[0][1] unless errors.size == 0
set_cookies login.headers['set-cookie']
@modhash = login['json']['data']['modhash']
@username = username
@userid = 't2_' + get('/api/me.json')['data']['id']
return login
end
|
ruby
|
{
"resource": ""
}
|
q27192
|
Snoo.Account.auth
|
test
|
def auth modhash, cookies
set_cookies cookies
@modhash = modhash
meinfo = get("/api/me.json")
@username = meinfo['data']['name']
@userid = 't2_' + meinfo['data']['id']
end
|
ruby
|
{
"resource": ""
}
|
q27193
|
Snoo.Account.delete_user
|
test
|
def delete_user password, reason = "deleted by script command"
logged_in?
delete = post('/api/delete_user', body: {
confirm: true,
delete_message: reason,
passwd: password,
uh: @modhash,
user: @username,
api_type: 'json'
})
return delete
end
|
ruby
|
{
"resource": ""
}
|
q27194
|
Snoo.PM.get_messages
|
test
|
def get_messages where = "inbox", opts = {}
query = {
mark: false
}
query.merge! opts
get("/message/#{where}.json", query: query)
end
|
ruby
|
{
"resource": ""
}
|
q27195
|
Snoo.Flair.clear_flair_templates
|
test
|
def clear_flair_templates type, subreddit
logged_in?
post('/api/clearflairtemplates', body: { flair_type: type, r: subreddit, uh: @modhash, api_type: 'json'})
end
|
ruby
|
{
"resource": ""
}
|
q27196
|
Snoo.Flair.delete_user_flair
|
test
|
def delete_user_flair user, subreddit
logged_in?
post('/api/deleteflair', body: {name: user, r: subreddit, uh: @modhash, api_type: 'json'})
end
|
ruby
|
{
"resource": ""
}
|
q27197
|
Snoo.Flair.delete_flair_template
|
test
|
def delete_flair_template id, subreddit
logged_in?
post('/api/deleteflairtemplate', body: {flair_template_id: id, r: subreddit, uh: @modhash, api_type: 'json'})
end
|
ruby
|
{
"resource": ""
}
|
q27198
|
Snoo.Flair.flair_config
|
test
|
def flair_config subreddit, opts = {}
logged_in?
options = {
flair_enabled: true,
flair_position: 'right',
flair_self_assign_enabled: false,
link_flair_position: 'right',
link_flair_self_assign_enabled: false,
uh: @modhash,
r: subreddit,
api_type: 'json'
}
options.merge! opts
post('/api/flairconfig', body: options)
end
|
ruby
|
{
"resource": ""
}
|
q27199
|
Snoo.Flair.flair_csv
|
test
|
def flair_csv csv, subreddit
logged_in?
post('/api/flaircsv.json', body: {flair_csv: csv, r: subreddit, uh: @modhash})
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.