_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q2900
|
Faalis.User.join_guests
|
train
|
def join_guests
#::Faalis::Group.find_by(role: 'guest')
if groups.empty?
guest_group = ::Faalis::Group.find_or_create_by(name: 'Guest',
role: 'guest')
self.groups << guest_group
end
end
|
ruby
|
{
"resource": ""
}
|
q2901
|
Faalis::Dashboard::DSL.Base.attributes
|
train
|
def attributes(*fields_name, **options, &block)
if options.include? :except
@fields = resolve_model_reflections.reject do |field|
options[:except].include? field.to_sym
end
elsif options.include? :append
@fields += options[:append]
else
# Check for valid field names
fields_name.each do |name|
unless @fields.include? name.to_s
raise ArgumentError, "can't find '#{name}' field for model '#{model}'."
end
end
# set new value for fields
@fields = fields_name.map(&:to_s) unless fields_name.empty?
end
@fields.concat(block.call.map(&:to_s)) if block_given?
end
|
ruby
|
{
"resource": ""
}
|
q2902
|
Faalis::Dashboard::DSL.Base.resolve_model_reflections
|
train
|
def resolve_model_reflections
# TODO: cach the result using and instance_var or something
reflections = model.reflections
columns = Set.new model.column_names
new_fields = Set.new
fields_to_remove = Set.new
reflections.each do |name, column|
has_many = ActiveRecord::Reflection::HasManyReflection
has_and_belongs_to_many = ActiveRecord::Reflection::HasAndBelongsToManyReflection
if !column.is_a?(has_many) && !column.is_a?(has_and_belongs_to_many)
new_fields << name.to_s
fields_to_remove << column.foreign_key.to_s
end
end
if model.respond_to? :attachment_definitions
# Paperclip is installed and model contains attachments
model.attachment_definitions.each do |name, _|
new_fields << name.to_s
["file_name", "content_type", "file_size", "updated_at"].each do |x|
fields_to_remove << "#{name}_#{x}"
end
end
end
columns.union(new_fields) - fields_to_remove
end
|
ruby
|
{
"resource": ""
}
|
q2903
|
Ajax.Application.rails?
|
train
|
def rails?(*args)
version, comparator = args.pop, (args.pop || :==)
result =
if version.nil?
defined?(::Rails)
elsif defined?(::Rails)
if ::Rails.respond_to?(:version)
rails_version = Rails.version.to_f
rails_version = rails_version.floor if version.is_a?(Integer)
rails_version.send(comparator, version.to_f)
else
version.to_f <= 2.0
end
else
false
end
!!result
end
|
ruby
|
{
"resource": ""
}
|
q2904
|
Ajax.Application.init
|
train
|
def init
return unless rails?
if rails?(:>=, 3)
require 'ajax/railtie'
else
require 'ajax/action_controller'
require 'ajax/action_view'
Ajax.logger = ::Rails.logger
# Customize rendering. Include custom headers and don't render the layout for AJAX.
::ActionController::Base.send(:include, Ajax::ActionController)
# Insert the Rack::Ajax middleware to rewrite and handle requests
::ActionController::Dispatcher.middleware.insert_before(Rack::Head, Rack::Ajax)
# Add custom attributes to outgoing links
::ActionView::Base.send(:include, Ajax::ActionView)
end
end
|
ruby
|
{
"resource": ""
}
|
q2905
|
Opulent.Compiler.evaluate
|
train
|
def evaluate(node, indent)
# Check if this is a substructure of a control block and remove the last
# end evaluation if it is
if node[@value] =~ Settings::END_REMOVAL
@template.pop if @template[-1] == [:eval, 'end']
end
# Check for explicit end node
if node[@value] =~ Settings::END_EXPLICIT
Logger.error :compile, @template, :explicit_end, node
end
# Evaluate the current expression
buffer_eval node[@value]
# If the node has children, evaluate each one of them
node[@children].each do |child|
root child, indent + @settings[:indent]
end if node[@children]
# Check if the node is actually a block expression
buffer_eval 'end' if node[@value] =~ Settings::END_INSERTION
end
|
ruby
|
{
"resource": ""
}
|
q2906
|
Faalis.RouteHelpers.localized_scope
|
train
|
def localized_scope
langs = ::I18n.available_locales.join('|')
scope '(:locale)', locale: Regexp.new(langs) do
yield
end
end
|
ruby
|
{
"resource": ""
}
|
q2907
|
Faalis.RouteHelpers.api_routes
|
train
|
def api_routes(version: :v1)
# TODO: Add a dynamic solution for formats
namespace :api, defaults: { format: :json } do
namespace version do
# Call user given block to define user routes
# inside this namespace
yield if block_given?
end
end
scope 'module'.to_sym => 'faalis' do
#dashboard = Faalis::Engine.dashboard_namespace
#get "#{dashboard}/auth/groups/new", to: "#{dashboard}/groups#new"
get 'auth/profile/edit', to: "profile#edit"
post 'auth/profile/edit', to: "profile#update"
end
# TODO: Add a dynamic solution for formats
namespace :api, defaults: { format: :json } do
namespace version do
get 'permissions', to: 'permissions#index'
get 'permissions/user', to: 'permissions#user_permissions'
resources :groups, except: [:new]
resources :users, except: [:new]
resource :profile, except: [:new, :destroy]
get 'logs', to: 'logs#index'
end
end
end
|
ruby
|
{
"resource": ""
}
|
q2908
|
Configurations.Configuration.to_h
|
train
|
def to_h
@data.reduce({}) do |h, (k, v)|
h[k] = v.is_a?(__class__) ? v.to_h : v
h
end
end
|
ruby
|
{
"resource": ""
}
|
q2909
|
Configurations.Configuration.from_h
|
train
|
def from_h(h)
@key_ambiguity_validator.validate!(h)
h.each do |property, value|
p = property.to_sym
if value.is_a?(::Hash) && __nested?(p)
@data[p].from_h(value)
elsif __configurable?(p)
__assign!(p, value)
end
end
self
end
|
ruby
|
{
"resource": ""
}
|
q2910
|
Opulent.Compiler.if_node
|
train
|
def if_node(node, indent)
# Check if we have any condition met, or an else branch
node[@value].each_with_index do |value, index|
# If we have a branch that meets the condition, generate code for the
# children related to that specific branch
case value
when node[@value].first then buffer_eval "if #{value}"
when node[@value].last then buffer_eval "else"
else buffer_eval "elsif #{value}"
end
# Evaluate child nodes
node[@children][index].each do |child|
root child, indent
end
end
# End
buffer_eval "end"
end
|
ruby
|
{
"resource": ""
}
|
q2911
|
Opulent.Compiler.unless_node
|
train
|
def unless_node(node, indent)
# Check if we have any condition met, or an else branch
node[@value].each_with_index do |value, index|
# If we have a branch that meets the condition, generate code for the
# children related to that specific branch
case value
when node[@value].first then buffer_eval "unless #{value}"
else buffer_eval "else"
end
# Evaluate child nodes
node[@children][index].each do |child|
root child, indent
end
end
# End
buffer_eval "end"
end
|
ruby
|
{
"resource": ""
}
|
q2912
|
Opulent.Compiler.case_node
|
train
|
def case_node(node, indent)
# Evaluate the switching condition
buffer_eval "case #{node[@options][:condition]}"
# Check if we have any condition met, or an else branch
node[@value].each_with_index do |value, index|
# If we have a branch that meets the condition, generate code for the
# children related to that specific branch
case value
when node[@value].last then buffer_eval 'else'
else buffer_eval "when #{value}"
end
# Evaluate child nodes
node[@children][index].each do |child|
root child, indent
end
end
# End
buffer_eval 'end'
end
|
ruby
|
{
"resource": ""
}
|
q2913
|
Representative.Nokogiri.comment
|
train
|
def comment(text)
comment_node = ::Nokogiri::XML::Comment.new(doc, " #{text} ")
current_element.add_child(comment_node)
end
|
ruby
|
{
"resource": ""
}
|
q2914
|
Opulent.Parser.node
|
train
|
def node(parent, indent = nil)
return unless (name = lookahead(:node_lookahead) ||
lookahead(:shorthand_lookahead))
# Skip node if it's a reserved keyword
return nil if KEYWORDS.include? name[0].to_sym
# Accept either explicit node_name or implicit :div node_name
# with shorthand attributes
if (node_name = accept :node)
node_name = node_name.to_sym
shorthand = shorthand_attributes
elsif (shorthand = shorthand_attributes)
node_name = :div
end
# Node creation options
options = {}
# Get leading whitespace
options[:recursive] = accept(:recursive)
# Get leading whitespace
options[:leading_whitespace] = accept_stripped(:leading_whitespace)
# Get trailing whitespace
options[:trailing_whitespace] = accept_stripped(:trailing_whitespace)
# Get wrapped node attributes
atts = attributes(shorthand) || {}
# Inherit attributes from definition
options[:extension] = extend_attributes
# Get unwrapped node attributes
options[:attributes] = attributes_assignments atts, false
# Create node
current_node = [:node, node_name, options, [], indent]
# Check for self enclosing tags and definitions
def_check = [email protected]?(node_name) &&
Settings::SELF_ENCLOSING.include?(node_name)
# Check if the node is explicitly self enclosing
if (close = accept_stripped :self_enclosing) || def_check
current_node[@options][:self_enclosing] = true
unless close.nil? || close.strip.empty?
undo close
Logger.error :parse, @code, @i, @j, :self_enclosing
end
end
# Check whether we have explicit inline elements and add them
# with increased base indentation
if accept :inline_child
# Inline node element
Logger.error :parse,
@code,
@i,
@j,
:inline_child unless node current_node, indent
elsif comment current_node, indent
# Accept same line comments
else
# Accept inline text element
text current_node, indent, false
end
# Add the current node to the root
root current_node, indent
# Add the parsed node to the parent
parent[@children] << current_node
end
|
ruby
|
{
"resource": ""
}
|
q2915
|
Opulent.Parser.shorthand_attributes
|
train
|
def shorthand_attributes(atts = {})
while (key = accept :shorthand)
key = Settings::SHORTHAND[key.to_sym]
# Check whether the value is escaped or unescaped
escaped = accept(:unescaped_value) ? false : true
# Get the attribute value and process it
if (value = accept(:shorthand_node))
value = [:expression, value.inspect, { escaped: escaped }]
elsif (value = accept(:exp_string))
value = [:expression, value, { escaped: escaped }]
elsif (value = paranthesis)
value = [:expression, value, { escaped: escaped }]
else
Logger.error :parse, @code, @i, @j, :shorthand
end
# IDs are unique, the rest of the attributes turn into arrays in
# order to allow multiple values or identifiers
add_attribute(atts, key, value)
end
atts
end
|
ruby
|
{
"resource": ""
}
|
q2916
|
Opulent.Parser.attributes
|
train
|
def attributes(atts = {}, for_definition = false)
wrapped_attributes atts, for_definition
attributes_assignments atts, false, for_definition
atts
end
|
ruby
|
{
"resource": ""
}
|
q2917
|
Opulent.Parser.wrapped_attributes
|
train
|
def wrapped_attributes(list = {}, for_definition = false)
return unless (bracket = accept :brackets)
accept_newline
attributes_assignments list, true, for_definition
accept_newline
accept_stripped bracket.to_sym, :*
list
end
|
ruby
|
{
"resource": ""
}
|
q2918
|
Opulent.Parser.attributes_assignments
|
train
|
def attributes_assignments(list, wrapped = true, for_definition = false)
if wrapped && lookahead(:exp_identifier_stripped_lookahead).nil? ||
!wrapped && lookahead(:assignment_lookahead).nil?
return list
end
return unless (argument = accept_stripped :node)
argument = argument.to_sym
if accept_stripped :assignment
# Check if we have an attribute escape or not
escaped = if accept :assignment_unescaped
false
else
true
end
# Get the argument value if we have an assignment
if (value = expression(false, wrapped))
value[@options][:escaped] = escaped
# IDs are unique, the rest of the attributes turn into arrays in
# order to allow multiple values or identifiers
add_attribute(list, argument, value)
else
Logger.error :parse, @code, @i, @j, :assignments_colon
end
else
unless list[argument]
default_value = for_definition ? 'nil' : 'true'
list[argument] = [:expression, default_value, { escaped: false }]
end
end
# If our attributes are wrapped, we allow method calls without
# paranthesis, ruby style, therefore we need a terminator to signify
# the expression end. If they are not wrapped (inline), we require
# paranthesis and allow inline calls
if wrapped
# Accept optional comma between attributes
accept_stripped :assignment_terminator
# Lookahead for attributes on the current line and the next one
if lookahead(:exp_identifier_stripped_lookahead)
attributes_assignments list, wrapped, for_definition
elsif lookahead_next_line(:exp_identifier_stripped_lookahead)
accept_newline
attributes_assignments list, wrapped, for_definition
end
elsif !wrapped && lookahead(:assignment_lookahead)
attributes_assignments list, wrapped, for_definition
end
list
end
|
ruby
|
{
"resource": ""
}
|
q2919
|
Opulent.Parser.extend_attributes
|
train
|
def extend_attributes
return unless accept :extend_attributes
unescaped = accept :unescaped_value
extension = expression(false, false, false)
extension[@options][:escaped] = !unescaped
extension
end
|
ruby
|
{
"resource": ""
}
|
q2920
|
Opulent.Parser.root
|
train
|
def root(parent = @root, min_indent = -1)
while (@line = @code[(@i += 1)])
# Reset character position cursor
@j = 0
# Skip to next iteration if we have a blank line
next if @line =~ /\A\s*\Z/
# Reset the line offset
@offset = 0
# Parse the current line by trying to match each node type towards it
# Add current indentation to the indent stack
indent = accept(:indent).size
# Stop using the current parent as root if it does not match the
# minimum indentation includements
unless min_indent < indent
@i -= 1
break
end
# If last include path had a greater indentation, pop the last file path
@file.pop if @file[-1][1] >= indent
# Try the main Opulent node types and process each one of them using
# their matching evaluation procedure
current_node = node(parent, indent) ||
text(parent, indent) ||
comment(parent, indent) ||
define(parent, indent) ||
control(parent, indent) ||
evaluate(parent, indent) ||
filter(parent, indent) ||
block_yield(parent, indent) ||
include_file(parent, indent) ||
html_text(parent, indent) ||
doctype(parent, indent)
# Throw an error if we couldn't find any valid node
unless current_node
Logger.error :parse, @code, @i, @j, :unknown_node_type
end
end
parent
end
|
ruby
|
{
"resource": ""
}
|
q2921
|
Opulent.Compiler.define
|
train
|
def define(node)
# Write out def method_name
definition = "def _opulent_definition_#{node[@value].to_s.tr '-', '_'}"
# Node attributes
parameters = []
node[@options][:parameters].each do |key, value|
parameters << "#{key} = #{value[@value]}"
end
parameters << 'attributes = {}'
parameters << 'indent'
parameters << '&block'
definition += '(' + parameters.join(', ') + ')'
buffer_eval 'instance_eval do'
buffer_eval definition
@in_definition = true
node[@children].each do |child|
root child, 0
end
@in_definition = false
buffer_eval 'end'
buffer_eval 'end'
end
|
ruby
|
{
"resource": ""
}
|
q2922
|
Configurations.Arbitrary.respond_to_missing?
|
train
|
def respond_to_missing?(method, include_private = false)
__respond_to_writer?(method) ||
__respond_to_method_for_read?(method, *args, &block) ||
__respond_to_method_for_write?(method) ||
super
end
|
ruby
|
{
"resource": ""
}
|
q2923
|
Opulent.Parser.apply_definitions
|
train
|
def apply_definitions(node)
# Apply definition check to all of the node's children
process_definitions = proc do |children|
children.each do |child|
# Check if we have a definition
is_definition = if child[@value] == @current_def
child[@options][:recursive]
else
@definitions.key?(child[@value])
end
# Set child as a defined node
child[@type] = :def if is_definition
# Recursively apply definitions to child nodes
apply_definitions child if child[@children]
end
end
# Apply definitions to each case of the control node
if [:if, :unless, :case].include? node[@type]
node[@children].each do |array|
process_definitions[array]
end
# Apply definition to all of the node's children
else
process_definitions[node[@children]]
end
end
|
ruby
|
{
"resource": ""
}
|
q2924
|
Opulent.Parser.accept
|
train
|
def accept(token, required = false, strip = false)
# Consume leading whitespace if we want to ignore it
accept :whitespace if strip
# We reached the end of the parsing process and there are no more lines
# left to parse
return nil unless @line
# Match the token to the current line. If we find it, return the match.
# If it is required, signal an :expected error
if (match = @line[@offset..-1].match(Tokens[token]))
# Advance current offset with match length
@offset += match[0].size
@j += match[0].size
return match[0]
elsif required
Logger.error :parse, @code, @i, @j, :expected, token
end
end
|
ruby
|
{
"resource": ""
}
|
q2925
|
Opulent.Parser.indent_lines
|
train
|
def indent_lines(text, indent)
text ||= ''
text.lines.map { |line| indent + line }.join
end
|
ruby
|
{
"resource": ""
}
|
q2926
|
RedboothRuby.Client.perform!
|
train
|
def perform!(resource_name, action, options = {})
ClientOperations::Perform.new(resource_name, action, session, options).perform!
end
|
ruby
|
{
"resource": ""
}
|
q2927
|
Faalis.Concerns::User::AuthDefinitions.password_required?
|
train
|
def password_required?
# TODO: nil? is not suitable for here we should use empty? or blink?
if Devise.omniauth_configs.any?
return (provider.nil? || password.nil?) && super
else
password.nil? && super
end
end
|
ruby
|
{
"resource": ""
}
|
q2928
|
RedboothRuby.File.download
|
train
|
def download(style='original', path=nil)
options = { session: session }
options[:download_path] = path unless path.nil?
request = RedboothRuby.request(:download, nil, "files/#{id}/download/#{style}/#{name}", {}, options)
request.body
end
|
ruby
|
{
"resource": ""
}
|
q2929
|
Opulent.Engine.render
|
train
|
def render(scope = Object.new, locals = {}, &block)
# Get opulent buffer value
if scope.instance_variable_defined?(:@_opulent_buffer)
initial_buffer = scope.instance_variable_get(:@_opulent_buffer)
else
initial_buffer = []
end
# If a layout is set, get the specific layout, otherwise, set the default
# one. If a layout is set to false, the page will be render as it is.
if scope.is_a? binding.class
scope_object = eval 'self', scope
scope = scope_object.instance_eval { binding } if block_given?
else
scope_object = scope
scope = scope_object.instance_eval { binding }
end
# Set input local variables in current scope
if scope.respond_to? :local_variable_set
locals.each do |key, value|
scope.local_variable_set key, value
end
else
locals.each do |key, value|
eval("#{key} = nil; lambda {|v| #{key} = v}", scope).call(value)
end
end
# Evaluate the template in the given scope (context)
begin
eval @src, scope
rescue ::SyntaxError => e
raise SyntaxError, e.message
ensure
# Get rid of the current buffer
scope_object.instance_variable_set :@_opulent_buffer, initial_buffer
end
end
|
ruby
|
{
"resource": ""
}
|
q2930
|
Opulent.Engine.read
|
train
|
def read(input)
if input.is_a? Symbol
@file = File.expand_path get_eval_file input
File.read @file
else
@file = File.expand_path __FILE__
input
end
end
|
ruby
|
{
"resource": ""
}
|
q2931
|
Opulent.Engine.get_eval_file
|
train
|
def get_eval_file(input)
input = input.to_s
unless File.extname(input) == Settings::FILE_EXTENSION
input += Settings::FILE_EXTENSION
end
input
end
|
ruby
|
{
"resource": ""
}
|
q2932
|
Opulent.Compiler.buffer_attributes_to_hash
|
train
|
def buffer_attributes_to_hash(attributes)
'{' + attributes.inject([]) do |extend_map, (key, attribute)|
extend_map << (
":\"#{key}\" => " + if key == :class
'[' + attribute.map do |exp|
exp[@value]
end.join(', ') + ']'
else
attribute[@value]
end
)
end.join(', ') + '}'
end
|
ruby
|
{
"resource": ""
}
|
q2933
|
Opulent.Compiler.buffer_attributes
|
train
|
def buffer_attributes(attributes, extension)
# Proc for setting class attribute extension, used as DRY closure
#
buffer_class_attribute_type_check = proc do |variable, escape = true|
class_variable = buffer_set_variable :local, variable
# Check if we need to add the class attribute
buffer_eval "unless #{class_variable} and true === #{class_variable}"
# Check if class attribute has array value
buffer_eval "if Array === #{class_variable}"
ruby_code = "#{class_variable}.join ' '"
if escape
buffer_escape ruby_code
else
buffer ruby_code
end
# Check if class attribute has hash value
buffer_eval "elsif Hash === #{class_variable}"
ruby_code = "#{class_variable}.to_a.join ' '"
if escape
buffer_escape ruby_code
else
buffer ruby_code
end
# Other values
buffer_eval 'else'
ruby_code = "#{class_variable}"
if escape
buffer_escape ruby_code
else
buffer ruby_code
end
# End cases
buffer_eval 'end'
# End
buffer_eval 'end'
end
# Handle class attributes by checking if they're simple, noninterpolated
# strings or not and extend them if needed
#
buffer_class_attribute = proc do |attribute|
if attribute[@value] =~ Tokens[:exp_string_match]
buffer_split_by_interpolation attribute[@value][1..-2],
attribute[@options][:escaped]
else
buffer_class_attribute_type_check[
attribute[@value],
attribute[@options][:escaped]
]
end
end
# If we have class attributes, process each one and check if we have an
# extension for them
if attributes[:class]
buffer_freeze " class=\""
# Process every class attribute
attributes[:class].each do |node_class|
buffer_class_attribute[node_class]
buffer_freeze ' '
end
# Remove trailing whitespace from the buffer
buffer_remove_last_character
# Check for extension with :class key
if extension
buffer_eval "if #{extension[:name]}.has_key? :class"
buffer_freeze ' '
buffer_class_attribute_type_check[
"#{extension[:name]}.delete(:class)"
]
buffer_eval 'end'
end
buffer_freeze '"'
elsif extension
# If we do not have class attributes but we do have an extension, try to
# see if the extension contains a class attribute
buffer_eval "if #{extension[:name]}.has_key? :class"
buffer_freeze " class=\""
buffer_class_attribute_type_check["#{extension[:name]}.delete(:class)"]
buffer_freeze '"'
buffer_eval 'end'
end
# Proc for setting class attribute extension, used as DRY closure
#
buffer_data_attribute_type_check = proc do |key, variable, escape = true, dynamic = false|
# Check if variable is set
buffer_eval "if #{variable}"
# @Array
buffer_eval "if Array === #{variable}"
dynamic ? buffer("\" #{key}=\\\"\"") : buffer_freeze(" #{key}=\"")
ruby_code = "#{variable}.join '_'"
if escape
buffer_escape ruby_code
else
buffer ruby_code
end
buffer_freeze '"'
# @Hash
buffer_eval "elsif Hash === #{variable}"
buffer_eval "#{variable}.each do |#{OPULENT_KEY}, #{OPULENT_VALUE}|"
# key-hashkey
dynamic ? buffer("\" #{key}-\"") : buffer_freeze(" #{key}-")
buffer "#{OPULENT_KEY}.to_s"
#="value"
buffer_freeze "=\""
escape ? buffer_escape(OPULENT_VALUE) : buffer(OPULENT_VALUE)
buffer_freeze '"'
buffer_eval 'end'
# @TrueClass
buffer_eval "elsif true === #{variable}"
dynamic ? buffer("\" #{key}\"") : buffer_freeze(" #{key}")
# @Object
buffer_eval 'else'
dynamic ? buffer("\" #{key}=\\\"\"") : buffer_freeze(" #{key}=\"")
escape ? buffer_escape("#{variable}") : buffer("#{variable}")
buffer_freeze '"'
# End Cases
buffer_eval 'end'
# End
buffer_eval 'end'
end
# Handle data (normal) attributes by checking if they're simple, noninterpolated
# strings and extend them if needed
#
buffer_data_attribute = proc do |key, attribute|
# When we have an extension for our attributes, check current key.
# If it exists, check it's type and generate everything dynamically
if extension
buffer_eval "if #{extension[:name]}.has_key? :\"#{key}\""
variable = buffer_set_variable :local,
"#{extension[:name]}" \
".delete(:\"#{key}\")"
buffer_data_attribute_type_check[
key,
variable,
attribute[@options][:escaped]
]
buffer_eval 'else'
end
# Check if the set attribute is a simple string. If it is, freeze it or
# escape it. Otherwise, evaluate and initialize the type check.
if attribute[@value] =~ Tokens[:exp_string_match]
buffer_freeze " #{key}=\""
buffer_split_by_interpolation attribute[@value][1..-2],
attribute[@options][:escaped]
buffer_freeze "\""
else
# Evaluate and type check
variable = buffer_set_variable :local, attribute[@value]
buffer_data_attribute_type_check[
key,
variable,
attribute[@options][:escaped]
]
end
# Extension end
buffer_eval 'end' if extension
end
# Process the remaining, non-class related attributes
attributes.each do |key, attribute|
next if key == :class
buffer_data_attribute[key, attribute]
end
# Process remaining extension keys if there are any
return unless extension
buffer_eval "#{extension[:name]}.each do " \
"|ext#{OPULENT_KEY}, ext#{OPULENT_VALUE}|"
buffer_data_attribute_type_check[
"\#{ext#{OPULENT_KEY}}",
"ext#{OPULENT_VALUE}",
extension[:escaped],
true
]
buffer_eval 'end'
end
|
ruby
|
{
"resource": ""
}
|
q2934
|
Opulent.Compiler.buffer_split_by_interpolation
|
train
|
def buffer_split_by_interpolation(string, escape = true)
# Interpolate variables in text (#{variable}).
# Split the text into multiple dynamic and static parts.
begin
case string
when /\A\\\#\{/
# Escaped interpolation
buffer_freeze '#{'
string = $'
when /\A#\{((?>[^{}]|(\{(?>[^{}]|\g<1>)*\}))*)\}/
# Interpolation
string = $'
code = $1
# escape = code !~ /\A\{.*\}\Z/
if escape
buffer_escape code
else
buffer code
end
when /\A([\\#]?[^#\\]*([#\\][^\\#\{][^#\\]*)*)/
string_remaining = $'
string_current = $&
# Static text
if escape && string_current =~ Utils::ESCAPE_HTML_PATTERN
buffer_escape string_current.inspect
else
buffer_freeze string_current
end
string = string_remaining
end
end until string.empty?
end
|
ruby
|
{
"resource": ""
}
|
q2935
|
Configurations.Strict.__evaluate_configurable!
|
train
|
def __evaluate_configurable!
entries = @properties.entries_at(@path)
entries.each do |property, value|
if value.is_a?(Maps::Properties::Entry)
__install_property__(property)
else
__install_nested_getter__(property)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q2936
|
Configurations.Strict.__assign!
|
train
|
def __assign!(property, value)
@types.test!(@path.add(property), value)
v = @blocks.evaluate!(@path.add(property), value)
value = v unless v.nil?
super(property, value)
end
|
ruby
|
{
"resource": ""
}
|
q2937
|
Representative.AbstractXml.element
|
train
|
def element(name, *args, &block)
metadata = @inspector.get_metadata(current_subject, name)
attributes = args.extract_options!.merge(metadata)
subject_of_element = if args.empty?
@inspector.get_value(current_subject, name)
else
args.shift
end
raise ArgumentError, "too many arguments" unless args.empty?
representing(subject_of_element) do
resolved_attributes = resolve_attributes(attributes)
content_string = content_block = nil
unless current_subject.nil?
if block
unless block == Representative::EMPTY
content_block = Proc.new { block.call(current_subject) }
end
else
content_string = current_subject.to_s
end
end
generate_element(format_name(name), resolved_attributes, content_string, &content_block)
end
end
|
ruby
|
{
"resource": ""
}
|
q2938
|
Representative.AbstractXml.list_of
|
train
|
def list_of(name, *args, &block)
options = args.extract_options!
list_subject = args.empty? ? name : args.shift
raise ArgumentError, "too many arguments" unless args.empty?
list_attributes = options[:list_attributes] || {}
item_name = options[:item_name] || name.to_s.singularize
item_attributes = options[:item_attributes] || {}
items = resolve_value(list_subject)
element(name, items, list_attributes.merge(:type => proc{"array"})) do
items.each do |item|
element(item_name, item, item_attributes, &block)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q2939
|
Opulent.Parser.expression
|
train
|
def expression(allow_assignments = true, wrapped = true, whitespace = true)
buffer = ''
# Build a ruby expression out of accepted literals
while (term = (whitespace ? accept(:whitespace) : nil) ||
modifier ||
identifier ||
method_call ||
paranthesis ||
array ||
hash ||
symbol ||
percent ||
primary_term)
buffer += term
# Accept operations which have a right term and raise an error if
# we have an unfinished expression such as "a +", "b - 1 >" and other
# expressions following the same pattern
if wrapped && (op = operation ||
(allow_assignments ? accept_stripped(:exp_assignment) : nil))
buffer += op
if (right_term = expression(allow_assignments, wrapped)).nil?
Logger.error :parse, @code, @i, @j, :expression
else
buffer += right_term[@value]
end
elsif (op = array || op = method_call || op = ternary_operator(allow_assignments, wrapped))
buffer += op
end
# Do not continue if the expression has whitespace method calls in
# an unwrapped context because this will confuse the parser
unless buffer.strip.empty?
break if lookahead(:exp_identifier_lookahead).nil?
end
end
if buffer.strip.empty?
undo buffer
else
[:expression, buffer.strip, {}]
end
end
|
ruby
|
{
"resource": ""
}
|
q2940
|
Opulent.Parser.array_elements
|
train
|
def array_elements(buffer = '')
if (term = expression)
buffer += term[@value]
# If there is an array_terminator ",", recursively gather the next
# array element into the buffer
if (terminator = accept_stripped :comma)
accept_newline
buffer += array_elements terminator
end
end
# Array ended prematurely with a trailing comma, therefore the current
# parsing process will stop
error :array_elements_terminator if buffer.strip[-1] == ','
buffer
end
|
ruby
|
{
"resource": ""
}
|
q2941
|
Opulent.Parser.method_call
|
train
|
def method_call
method_code = ''
while (method_start = accept(:exp_method_call))
method_code += method_start
argument = call
method_code += argument if argument
end
method_code == '' ? nil : method_code
end
|
ruby
|
{
"resource": ""
}
|
q2942
|
Opulent.Parser.call_elements
|
train
|
def call_elements(buffer = '')
# Accept both shorthand and default ruby hash style. Following DRY
# principles, a Proc is used to assign the value to the current key
#
# key: value
# :key => value
# value
if (symbol = accept_stripped :hash_symbol)
buffer += symbol
# Get the value associated to the current hash key
if (exp = expression(true))
buffer += exp[@value]
else
error :call_elements
end
# If there is an comma ",", recursively gather the next
# array element into the buffer
if (terminator = accept_stripped :comma)
buffer += call_elements terminator
end
elsif (exp = expression(true))
buffer += exp[@value]
if (assign = accept_stripped :hash_assignment)
buffer += assign
# Get the value associated to the current hash key
if (exp = expression(true))
buffer += exp[@value]
else
error :call_elements
end
end
# If there is an comma ",", recursively gather the next
# array element into the buffer
if (terminator = accept_stripped :comma)
buffer += call_elements terminator
end
end
buffer
end
|
ruby
|
{
"resource": ""
}
|
q2943
|
Opulent.Parser.symbol
|
train
|
def symbol
return unless (colon = accept :colon)
return undo colon if lookahead(:whitespace)
if (exp = expression).nil?
error :symbol
else
colon + exp[@value]
end
end
|
ruby
|
{
"resource": ""
}
|
q2944
|
Opulent.Parser.ternary_operator
|
train
|
def ternary_operator(allow_assignments, wrapped)
if (buffer = accept :exp_ternary)
buffer += expression(allow_assignments, wrapped)[@value]
if (else_branch = accept :exp_ternary_else)
buffer += else_branch
buffer += expression(allow_assignments, wrapped)[@value]
end
return buffer
end
end
|
ruby
|
{
"resource": ""
}
|
q2945
|
Ajax.ActionController.serialize_ajax_info
|
train
|
def serialize_ajax_info
layout_name =
if Ajax.app.rails?(3)
if @_rendered_layout.is_a?(String)
@_rendered_layout =~ /.*\/([^\/]*)/ ? $1 : @_rendered_layout
elsif @_rendered_layout
@_rendered_layout.variable_name
end
else
active_layout
end
Ajax.set_header(response, :layout, layout_name)
Ajax.set_header(response, :controller, self.class.controller_name)
end
|
ruby
|
{
"resource": ""
}
|
q2946
|
Ajax.ActionController._layout_for_ajax
|
train
|
def _layout_for_ajax(default) #:nodoc:
ajax_layout = self.class.read_inheritable_attribute(:ajax_layout)
ajax_layout = if ajax_layout.nil? && default.nil?
nil
elsif ajax_layout.nil? && !default.nil? # look for one with the default name in layouts/ajax
if default =~ /^layouts\/ajax\//
default
elsif !(default =~ /^ajax\//)
"ajax/#{default.sub(/layouts(\/)?/, '')}"
else
default
end
elsif ajax_layout.include?(?/) # path to specific layout
ajax_layout
else # layout name, look in ajax/
"ajax/#{ajax_layout}"
end
ajax_layout = ajax_layout =~ /\blayouts/ ? ajax_layout : "layouts/#{ajax_layout}" if ajax_layout
ajax_layout
end
|
ruby
|
{
"resource": ""
}
|
q2947
|
Opulent.Parser.filter
|
train
|
def filter(parent, indent)
return unless (filter_name = accept :filter)
# Get element attributes
atts = attributes(shorthand_attributes) || {}
# Accept inline text or multiline text feed as first child
error :fiter unless accept(:line_feed).strip.empty?
# Get everything under the filter and set it as the node value
# and create a new node and set its extension
parent[@children] << [
:filter,
filter_name[1..-1].to_sym,
atts,
get_indented_lines(indent),
indent
]
end
|
ruby
|
{
"resource": ""
}
|
q2948
|
Opulent.Compiler.plain
|
train
|
def plain(node, indent)
# Text value
value = node[@options][:value]
# Pretty print
if @settings[:pretty]
indentation = ' ' * indent
inline = @sibling_stack[-1][-1] &&
@sibling_stack[-1][-1][0] == :node &&
Settings::INLINE_NODE.include?(@sibling_stack[-1][-1][1])
# Add current node to the siblings stack
@sibling_stack[-1] << [node[@type], node[@value]]
# If we have a text on multiple lines and the text isn't supposed to be
# inline, indent all the lines of the text
if node[@value] == :text
if !inline
value.gsub!(/^(?!$)/, indentation)
else
buffer_remove_trailing_newline
value.strip!
end
else
buffer_freeze indentation
end
end
# Leading whitespace
buffer_freeze ' ' if node[@options][:leading_whitespace]
# Evaluate text node if it's marked as such and print nodes in the
# current context
if node[@value] == :text
buffer_split_by_interpolation value, node[@options][:escaped]
else
node[@options][:escaped] ? buffer_escape(value) : buffer(value)
end
# Trailing whitespace
buffer_freeze ' ' if node[@options][:trailing_whitespace]
# Pretty print
if @settings[:pretty]
buffer_freeze "\n" if !inline or node[@value] == :print
end
end
|
ruby
|
{
"resource": ""
}
|
q2949
|
Opulent.Parser.include_file
|
train
|
def include_file(_parent, indent)
return unless accept :include
# Process data
name = accept :line_feed || ''
name.strip!
# Check if there is any string after the include input
Logger.error :parse, @code, @i, @j, :include_end if name.empty?
# Get the complete file path based on the current file being compiled
include_path = File.expand_path name, File.dirname(@file[-1][0])
# Try to see if it has any existing extension, otherwise add .op
include_path += Settings::FILE_EXTENSION if File.extname(name).empty?
# Throw an error if the file doesn't exist
unless Dir[include_path].any?
Logger.error :parse, @code, @i, @j, :include, name
end
# include entire directory tree
Dir[include_path].each do |file|
# Skip current file when including from same directory
next if file == @file[-1][0]
@file << [include_path, indent]
# Throw an error if the file doesn't exist
if File.directory? file
Logger.error :parse, @code, @i, @j, :include_dir, file
end
# Throw an error if the file doesn't exist
unless File.file? file
Logger.error :parse, @code, @i, @j, :include, file
end
# Indent all lines and prepare them for the parser
lines = indent_lines File.read(file), ' ' * indent
lines << ' '
# Indent all the output lines with the current indentation
@code.insert @i + 1, *lines.lines
end
true
end
|
ruby
|
{
"resource": ""
}
|
q2950
|
RedboothRuby.Base.parse_timestamps
|
train
|
def parse_timestamps
@created_time = created_time.to_i if created_time.is_a? String
@created_time = Time.at(created_time) if created_time
end
|
ruby
|
{
"resource": ""
}
|
q2951
|
Opulent.Compiler.node
|
train
|
def node(node, indent)
# Pretty print
if @settings[:pretty]
indentation = ' ' * indent
inline = Settings::INLINE_NODE.include? node[@value]
indentate = proc do
if @in_definition
buffer "' ' * (indent + #{indent})"
else
buffer_freeze indentation
end
end
if inline
inline_last_sibling = @sibling_stack[-1][-1] ? Settings::INLINE_NODE.include?(@sibling_stack[-1][-1][1]) : true
if @sibling_stack[-1][-1] && @sibling_stack[-1][-1][0] == :plain
buffer_remove_trailing_newline
end
if @in_definition || @sibling_stack[-1].length == 1 || !inline_last_sibling
indentate[]
end
else
indentate[]
end
@sibling_stack[-1] << [node[@type], node[@value]]
@sibling_stack << [[node[@type], node[@value]]]
end
# Add the tag opening, with leading whitespace to the code buffer
buffer_freeze ' ' if node[@options][:leading_whitespace]
buffer_freeze "<#{node[@value]}"
# Evaluate node extension in the current context
if node[@options][:extension]
extension_name = buffer_set_variable :extension,
node[@options][:extension][@value]
extension = {
name: extension_name,
escaped: node[@options][:extension][@options][:escaped]
}
end
# Evaluate and generate node attributes, then process each one to
# by generating the required attribute code
buffer_attributes node[@options][:attributes],
extension
# Check if the current node is self enclosing. Self enclosing nodes
# do not have any child elements
if node[@options][:self_enclosing]
# If the tag is self enclosing, it cannot have any child elements.
buffer_freeze '>'
# Pretty print
buffer_freeze "\n" if @settings[:pretty]
# If we mistakenly add children to self enclosing nodes,
# process each child element as if it was correctly indented
# node[@children].each do |child|
# root child, indent + @settings[:indent]
# end
else
# Set tag ending code
buffer_freeze '>'
# Pretty print
if @settings[:pretty]
if node[@children].length > 0
buffer_freeze "\n" unless inline
end
# @sibling_stack << [[node[@type], node[@value]]]
end
# Process each child element recursively, increasing indentation
node[@children].each do |child|
root child, indent + @settings[:indent]
end
inline_last_child = @sibling_stack[-1][-2] &&
(@sibling_stack[-1][-2][0] == :plain ||
Settings::INLINE_NODE.include?(@sibling_stack[-1][-2][1]))
# Pretty print
if @settings[:pretty]
if node[@children].length > 1 && inline_last_child
buffer_freeze "\n"
end
if node[@children].size > 0 && !inline
indentate[]
end
end
# Set tag closing code
buffer_freeze "</#{node[@value]}>"
buffer_freeze ' ' if node[@options][:trailing_whitespace]
# Pretty print
if @settings[:pretty]
buffer_freeze "\n" if !inline || @in_definition
end
end
if @settings[:pretty]
@sibling_stack.pop
end
end
|
ruby
|
{
"resource": ""
}
|
q2952
|
FlexColumns.HasFlexColumns._flex_columns_before_save!
|
train
|
def _flex_columns_before_save!
self.class._all_flex_column_names.each do |flex_column_name|
klass = self.class._flex_column_class_for(flex_column_name)
if klass.requires_serialization_on_save?(self)
_flex_column_object_for(flex_column_name).before_save!
end
end
end
|
ruby
|
{
"resource": ""
}
|
q2953
|
FlexColumns.HasFlexColumns._flex_column_owned_object_for
|
train
|
def _flex_column_owned_object_for(column_name, create_if_needed = true)
column_name = self.class._flex_column_normalize_name(column_name)
out = _flex_column_objects[column_name]
if (! out) && create_if_needed
out = _flex_column_objects[column_name] = self.class._flex_column_class_for(column_name).new(self)
end
out
end
|
ruby
|
{
"resource": ""
}
|
q2954
|
Opulent.Parser.define
|
train
|
def define(parent, indent)
return unless accept(:def)
# Definition parent check
Logger.error :parse, @code, @i, @j, :definition if parent[@type] != :root
# Process data
name = accept(:node, :*).to_sym
# Create node
definition = [
:def,
name,
{ parameters: attributes({}, true) },
[],
indent
]
# Set definition as root node and let the parser know that we're inside
# a definition. This is used because inside definitions we do not
# process nodes (we do not check if they are have a definition or not).
root definition, indent
# Add to parent
@definitions[name] = definition
end
|
ruby
|
{
"resource": ""
}
|
q2955
|
Rack.Ajax.encode_env
|
train
|
def encode_env(env)
env = env.dup
env.keep_if { |k, v| k =~ /[A-Z]/ }
env.to_yaml(:Encoding => :Utf8)
end
|
ruby
|
{
"resource": ""
}
|
q2956
|
Repack.Helper.webpack_asset_paths
|
train
|
def webpack_asset_paths(source, extension: nil)
return "" unless source.present?
paths = Repack::Manifest.asset_paths(source)
paths = paths.select {|p| p.ends_with? ".#{extension}" } if extension
host = ::Rails.configuration.repack.dev_server.host
port = ::Rails.configuration.repack.dev_server.port
if ::Rails.configuration.repack.dev_server.enabled
paths.map! do |p|
"//#{host}:#{port}#{p}"
end
end
paths
end
|
ruby
|
{
"resource": ""
}
|
q2957
|
ChefHelpers.HasSource.has_source?
|
train
|
def has_source?(source, segment, cookbook=nil)
cookbook ||= cookbook_name
begin
run_context.cookbook_collection[cookbook].
send(:find_preferred_manifest_record, run_context.node, segment, source)
rescue Chef::Exceptions::FileNotFound
nil
end
end
|
ruby
|
{
"resource": ""
}
|
q2958
|
Tribe.Actable.process_events
|
train
|
def process_events
while (event = @_actable.mailbox.obtain_and_shift)
event_handler(event)
end
rescue Exception => exception
cleanup_handler(exception)
exception_handler(exception)
ensure
@_actable.mailbox.release do
process_events
end
nil
end
|
ruby
|
{
"resource": ""
}
|
q2959
|
Opulent.Context.evaluate
|
train
|
def evaluate(code, &block)
begin
eval code, @binding, &block
rescue NameError => variable
Compiler.error :binding, variable, code
end
end
|
ruby
|
{
"resource": ""
}
|
q2960
|
Opulent.Context.extend_locals
|
train
|
def extend_locals(locals)
# Create new local variables from the input hash
locals.each do |key, value|
begin
@binding.local_variable_set key.to_sym, value
rescue NameError => variable
Compiler.error :variable_name, variable, key
end
end
end
|
ruby
|
{
"resource": ""
}
|
q2961
|
Opulent.Context.extend_nonlocals
|
train
|
def extend_nonlocals(bind)
bind.eval('instance_variables').each do |var|
@binding.eval('self').instance_variable_set var, bind.eval(var.to_s)
end
bind.eval('self.class.class_variables').each do |var|
@binding.eval('self').class_variable_set var, bind.eval(var.to_s)
end
end
|
ruby
|
{
"resource": ""
}
|
q2962
|
Faalis::Dashboard::DSL.Index.attributes
|
train
|
def attributes(*fields_name, **options, &block)
if options.include? :except
@fields = resolve_model_reflections.reject do |field|
options[:except].include? field.to_sym
end
elsif options.include? :append
@fields += options[:append]
else
# set new value for fields
@fields = fields_name.map(&:to_s) unless fields_name.empty?
end
@fields.concat(block.call.map(&:to_s)) if block_given?
end
|
ruby
|
{
"resource": ""
}
|
q2963
|
Faalis::Dashboard::Sections.ResourcesIndex.fetch_index_objects
|
train
|
def fetch_index_objects
scope = index_properties.default_scope
puts "<<<<<<<" * 100, scope
if !scope.nil?
# If user provided an scope for `index` section.
if scope.respond_to? :call
# If scope provided by a block
scope = scope.call
else
# If scope provided by a symbol
# which should be a method name
scope = self.send(scope)
end
else
scope = model.all
#scope = ApplicationPolicy::Scope.new(current_user, model.all).resolve
end
scope = scope.order('created_at DESC').page(params[:page])
policy_scope(scope)
end
|
ruby
|
{
"resource": ""
}
|
q2964
|
Sanitize::Rails::Matchers.SanitizeFieldsMatcher.matches?
|
train
|
def matches?(instance)
self.instance = instance
# assign invalid value to each field
fields.each { |field| instance.send("#{field}=", invalid_value) }
# sanitize the object calling the method
instance.send(sanitizer) rescue nil
# check expectation on results
fields.all? { |field| valid_value == instance.send(field) }
end
|
ruby
|
{
"resource": ""
}
|
q2965
|
Opulent.Parser.control
|
train
|
def control(parent, indent)
# Accept eval or multiline eval syntax and return a new node,
return unless (structure = accept(:control))
structure = structure.to_sym
# Handle each and the other control structures
condition = accept(:line_feed).strip
# Process each control structure condition
if structure == :each
# Check if arguments provided correctly
unless condition.match Tokens[:each_pattern]
Logger.error :parse, @code, @i, @j, :each_arguments
end
# Conditions for each iterator
condition = [
Regexp.last_match[1].split(' '),
Regexp.last_match[2].split(/,(.+)$/).map(&:strip).map(&:to_sym)
]
# Array loop as default
condition[0].unshift '{}' if condition[0].length == 1
end
# Else and default structures are not allowed to have any condition
# set and the other control structures require a condition
if structure == :else
unless condition.empty?
Logger.error :parse, @code, @i, @j, :condition_exists
end
else
if condition.empty?
Logger.error :parse, @code, @i, @j, :condition_missing
end
end
# Add the condition and create a new child to the control parent.
# The control parent keeps condition -> children matches for our
# document's content
# add_options = proc do |control_parent|
# control_parent.value << condition
# control_parent.children << []
#
# root control_parent
# end
# If the current control structure is a parent which allows multiple
# branches, such as an if or case, we create an array of conditions
# which can be matched and an array of children belonging to each
# conditional branch
if [:if, :unless].include? structure
# Create the control structure and get its child nodes
control_structure = [structure, [condition], {}, [], indent]
root control_structure, indent
# Turn children into an array because we allow multiple branches
control_structure[@children] = [control_structure[@children]]
# Add it to the parent node
parent[@children] << control_structure
elsif structure == :case
# Create the control structure and get its child nodes
control_structure = [
structure,
[],
{ condition: condition },
[],
indent
]
# Add it to the parent node
parent[@children] << control_structure
# If the control structure is a child structure, we need to find the
# node it belongs to amont the current parent. Search from end to
# beginning until we find the node parent
elsif control_child structure
# During the search, we try to find the matching parent type
unless control_parent(structure).include? parent[@children][-1][@type]
Logger.error :parse,
@code,
@i,
@j,
:control_child,
control_parent(structure)
end
# Gather child elements for current structure
control_structure = [structure, [condition], {}, [], indent]
root control_structure, indent
# Add the new condition and children to our parent structure
parent[@children][-1][@value] << condition
parent[@children][-1][@children] << control_structure[@children]
# When our control structure isn't a complex composite, we create
# it the same way as a normal node
else
control_structure = [structure, condition, {}, [], indent]
root control_structure, indent
parent[@children] << control_structure
end
end
|
ruby
|
{
"resource": ""
}
|
q2966
|
Polipus.Robotex.delay!
|
train
|
def delay!(uri)
delay = delay(uri)
sleep delay - (Time.now - @last_accessed) if delay
@last_accessed = Time.now
end
|
ruby
|
{
"resource": ""
}
|
q2967
|
Faalis.DashboardHelper.get_url
|
train
|
def get_url(route_name, id = nil, engine = Rails.application)
return route_name.call if id.nil?
return route_name.call(id) unless id.nil?
end
|
ruby
|
{
"resource": ""
}
|
q2968
|
WardenStrategies.Simple.authenticate!
|
train
|
def authenticate!
if u = user_class.send(config[:authenticate_method], *required_param_values)
success!(u)
else
fail!(config[:error_message])
end
end
|
ruby
|
{
"resource": ""
}
|
q2969
|
Charging.Invoice.create!
|
train
|
def create!
super do
raise 'can not create without a domain' if invalid_domain?
raise 'can not create wihtout a charge account' if invalid_charge_account?
Invoice.post_charge_accounts_invoices(domain, charge_account, attributes)
end
reload_attributes!(Helpers.extract_uuid(last_response.headers[:location]) || uuid)
end
|
ruby
|
{
"resource": ""
}
|
q2970
|
Charging.Invoice.payments
|
train
|
def payments
reset_errors!
response = Http.get("/invoices/#{uuid}/payments/", domain.token)
return [] if response.code != 200
MultiJson.decode(response.body)
end
|
ruby
|
{
"resource": ""
}
|
q2971
|
Charging.Invoice.billet_url
|
train
|
def billet_url
return if unpersisted?
response = Http.get("/invoices/#{uuid}/billet/", domain.token)
return if response.code != 200
MultiJson.decode(response.body)["billet"]
rescue
nil
end
|
ruby
|
{
"resource": ""
}
|
q2972
|
Rexpense::Resources.Participant.participants
|
train
|
def participants(resource_id)
http.get(participants_endpoint(resource_id)) do |response|
Rexpense::Entities::UserCollection.build response
end
end
|
ruby
|
{
"resource": ""
}
|
q2973
|
Charging.ChargeAccount.update_attribute!
|
train
|
def update_attribute!(attribute, value, should_reload_attributes = true)
execute_and_capture_raises_at_errors(204) do
@last_response = Http.patch("/charge-accounts/#{uuid}/", domain.token, etag, attribute => value)
end
reload_attributes! if should_reload_attributes
end
|
ruby
|
{
"resource": ""
}
|
q2974
|
Rexpense::Resources.Membership.memberships
|
train
|
def memberships(organization_id)
http.get(membership_endpoint(organization_id)) do |response|
Rexpense::Entities::MembershipCollection.build response
end
end
|
ruby
|
{
"resource": ""
}
|
q2975
|
Rexpense::Resources.Membership.create_membership
|
train
|
def create_membership(organization_id, params)
http.post(membership_endpoint(organization_id), body: params) do |response|
response.parsed_body
end
end
|
ruby
|
{
"resource": ""
}
|
q2976
|
Rexpense::Resources.Membership.update_membership
|
train
|
def update_membership(organization_id, membership_id, params)
http.put("#{membership_endpoint(organization_id)}/#{membership_id}", body: params) do |response|
Rexpense::Entities::Membership.new response.parsed_body
end
end
|
ruby
|
{
"resource": ""
}
|
q2977
|
Rexpense::Resources.Attachment.attachments
|
train
|
def attachments(resource_id)
http.get(attachment_endpoint(resource_id)) do |response|
Rexpense::Entities::AttachmentCollection.build response
end
end
|
ruby
|
{
"resource": ""
}
|
q2978
|
Rexpense::Resources.Attachment.find_attachment
|
train
|
def find_attachment(resource_id, attachment_id)
http.get("#{attachment_endpoint(resource_id)}/#{attachment_id}") do |response|
Rexpense::Entities::Attachment.new response.parsed_body
end
end
|
ruby
|
{
"resource": ""
}
|
q2979
|
Rexpense::Resources.Comment.comments
|
train
|
def comments(resource_id)
http.get(comment_endpoint(resource_id)) do |response|
Rexpense::Entities::CommentCollection.build response
end
end
|
ruby
|
{
"resource": ""
}
|
q2980
|
Rexpense::Resources.Comment.find_comment
|
train
|
def find_comment(resource_id, comment_id)
http.get("#{comment_endpoint(resource_id)}/#{comment_id}") do |response|
Rexpense::Entities::Comment.new response.parsed_body
end
end
|
ruby
|
{
"resource": ""
}
|
q2981
|
Rexpense::Resources.Comment.create_comment
|
train
|
def create_comment(resource_id, params)
http.post(comment_endpoint(resource_id), body: params) do |response|
Rexpense::Entities::Comment.new response.parsed_body
end
end
|
ruby
|
{
"resource": ""
}
|
q2982
|
Rexpense::Resources.Comment.update_comment
|
train
|
def update_comment(resource_id, comment_id, params)
http.put("#{comment_endpoint(resource_id)}/#{comment_id}", body: params) do |response|
Rexpense::Entities::Comment.new response.parsed_body
end
end
|
ruby
|
{
"resource": ""
}
|
q2983
|
Enom.Domain.sync_auth_info
|
train
|
def sync_auth_info(options = {})
opts = {
"RunSynchAutoInfo" => 'True',
"EmailEPP" => 'True'
}
opts["EmailEPP"] = 'True' if options[:email]
Client.request({"Command" => "SynchAuthInfo", "SLD" => sld, "TLD" => tld}.merge(opts))
return self
end
|
ruby
|
{
"resource": ""
}
|
q2984
|
Enom.Domain.get_extended_domain_attributes
|
train
|
def get_extended_domain_attributes
sld, tld = name.split(".")
attributes = Client.request("Command" => "GetDomainInfo", "SLD" => sld, "TLD" => tld)["interface_response"]["GetDomainInfo"]
set_extended_domain_attributes(attributes)
end
|
ruby
|
{
"resource": ""
}
|
q2985
|
ActsAsRevisionable.RevisionRecord.restore
|
train
|
def restore
restore_class = self.revisionable_type.constantize
# Check if we have a type field, if yes, assume single table inheritance and restore the actual class instead of the stored base class
sti_type = self.revision_attributes[restore_class.inheritance_column]
if sti_type
begin
if !restore_class.store_full_sti_class && !sti_type.start_with?("::")
sti_type = "#{restore_class.parent.name}::#{sti_type}"
end
restore_class = sti_type.constantize
rescue NameError => e
raise e
# Seems our assumption was wrong and we have no STI
end
end
record = restore_class.new
restore_record(record, revision_attributes)
return record
end
|
ruby
|
{
"resource": ""
}
|
q2986
|
ActsAsRevisionable.RevisionRecord.restore_record
|
train
|
def restore_record(record, attributes)
primary_key = record.class.primary_key
primary_key = [primary_key].compact unless primary_key.is_a?(Array)
primary_key.each do |key|
record.send("#{key.to_s}=", attributes[key.to_s])
end
attrs, association_attrs = attributes_and_associations(record.class, attributes)
attrs.each_pair do |key, value|
begin
record.send("#{key}=", value)
rescue
record.errors.add(key.to_sym, "could not be restored to #{value.inspect}")
end
end
association_attrs.each_pair do |key, values|
restore_association(record, key, values) if values
end
# Check if the record already exists in the database and restore its state.
# This must be done last because otherwise associations on an existing record
# can be deleted when a revision is restored to memory.
exists = record.class.find(record.send(record.class.primary_key)) rescue nil
if exists
record.instance_variable_set(:@new_record, nil) if record.instance_variable_defined?(:@new_record)
# ActiveRecord 3.0.2 and 3.0.3 used @persisted instead of @new_record
record.instance_variable_set(:@persisted, true) if record.instance_variable_defined?(:@persisted)
end
end
|
ruby
|
{
"resource": ""
}
|
q2987
|
ShipCompliant.SearchSalesOrdersResult.parse!
|
train
|
def parse!
unless raw.has_key?(:sales_orders)
raw[:sales_orders] = {}
end
# force orders to be an array
orders = raw[:sales_orders].fetch(:sales_order_summary, {})
unless orders.kind_of?(Array)
raw[:sales_orders][:sales_order_summary] = [orders]
end
# typecast :count_more_sales_orders_available to integer
if raw.has_key?(:count_more_sales_orders_available)
convert_to_integer!(:count_more_sales_orders_available, raw)
end
# typecast :count_sales_orders_returned to integer
if raw.has_key?(:count_sales_orders_returned)
convert_to_integer!(:count_sales_orders_returned, raw)
end
raw[:sales_orders][:sales_order_summary].each do |summary|
# typecast :shipment_key to integer
if summary.fetch(:shipments, {}).fetch(:shipment_summary, {}).has_key?(:shipment_key)
convert_to_integer!(:shipment_key, summary[:shipments][:shipment_summary])
end
# typecast :zip1 to integer
if summary.fetch(:shipments, {}).fetch(:shipment_summary, {}).fetch(:ship_to, {}).has_key?(:zip1)
convert_to_integer!(:zip1, summary[:shipments][:shipment_summary][:ship_to])
end
end
end
|
ruby
|
{
"resource": ""
}
|
q2988
|
ShipCompliant.Client.call
|
train
|
def call(operation, locals = {})
locals['Security'] = ShipCompliant.configuration.credentials
response = savon_call(operation, message: {
'Request' => locals
})
get_result_from_response(operation, response)
end
|
ruby
|
{
"resource": ""
}
|
q2989
|
Elasticrawl.Job.confirm_message
|
train
|
def confirm_message
cluster = Cluster.new
case self.type
when 'Elasticrawl::ParseJob'
message = segment_list
else
message = []
end
message.push('Job configuration')
message.push(self.job_desc)
message.push('')
message.push(cluster.cluster_desc)
message.join("\n")
end
|
ruby
|
{
"resource": ""
}
|
q2990
|
Elasticrawl.Job.run_job_flow
|
train
|
def run_job_flow(emr_config)
cluster = Cluster.new
job_flow = cluster.create_job_flow(self, emr_config)
job_steps.each do |step|
job_flow.add_step(step.job_flow_step(job_config))
end
begin
job_flow.run
rescue StandardError => e
raise ElasticMapReduceAccessError, e.message
end
end
|
ruby
|
{
"resource": ""
}
|
q2991
|
Scruffy::Layers.Scatter.draw
|
train
|
def draw(svg, coords, options={})
options.merge!(@options)
if options[:shadow]
svg.g(:class => 'shadow', :transform => "translate(#{relative(0.5)}, #{relative(0.5)})") {
coords.each { |coord| svg.circle( :cx => coord.first, :cy => coord.last + relative(0.9), :r => relative(2),
:style => "stroke-width: #{relative(2)}; stroke: black; opacity: 0.35;" ) }
}
end
coords.each { |coord| svg.circle( :cx => coord.first, :cy => coord.last, :r => relative(2),
:style => "stroke-width: #{relative(2)}; stroke: #{color.to_s}; fill: #{color.to_s}" ) }
end
|
ruby
|
{
"resource": ""
}
|
q2992
|
Scruffy::Layers.Area.draw
|
train
|
def draw(svg, coords, options={})
# svg.polygon wants a long string of coords.
points_value = "0,#{height} #{stringify_coords(coords).join(' ')} #{width},#{height}"
# Experimental, for later user.
# This was supposed to add some fun filters, 3d effects and whatnot.
# Neither ImageMagick nor Mozilla SVG render this well (at all). Maybe a future thing.
#
# svg.defs {
# svg.filter(:id => 'MyFilter', :filterUnits => 'userSpaceOnUse', :x => 0, :y => 0, :width => 200, :height => '120') {
# svg.feGaussianBlur(:in => 'SourceAlpha', :stdDeviation => 4, :result => 'blur')
# svg.feOffset(:in => 'blur', :dx => 4, :dy => 4, :result => 'offsetBlur')
# svg.feSpecularLighting( :in => 'blur', :surfaceScale => 5, :specularConstant => '.75',
# :specularExponent => 20, 'lighting-color' => '#bbbbbb',
# :result => 'specOut') {
# svg.fePointLight(:x => '-5000', :y => '-10000', :z => '20000')
# }
#
# svg.feComposite(:in => 'specOut', :in2 => 'SourceAlpha', :operator => 'in', :result => 'specOut')
# svg.feComposite(:in => 'sourceGraphic', :in2 => 'specOut', :operator => 'arithmetic',
# :k1 => 0, :k2 => 1, :k3 => 1, :k4 => 0, :result => 'litPaint')
#
# svg.feMerge {
# svg.feMergeNode(:in => 'offsetBlur')
# svg.feMergeNode(:in => 'litPaint')
# }
# }
# }
svg.g(:transform => "translate(0, -#{relative(2)})") {
svg.polygon(:points => points_value, :style => "fill: black; stroke: black; fill-opacity: 0.06; stroke-opacity: 0.06;")
}
svg.polygon(:points => points_value, :fill => color.to_s, :stroke => color.to_s, 'style' => "opacity: #{opacity}")
end
|
ruby
|
{
"resource": ""
}
|
q2993
|
LandingPage.UsersController.create
|
train
|
def create
params.require(:user).permit!
user = User.new(params[:user])
if user.valid?
user.save
flash.now[:success] = t('landing_page.subscribed')
render :create
else
@user = user
render :new
end
end
|
ruby
|
{
"resource": ""
}
|
q2994
|
Travish.EnvironmentParser.build_environment_hash
|
train
|
def build_environment_hash
parsed_variables = {}
@env.each do |env_row|
# Each row can potentially contain multiple environment
# variables
variables = extract_variables(env_row)
variables.each do |variables_with_values|
variables_with_values.each do |key, value|
parsed_variables[key] = value
end
end
end
@override_envs.each do |env|
parsed_variables = parsed_variables.merge env
end
parsed_variables
end
|
ruby
|
{
"resource": ""
}
|
q2995
|
Travish.EnvironmentParser.extract_variables
|
train
|
def extract_variables(variable)
return [variable] if variable.is_a? Hash
return extract_variables_from_string(variable) if variable.is_a? String
[]
end
|
ruby
|
{
"resource": ""
}
|
q2996
|
Travish.EnvironmentParser.extract_variables_from_string
|
train
|
def extract_variables_from_string(string)
string.split(/ /).map do |defintion|
match = defintion.match STRING_REG_EX
next nil unless match
{ match[1] => match[2] }
end.reject(&:nil?)
end
|
ruby
|
{
"resource": ""
}
|
q2997
|
PoiseProfiler.Base._monkey_patch_old_chef!
|
train
|
def _monkey_patch_old_chef!
require 'chef/event_dispatch/dispatcher'
instance = self
orig_method = Chef::EventDispatch::Dispatcher.instance_method(:library_file_loaded)
Chef::EventDispatch::Dispatcher.send(:define_method, :library_file_loaded) do |filename|
instance.events = self
instance.monkey_patched = false
@subscribers |= [instance]
Chef::EventDispatch::Dispatcher.send(:define_method, :library_file_loaded, orig_method)
orig_method.bind(self).call(filename)
end
end
|
ruby
|
{
"resource": ""
}
|
q2998
|
Rango.Controller.rescue_http_error
|
train
|
def rescue_http_error(exception)
# we need to call it before we assign the variables
body = self.render_http_error(exception)
[exception.status, exception.headers, body]
end
|
ruby
|
{
"resource": ""
}
|
q2999
|
Tsuga::Service.Clusterer._build_clusters
|
train
|
def _build_clusters(tile)
used_ids = []
clusters = []
_adapter.in_tile(*tile.children).find_each do |child|
cluster = _adapter.build_from(tile.depth, child)
clusters << cluster
used_ids << child.id
end
return [used_ids, clusters]
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.