_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 30
4.3k
| 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',
|
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]
|
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
|
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)
|
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
|
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
|
ruby
|
{
"resource": ""
}
|
q2906
|
Faalis.RouteHelpers.localized_scope
|
train
|
def localized_scope
langs = ::I18n.available_locales.join('|')
scope '(:locale)', locale:
|
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
|
ruby
|
{
"resource": ""
}
|
q2908
|
Configurations.Configuration.to_h
|
train
|
def to_h
@data.reduce({}) do |h, (k, v)|
h[k] = v.is_a?(__class__)
|
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)
|
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
|
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}"
|
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
|
ruby
|
{
"resource": ""
}
|
q2913
|
Representative.Nokogiri.comment
|
train
|
def comment(text)
comment_node = ::Nokogiri::XML::Comment.new(doc, " #{text} ")
|
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
|
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 }]
|
ruby
|
{
"resource": ""
}
|
q2916
|
Opulent.Parser.attributes
|
train
|
def attributes(atts = {}, for_definition = false)
wrapped_attributes
|
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
|
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,
|
ruby
|
{
"resource": ""
}
|
q2919
|
Opulent.Parser.extend_attributes
|
train
|
def extend_attributes
return unless accept :extend_attributes
unescaped = accept :unescaped_value
|
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) ||
|
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]}"
|
ruby
|
{
"resource": ""
}
|
q2922
|
Configurations.Arbitrary.respond_to_missing?
|
train
|
def respond_to_missing?(method, include_private = false)
__respond_to_writer?(method) ||
|
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
|
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
|
ruby
|
{
"resource": ""
}
|
q2925
|
Opulent.Parser.indent_lines
|
train
|
def indent_lines(text, indent)
text ||= ''
text.lines.map {
|
ruby
|
{
"resource": ""
}
|
q2926
|
RedboothRuby.Client.perform!
|
train
|
def perform!(resource_name, action, options = {})
ClientOperations::Perform.new(resource_name,
|
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?
|
ruby
|
{
"resource": ""
}
|
q2928
|
RedboothRuby.File.download
|
train
|
def download(style='original', path=nil)
options = { session: session }
options[:download_path] = path unless path.nil?
request
|
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?
|
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
|
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
|
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]
|
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?
|
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 =
|
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)
|
ruby
|
{
"resource": ""
}
|
q2936
|
Configurations.Strict.__assign!
|
train
|
def __assign!(property, value)
@types.test!(@path.add(property), value)
v = @blocks.evaluate!(@path.add(property), value)
|
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
|
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)
|
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
|
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
|
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
|
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))
|
ruby
|
{
"resource": ""
}
|
q2943
|
Opulent.Parser.symbol
|
train
|
def symbol
return unless (colon = accept :colon)
return undo colon if lookahead(:whitespace)
if (exp = expression).nil?
|
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
|
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
|
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
|
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
|
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]
|
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
|
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
|
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 '>'
#
|
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
|
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)
|
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
|
ruby
|
{
"resource": ""
}
|
q2955
|
Rack.Ajax.encode_env
|
train
|
def encode_env(env)
env = env.dup
env.keep_if { |k, v| k =~ /[A-Z]/ }
|
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
|
ruby
|
{
"resource": ""
}
|
q2957
|
ChefHelpers.HasSource.has_source?
|
train
|
def has_source?(source, segment, cookbook=nil)
cookbook ||= cookbook_name
begin
run_context.cookbook_collection[cookbook].
|
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)
|
ruby
|
{
"resource": ""
}
|
q2959
|
Opulent.Context.evaluate
|
train
|
def evaluate(code, &block)
begin
eval code, @binding, &block
rescue NameError => variable
|
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
|
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
|
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]
|
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)
|
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
|
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 },
[],
|
ruby
|
{
"resource": ""
}
|
q2966
|
Polipus.Robotex.delay!
|
train
|
def delay!(uri)
delay = delay(uri)
sleep delay - (Time.now - @last_accessed)
|
ruby
|
{
"resource": ""
}
|
q2967
|
Faalis.DashboardHelper.get_url
|
train
|
def get_url(route_name, id = nil, engine = Rails.application)
|
ruby
|
{
"resource": ""
}
|
q2968
|
WardenStrategies.Simple.authenticate!
|
train
|
def authenticate!
if u = user_class.send(config[:authenticate_method], *required_param_values)
|
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?
|
ruby
|
{
"resource": ""
}
|
q2970
|
Charging.Invoice.payments
|
train
|
def payments
reset_errors!
response = Http.get("/invoices/#{uuid}/payments/", domain.token)
|
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 !=
|
ruby
|
{
"resource": ""
}
|
q2972
|
Rexpense::Resources.Participant.participants
|
train
|
def participants(resource_id)
http.get(participants_endpoint(resource_id)) do |response|
|
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
|
ruby
|
{
"resource": ""
}
|
q2974
|
Rexpense::Resources.Membership.memberships
|
train
|
def memberships(organization_id)
http.get(membership_endpoint(organization_id)) do |response|
|
ruby
|
{
"resource": ""
}
|
q2975
|
Rexpense::Resources.Membership.create_membership
|
train
|
def create_membership(organization_id, params)
http.post(membership_endpoint(organization_id),
|
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|
|
ruby
|
{
"resource": ""
}
|
q2977
|
Rexpense::Resources.Attachment.attachments
|
train
|
def attachments(resource_id)
http.get(attachment_endpoint(resource_id)) do |response|
|
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|
|
ruby
|
{
"resource": ""
}
|
q2979
|
Rexpense::Resources.Comment.comments
|
train
|
def comments(resource_id)
http.get(comment_endpoint(resource_id)) do |response|
|
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|
|
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|
|
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|
|
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]
|
ruby
|
{
"resource": ""
}
|
q2984
|
Enom.Domain.get_extended_domain_attributes
|
train
|
def get_extended_domain_attributes
sld, tld = name.split(".")
attributes = Client.request("Command"
|
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
|
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
|
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,
|
ruby
|
{
"resource": ""
}
|
q2988
|
ShipCompliant.Client.call
|
train
|
def call(operation, locals = {})
locals['Security'] = ShipCompliant.configuration.credentials
response = savon_call(operation, message: {
|
ruby
|
{
"resource": ""
}
|
q2989
|
Elasticrawl.Job.confirm_message
|
train
|
def confirm_message
cluster = Cluster.new
case self.type
when 'Elasticrawl::ParseJob'
message = segment_list
else
|
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|
|
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;" ) }
}
|
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
|
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')
|
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|
|
ruby
|
{
"resource": ""
}
|
q2995
|
Travish.EnvironmentParser.extract_variables
|
train
|
def extract_variables(variable)
return [variable] if variable.is_a?
|
ruby
|
{
"resource": ""
}
|
q2996
|
Travish.EnvironmentParser.extract_variables_from_string
|
train
|
def extract_variables_from_string(string)
string.split(/ /).map do |defintion|
|
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
|
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 =
|
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)
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.