_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q17100 | ActiveMocker.Queries.sum | train | def sum(key)
values = values_by_key(key)
values.inject(0) do |sum, n|
sum + (n || 0)
end
end | ruby | {
"resource": ""
} |
q17101 | ActiveMocker.Queries.average | train | def average(key)
values = values_by_key(key)
total = values.inject { |sum, n| sum + n }
BigDecimal.new(total) / BigDecimal.new(values.count)
end | ruby | {
"resource": ""
} |
q17102 | ActiveMocker.Base.slice | train | def slice(*methods)
Hash[methods.map! { |method| [method, public_send(method)] }].with_indifferent_access
end | ruby | {
"resource": ""
} |
q17103 | Danger.DangerXcodeSummary.warning_error_count | train | def warning_error_count(file_path)
if File.file?(file_path)
xcode_summary = JSON.parse(File.read(file_path), symbolize_names: true)
warning_count = warnings(xcode_summary).count
error_count = errors(xcode_summary).count
result = { warnings: warning_count, errors: error_count }
result.to_json
else
fail 'summary file not found'
end
end | ruby | {
"resource": ""
} |
q17104 | RegexpExamples.MultiGroup.result | train | def result
strings = @groups.map { |repeater| repeater.public_send(__callee__) }
RegexpExamples.permutations_of_strings(strings).map do |result|
GroupResult.new(result, group_id)
end
end | ruby | {
"resource": ""
} |
q17105 | Bh.Helpers.button | train | def button(*args, &block)
button = Bh::Button.new(self, *args, &block)
button.extract! :context, :size, :layout
button.append_class! :btn
button.append_class! button.context_class
button.append_class! button.size_class
button.append_class! button.layout_class
button.render_tag :button
end | ruby | {
"resource": ""
} |
q17106 | Bh.Helpers.panel_row | train | def panel_row(options = {}, &block)
panel_row = Bh::PanelRow.new self, options, &block
panel_row.extract! :column_class
panel_row.append_class! :row
panel_row.render_tag :div
end | ruby | {
"resource": ""
} |
q17107 | Bh.Helpers.panel | train | def panel(*args, &block)
panel = Bh::Panel.new self, *args, &block
panel.extract! :body, :context, :title, :heading, :tag
panel.append_class! :panel
panel.append_class! panel.context_class
panel.merge_html! panel.body
panel.prepend_html! panel.heading
if panel_row = Bh::Stack.find(Bh::PanelRow)
container = Bh::Base.new(self) { panel.content_tag panel.tag }
container.append_class! panel_row.column_class
container.render_tag :div
else
panel.render_tag panel.tag
end
end | ruby | {
"resource": ""
} |
q17108 | Bh.Helpers.modal | train | def modal(*args, &block)
modal = Bh::Modal.new self, *args, &block
modal.extract! :button, :size, :body, :title, :id
modal.extract_from :button, [:context, :size, :layout, :caption]
modal.append_class_to! :button, :btn
modal.append_class_to! :button, modal.button_context_class
modal.append_class_to! :button, modal.button_size_class
modal.merge! button: {caption: modal.caption}
modal.append_class_to! :div, :'modal-dialog'
modal.append_class_to! :div, modal.dialog_size_class
modal.merge! div: {title: modal.title, id: modal.id}
modal.render_partial 'modal'
end | ruby | {
"resource": ""
} |
q17109 | Bh.Helpers.nav | train | def nav(options = {}, &block)
nav = Bh::Nav.new(self, options, &block)
nav.extract! :as, :layout
nav.append_class! :nav
if Bh::Stack.find(Bh::Navbar)
nav.append_class! :'navbar-nav'
else
nav.merge! role: :tablist
nav.append_class! nav.style_class
nav.append_class! nav.layout_class
end
nav.render_tag :ul
end | ruby | {
"resource": ""
} |
q17110 | Bh.Helpers.horizontal | train | def horizontal(*args, &block)
if navbar = Bh::Stack.find(Bh::Navbar)
horizontal = Bh::Base.new self, *args, &block
horizontal.append_class! :'collapse navbar-collapse'
horizontal.merge! id: navbar.id
horizontal.render_tag :div
end
end | ruby | {
"resource": ""
} |
q17111 | Bh.Helpers.icon | train | def icon(name = nil, options = {})
icon = Bh::Icon.new self, nil, options.merge(name: name)
icon.extract! :library, :name
icon.append_class! icon.library_class
icon.append_class! icon.name_class
icon.render_tag :span
end | ruby | {
"resource": ""
} |
q17112 | Bh.Helpers.vertical | train | def vertical(*args, &block)
if navbar = Bh::Stack.find(Bh::Navbar)
vertical = Bh::Vertical.new self, *args, &block
vertical.append_class! :'navbar-header'
vertical.prepend_html! vertical.toggle_button(navbar.id)
vertical.render_tag :div
end
end | ruby | {
"resource": ""
} |
q17113 | Bh.Helpers.progress_bar | train | def progress_bar(args = nil, container_options = {})
progress_bars = Array.wrap(args).map do |options|
progress_bar = Bh::ProgressBar.new self, nil, options
progress_bar.extract! :percentage, :context, :striped, :animated, :label
progress_bar.merge! progress_bar.aria_values
progress_bar.append_class! :'progress-bar'
progress_bar.append_class! progress_bar.context_class
progress_bar.append_class! progress_bar.striped_class
progress_bar.append_class! progress_bar.animated_class
progress_bar.merge! progress_bar.values
progress_bar.prepend_html! progress_bar.label
progress_bar
end
container = Bh::Base.new self, progress_bars, container_options
container.append_class! :progress
container.render_tag :div
end | ruby | {
"resource": ""
} |
q17114 | Bh.Helpers.navbar | train | def navbar(options = {}, &block)
navbar = Bh::Navbar.new(self, options, &block)
navbar.extract! :inverted, :position, :padding, :fluid, :id
navbar.append_class_to! :navigation, :navbar
navbar.append_class_to! :navigation, navbar.style_class
navbar.append_class_to! :navigation, navbar.position_class
navbar.append_class_to! :div, navbar.layout_class
navbar.prepend_html! navbar.body_padding_style
navbar.render_partial 'navbar'
end | ruby | {
"resource": ""
} |
q17115 | Bh.Helpers.link_to | train | def link_to(*args, &block)
link_to = Bh::LinkTo.new self, *args, &block
link_to.append_class! :'alert-link' if Bh::Stack.find(Bh::AlertBox)
link_to.append_class! :'navbar-brand' if Bh::Stack.find(Bh::Vertical)
link_to.merge! role: :menuitem if Bh::Stack.find(Bh::Dropdown)
link_to.merge! tabindex: -1 if Bh::Stack.find(Bh::Dropdown)
html = super link_to.content, link_to.url, link_to.attributes, &nil
if Bh::Stack.find(Bh::Dropdown)
container = Bh::Base.new(self) { html }
container.merge! role: :presentation
container.render_tag :li
elsif Bh::Stack.find(Bh::Nav)
container = Bh::Base.new(self) { html }
container.append_class! :active if link_to.current_page?
container.render_tag :li
else
html
end
end | ruby | {
"resource": ""
} |
q17116 | Bh.Helpers.alert_box | train | def alert_box(*args, &block)
alert_box = Bh::AlertBox.new(self, *args, &block)
alert_box.extract! :context, :priority, :dismissible
alert_box.append_class! :alert
alert_box.append_class! alert_box.context_class
alert_box.merge! role: :alert
alert_box.prepend_html! alert_box.dismissible_button
alert_box.render_tag :div
end | ruby | {
"resource": ""
} |
q17117 | Jekyll.OctopodFilters.otherwise | train | def otherwise(first, second)
first = first.to_s
first.empty? ? second : first
end | ruby | {
"resource": ""
} |
q17118 | Jekyll.OctopodFilters.audio | train | def audio(hsh, key = nil)
if !hsh.nil? && hsh.length
if key.nil?
hsh['mp3'] ? hsh['mp3'] : hsh['m4a'] ? hsh['m4a'] : hsh['ogg'] ? hsh['ogg'] : hsh['opus'] ? hsh['opus'] : hsh.values.first
else
hsh[key]
end
end
end | ruby | {
"resource": ""
} |
q17119 | Jekyll.OctopodFilters.audio_type | train | def audio_type(hsh)
if !hsh.nil? && hsh.length
hsh['mp3'] ? mime_type('mp3') : hsh['m4a'] ? mime_type('m4a') : hsh['ogg'] ? mime_type('ogg') : mime_type('opus')
end
end | ruby | {
"resource": ""
} |
q17120 | Jekyll.OctopodFilters.split_chapter | train | def split_chapter(chapter_str, attribute = nil)
attributes = chapter_str.split(/ /, 2)
return nil unless attributes.first.match(/\A(\d|:|\.)+\z/)
if attribute.nil?
{ 'start' => attributes.first, 'title' => attributes.last }
else
attribute == 'start' ? attributes.first : attributes.last
end
end | ruby | {
"resource": ""
} |
q17121 | Jekyll.OctopodFilters.string_of_size | train | def string_of_size(bytes)
bytes = bytes.to_i.to_f
out = '0'
return out if bytes == 0.0
jedec = %w[b K M G]
[3, 2, 1, 0].each { |i|
if bytes > 1024 ** i
out = "%.1f#{jedec[i]}" % (bytes / 1024 ** i)
break
end
}
return out
end | ruby | {
"resource": ""
} |
q17122 | Jekyll.OctopodFilters.disqus_config | train | def disqus_config(site, page = nil)
if page
disqus_vars = {
'disqus_identifier' => page['url'],
'disqus_url' => "#{site['url']}#{page['url']}",
'disqus_category_id' => page['disqus_category_id'] || site['disqus_category_id'],
'disqus_title' => j(page['title'] || site['site'])
}
else
disqus_vars = {
'disqus_developer' => site['disqus_developer'],
'disqus_shortname' => site['disqus_shortname']
}
end
disqus_vars.delete_if { |_, v| v.nil? }
disqus_vars.map { |k, v| "var #{k} = '#{v}';" }.compact.join("\n")
end | ruby | {
"resource": ""
} |
q17123 | Jekyll.OctopodFilters.sha1 | train | def sha1(str, lenght = 8)
sha1 = Digest::SHA1.hexdigest(str)
sha1[0, lenght.to_i]
end | ruby | {
"resource": ""
} |
q17124 | Jekyll.DateDe.format_date | train | def format_date(date, format)
date = datetime(date)
if format.nil? || format.empty? || format == "ordinal"
date_formatted = ordinalize(date)
else
format.gsub!(/%a/, ABBR_DAYNAMES_DE[date.wday])
format.gsub!(/%A/, DAYNAMES_DE[date.wday])
format.gsub!(/%b/, ABBR_MONTHNAMES_DE[date.mon])
format.gsub!(/%B/, MONTHNAMES_DE[date.mon])
date_formatted = date.strftime(format)
end
date_formatted
end | ruby | {
"resource": ""
} |
q17125 | Jekyll.FlattrFilters.flattr_loader_options | train | def flattr_loader_options(site)
return if site['flattr_uid'].nil?
keys = %w[mode https popout uid button language category]
options = flattr_options(site, nil, keys).delete_if { |_, v| v.to_s.empty? }
options.map { |k, v| "#{k}=#{ERB::Util.url_encode(v)}" }.join('&')
end | ruby | {
"resource": ""
} |
q17126 | Jekyll.FlattrFilters.flattr_button | train | def flattr_button(site, page = nil)
return if site['flattr_uid'].nil?
keys = %w[url title description uid popout button category language tags]
options = flattr_options(site, page, keys)
button = '<a class="FlattrButton" style="display:none;" '
button << %Q{title="#{options.delete('title')}" href="#{options.delete('url')}" }
button << options.map { |k, v|
%Q{data-flattr-#{k}="#{v}"} unless k == 'description'
}.join(' ')
button << ">\n\n#{options['description'].gsub(/<\/?[^>]*>/, "")}\n</a>"
end | ruby | {
"resource": ""
} |
q17127 | Jekyll.FlattrFilters.flattrize | train | def flattrize(hsh)
config = {}
hsh.to_hash.each { |k, v|
if new_key = k.to_s.match(/\Aflattr_(.*)\z/)
config[new_key[1]] = v
else
config[k] = v
end
}
config
end | ruby | {
"resource": ""
} |
q17128 | Prius.Registry.load | train | def load(name, options = {})
env_var = options.fetch(:env_var, name.to_s.upcase)
type = options.fetch(:type, :string)
required = options.fetch(:required, true)
@registry[name] = case type
when :string then load_string(env_var, required)
when :int then load_int(env_var, required)
when :bool then load_bool(env_var, required)
else raise ArgumentError, "Invalid type #{type}"
end
end | ruby | {
"resource": ""
} |
q17129 | Interferon.Interferon.run | train | def run
start_time = Time.new.to_f
Signal.trap('TERM') do
log.info('SIGTERM received. shutting down gracefully...')
@request_shutdown = true
end
run_desc = @dry_run ? 'dry run' : 'run'
log.info("beginning alerts #{run_desc}")
alerts = read_alerts(@alert_sources)
groups = read_groups(@group_sources)
hosts = read_hosts(@host_sources)
@destinations.each do |dest|
dest['options'] ||= {}
dest['options']['dry_run'] = true if @dry_run
end
update_alerts(@destinations, hosts, alerts, groups)
run_time = Time.new.to_f - start_time
if @request_shutdown
log.info("interferon #{run_desc} shut down by SIGTERM")
else
statsd.gauge('run_time', run_time)
log.info("interferon #{run_desc} complete in %.2f seconds" % run_time)
end
end | ruby | {
"resource": ""
} |
q17130 | Interferon::HostSources.AwsRds.account_number | train | def account_number
return @account_number if @account_number
begin
my_arn = AWS::IAM.new(
access_key_id: @access_key_id,
secret_access_key: @secret_access_key
).client.get_user[:user][:arn]
rescue AWS::IAM::Errors::AccessDenied => e
my_arn = e.message.split[1]
end
@account_number = my_arn.split(':')[4]
end | ruby | {
"resource": ""
} |
q17131 | TimeMath.Op.call | train | def call(*tms)
unless @arguments.empty?
tms.empty? or raise(ArgumentError, 'Op arguments is already set, use call()')
tms = @arguments
end
res = [*tms].flatten.map(&method(:perform))
tms.count == 1 && Util.timey?(tms.first) ? res.first : res
end | ruby | {
"resource": ""
} |
q17132 | Tire.Alias.indices | train | def indices(*names)
names = Array(names).flatten
names.compact.empty? ? @attributes[:indices] : (names.each { |n| @attributes[:indices].push(n) } and return self)
end | ruby | {
"resource": ""
} |
q17133 | Tire.Alias.filter | train | def filter(type=nil, *options)
type ? (@attributes[:filter] = Search::Filter.new(type, *options).to_hash and return self ) : @attributes[:filter]
end | ruby | {
"resource": ""
} |
q17134 | Tire.Alias.as_json | train | def as_json(options=nil)
actions = []
indices.add_indices.each do |index|
operation = { :index => index, :alias => name }
operation.update( { :routing => routing } ) if respond_to?(:routing) and routing
operation.update( { :filter => filter } ) if respond_to?(:filter) and filter
actions.push( { :add => operation } )
end
indices.remove_indices.each do |index|
operation = { :index => index, :alias => name }
actions.push( { :remove => operation } )
end
{ :actions => actions }
end | ruby | {
"resource": ""
} |
q17135 | Tire.Index.mapping! | train | def mapping!(*args)
mapping(*args)
raise RuntimeError, response.body unless response.success?
end | ruby | {
"resource": ""
} |
q17136 | AmazonSellerCentral.InventoryPage.listing_row_to_object | train | def listing_row_to_object(row)
l = Listing.new
row.css('td').each_with_index do |td, i|
txt = td.text.strip # yes, slightly slower to do this here, but I type less.
case i
when 4
l.sku = txt
when 5
l.asin = txt
when 6
l.product_name = txt
when 7
l.created_at = parse_amazon_time(txt)
when 8
l.quantity = (inputs = td.css('input')).any? ? inputs.first['value'].to_i : txt.to_i
when 10
l.price = get_price(td)
when 11
l.condition = txt
when 12
l.low_price = get_low_price(td)
when 3
l.status = txt
end
end
l
end | ruby | {
"resource": ""
} |
q17137 | Gruff.Base.theme= | train | def theme=(options)
reset_themes
defaults = {
:colors => %w(black white),
:additional_line_colors => [],
:marker_color => 'white',
:marker_shadow_color => nil,
:font_color => 'black',
:background_colors => nil,
:background_image => nil
}
@theme_options = defaults.merge options
@colors = @theme_options[:colors]
@marker_color = @theme_options[:marker_color]
@marker_shadow_color = @theme_options[:marker_shadow_color]
@font_color = @theme_options[:font_color] || @marker_color
@additional_line_colors = @theme_options[:additional_line_colors]
render_background
end | ruby | {
"resource": ""
} |
q17138 | Gruff.Base.data | train | def data(name, data_points=[], color=nil)
data_points = Array(data_points) # make sure it's an array
@data << [name, data_points, color]
# Set column count if this is larger than previous counts
@column_count = (data_points.length > @column_count) ? data_points.length : @column_count
# Pre-normalize
data_points.each do |data_point|
next if data_point.nil?
# Setup max/min so spread starts at the low end of the data points
if @maximum_value.nil? && @minimum_value.nil?
@maximum_value = @minimum_value = data_point
end
# TODO Doesn't work with stacked bar graphs
# Original: @maximum_value = larger_than_max?(data_point, index) ? max(data_point, index) : @maximum_value
@maximum_value = larger_than_max?(data_point) ? data_point : @maximum_value
@has_data = true if @maximum_value >= 0
@minimum_value = less_than_min?(data_point) ? data_point : @minimum_value
@has_data = true if @minimum_value < 0
end
end | ruby | {
"resource": ""
} |
q17139 | Gruff.Base.draw | train | def draw
# Maybe should be done in one of the following functions for more granularity.
unless @has_data
draw_no_data
return
end
setup_data
setup_drawing
debug {
# Outer margin
@d.rectangle(@left_margin, @top_margin,
@raw_columns - @right_margin, @raw_rows - @bottom_margin)
# Graph area box
@d.rectangle(@graph_left, @graph_top, @graph_right, @graph_bottom)
}
draw_legend
draw_line_markers
draw_axis_labels
draw_title
end | ruby | {
"resource": ""
} |
q17140 | Gruff.Base.normalize | train | def normalize(force=false)
if @norm_data.nil? || force
@norm_data = []
return unless @has_data
@data.each do |data_row|
norm_data_points = []
data_row[DATA_VALUES_INDEX].each do |data_point|
if data_point.nil?
norm_data_points << nil
else
norm_data_points << ((data_point.to_f - @minimum_value.to_f) / @spread)
end
end
if @show_labels_for_bar_values
@norm_data << [data_row[DATA_LABEL_INDEX], norm_data_points, data_row[DATA_COLOR_INDEX], data_row[DATA_VALUES_INDEX]]
else
@norm_data << [data_row[DATA_LABEL_INDEX], norm_data_points, data_row[DATA_COLOR_INDEX]]
end
end
end
end | ruby | {
"resource": ""
} |
q17141 | Gruff.Base.setup_graph_measurements | train | def setup_graph_measurements
@marker_caps_height = @hide_line_markers ? 0 :
calculate_caps_height(@marker_font_size)
@title_caps_height = (@hide_title || @title.nil?) ? 0 :
calculate_caps_height(@title_font_size) * @title.lines.to_a.size
@legend_caps_height = @hide_legend ? 0 :
calculate_caps_height(@legend_font_size)
if @hide_line_markers
(@graph_left,
@graph_right_margin,
@graph_bottom_margin) = [@left_margin, @right_margin, @bottom_margin]
else
if @has_left_labels
longest_left_label_width = calculate_width(@marker_font_size,
labels.values.inject('') { |value, memo| (value.to_s.length > memo.to_s.length) ? value : memo }) * 1.25
else
longest_left_label_width = calculate_width(@marker_font_size,
label(@maximum_value.to_f, @increment))
end
# Shift graph if left line numbers are hidden
line_number_width = @hide_line_numbers && !@has_left_labels ?
0.0 :
(longest_left_label_width + LABEL_MARGIN * 2)
@graph_left = @left_margin +
line_number_width +
(@y_axis_label.nil? ? 0.0 : @marker_caps_height + LABEL_MARGIN * 2)
# Make space for half the width of the rightmost column label.
# Might be greater than the number of columns if between-style bar markers are used.
last_label = @labels.keys.sort.last.to_i
extra_room_for_long_label = (last_label >= (@column_count-1) && @center_labels_over_point) ?
calculate_width(@marker_font_size, @labels[last_label]) / 2.0 :
0
@graph_right_margin = @right_margin + extra_room_for_long_label
@graph_bottom_margin = @bottom_margin +
@marker_caps_height + LABEL_MARGIN
end
@graph_right = @raw_columns - @graph_right_margin
@graph_width = @raw_columns - @graph_left - @graph_right_margin
# When @hide title, leave a title_margin space for aesthetics.
# Same with @hide_legend
@graph_top = @legend_at_bottom ? @top_margin : (@top_margin +
(@hide_title ? title_margin : @title_caps_height + title_margin) +
(@hide_legend ? legend_margin : @legend_caps_height + legend_margin))
x_axis_label_height = @x_axis_label.nil? ? 0.0 :
@marker_caps_height + LABEL_MARGIN
# FIXME: Consider chart types other than bar
@graph_bottom = @raw_rows - @graph_bottom_margin - x_axis_label_height - @label_stagger_height
@graph_height = @graph_bottom - @graph_top
end | ruby | {
"resource": ""
} |
q17142 | Gruff.Base.draw_axis_labels | train | def draw_axis_labels
unless @x_axis_label.nil?
# X Axis
# Centered vertically and horizontally by setting the
# height to 1.0 and the width to the width of the graph.
x_axis_label_y_coordinate = @graph_bottom + LABEL_MARGIN * 2 + @marker_caps_height
# TODO Center between graph area
@d.fill = @font_color
@d.font = @font if @font
@d.stroke('transparent')
@d.pointsize = scale_fontsize(@marker_font_size)
@d.gravity = NorthGravity
@d = @d.annotate_scaled(@base_image,
@raw_columns, 1.0,
0.0, x_axis_label_y_coordinate,
@x_axis_label, @scale)
debug { @d.line 0.0, x_axis_label_y_coordinate, @raw_columns, x_axis_label_y_coordinate }
end
unless @y_axis_label.nil?
# Y Axis, rotated vertically
@d.rotation = -90.0
@d.gravity = CenterGravity
@d = @d.annotate_scaled(@base_image,
1.0, @raw_rows,
@left_margin + @marker_caps_height / 2.0, 0.0,
@y_axis_label, @scale)
@d.rotation = 90.0
end
end | ruby | {
"resource": ""
} |
q17143 | Gruff.Base.draw_line_markers | train | def draw_line_markers
return if @hide_line_markers
@d = @d.stroke_antialias false
if @y_axis_increment.nil?
# Try to use a number of horizontal lines that will come out even.
#
# TODO Do the same for larger numbers...100, 75, 50, 25
if @marker_count.nil?
(3..7).each do |lines|
if @spread % lines == 0.0
@marker_count = lines
break
end
end
@marker_count ||= 4
end
@increment = (@spread > 0 && @marker_count > 0) ? significant(@spread / @marker_count) : 1
else
# TODO Make this work for negative values
@marker_count = (@spread / @y_axis_increment).to_i
@increment = @y_axis_increment
end
@increment_scaled = @graph_height.to_f / (@spread / @increment)
# Draw horizontal line markers and annotate with numbers
(0..@marker_count).each do |index|
y = @graph_top + @graph_height - index.to_f * @increment_scaled
@d = @d.fill(@marker_color)
# FIXME(uwe): Workaround for Issue #66
# https://github.com/topfunky/gruff/issues/66
# https://github.com/rmagick/rmagick/issues/82
# Remove if the issue gets fixed.
y += 0.001 unless defined?(JRUBY_VERSION)
# EMXIF
@d = @d.line(@graph_left, y, @graph_right, y)
#If the user specified a marker shadow color, draw a shadow just below it
unless @marker_shadow_color.nil?
@d = @d.fill(@marker_shadow_color)
@d = @d.line(@graph_left, y + 1, @graph_right, y + 1)
end
marker_label = BigDecimal(index.to_s) * BigDecimal(@increment.to_s) +
BigDecimal(@minimum_value.to_s)
unless @hide_line_numbers
@d.fill = @font_color
@d.font = @font if @font
@d.stroke('transparent')
@d.pointsize = scale_fontsize(@marker_font_size)
@d.gravity = EastGravity
# Vertically center with 1.0 for the height
@d = @d.annotate_scaled(@base_image,
@graph_left - LABEL_MARGIN, 1.0,
0.0, y,
label(marker_label, @increment), @scale)
end
end
# # Submitted by a contibutor...the utility escapes me
# i = 0
# @additional_line_values.each do |value|
# @increment_scaled = @graph_height.to_f / (@maximum_value.to_f / value)
#
# y = @graph_top + @graph_height - @increment_scaled
#
# @d = @d.stroke(@additional_line_colors[i])
# @d = @d.line(@graph_left, y, @graph_right, y)
#
#
# @d.fill = @additional_line_colors[i]
# @d.font = @font if @font
# @d.stroke('transparent')
# @d.pointsize = scale_fontsize(@marker_font_size)
# @d.gravity = EastGravity
# @d = @d.annotate_scaled( @base_image,
# 100, 20,
# -10, y - (@marker_font_size/2.0),
# "", @scale)
# i += 1
# end
@d = @d.stroke_antialias true
end | ruby | {
"resource": ""
} |
q17144 | Gruff.Base.draw_legend | train | def draw_legend
return if @hide_legend
@legend_labels = @data.collect { |item| item[DATA_LABEL_INDEX] }
legend_square_width = @legend_box_size # small square with color of this item
# May fix legend drawing problem at small sizes
@d.font = @font if @font
@d.pointsize = @legend_font_size
label_widths = [[]] # Used to calculate line wrap
@legend_labels.each do |label|
metrics = @d.get_type_metrics(@base_image, label.to_s)
label_width = metrics.width + legend_square_width * 2.7
label_widths.last.push label_width
if sum(label_widths.last) > (@raw_columns * 0.9)
label_widths.push [label_widths.last.pop]
end
end
current_x_offset = center(sum(label_widths.first))
current_y_offset = @legend_at_bottom ? @graph_height + title_margin : (@hide_title ?
@top_margin + title_margin :
@top_margin + title_margin + @title_caps_height)
@legend_labels.each_with_index do |legend_label, index|
# Draw label
@d.fill = @font_color
@d.font = @font if @font
@d.pointsize = scale_fontsize(@legend_font_size)
@d.stroke('transparent')
@d.font_weight = NormalWeight
@d.gravity = WestGravity
@d = @d.annotate_scaled(@base_image,
@raw_columns, 1.0,
current_x_offset + (legend_square_width * 1.7), current_y_offset,
legend_label.to_s, @scale)
# Now draw box with color of this dataset
@d = @d.stroke('transparent')
@d = @d.fill @data[index][DATA_COLOR_INDEX]
@d = @d.rectangle(current_x_offset,
current_y_offset - legend_square_width / 2.0,
current_x_offset + legend_square_width,
current_y_offset + legend_square_width / 2.0)
@d.pointsize = @legend_font_size
metrics = @d.get_type_metrics(@base_image, legend_label.to_s)
current_string_offset = metrics.width + (legend_square_width * 2.7)
# Handle wrapping
label_widths.first.shift
if label_widths.first.empty?
debug { @d.line 0.0, current_y_offset, @raw_columns, current_y_offset }
label_widths.shift
current_x_offset = center(sum(label_widths.first)) unless label_widths.empty?
line_height = [@legend_caps_height, legend_square_width].max + legend_margin
if label_widths.length > 0
# Wrap to next line and shrink available graph dimensions
current_y_offset += line_height
@graph_top += line_height
@graph_height = @graph_bottom - @graph_top
end
else
current_x_offset += current_string_offset
end
end
@color_index = 0
end | ruby | {
"resource": ""
} |
q17145 | Gruff.Base.draw_title | train | def draw_title
return if (@hide_title || @title.nil?)
@d.fill = @font_color
@d.font = @title_font || @font if @title_font || @font
@d.stroke('transparent')
@d.pointsize = scale_fontsize(@title_font_size)
@d.font_weight = if @bold_title then BoldWeight else NormalWeight end
@d.gravity = NorthGravity
@d = @d.annotate_scaled(@base_image,
@raw_columns, 1.0,
0, @top_margin,
@title, @scale)
end | ruby | {
"resource": ""
} |
q17146 | Gruff.Base.draw_value_label | train | def draw_value_label(x_offset, y_offset, data_point, bar_value=false)
return if @hide_line_markers && !bar_value
#y_offset = @graph_bottom + LABEL_MARGIN
@d.fill = @font_color
@d.font = @font if @font
@d.stroke('transparent')
@d.font_weight = NormalWeight
@d.pointsize = scale_fontsize(@marker_font_size)
@d.gravity = NorthGravity
@d = @d.annotate_scaled(@base_image,
1.0, 1.0,
x_offset, y_offset,
data_point.to_s, @scale)
debug { @d.line 0.0, y_offset, @raw_columns, y_offset }
end | ruby | {
"resource": ""
} |
q17147 | Gruff.Base.draw_no_data | train | def draw_no_data
@d.fill = @font_color
@d.font = @font if @font
@d.stroke('transparent')
@d.font_weight = NormalWeight
@d.pointsize = scale_fontsize(80)
@d.gravity = CenterGravity
@d = @d.annotate_scaled(@base_image,
@raw_columns, @raw_rows/2.0,
0, 10,
@no_data_message, @scale)
end | ruby | {
"resource": ""
} |
q17148 | Gruff.Base.render_gradiated_background | train | def render_gradiated_background(top_color, bottom_color, direct = :top_bottom)
case direct
when :bottom_top
gradient_fill = GradientFill.new(0, 0, 100, 0, bottom_color, top_color)
when :left_right
gradient_fill = GradientFill.new(0, 0, 0, 100, top_color, bottom_color)
when :right_left
gradient_fill = GradientFill.new(0, 0, 0, 100, bottom_color, top_color)
when :topleft_bottomright
gradient_fill = GradientFill.new(0, 100, 100, 0, top_color, bottom_color)
when :topright_bottomleft
gradient_fill = GradientFill.new(0, 0, 100, 100, bottom_color, top_color)
else
gradient_fill = GradientFill.new(0, 0, 100, 0, top_color, bottom_color)
end
Image.new(@columns, @rows, gradient_fill)
end | ruby | {
"resource": ""
} |
q17149 | Gruff.Base.sort_data | train | def sort_data
@data = @data.sort_by { |a| -a[DATA_VALUES_INDEX].inject(0) { |sum, num| sum + num.to_f } }
end | ruby | {
"resource": ""
} |
q17150 | Gruff.Base.sort_norm_data | train | def sort_norm_data
@norm_data =
@norm_data.sort_by { |a| -a[DATA_VALUES_INDEX].inject(0) { |sum, num| sum + num.to_f } }
end | ruby | {
"resource": ""
} |
q17151 | Gruff.Base.get_maximum_by_stack | train | def get_maximum_by_stack
# Get sum of each stack
max_hash = {}
@data.each do |data_set|
data_set[DATA_VALUES_INDEX].each_with_index do |data_point, i|
max_hash[i] = 0.0 unless max_hash[i]
max_hash[i] += data_point.to_f
end
end
# @maximum_value = 0
max_hash.keys.each do |key|
@maximum_value = max_hash[key] if max_hash[key] > @maximum_value
end
@minimum_value = 0
end | ruby | {
"resource": ""
} |
q17152 | Gruff.Base.label | train | def label(value, increment)
label = if increment
if increment >= 10 || (increment * 1) == (increment * 1).to_i.to_f
sprintf('%0i', value)
elsif increment >= 1.0 || (increment * 10) == (increment * 10).to_i.to_f
sprintf('%0.1f', value)
elsif increment >= 0.1 || (increment * 100) == (increment * 100).to_i.to_f
sprintf('%0.2f', value)
elsif increment >= 0.01 || (increment * 1000) == (increment * 1000).to_i.to_f
sprintf('%0.3f', value)
elsif increment >= 0.001 || (increment * 10000) == (increment * 10000).to_i.to_f
sprintf('%0.4f', value)
else
value.to_s
end
elsif (@spread.to_f % (@marker_count.to_f==0 ? 1 : @marker_count.to_f) == 0) || !@y_axis_increment.nil?
value.to_i.to_s
elsif @spread > 10.0
sprintf('%0i', value)
elsif @spread >= 3.0
sprintf('%0.2f', value)
else
value.to_s
end
parts = label.split('.')
parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{THOUSAND_SEPARATOR}")
parts.join('.')
end | ruby | {
"resource": ""
} |
q17153 | Gruff.Base.calculate_width | train | def calculate_width(font_size, text)
return 0 if text.nil?
@d.pointsize = font_size
@d.font = @font if @font
@d.get_type_metrics(@base_image, text.to_s).width
end | ruby | {
"resource": ""
} |
q17154 | Magick.Draw.annotate_scaled | train | def annotate_scaled(img, width, height, x, y, text, scale)
scaled_width = (width * scale) >= 1 ? (width * scale) : 1
scaled_height = (height * scale) >= 1 ? (height * scale) : 1
self.annotate(img,
scaled_width, scaled_height,
x * scale, y * scale,
text.gsub('%', '%%'))
end | ruby | {
"resource": ""
} |
q17155 | TrafficJam.Configuration.limits | train | def limits(action)
@limits ||= {}
limits = @limits[action.to_sym]
raise TrafficJam::LimitNotFound.new(action) if limits.nil?
limits
end | ruby | {
"resource": ""
} |
q17156 | TrafficJam.LimitGroup.increment | train | def increment(amount = 1, time: Time.now)
exceeded_index = limits.find_index do |limit|
!limit.increment(amount, time: time)
end
if exceeded_index
limits[0...exceeded_index].each do |limit|
limit.decrement(amount, time: time)
end
end
exceeded_index.nil?
end | ruby | {
"resource": ""
} |
q17157 | TrafficJam.LimitGroup.increment! | train | def increment!(amount = 1, time: Time.now)
exception = nil
exceeded_index = limits.find_index do |limit|
begin
limit.increment!(amount, time: time)
rescue TrafficJam::LimitExceededError => e
exception = e
true
end
end
if exceeded_index
limits[0...exceeded_index].each do |limit|
limit.decrement(amount, time: time)
end
raise exception
end
end | ruby | {
"resource": ""
} |
q17158 | TrafficJam.LimitGroup.decrement | train | def decrement(amount = 1, time: Time.now)
limits.all? { |limit| limit.decrement(amount, time: time) }
end | ruby | {
"resource": ""
} |
q17159 | TrafficJam.LimitGroup.limit_exceeded | train | def limit_exceeded(amount = 1)
limits.each do |limit|
limit_exceeded = limit.limit_exceeded(amount)
return limit_exceeded if limit_exceeded
end
nil
end | ruby | {
"resource": ""
} |
q17160 | TrafficJam.GCRALimit.increment | train | def increment(amount = 1, time: Time.now)
return true if amount == 0
return false if max == 0
raise ArgumentError.new("Amount must be positive") if amount < 0
if amount != amount.to_i
raise ArgumentError.new("Amount must be an integer")
end
return false if amount > max
incrby = (period * 1000 * amount / max).to_i
argv = [incrby, period * 1000]
result =
begin
redis.evalsha(
Scripts::INCREMENT_GCRA_HASH, keys: [key], argv: argv)
rescue Redis::CommandError
redis.eval(Scripts::INCREMENT_GCRA, keys: [key], argv: argv)
end
case result
when 0
return true
when -1
raise Errors::InvalidKeyError, "Redis key #{key} has no expire time set"
when -2
return false
else
raise Errors::UnknownReturnValue,
"Received unexpected return value #{result} from " \
"increment_gcra eval"
end
end | ruby | {
"resource": ""
} |
q17161 | TrafficJam.Limit.increment | train | def increment(amount = 1, time: Time.now)
return amount <= 0 if max.zero?
if amount != amount.to_i
raise ArgumentError.new("Amount must be an integer")
end
timestamp = (time.to_f * 1000).to_i
argv = [timestamp, amount.to_i, max, period * 1000]
result =
begin
redis.evalsha(
Scripts::INCREMENT_SCRIPT_HASH, keys: [key], argv: argv)
rescue Redis::CommandError
redis.eval(Scripts::INCREMENT_SCRIPT, keys: [key], argv: argv)
end
!!result
end | ruby | {
"resource": ""
} |
q17162 | TrafficJam.LifetimeLimit.used | train | def used
return 0 if max.zero?
amount = redis.get(key) || 0
[amount.to_i, max].min
end | ruby | {
"resource": ""
} |
q17163 | Volt.Dispatcher.dispatch | train | def dispatch(channel, message)
# Dispatch the task in the worker pool. Pas in the meta data
@worker_pool.post do
begin
dispatch_in_thread(channel, message)
rescue => e
err = "Worker Thread Exception for #{message}\n"
err += e.inspect
err += e.backtrace.join("\n") if e.respond_to?(:backtrace)
Volt.logger.error(err)
end
end
end | ruby | {
"resource": ""
} |
q17164 | Volt.Dispatcher.safe_method? | train | def safe_method?(klass, method_name)
# Make sure the class being called is a Task.
return false unless klass.ancestors.include?(Task)
# Make sure the method is defined on the klass we're using and not up the hiearchy.
# ^ This check prevents methods like #send, #eval, #instance_eval, #class_eval, etc...
klass.ancestors.each do |ancestor_klass|
if ancestor_klass.instance_methods(false).include?(method_name)
return true
elsif ancestor_klass == Task
# We made it to Task and didn't find the method, that means it
# was defined above Task, so we reject the call.
return false
end
end
false
end | ruby | {
"resource": ""
} |
q17165 | Volt.Dispatcher.dispatch_in_thread | train | def dispatch_in_thread(channel, message)
callback_id, class_name, method_name, meta_data, *args = message
method_name = method_name.to_sym
# Get the class
klass = Object.send(:const_get, class_name)
promise = Promise.new
cookies = nil
start_time = Time.now.to_f
# Check that we are calling on a Task class and a method provide at
# Task or above in the ancestor chain. (so no :send or anything)
if safe_method?(klass, method_name)
promise.resolve(nil)
# Init and send the method
promise = promise.then do
result = nil
Timeout.timeout(klass.__timeout || @worker_timeout) do
Thread.current['meta'] = meta_data
begin
klass_inst = klass.new(@volt_app, channel, self)
result = klass_inst.send(method_name, *args)
cookies = klass_inst.fetch_cookies
ensure
Thread.current['meta'] = nil
end
end
result
end
else
# Unsafe method
promise.reject(RuntimeError.new("unsafe method: #{method_name}"))
end
# Called after task runs or fails
finish = proc do |error|
if error.is_a?(Timeout::Error)
# re-raise with a message
error = Timeout::Error.new("Task Timed Out after #{@worker_timeout} seconds: #{message}")
end
run_time = ((Time.now.to_f - start_time) * 1000).round(3)
Volt.logger.log_dispatch(class_name, method_name, run_time, args, error)
end
# Run the promise and pass the return value/error back to the client
promise.then do |result|
reply = EJSON.stringify(['response', callback_id, result, nil, cookies])
channel.send_string_message(reply)
finish.call
end.fail do |error|
begin
finish.call(error)
begin
# Try to send, handle error if we can't convert the result to EJSON
reply = EJSON.stringify(['response', callback_id, nil, error, cookies])
# use send_string_message, since we stringify here, not on the other
# side of Drb.
channel.send_string_message(reply)
rescue EJSON::NonEjsonType => e
# Convert the error into a string so it can be serialized to
# something.
error = "#{error.class.to_s}: #{error.to_s}"
channel.send_message('response', callback_id, nil, error, cookies)
end
rescue => e
Volt.logger.error "Error in fail dispatch: #{e.inspect}"
Volt.logger.error(e.backtrace.join("\n")) if e.respond_to?(:backtrace)
raise
end
end
end | ruby | {
"resource": ""
} |
q17166 | Volt.Validations.validate | train | def validate(field_name = nil, options = nil, &block)
if block
# Setup a custom validation inside of the current validations block.
if field_name || options
fail 'validate should be passed a field name and options or a block, not both.'
end
@instance_custom_validations << block
else
@instance_validations[field_name] ||= {}
@instance_validations[field_name].merge!(options)
end
end | ruby | {
"resource": ""
} |
q17167 | Volt.Validations.mark_all_fields! | train | def mark_all_fields!
# TODO: We can use a Set here, but set was having issues. Check in a
# later version of opal.
fields_to_mark = []
# Look at each validation
validations = self.class.validations_to_run
if validations
fields_to_mark += validations.keys
end
# Also include any current fields
fields_to_mark += attributes.keys
fields_to_mark.each do |key|
mark_field!(key.to_sym)
end
end | ruby | {
"resource": ""
} |
q17168 | Volt.Validations.error_in_changed_attributes? | train | def error_in_changed_attributes?
errs = errors
changed_attributes.each_pair do |key, _|
# If any of the fields with errors are also the ones that were
return true if errs[key]
end
false
end | ruby | {
"resource": ""
} |
q17169 | Volt.Validations.run_validations | train | def run_validations(validations = nil)
# Default to running the class level validations
validations ||= self.class.validations_to_run
promise = Promise.new.resolve(nil)
if validations
# Run through each validation
validations.each_pair do |field_name, options|
promise = promise.then { run_validation(field_name, options) }
end
end
promise
end | ruby | {
"resource": ""
} |
q17170 | Volt.Validations.run_validation | train | def run_validation(field_name, options)
promise = Promise.new.resolve(nil)
options.each_pair do |validation, args|
# Call the specific validator, then merge the results back
# into one large errors hash.
klass = validation_class(validation, args)
if klass
# Chain on the promises
promise = promise.then do
klass.validate(self, field_name, args)
end.then do |errs|
errors.merge!(errs)
end
else
fail "validation type #{validation} is not specified."
end
end
promise
end | ruby | {
"resource": ""
} |
q17171 | Volt.ReactiveArray.__clear | train | def __clear
old_size = @array.size
deps = @array_deps
@array_deps = []
# Trigger remove for each cell
old_size.times do |index|
trigger_removed!(old_size - index - 1)
end
# Trigger on each cell since we are clearing out the array
if deps
deps.each do |dep|
dep.changed! if dep
end
end
# clear the array
@array = []
end | ruby | {
"resource": ""
} |
q17172 | Volt.Buffer.promise_for_errors | train | def promise_for_errors(errors)
mark_all_fields!
# Wrap in an Errors class unless it already is one
errors = errors.is_a?(Errors) ? errors : Errors.new(errors)
Promise.new.reject(errors)
end | ruby | {
"resource": ""
} |
q17173 | Volt.Buffer.buffer | train | def buffer
model_path = options[:path]
model_klass = self.class
new_options = options.merge(path: model_path, save_to: self, buffer: true).reject { |k, _| k.to_sym == :persistor }
model = nil
Volt::Model.no_validate do
model = model_klass.new(attributes, new_options, :loaded)
model.instance_variable_set('@new', @new)
end
model
end | ruby | {
"resource": ""
} |
q17174 | Volt.ModelHashBehaviour.to_h | train | def to_h
@size_dep.depend
if @attributes.nil?
nil
else
hash = {}
@attributes.each_pair do |key, value|
hash[key] = deep_unwrap(value)
end
hash
end
end | ruby | {
"resource": ""
} |
q17175 | Volt.ArrayModel.to_a | train | def to_a
@size_dep.depend
array = []
Volt.run_in_mode(:no_model_promises) do
attributes.size.times do |index|
array << deep_unwrap(self[index])
end
end
array
end | ruby | {
"resource": ""
} |
q17176 | Volt.ArrayModel.create_new_model | train | def create_new_model(model, from_method)
if model.is_a?(Model)
if model.buffer?
fail "The #{from_method} does not take a buffer. Call .save! on buffer's to persist them."
end
# Set the new path and the persistor.
model.options = @options.merge(parent: self, path: @options[:path] + [:[]])
else
model = wrap_values([model]).first
end
if model.is_a?(Model)
promise = model.can_create?.then do |can_create|
unless can_create
fail "permissions did not allow create for #{model.inspect}"
end
end.then do
# Add it to the array and trigger any watches or on events.
reactive_array_append(model)
@persistor.added(model, @array.size - 1)
end.then do
nil.then do
# Validate and save
model.run_changed
end.then do
# Mark the model as not new
model.instance_variable_set('@new', false)
# Mark the model as loaded
model.change_state_to(:loaded_state, :loaded)
end.fail do |err|
# remove from the collection because it failed to save on the server
# we don't need to call delete on the server.
index = @array.index(model)
delete_at(index, true)
# remove from the id list
@persistor.try(:remove_tracking_id, model)
# re-raise, err might not be an Error object, so we use a rejected promise to re-raise
Promise.new.reject(err)
end
end
else
promise = nil.then do
# Add it to the array and trigger any watches or on events.
reactive_array_append(model)
@persistor.added(model, @array.size - 1)
end
end
promise = promise.then do
# resolve the model
model
end
# unwrap the promise if the persistor is synchronus.
# This will return the value or raise the exception.
promise = promise.unwrap unless @persistor.async?
# return
promise
end | ruby | {
"resource": ""
} |
q17177 | Volt.URL.url_for | train | def url_for(params)
host_with_port = host || location.host
host_with_port += ":#{port}" if port && port != 80
scheme = scheme || location.scheme
unless RUBY_PLATFORM == 'opal'
# lazy load routes and views on the server
if !@router && @routes_loader
# Load the templates
@routes_loader.call
end
end
path, params = @router.params_to_url(params)
if path == nil
raise "No route matched, make sure you have the base route defined last: `client '/', {}`"
end
new_url = "#{scheme}://#{host_with_port}#{path.chomp('/')}"
# Add query params
params_str = ''
unless params.empty?
query_parts = []
nested_params_hash(params).each_pair do |key, value|
# remove the _ from the front
value = Volt::Parsing.encodeURI(value)
query_parts << "#{key}=#{value}"
end
if query_parts.size > 0
query = query_parts.join('&')
new_url += "?#{query}"
end
end
# Add fragment
frag = fragment
new_url += '#' + frag if frag.present?
new_url
end | ruby | {
"resource": ""
} |
q17178 | Volt.URL.assign_query_hash_to_params | train | def assign_query_hash_to_params
# Get a nested hash representing the current url params.
query_hash = parse_query
# Get the params that are in the route
new_params = @router.url_to_params(path)
fail "no routes match path: #{path}" if new_params == false
return false if new_params == nil
query_hash.merge!(new_params)
# Loop through the .params we already have assigned.
lparams = params
assign_from_old(lparams, query_hash)
assign_new(lparams, query_hash)
true
end | ruby | {
"resource": ""
} |
q17179 | Volt.URL.assign_new | train | def assign_new(params, new_params)
new_params.each_pair do |name, value|
if value.is_a?(Hash)
assign_new(params.get(name), value)
else
# assign
params.set(name, value)
end
end
end | ruby | {
"resource": ""
} |
q17180 | Volt.URL.query_key | train | def query_key(path)
i = 0
path.map do |v|
i += 1
if i != 1
"[#{v}]"
else
v
end
end.join('')
end | ruby | {
"resource": ""
} |
q17181 | Volt.ViewBinding.create_controller_handler | train | def create_controller_handler(full_path, controller_path)
# If arguments is nil, then an blank SubContext will be created
args = [SubContext.new(@arguments, nil, true)]
# get the controller class and action
controller_class, action = ControllerHandler.get_controller_and_action(controller_path)
generated_new = false
new_controller = proc do
# Mark that we needed to generate a new controller instance (not reused
# from the group)
generated_new = true
# Setup the controller
controller_class.new(@volt_app, *args)
end
# Fetch grouped controllers if we're grouping
if @grouped_controller
# Find the controller in the group, or create it
controller = @grouped_controller.lookup_or_create(controller_class, &new_controller)
else
# Just create the controller
controller = new_controller.call
end
handler = ControllerHandler.fetch(controller, action)
if generated_new
# Call the action
stopped = handler.call_action
controller.instance_variable_set('@chain_stopped', true) if stopped
else
stopped = controller.instance_variable_get('@chain_stopped')
end
[handler, generated_new, stopped]
end | ruby | {
"resource": ""
} |
q17182 | Volt.ComponentPaths.app_folders | train | def app_folders
# Find all app folders
@app_folders ||= begin
volt_app = File.expand_path(File.join(File.dirname(__FILE__), '../../../../app'))
app_folders = [volt_app, "#{@root}/app", "#{@root}/vendor/app"].map { |f| File.expand_path(f) }
# Gem folders with volt in them
# TODO: we should probably qualify this a bit more
app_folders += Gem.loaded_specs.values
.select {|gem| gem.name =~ /^volt/ }
.map {|gem| "#{gem.full_gem_path}/app" }
app_folders.uniq
end
# Yield each app folder and return a flattened array with
# the results
files = []
@app_folders.each do |app_folder|
files << yield(app_folder)
end
files.flatten
end | ruby | {
"resource": ""
} |
q17183 | Volt.ComponentPaths.components | train | def components
return @components if @components
@components = {}
app_folders do |app_folder|
Dir["#{app_folder}/*"].sort.each do |folder|
if File.directory?(folder)
folder_name = folder[/[^\/]+$/]
# Add in the folder if it's not alreay in there
folders = (@components[folder_name] ||= [])
folders << folder unless folders.include?(folder)
end
end
end
@components
end | ruby | {
"resource": ""
} |
q17184 | Volt.ComponentPaths.asset_folders | train | def asset_folders
folders = []
app_folders do |app_folder|
Dir["#{app_folder}/*/assets"].sort.each do |asset_folder|
folders << yield(asset_folder)
end
end
folders.flatten
end | ruby | {
"resource": ""
} |
q17185 | Volt.DomTemplate.track_binding_anchors | train | def track_binding_anchors
@binding_anchors = {}
# Loop through the bindings, find in nodes.
@bindings.each_pair do |name, binding|
if name.is_a?(String)
# Find the dom node for an attribute anchor
node = nil
`
node = self.nodes.querySelector('#' + name);
`
@binding_anchors[name] = node
else
# Find the dom node for a comment anchor
start_comment = find_by_comment("$#{name}", @nodes)
end_comment = find_by_comment("$/#{name}", @nodes)
@binding_anchors[name] = [start_comment, end_comment]
end
end
end | ruby | {
"resource": ""
} |
q17186 | Volt.ViewLookupForPath.path_for_template | train | def path_for_template(lookup_path, force_section = nil)
parts = lookup_path.split('/')
parts_size = parts.size
return nil, nil if parts_size == 0
default_parts = %w(main main index body)
# When forcing a sub template, we can default the sub template section
default_parts[-1] = force_section if force_section
(5 - parts_size).times do |path_position|
# If they passed in a force_section, we can skip the first
next if force_section && path_position == 0
full_path = [@collection_name, @controller_name, @page_name, nil]
start_at = full_path.size - parts_size - path_position
full_path.size.times do |index|
if index >= start_at
if (part = parts[index - start_at])
full_path[index] = part
else
full_path[index] = default_parts[index]
end
end
end
path = full_path.join('/')
if check_for_template?(path)
controller = nil
if path_position >= 1
init_method = full_path[2]
else
init_method = full_path[3]
end
# Lookup the controller
controller = [full_path[0], full_path[1] + '_controller', init_method]
return path, controller
end
end
[nil, nil]
end | ruby | {
"resource": ""
} |
q17187 | Volt.ModelController.first_element | train | def first_element
check_section!('first_element')
range = dom_nodes
nodes = `range.startContainer.childNodes`
start_index = `range.startOffset`
end_index = `range.endOffset`
start_index.upto(end_index) do |index|
node = `nodes[index]`
# Return if an element
if `node.nodeType === 1`
return node
end
end
return nil
end | ruby | {
"resource": ""
} |
q17188 | Volt.ModelController.yield_html | train | def yield_html
if (template_path = attrs.content_template_path)
@yield_renderer ||= StringTemplateRenderer.new(@volt_app, attrs.content_controller, template_path)
@yield_renderer.html
else
# no template, empty string
''
end
end | ruby | {
"resource": ""
} |
q17189 | Volt.ModelController.model= | train | def model=(val)
if val.is_a?(Promise)
# Resolve the promise before setting
self.last_promise = val
val.then do |result|
# Only assign if nothing else has been assigned since we started the resolve
self.model = result if last_promise == val
end.fail do |err|
Volt.logger.error("Unable to resolve promise assigned to model on #{inspect}")
end
return
end
# Clear
self.last_promise = nil
# Start with a nil reactive value.
self.current_model ||= Model.new
if Symbol === val || String === val
collections = [:page, :store, :params, :controller]
if collections.include?(val.to_sym)
self.current_model = send(val)
else
fail "#{val} is not the name of a valid model, choose from: #{collections.join(', ')}"
end
else
self.current_model = val
end
end | ruby | {
"resource": ""
} |
q17190 | Volt.ModelController.loaded? | train | def loaded?
if model.respond_to?(:loaded?)
# There is a model and it is loaded
return model.loaded?
elsif last_promise || model.is_a?(Promise)
# The model is a promise or is resolving
return false
else
# Otherwise, its loaded
return true
end
end | ruby | {
"resource": ""
} |
q17191 | Volt.ModelController.raw | train | def raw(str)
# Promises need to have .to_s called using .then, since .to_s is a promise
# method, so it won't be passed down to the value.
if str.is_a?(Promise)
str = str.then(&:to_s)
else
str = str.to_s unless str.is_a?(String)
end
str.html_safe
end | ruby | {
"resource": ""
} |
q17192 | Volt.NumericalityValidator.check_errors | train | def check_errors
if @value && @value.is_a?(Numeric)
if @args.is_a?(Hash)
@args.each do |arg, val|
case arg
when :min
add_error("number must be greater than #{val}") if @value < val
when :max
add_error("number must be less than #{val}") if @value > val
end
end
end
else
message = (@args.is_a?(Hash) && @args[:message]) || 'must be a number'
add_error(message)
end
end | ruby | {
"resource": ""
} |
q17193 | Volt.HttpController.params | train | def params
@params ||= begin
params = request.params.symbolize_keys.merge(@initial_params)
Volt::Model.new(params, persistor: Volt::Persistors::Params)
end
end | ruby | {
"resource": ""
} |
q17194 | Volt.AttributeSection.rezero_bindings | train | def rezero_bindings(html, bindings)
@@base_binding_id ||= 20_000
# rezero
parts = html.split(/(\<\!\-\- \$\/?[0-9]+ \-\-\>)/).reject { |v| v == '' }
new_html = []
new_bindings = {}
id_map = {}
parts.each do |part|
case part
when /\<\!\-\- \$[0-9]+ \-\-\>/
# Open
binding_id = part.match(/\<\!\-\- \$([0-9]+) \-\-\>/)[1].to_i
binding = bindings[binding_id]
new_bindings[@@base_binding_id] = binding if binding
new_html << "<!-- $#{@@base_binding_id} -->"
id_map[binding_id] = @@base_binding_id
@@base_binding_id += 1
when /\<\!\-\- \$\/[0-9]+ \-\-\>/
# Close
binding_id = part.match(/\<\!\-\- \$\/([0-9]+) \-\-\>/)[1].to_i
new_html << "<!-- $/#{id_map[binding_id]} -->"
else
# html string
new_html << part
end
end
# Also copy the attribute bindings
bindings.each_pair do |name, binding|
if name.is_a?(String) && name[0..1] == 'id'
new_bindings[name] = binding
end
end
return new_html.join(''), new_bindings
end | ruby | {
"resource": ""
} |
q17195 | Volt.AttributeSection.set_content_and_rezero_bindings | train | def set_content_and_rezero_bindings(html, bindings)
html, bindings = rezero_bindings(html, bindings)
if @binding_name == 'main'
@target.html = html
else
@target.find_by_binding_id(@binding_name).html = html
end
bindings
end | ruby | {
"resource": ""
} |
q17196 | Volt.ViewParser.code | train | def code(app_reference)
code = ''
templates.each_pair do |name, template|
binding_code = []
if template['bindings']
template['bindings'].each_pair do |key, value|
binding_code << "#{key.inspect} => [#{value.join(', ')}]"
end
end
binding_code = "{#{binding_code.join(', ')}}"
code << "#{app_reference}.add_template(#{name.inspect}, #{template['html'].inspect}, #{binding_code})\n"
end
code
end | ruby | {
"resource": ""
} |
q17197 | Volt.Duration.duration_in_words | train | def duration_in_words(places=2, min_unit=:minutes, recent_message='just now')
parts = []
secs = to_i
UNIT_MAP.each_pair do |unit, count|
val = (secs / count).floor
secs = secs % count
parts << [val, unit] if val > 0
break if unit == min_unit
end
# Trim number of units
parts = parts.take(places) if places
parts = parts.map do |val, unit|
pl_units = val == 1 ? unit.singularize : unit
"#{val} #{pl_units}"
end
# Round up to the nearest unit
if parts.size == 0
parts << recent_message
end
parts.to_sentence
end | ruby | {
"resource": ""
} |
q17198 | Volt.Tasks.response | train | def response(promise_id, result, error, cookies)
# Set the cookies
if cookies
cookies.each do |key, value|
@volt_app.cookies.set(key, value)
end
end
promise = @promises.delete(promise_id)
if promise
if error
# TODO: full error handling
Volt.logger.error('Task Response:')
Volt.logger.error(error)
promise.reject(error)
else
promise.resolve(result)
end
end
end | ruby | {
"resource": ""
} |
q17199 | Volt.Tasks.notify_query | train | def notify_query(method_name, collection, query, *args)
query_obj = Persistors::ArrayStore.query_pool.lookup(collection, query)
query_obj.send(method_name, *args)
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.