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
|
---|---|---|---|---|---|
019e3fc84506c562c0b6b02ce592760383abcb5b | 3,027 | require_relative 'matlab_clone/version'
module MatlabClone
require_relative 'matlabclone_class'
require 'colorize'
include Hassan
test = MatLabclone.new
puts '...........................................................'.yellow
puts '| |'.yellow
puts '| Welcome to MatLab Clone developed by Hassan Oyeboade |'.yellow
puts '| Andela Fellow Class XIII Bootcamp Project |'.yellow
puts '| Done between 15/02/2016-26/02/2015 |'.yellow
puts '| |'.yellow
puts '|.........................................................|'.yellow
run = true
while run
puts 'Enter 1 to create an array'
puts 'Enter 2 to create a matrix'
puts 'Enter 3 to create a x-by-y vector of zero'
puts 'Enter 4 to add a matrix and a number'
puts 'Enter 5 to transpose a matrix'
puts 'Enter 6 to find the inverse of a matrix'
puts 'Enter 7 to concatenate matrixes'
puts 'Enter 8 to save to file'
puts 'Enter 9 to load from file'
puts 'Enter 10 to exit'
input = gets.chomp
case input
when '1'
puts 'Enter array to be created in the following format x y z'
print 'a = '
array = gets.chomp
test.create_arr(array)
when '2'
puts 'Enter matrix to be created in the following format a b c;e f g;h i j'
print 'a = '
matrix = gets.chomp
test.create_mat(matrix)
when '3'
puts 'Enter the value of x: number of rows'
print 'rows = '
rows = gets.chomp
puts 'Enter the value of y: number of columns'
print 'columns = '
columns = gets.chomp
test.zeros(rows, columns)
when '4'
puts 'Enter the matrix. Must follow the format a b c;d e f;g h i'
print 'a = '
matrix = gets.chomp
puts 'Enter the number you want to add to the matrix'
print 'number = '
number = gets.chomp
test.add(matrix, number)
when '5'
puts 'Enter the matrix to be transposed.'
matrix = gets.chomp
test.transpose(matrix)
when '6'
puts 'Enter the matrix to be inversed.'
matrix = gets.chomp
test.inverse(matrix)
when '7'
print "Enter first matrix to be concatenated.\nmatrix a = "
mata = gets.chomp
print "Enter second matrix to be concatenated. \nmatrix b = "
matb = gets.chomp
puts 'Please supply the type of concatenation(, or ;). , is for horizontal '
print "concatenation and ; is for vertical concatenation.\noperation = "
operator = gets.chomp
test.concat(mata, matb, operator)
when '8'
puts 'Use this command to save: save > filename.mat'
puts 'If file exist initially, new content will be appended to file'
input = gets.chomp
test.save(input)
when '9'
puts 'Use this command to load file: load filename.mat'
input = gets.chomp
test.load(input)
when '10'
puts 'Thank you for making use of MatLabclone. See you next time'.green
run = false
else
puts 'Enter a valid number. Number must be between 1 and 10'.red
end
end
end
| 32.202128 | 80 | 0.6148 |
21bd1856c46b4a25026096ee0754d62d9efa2825 | 532 | class IqQueryStanza
def initialize(params = {})
@doc = Nokogiri::XML::Document.new
@iq = Nokogiri::XML::Node.new("iq", @doc)
@iq["type"] = params[:type].to_s
@iq["to"] = Superfeedr.conf[:superfeedr_jid]
@iq["id"] = "#{random_iq_id}"
@iq["from"] = params[:from] if params[:from]
end
def type
@iq["type"]
end
def to
@iq["to"]
end
def from
@iq["from"]
end
def id
@iq["id"]
end
def random_iq_id
rand(1000)
end
def to_s
@iq.to_s
end
end | 14.777778 | 48 | 0.539474 |
7a688530917e1a54f57cc9807c592c72c5b12bbb | 1,114 | class KitchenSync < Formula
desc "Fast efficiently sync database without dumping & reloading"
homepage "https://github.com/willbryant/kitchen_sync"
url "https://github.com/willbryant/kitchen_sync/archive/0.38.tar.gz"
sha256 "786bf30caca4e58347c0880dc1ca54685cd01d0834024c425029fb5466c96041"
head "https://github.com/willbryant/kitchen_sync.git"
bottle do
cellar :any
sha256 "3e51f0cdeefc74a5d3c87f9dd701c07adff75323ffd90a15424f21a3666d2ea0" => :yosemite
sha256 "da57b940d500ded730b4d9defaa197dab1c2e5e59b14cab5209243b21c7ff9ac" => :mavericks
sha256 "c7fd76c7ef6eef65ef0dbc69bc3063accf1f0262ebce4a5b8eb8fdc3f3515cb8" => :mountain_lion
end
depends_on "cmake" => :build
depends_on "boost"
depends_on :mysql => :recommended
depends_on :postgresql => :optional
needs :cxx11
def install
ENV.cxx11
system "cmake", ".", *std_cmake_args
system "make", "install"
end
test do
assert File.exist?("#{bin}/ks")
assert File.exist?("#{bin}/ks_mysql") if build.with? "mysql"
assert File.exist?("#{bin}/ks_postgresql") if build.with? "postgresql"
end
end
| 32.764706 | 95 | 0.750449 |
d58d43b83aeada05d70b818b5039e8794dbdf91f | 146 | # This is an example of a good cronotab for tests
class TestJob
def perform
puts 'Test!'
end
end
Crono.perform(TestJob).every 5.seconds
| 14.6 | 49 | 0.726027 |
fff5864b2b6b38fb8767fd9fe40639c9dfd20117 | 156 | # encoding: utf-8
BUILD_INFO = {"build_date"=>"2016-12-06T13:17:53+00:00", "build_sha"=>"aa36c4f4b702c6d379e5a97c22627933bca04f68", "build_snapshot"=>false} | 78 | 138 | 0.762821 |
26da3a5dfbc159719fdc62b2296f2881a4266766 | 1,865 | require 'logger'
require 'logstash-event'
module LogStasher
class << self
attr_reader :append_fields_callback
attr_writer :enabled
attr_writer :include_parameters
attr_writer :serialize_parameters
attr_writer :silence_standard_logging
attr_accessor :metadata
def append_fields(&block)
@append_fields_callback = block
end
def enabled?
if @enabled.nil?
@enabled = false
end
@enabled
end
def include_parameters?
if @include_parameters.nil?
@include_parameters = true
end
@include_parameters
end
def serialize_parameters?
if @serialize_parameters.nil?
@serialize_parameters = true
end
@serialize_parameters
end
def initialize_logger(device = $stdout, level = ::Logger::INFO)
::Logger.new(device).tap do |new_logger|
new_logger.level = level
end
end
def log_as_json(payload, as_logstash_event: false)
payload = payload.dup
payload.merge!(:metadata => metadata) if !metadata&.empty? && payload.is_a?(::Hash)
# Wrap the hash in a logstash event if the caller wishes for a specific
# formatting applied to the hash. This is used by log subscriber, for
# example.
json_payload = if as_logstash_event
::LogStash::Event.new(payload).to_json
else
payload.to_json
end
logger << json_payload + $INPUT_RECORD_SEPARATOR
end
def logger
@logger ||= initialize_logger
end
def logger=(log)
@logger = log
end
def silence_standard_logging?
if @silence_standard_logging.nil?
@silence_standard_logging = false
end
@silence_standard_logging
end
end
end
require 'logstasher/railtie' if defined?(Rails)
| 22.743902 | 89 | 0.639142 |
6a76d80c47b0fd59dc8446ce7e6766ff25145d38 | 7,442 | require 'concurrent/map'
require 'active_support/core_ext/module/remove_method'
require 'active_support/core_ext/module/attribute_accessors'
require 'action_view/template/resolver'
module ActionView
# = Action View Lookup Context
#
# <tt>LookupContext</tt> is the object responsible for holding all information
# required for looking up templates, i.e. view paths and details.
# <tt>LookupContext</tt> is also responsible for generating a key, given to
# view paths, used in the resolver cache lookup. Since this key is generated
# only once during the request, it speeds up all cache accesses.
class LookupContext #:nodoc:
attr_accessor :prefixes, :rendered_format
mattr_accessor :fallbacks
@@fallbacks = FallbackFileSystemResolver.instances
mattr_accessor :registered_details
self.registered_details = []
def self.register_detail(name, &block)
self.registered_details << name
initialize = registered_details.map { |n| "@details[:#{n}] = details[:#{n}] || default_#{n}" }
Accessors.send :define_method, :"default_#{name}", &block
Accessors.module_eval <<-METHOD, __FILE__, __LINE__ + 1
def #{name}
@details.fetch(:#{name}, [])
end
def #{name}=(value)
value = value.present? ? Array(value) : default_#{name}
_set_detail(:#{name}, value) if value != @details[:#{name}]
end
remove_possible_method :initialize_details
def initialize_details(details)
#{initialize.join("\n")}
end
METHOD
end
# Holds accessors for the registered details.
module Accessors #:nodoc:
end
register_detail(:locale) do
locales = [I18n.locale]
locales.concat(I18n.fallbacks[I18n.locale]) if I18n.respond_to? :fallbacks
locales << I18n.default_locale
locales.uniq!
locales
end
register_detail(:formats) { ActionView::Base.default_formats || [:html, :text, :js, :css, :xml, :json] }
register_detail(:variants) { [] }
register_detail(:handlers) { Template::Handlers.extensions }
class DetailsKey #:nodoc:
alias :eql? :equal?
alias :object_hash :hash
attr_reader :hash
@details_keys = Concurrent::Map.new
def self.get(details)
if details[:formats]
details = details.dup
details[:formats] &= Template::Types.symbols
end
@details_keys[details] ||= new
end
def self.clear
@details_keys.clear
end
def initialize
@hash = object_hash
end
end
# Add caching behavior on top of Details.
module DetailsCache
attr_accessor :cache
# Calculate the details key. Remove the handlers from calculation to improve performance
# since the user cannot modify it explicitly.
def details_key #:nodoc:
@details_key ||= DetailsKey.get(@details) if @cache
end
# Temporary skip passing the details_key forward.
def disable_cache
old_value, @cache = @cache, false
yield
ensure
@cache = old_value
end
protected
def _set_detail(key, value)
@details = @details.dup if @details_key
@details_key = nil
@details[key] = value
end
end
# Helpers related to template lookup using the lookup context information.
module ViewPaths
attr_reader :view_paths, :html_fallback_for_js
# Whenever setting view paths, makes a copy so that we can manipulate them in
# instance objects as we wish.
def view_paths=(paths)
@view_paths = ActionView::PathSet.new(Array(paths))
end
def find(name, prefixes = [], partial = false, keys = [], options = {})
@view_paths.find(*args_for_lookup(name, prefixes, partial, keys, options))
end
alias :find_template :find
def find_file(name, prefixes = [], partial = false, keys = [], options = {})
@view_paths.find_file(*args_for_lookup(name, prefixes, partial, keys, options))
end
def find_all(name, prefixes = [], partial = false, keys = [], options = {})
@view_paths.find_all(*args_for_lookup(name, prefixes, partial, keys, options))
end
def exists?(name, prefixes = [], partial = false, keys = [], **options)
@view_paths.exists?(*args_for_lookup(name, prefixes, partial, keys, options))
end
alias :template_exists? :exists?
# Adds fallbacks to the view paths. Useful in cases when you are rendering
# a :file.
def with_fallbacks
added_resolvers = 0
self.class.fallbacks.each do |resolver|
next if view_paths.include?(resolver)
view_paths.push(resolver)
added_resolvers += 1
end
yield
ensure
added_resolvers.times { view_paths.pop }
end
protected
def args_for_lookup(name, prefixes, partial, keys, details_options) #:nodoc:
name, prefixes = normalize_name(name, prefixes)
details, details_key = detail_args_for(details_options)
[name, prefixes, partial || false, details, details_key, keys]
end
# Compute details hash and key according to user options (e.g. passed from #render).
def detail_args_for(options)
return @details, details_key if options.empty? # most common path.
user_details = @details.merge(options)
if @cache
details_key = DetailsKey.get(user_details)
else
details_key = nil
end
[user_details, details_key]
end
# Support legacy foo.erb names even though we now ignore .erb
# as well as incorrectly putting part of the path in the template
# name instead of the prefix.
def normalize_name(name, prefixes) #:nodoc:
prefixes = prefixes.presence
parts = name.to_s.split('/'.freeze)
parts.shift if parts.first.empty?
name = parts.pop
return name, prefixes || [""] if parts.empty?
parts = parts.join('/'.freeze)
prefixes = prefixes ? prefixes.map { |p| "#{p}/#{parts}" } : [parts]
return name, prefixes
end
end
include Accessors
include DetailsCache
include ViewPaths
def initialize(view_paths, details = {}, prefixes = [])
@details, @details_key = {}, nil
@cache = true
@prefixes = prefixes
@rendered_format = nil
self.view_paths = view_paths
initialize_details(details)
end
# Override formats= to expand ["*/*"] values and automatically
# add :html as fallback to :js.
def formats=(values)
if values
values.concat(default_formats) if values.delete "*/*".freeze
if values == [:js]
values << :html
@html_fallback_for_js = true
end
end
super(values)
end
# Override locale to return a symbol instead of array.
def locale
@details[:locale].first
end
# Overload locale= to also set the I18n.locale. If the current I18n.config object responds
# to original_config, it means that it has a copy of the original I18n configuration and it's
# acting as proxy, which we need to skip.
def locale=(value)
if value
config = I18n.config.respond_to?(:original_config) ? I18n.config.original_config : I18n.config
config.locale = value
end
super(default_locale)
end
end
end
| 31.268908 | 109 | 0.639076 |
332944d11b7251f93929479e69ec6d60059004c8 | 2,960 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2019_12_01
module Models
#
# Rewrite rule of an application gateway.
#
class ApplicationGatewayRewriteRule
include MsRestAzure
# @return [String] Name of the rewrite rule that is unique within an
# Application Gateway.
attr_accessor :name
# @return [Integer] Rule Sequence of the rewrite rule that determines the
# order of execution of a particular rule in a RewriteRuleSet.
attr_accessor :rule_sequence
# @return [Array<ApplicationGatewayRewriteRuleCondition>] Conditions
# based on which the action set execution will be evaluated.
attr_accessor :conditions
# @return [ApplicationGatewayRewriteRuleActionSet] Set of actions to be
# done as part of the rewrite Rule.
attr_accessor :action_set
#
# Mapper for ApplicationGatewayRewriteRule class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ApplicationGatewayRewriteRule',
type: {
name: 'Composite',
class_name: 'ApplicationGatewayRewriteRule',
model_properties: {
name: {
client_side_validation: true,
required: false,
serialized_name: 'name',
type: {
name: 'String'
}
},
rule_sequence: {
client_side_validation: true,
required: false,
serialized_name: 'ruleSequence',
type: {
name: 'Number'
}
},
conditions: {
client_side_validation: true,
required: false,
serialized_name: 'conditions',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ApplicationGatewayRewriteRuleConditionElementType',
type: {
name: 'Composite',
class_name: 'ApplicationGatewayRewriteRuleCondition'
}
}
}
},
action_set: {
client_side_validation: true,
required: false,
serialized_name: 'actionSet',
type: {
name: 'Composite',
class_name: 'ApplicationGatewayRewriteRuleActionSet'
}
}
}
}
}
end
end
end
end
| 31.489362 | 91 | 0.528716 |
bf75e4fcafd6ee0b1bc1036d7f4d6dbb98aad1c6 | 1,989 | #
# Copyright (c) 2014 Constant Contact
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
module JenkinsPipelineBuilder
module CLI
class List < Thor
JenkinsPipelineBuilder.registry.entries.keys.each do |entry|
desc entry, "List all #{entry}"
define_method(entry) do
entries = JenkinsPipelineBuilder.registry.registry[:job][entry]
entries.each do |name, set|
ext = set.extensions.first
display_module(name, ext)
end
end
end
desc 'job_attributes', 'List all job attributes'
def job_attributes
entries = JenkinsPipelineBuilder.registry.registry[:job]
entries.each do |name, set|
next unless set.is_a? ExtensionSet
ext = set.extensions.first
display_module(name, ext)
end
end
private
def display_module(name, ext)
puts "#{name}: Jenkins Name: #{ext.jenkins_name}"
end
end
end
end
| 36.163636 | 79 | 0.703369 |
26bdabfbac898051f6f2bbe5602e5e5e86217997 | 12,980 | # frozen_string_literal: true
require 'test_helper'
# was the web request successful?
# was the user redirected to the right page?
# was the user successfully authenticated?
# was the correct object stored in the response?
# was the appropriate message delivered in the json payload?
class OmniauthTest < ActionDispatch::IntegrationTest
setup do
OmniAuth.config.test_mode = true
end
before do
@redirect_url = 'http://ng-token-auth.dev/'
end
def get_parsed_data_json
encoded_json_data = @response.body.match(/var data \= JSON.parse\(decodeURIComponent\(\'(.+)\'\)\)\;/)[1]
JSON.parse(URI.unescape(encoded_json_data))
end
describe 'success callback' do
setup do
OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new(
provider: 'facebook',
uid: '123545',
info: {
name: 'chong',
email: '[email protected]'
}
)
end
test 'request should pass correct redirect_url' do
get_success
assert_equal @redirect_url,
controller.send(:omniauth_params)['auth_origin_url']
end
test 'user should have been created' do
get_success
assert @resource
end
test 'user should be assigned info from provider' do
get_success
assert_equal '[email protected]', @resource.email
end
test 'user should be assigned token' do
get_success
client_id = controller.auth_params[:client_id]
token = controller.auth_params[:auth_token]
expiry = controller.auth_params[:expiry]
# the expiry should have been set
assert_equal expiry, @resource.tokens[client_id]['expiry'] || @resource.tokens[client_id][:expiry]
# the token sent down to the client should now be valid
assert @resource.valid_token?(token, client_id)
end
test 'session vars have been cleared' do
get_success
refute request.session['dta.omniauth.auth']
refute request.session['dta.omniauth.params']
end
test 'sign_in was called' do
DeviseTokenAuth::OmniauthCallbacksController.any_instance\
.expects(:sign_in).with(
:user, instance_of(User), has_entries(store: false, bypass: false)
)
get_success
end
test 'should be redirected via valid url' do
get_success
assert_equal 'http://www.example.com/auth/facebook/callback',
request.original_url
end
describe 'with default user model' do
before do
get_success
end
test 'request should determine the correct user_resource_class' do
assert_equal 'User', controller.send(:omniauth_params)['user_resource_class']
end
test 'user should be of the correct class' do
assert_equal User, @resource.class
end
end
describe 'with alternate user model' do
before do
get '/mangs/facebook',
params: {
auth_origin_url: @redirect_url,
omniauth_window_type: 'newWindow'
}
follow_all_redirects!
assert_equal 200, response.status
@resource = assigns(:resource)
end
test 'request should determine the correct user_resource_class' do
assert_equal 'Mang', controller.send(:omniauth_params)['user_resource_class']
end
test 'user should be of the correct class' do
assert_equal Mang, @resource.class
end
end
describe 'pass additional params' do
before do
@fav_color = 'alizarin crimson'
@unpermitted_param = 'M. Bison'
get '/auth/facebook',
params: { auth_origin_url: @redirect_url,
favorite_color: @fav_color,
name: @unpermitted_param,
omniauth_window_type: 'newWindow' }
follow_all_redirects!
@resource = assigns(:resource)
end
test 'status shows success' do
assert_equal 200, response.status
end
test 'additional attribute was passed' do
assert_equal @fav_color, @resource.favorite_color
end
test 'non-whitelisted attributes are ignored' do
refute_equal @unpermitted_param, @resource.name
end
end
describe 'oauth registration attr' do
after do
User.any_instance.unstub(:new_record?)
end
describe 'with new user' do
before do
User.any_instance.expects(:new_record?).returns(true).at_least_once
# https://docs.mongodb.com/mongoid/master/tutorials/mongoid-documents/#notes-on-persistence
User.any_instance.expects(:save!).returns(true)
end
test 'response contains oauth_registration attr' do
get '/auth/facebook',
params: { auth_origin_url: @redirect_url,
omniauth_window_type: 'newWindow' }
follow_all_redirects!
assert_equal true, controller.auth_params[:oauth_registration]
end
end
describe 'with existing user' do
before do
User.any_instance.expects(:new_record?).returns(false).at_least_once
end
test 'response does not contain oauth_registration attr' do
get '/auth/facebook',
params: { auth_origin_url: @redirect_url,
omniauth_window_type: 'newWindow' }
follow_all_redirects!
assert_equal false, controller.auth_params.key?(:oauth_registration)
end
end
end
describe 'using namespaces' do
before do
get '/api/v1/auth/facebook',
params: { auth_origin_url: @redirect_url,
omniauth_window_type: 'newWindow' }
follow_all_redirects!
@resource = assigns(:resource)
end
test 'request is successful' do
assert_equal 200, response.status
end
test 'user should have been created' do
assert @resource
end
test 'user should be of the correct class' do
assert_equal User, @resource.class
end
end
describe 'with omniauth_window_type=inAppBrowser' do
test 'response contains all expected data' do
get_success(omniauth_window_type: 'inAppBrowser')
assert_expected_data_in_new_window
end
end
describe 'with omniauth_window_type=newWindow' do
test 'response contains all expected data' do
get_success(omniauth_window_type: 'newWindow')
assert_expected_data_in_new_window
end
end
def assert_expected_data_in_new_window
data = get_parsed_data_json
expected_data = @resource.as_json.merge(controller.auth_params.as_json)
expected_data = ActiveSupport::JSON.decode(expected_data.to_json)
assert_equal(expected_data.merge('message' => 'deliverCredentials'), data)
end
describe 'with omniauth_window_type=sameWindow' do
test 'redirects to auth_origin_url with all expected query params' do
get '/auth/facebook',
params: { auth_origin_url: '/auth_origin',
omniauth_window_type: 'sameWindow' }
follow_all_redirects!
assert_equal 200, response.status
# We have been forwarded to a url with all the expected
# data in the query params.
# Assert that a uid was passed along. We have to assume
# that the rest of the values were as well, as we don't
# have access to @resource in this test anymore
assert(controller.params['uid'], 'No uid found')
# check that all the auth stuff is there
%i[auth_token client_id uid expiry config].each do |key|
assert(controller.params.key?(key), "No value for #{key.inspect}")
end
end
end
def get_success(params = {})
get '/auth/facebook',
params: {
auth_origin_url: @redirect_url,
omniauth_window_type: 'newWindow'
}.merge(params)
follow_all_redirects!
assert_equal 200, response.status
@resource = assigns(:resource)
end
end
describe 'failure callback' do
setup do
OmniAuth.config.mock_auth[:facebook] = :invalid_credentials
OmniAuth.config.on_failure = proc { |env|
OmniAuth::FailureEndpoint.new(env).redirect_to_failure
}
end
test 'renders expected data' do
silence_omniauth do
get '/auth/facebook',
params: { auth_origin_url: @redirect_url,
omniauth_window_type: 'newWindow' }
follow_all_redirects!
end
assert_equal 200, response.status
data = get_parsed_data_json
assert_equal({ 'error' => 'invalid_credentials', 'message' => 'authFailure' }, data)
end
test 'renders something with no auth_origin_url' do
silence_omniauth do
get '/auth/facebook'
follow_all_redirects!
end
assert_equal 200, response.status
assert_select 'body', 'invalid_credentials'
end
end
describe 'User with only :database_authenticatable and :registerable included' do
test 'OnlyEmailUser should not be able to use OAuth' do
assert_raises(ActionController::RoutingError) do
get '/only_email_auth/facebook',
params: { auth_origin_url: @redirect_url }
follow_all_redirects!
end
end
end
describe 'Using redirect_whitelist' do
describe "newWindow" do
before do
@user_email = '[email protected]'
OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new(
provider: 'facebook',
uid: '123545',
info: {
name: 'chong',
email: @user_email
}
)
@good_redirect_url = Faker::Internet.url
@bad_redirect_url = Faker::Internet.url
DeviseTokenAuth.redirect_whitelist = [@good_redirect_url]
end
teardown do
DeviseTokenAuth.redirect_whitelist = nil
end
test 'request using non-whitelisted redirect fail' do
get '/auth/facebook',
params: { auth_origin_url: @bad_redirect_url,
omniauth_window_type: 'newWindow' }
follow_all_redirects!
data = get_parsed_data_json
assert_equal "Redirect to '#{@bad_redirect_url}' not allowed.",
data['error']
end
test 'request to whitelisted redirect should succeed' do
get '/auth/facebook',
params: {
auth_origin_url: @good_redirect_url,
omniauth_window_type: 'newWindow'
}
follow_all_redirects!
data = get_parsed_data_json
assert_equal @user_email, data['email']
end
test 'should support wildcards' do
DeviseTokenAuth.redirect_whitelist = ["#{@good_redirect_url[0..8]}*"]
get '/auth/facebook',
params: { auth_origin_url: @good_redirect_url,
omniauth_window_type: 'newWindow' }
follow_all_redirects!
data = get_parsed_data_json
assert_equal @user_email, data['email']
end
end
describe "sameWindow" do
before do
@user_email = '[email protected]'
OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new(
provider: 'facebook',
uid: '123545',
info: {
name: 'chong',
email: @user_email
}
)
@good_redirect_url = '/auth_origin'
@bad_redirect_url = Faker::Internet.url
DeviseTokenAuth.redirect_whitelist = [@good_redirect_url]
end
teardown do
DeviseTokenAuth.redirect_whitelist = nil
end
test 'request using non-whitelisted redirect fail' do
get '/auth/facebook',
params: { auth_origin_url: @bad_redirect_url,
omniauth_window_type: 'sameWindow' }
follow_all_redirects!
assert_equal 200, response.status
assert_equal true, response.body.include?("Redirect to '#{@bad_redirect_url}' not allowed")
end
test 'request to whitelisted redirect should succeed' do
get '/auth/facebook',
params: {
auth_origin_url: '/auth_origin',
omniauth_window_type: 'sameWindow'
}
follow_all_redirects!
assert_equal 200, response.status
assert_equal false, response.body.include?("Redirect to '#{@good_redirect_url}' not allowed")
end
test 'should support wildcards' do
DeviseTokenAuth.redirect_whitelist = ["#{@good_redirect_url[0..8]}*"]
get '/auth/facebook',
params: {
auth_origin_url: '/auth_origin',
omniauth_window_type: 'sameWindow'
}
follow_all_redirects!
assert_equal 200, response.status
assert_equal false, response.body.include?("Redirect to '#{@good_redirect_url}' not allowed")
end
end
end
end
| 29.366516 | 109 | 0.631279 |
79e5a028ed33e36596bf5daaf29e3554403f0b1e | 2,481 | #
# = strrand.rb: Generates a random string from a pattern
#
# Author:: tama <[email protected]>
#
# (Stripped down to only relevant methods)
class StringRandom
Upper = Array('A'..'Z')
Lower = Array('a'..'z')
Digit = Array('0'..'9')
Punct = [33..47, 58..64, 91..96, 123..126].map { |r| r.map { |val| val.chr } }.flatten
Any = Upper | Lower | Digit | Punct
Salt = Upper | Lower | Digit | ['.', '/']
Binary = (0..255).map { |val| val.chr }
# These are the regex-based patterns.
Pattern = {
# These are the regex-equivalents.
'.' => Any,
'\d' => Digit,
'\D' => Upper | Lower | Punct,
'\w' => Upper | Lower | Digit | ['_'],
'\W' => Punct.reject { |val| val == '_' },
'\s' => [' ', "\t"],
'\S' => Upper | Lower | Digit | Punct,
# These are translated to their double quoted equivalents.
'\t' => ["\t"],
'\n' => ["\n"],
'\r' => ["\r"],
'\f' => ["\f"],
'\a' => ["\a"],
'\e' => ["\e"]
}
# These are the old patterns for random_pattern.
OldPattern = {
'C' => Upper,
'c' => Lower,
'n' => Digit,
'!' => Punct,
'.' => Any,
's' => Salt,
'b' => Binary
}
#
# Singleton method version of random_regex.
#
def self.random_regex(pattern)
StringRandom.new.random_regex(pattern)
end
#
# _max_ is default length for creating random string
#
def initialize(max = 10)
@max = max
@map = OldPattern.clone
@regch = {
'[' => method(:regch_bracket),
}
end
def random_regex(pattern)
_random_regex(pattern)
end
private
def _random_regex(pattern)
string = []
chars = pattern.split(//)
non_ch = /[\$\^\*\(\)\+\{\}\]\?]/ # not supported chars
while ch = chars.shift
if @regch.has_key?(ch)
@regch[ch].call(ch, chars, string)
else
warn "'#{ch}' not implemented. treating literally." if ch =~ non_ch
string << [ch]
end
end
result = ''
string.each do |ch|
result << ch[rand(ch.size)]
end
result
end
def regch_bracket(ch, chars, string)
tmp = []
while ch = chars.shift and ch != ']'
if ch == '-' and !chars.empty? and !tmp.empty?
max = chars.shift
min = tmp.last
tmp << min = min.succ while min < max
else
warn "${ch}' will be treated literally inside []" if ch =~ /\W/
tmp << ch
end
end
raise 'unmatched []' if ch != ']'
string << tmp
end
end
| 22.351351 | 89 | 0.516727 |
331e4470238f68eb8132fee1f4819c33c37669d5 | 4,534 | require 'rails/generators/resource_helpers'
module Butler
class AdminScaffoldGenerator < Rails::Generators::NamedBase
include Rails::Generators::ResourceHelpers
source_root File.expand_path('../templates', __FILE__)
class_option :orm, banner: 'NAME', type: :string, required: true
class_option :prefix_name, banner: 'admin', type: :string, default: 'admin'
class_option :parent_controller, banner: 'admin', type: :string, default: 'admin'
argument :attributes, type: :array, default: [], banner: 'field:type field:type'
def create_ressource_model
invoke 'active_record:model' unless model_exists? && behavior == :invoke
end
def create_admin_controller
template 'admin_controller_generator.rb', File.join('app', 'controllers', 'admin_controller.rb') unless file_exists?('app/controllers/admin_controller.rb')
end
def create_admin_ressource_controller
template 'controller_generator.rb', File.join('app', 'controllers', prefix, class_path, "#{controller_file_name}_controller.rb")
end
def create_admin_helper
template 'helpers/admin_helper.rb', File.join('app', 'helpers', 'admin_helper.rb') unless file_exists?('app/helpers/admin_helper.rb')
end
def create_admin_layout_views
unless file_exists?('app/views/layouts/admin.haml')
template 'layouts/admin.haml', File.join('app', 'views', 'layouts', 'admin.haml')
end
unless file_exists?('app/views/admin/partials/_menu.haml')
template 'admin/partials/_menu.haml', File.join('app', 'views', prefix, 'partials', '_menu.haml')
end
unless file_exists?('app/views/admin/partials/_user_profile.haml')
template 'admin/partials/_user_profile.haml', File.join('app', 'views', prefix, 'partials', '_user_profile.haml')
end
end
def copy_main_assets
unless file_exists?('app/assets/javascripts/admin.js.coffee')
template 'assets/admin.js.coffee', File.join('app', 'assets', 'javascripts', 'admin.js.coffee')
end
unless file_exists?('app/assets/stylesheets/admin.scss')
template 'assets/admin.scss', File.join('app', 'assets', 'stylesheets', 'admin.scss')
end
end
def create_admin_ressource_views
available_views.each do |view|
template "admin/views/#{view}.haml", File.join('app/views', prefix, controller_file_path, "#{view}.haml")
end
template 'admin/views/_form.haml', File.join('app/views', prefix, controller_file_path, '_form.haml')
end
hook_for :resource_route, in: :rails do |resource_route|
invoke resource_route, [prefixed_class_name]
end
def create_i18n_config
unless file_exists?('config/initializers/i18n.rb')
template 'config/initializers/i18n.rb', File.join('config', 'initializers', 'i18n.rb')
end
end
def create_simple_form_config
unless file_exists?('config/initializers/simple_form.rb')
invoke 'simple_form:install', nil, ['--bootstrap']
end
end
def copy_simple_form_custom_config
unless file_exists?('config/initializers/simple_form_inline_label_fix.rb')
template 'config/initializers/simple_form_inline_label_fix.rb', File.join('config', 'initializers', 'simple_form_inline_label_fix.rb')
end
unless file_exists?('config/initializers/simple_form_wrappers.rb')
template 'config/initializers/simple_form_wrappers.rb', File.join('config', 'initializers', 'simple_form_wrappers.rb')
end
end
def setup_kaminari
unless file_exists?('config/initializers/kaminari_config.rb')
invoke 'kaminari:config'
end
end
protected
def available_views
%w(index show edit new)
end
def prefix
options[:prefix_name]
end
def prefixed_class_name
"#{prefix.capitalize}::#{class_name}"
end
def prefixed_controller_class_name
"#{prefix.capitalize}::#{controller_class_name}"
end
def parent_controller_class_name
options[:parent_controller].capitalize
end
def prefixed_route_url
"/#{prefix}#{route_url}"
end
def prefixed_plain_model_url
"#{prefix}_#{singular_table_name}"
end
def prefixed_index_helper
"#{prefix}_#{index_helper}"
end
def model_exists?
file_exists?("app/models/#{file_path}.rb")
end
def file_exists?(file_path)
File.exists?(File.join(destination_root, file_path))
end
end
end
| 32.618705 | 161 | 0.685487 |
bb80506312db8bc67fab951dd534452ff06daf18 | 1,397 | #!/usr/bin/env ruby
# https://adventofcode.com/2020/day/10
# Run with: 'ruby solve10.rb'
# using Ruby 2.5.1
# by Zack Sargent
INPUTS = File.readlines("input10.txt").map(&:chomp)
GET_OPENER = {
')' => '(',
']' => '[',
'}' => '{',
'>' => '<',
}
GET_CLOSER = GET_OPENER.to_a.map(&:reverse).to_h
POINT_VALUE_1 = {
')' => 3,
']' => 57,
'}' => 1197,
'>' => 25137,
}
POINT_VALUE_2 = {
')' => 1,
']' => 2,
'}' => 3,
'>' => 4,
}
# @param [String] line
# @return [Array] (illegal_character_point_value, total_score)
def process line
stack = []
line.chars.each do |char|
if GET_OPENER.values.include? char
stack << char
else
if stack.last == GET_OPENER[char]
stack.pop
else
# return the point value of the invalid closing brace
return [POINT_VALUE_1[char], nil]
end
end
end
# close all of the open braces, and calculate the score
scores = stack.reverse.map{|opener| POINT_VALUE_2[GET_CLOSER[opener]]}
# calculate final score
total = 0
scores.each do |score|
total *= 5
total += score
end
return [nil, total]
end
# part 1
p INPUTS.filter_map {|input|
invalid_character, _ = process(input)
invalid_character # will be nil for incomplete lines
}.sum
# part 2
scores = INPUTS.filter_map {|input|
pt1, total_score = process(input)
total_score if !pt1
}.sort
p scores[scores.size/2]
| 18.878378 | 72 | 0.609878 |
6a35f24835f545793fdf1b3800e44f9cbfb71501 | 42 | ActsAsTaggableOn.strict_case_match = true
| 21 | 41 | 0.880952 |
790abd6296163544a0bb02cbf047a0b0902c68dc | 43 | module TacoTuesday
VERSION = "0.2.0"
end
| 10.75 | 19 | 0.697674 |
ffbf038c93945dc1647676a9c886c6ebded3cf09 | 1,993 | # frozen_string_literal: true
describe Facter::Resolvers::Kernel do
before do
ver_ptr = double('FFI::MemoryPointer')
ver = double('OsVersionInfoEx', size: nil)
allow(FFI::MemoryPointer).to receive(:new).with(OsVersionInfoEx.size).and_return(ver_ptr)
allow(OsVersionInfoEx).to receive(:new).with(ver_ptr).and_return(ver)
allow(ver).to receive(:[]=).with(:dwOSVersionInfoSize, ver.size)
allow(KernelFFI).to receive(:RtlGetVersion).with(ver_ptr).and_return(status)
allow(ver).to receive(:[]).with(:dwMajorVersion).and_return(maj)
allow(ver).to receive(:[]).with(:dwMinorVersion).and_return(min)
allow(ver).to receive(:[]).with(:dwBuildNumber).and_return(buildnr)
end
after do
Facter::Resolvers::Kernel.invalidate_cache
end
describe '#resolve' do
let(:status) { KernelFFI::STATUS_SUCCESS }
let(:maj) { 10 }
let(:min) { 0 }
let(:buildnr) { 123 }
it 'detects kernel version' do
expect(Facter::Resolvers::Kernel.resolve(:kernelversion)).to eql('10.0.123')
end
it 'detects kernel major version' do
expect(Facter::Resolvers::Kernel.resolve(:kernelmajorversion)).to eql('10.0')
end
it 'detects kernel name' do
expect(Facter::Resolvers::Kernel.resolve(:kernel)).to eql('windows')
end
end
describe '#resolve when RtlGetVersion function fails to get os version information' do
let(:status) { 10 }
let(:maj) { 10 }
let(:min) { 0 }
let(:buildnr) { 123 }
it 'logs debug message and kernel version nil' do
allow_any_instance_of(Facter::Log).to receive(:debug).with('Calling Windows RtlGetVersion failed')
expect(Facter::Resolvers::Kernel.resolve(:kernelversion)).to be(nil)
end
it 'detects that kernel major version is nil' do
expect(Facter::Resolvers::Kernel.resolve(:kernelmajorversion)).to be(nil)
end
it 'detects that kernel name is nil' do
expect(Facter::Resolvers::Kernel.resolve(:kernel)).to be(nil)
end
end
end
| 32.145161 | 104 | 0.685901 |
613fc99e054f1db9a256a76bfb2aef48b8e769f1 | 173 | Embulk::JavaPlugin.register_input(
"salesforce_bulk", "org.embulk.input.salesforce_bulk.SalesforceBulkInputPlugin",
File.expand_path('../../../../classpath', __FILE__))
| 43.25 | 82 | 0.757225 |
1dd8e085e7c9559eebd5c2bfcb7f92e17b11adb8 | 653 | class GetFieldTreeListTransaction < Cortex::ApplicationTransaction
step :init
step :process
def init(input)
field = Field.find_by_id(input[:args]['field_id'])
field ? Success({ content_item: input[:content_item], field: field }) : Failure(:not_found)
end
def process(input)
tree_array = input[:field].metadata['allowed_values']['data']['tree_array']
tree_values = input[:content_item].field_items.find {|field_item| field_item.field_id == input[:field].id}.data['values']
tree_list = tree_values.map {|value| tree_array.find {|node| node['id'] == value.to_i}['node']['name']}.join(',')
Success(tree_list)
end
end
| 34.368421 | 125 | 0.699847 |
1c48196762c35d4ed8d171163dea5d8e3f7e9848 | 16,675 | module ActiveRecord
# See ActiveRecord::Transactions::ClassMethods for documentation.
module Transactions
extend ActiveSupport::Concern
#:nodoc:
ACTIONS = [:create, :destroy, :update]
included do
define_callbacks :commit, :rollback,
scope: [:kind, :name]
end
# = Active Record Transactions
#
# Transactions are protective blocks where SQL statements are only permanent
# if they can all succeed as one atomic action. The classic example is a
# transfer between two accounts where you can only have a deposit if the
# withdrawal succeeded and vice versa. Transactions enforce the integrity of
# the database and guard the data against program errors or database
# break-downs. So basically you should use transaction blocks whenever you
# have a number of statements that must be executed together or not at all.
#
# For example:
#
# ActiveRecord::Base.transaction do
# david.withdrawal(100)
# mary.deposit(100)
# end
#
# This example will only take money from David and give it to Mary if neither
# +withdrawal+ nor +deposit+ raise an exception. Exceptions will force a
# ROLLBACK that returns the database to the state before the transaction
# began. Be aware, though, that the objects will _not_ have their instance
# data returned to their pre-transactional state.
#
# == Different Active Record classes in a single transaction
#
# Though the transaction class method is called on some Active Record class,
# the objects within the transaction block need not all be instances of
# that class. This is because transactions are per-database connection, not
# per-model.
#
# In this example a +balance+ record is transactionally saved even
# though +transaction+ is called on the +Account+ class:
#
# Account.transaction do
# balance.save!
# account.save!
# end
#
# The +transaction+ method is also available as a model instance method.
# For example, you can also do this:
#
# balance.transaction do
# balance.save!
# account.save!
# end
#
# == Transactions are not distributed across database connections
#
# A transaction acts on a single database connection. If you have
# multiple class-specific databases, the transaction will not protect
# interaction among them. One workaround is to begin a transaction
# on each class whose models you alter:
#
# Student.transaction do
# Course.transaction do
# course.enroll(student)
# student.units += course.units
# end
# end
#
# This is a poor solution, but fully distributed transactions are beyond
# the scope of Active Record.
#
# == +save+ and +destroy+ are automatically wrapped in a transaction
#
# Both +save+ and +destroy+ come wrapped in a transaction that ensures
# that whatever you do in validations or callbacks will happen under its
# protected cover. So you can use validations to check for values that
# the transaction depends on or you can raise exceptions in the callbacks
# to rollback, including <tt>after_*</tt> callbacks.
#
# As a consequence changes to the database are not seen outside your connection
# until the operation is complete. For example, if you try to update the index
# of a search engine in +after_save+ the indexer won't see the updated record.
# The +after_commit+ callback is the only one that is triggered once the update
# is committed. See below.
#
# == Exception handling and rolling back
#
# Also have in mind that exceptions thrown within a transaction block will
# be propagated (after triggering the ROLLBACK), so you should be ready to
# catch those in your application code.
#
# One exception is the <tt>ActiveRecord::Rollback</tt> exception, which will trigger
# a ROLLBACK when raised, but not be re-raised by the transaction block.
#
# *Warning*: one should not catch <tt>ActiveRecord::StatementInvalid</tt> exceptions
# inside a transaction block. <tt>ActiveRecord::StatementInvalid</tt> exceptions indicate that an
# error occurred at the database level, for example when a unique constraint
# is violated. On some database systems, such as PostgreSQL, database errors
# inside a transaction cause the entire transaction to become unusable
# until it's restarted from the beginning. Here is an example which
# demonstrates the problem:
#
# # Suppose that we have a Number model with a unique column called 'i'.
# Number.transaction do
# Number.create(i: 0)
# begin
# # This will raise a unique constraint error...
# Number.create(i: 0)
# rescue ActiveRecord::StatementInvalid
# # ...which we ignore.
# end
#
# # On PostgreSQL, the transaction is now unusable. The following
# # statement will cause a PostgreSQL error, even though the unique
# # constraint is no longer violated:
# Number.create(i: 1)
# # => "PGError: ERROR: current transaction is aborted, commands
# # ignored until end of transaction block"
# end
#
# One should restart the entire transaction if an
# <tt>ActiveRecord::StatementInvalid</tt> occurred.
#
# == Nested transactions
#
# +transaction+ calls can be nested. By default, this makes all database
# statements in the nested transaction block become part of the parent
# transaction. For example, the following behavior may be surprising:
#
# User.transaction do
# User.create(username: 'Kotori')
# User.transaction do
# User.create(username: 'Nemu')
# raise ActiveRecord::Rollback
# end
# end
#
# creates both "Kotori" and "Nemu". Reason is the <tt>ActiveRecord::Rollback</tt>
# exception in the nested block does not issue a ROLLBACK. Since these exceptions
# are captured in transaction blocks, the parent block does not see it and the
# real transaction is committed.
#
# In order to get a ROLLBACK for the nested transaction you may ask for a real
# sub-transaction by passing <tt>requires_new: true</tt>. If anything goes wrong,
# the database rolls back to the beginning of the sub-transaction without rolling
# back the parent transaction. If we add it to the previous example:
#
# User.transaction do
# User.create(username: 'Kotori')
# User.transaction(requires_new: true) do
# User.create(username: 'Nemu')
# raise ActiveRecord::Rollback
# end
# end
#
# only "Kotori" is created. This works on MySQL and PostgreSQL. SQLite3 version >= '3.6.8' also supports it.
#
# Most databases don't support true nested transactions. At the time of
# writing, the only database that we're aware of that supports true nested
# transactions, is MS-SQL. Because of this, Active Record emulates nested
# transactions by using savepoints on MySQL and PostgreSQL. See
# http://dev.mysql.com/doc/refman/5.6/en/savepoint.html
# for more information about savepoints.
#
# === Callbacks
#
# There are two types of callbacks associated with committing and rolling back transactions:
# +after_commit+ and +after_rollback+.
#
# +after_commit+ callbacks are called on every record saved or destroyed within a
# transaction immediately after the transaction is committed. +after_rollback+ callbacks
# are called on every record saved or destroyed within a transaction immediately after the
# transaction or savepoint is rolled back.
#
# These callbacks are useful for interacting with other systems since you will be guaranteed
# that the callback is only executed when the database is in a permanent state. For example,
# +after_commit+ is a good spot to put in a hook to clearing a cache since clearing it from
# within a transaction could trigger the cache to be regenerated before the database is updated.
#
# === Caveats
#
# If you're on MySQL, then do not use DDL operations in nested transactions
# blocks that are emulated with savepoints. That is, do not execute statements
# like 'CREATE TABLE' inside such blocks. This is because MySQL automatically
# releases all savepoints upon executing a DDL operation. When +transaction+
# is finished and tries to release the savepoint it created earlier, a
# database error will occur because the savepoint has already been
# automatically released. The following example demonstrates the problem:
#
# Model.connection.transaction do # BEGIN
# Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1
# Model.connection.create_table(...) # active_record_1 now automatically released
# end # RELEASE savepoint active_record_1
# # ^^^^ BOOM! database error!
# end
#
# Note that "TRUNCATE" is also a MySQL DDL statement!
module ClassMethods
# See ActiveRecord::Transactions::ClassMethods for detailed documentation.
def transaction(options = {}, &block)
# See the ConnectionAdapters::DatabaseStatements#transaction API docs.
connection.transaction(options, &block)
end
# This callback is called after a record has been created, updated, or destroyed.
#
# You can specify that the callback should only be fired by a certain action with
# the +:on+ option:
#
# after_commit :do_foo, on: :create
# after_commit :do_bar, on: :update
# after_commit :do_baz, on: :destroy
#
# after_commit :do_foo_bar, on: [:create, :update]
# after_commit :do_bar_baz, on: [:update, :destroy]
#
# Note that transactional fixtures do not play well with this feature. Please
# use the +test_after_commit+ gem to have these hooks fired in tests.
def after_commit(*args, &block)
set_options_for_callbacks!(args)
set_callback(:commit, :after, *args, &block)
end
# This callback is called after a create, update, or destroy are rolled back.
#
# Please check the documentation of +after_commit+ for options.
def after_rollback(*args, &block)
set_options_for_callbacks!(args)
set_callback(:rollback, :after, *args, &block)
end
def raise_in_transactional_callbacks
ActiveSupport::Deprecation.warn('ActiveRecord::Base.raise_in_transactional_callbacks is deprecated and will be removed without replacement.')
true
end
def raise_in_transactional_callbacks=(value)
ActiveSupport::Deprecation.warn('ActiveRecord::Base.raise_in_transactional_callbacks= is deprecated, has no effect and will be removed without replacement.')
value
end
private
def set_options_for_callbacks!(args)
options = args.last
if options.is_a?(Hash) && options[:on]
fire_on = Array(options[:on])
assert_valid_transaction_action(fire_on)
options[:if] = Array(options[:if])
options[:if] << "transaction_include_any_action?(#{fire_on})"
end
end
def assert_valid_transaction_action(actions)
if (actions - ACTIONS).any?
raise ArgumentError, ":on conditions for after_commit and after_rollback callbacks have to be one of #{ACTIONS}"
end
end
end
# See ActiveRecord::Transactions::ClassMethods for detailed documentation.
def transaction(options = {}, &block)
self.class.transaction(options, &block)
end
def destroy #:nodoc:
with_transaction_returning_status { super }
end
def save(*) #:nodoc:
rollback_active_record_state! do
with_transaction_returning_status { super }
end
end
def save!(*) #:nodoc:
with_transaction_returning_status { super }
end
def touch(*) #:nodoc:
with_transaction_returning_status { super }
end
# Reset id and @new_record if the transaction rolls back.
def rollback_active_record_state!
remember_transaction_record_state
yield
rescue Exception
restore_transaction_record_state
raise
ensure
clear_transaction_record_state
end
# Call the +after_commit+ callbacks.
#
# Ensure that it is not called if the object was never persisted (failed create),
# but call it after the commit of a destroyed object.
def committed!(should_run_callbacks = true) #:nodoc:
_run_commit_callbacks if should_run_callbacks && destroyed? || persisted?
ensure
force_clear_transaction_record_state
end
# Call the +after_rollback+ callbacks. The +force_restore_state+ argument indicates if the record
# state should be rolled back to the beginning or just to the last savepoint.
def rolledback!(force_restore_state = false, should_run_callbacks = true) #:nodoc:
_run_rollback_callbacks if should_run_callbacks
ensure
restore_transaction_record_state(force_restore_state)
clear_transaction_record_state
end
# Add the record to the current transaction so that the +after_rollback+ and +after_commit+ callbacks
# can be called.
def add_to_transaction
if self.class.connection.add_transaction_record(self)
remember_transaction_record_state
end
end
# Executes +method+ within a transaction and captures its return value as a
# status flag. If the status is true the transaction is committed, otherwise
# a ROLLBACK is issued. In any case the status flag is returned.
#
# This method is available within the context of an ActiveRecord::Base
# instance.
def with_transaction_returning_status
status = nil
self.class.transaction do
add_to_transaction
begin
status = yield
rescue ActiveRecord::Rollback
clear_transaction_record_state
status = nil
end
raise ActiveRecord::Rollback unless status
end
status
end
protected
# Save the new record state and id of a record so it can be restored later if a transaction fails.
def remember_transaction_record_state #:nodoc:
@_start_transaction_state[:id] = id
@_start_transaction_state.reverse_merge!(
new_record: @new_record,
destroyed: @destroyed,
frozen?: frozen?,
)
@_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) + 1
end
# Clear the new record state and id of a record.
def clear_transaction_record_state #:nodoc:
@_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1
force_clear_transaction_record_state if @_start_transaction_state[:level] < 1
end
# Force to clear the transaction record state.
def force_clear_transaction_record_state #:nodoc:
@_start_transaction_state.clear
end
# Restore the new record state and id of a record that was previously saved by a call to save_record_state.
def restore_transaction_record_state(force = false) #:nodoc:
unless @_start_transaction_state.empty?
transaction_level = (@_start_transaction_state[:level] || 0) - 1
if transaction_level < 1 || force
restore_state = @_start_transaction_state
thaw unless restore_state[:frozen?]
@new_record = restore_state[:new_record]
@destroyed = restore_state[:destroyed]
write_attribute(self.class.primary_key, restore_state[:id])
end
end
end
# Determine if a record was created or destroyed in a transaction. State should be one of :new_record or :destroyed.
def transaction_record_state(state) #:nodoc:
@_start_transaction_state[state]
end
# Determine if a transaction included an action for :create, :update, or :destroy. Used in filtering callbacks.
def transaction_include_any_action?(actions) #:nodoc:
actions.any? do |action|
case action
when :create
transaction_record_state(:new_record)
when :destroy
destroyed?
when :update
!(transaction_record_state(:new_record) || destroyed?)
end
end
end
end
end
| 41.071429 | 165 | 0.678081 |
7a2dc24d1b35ce1f2aa00bdcf089474468e3dea8 | 701 | require 'test_helper'
require 'vertex_array_expression_tests'
require 'test_adapter'
class NamedTest < Test
include VertexArrayExpressionTests
def setup
RPath.use TestAdapter.new
end
def vertex_array_expression
RPath::Named.new(RPath::Adjacent.new(RPath::Root.new), 'foo')
end
def test_eval_returns_vertices_with_name
graph = {adjacent: [{name: 'a'}, {name: 'b'}]}
exp = RPath::Named.new(RPath::Adjacent.new(RPath::Root.new), 'a')
assert_equal [{name: 'a'}], exp.eval(graph)
end
def test_eval_returns_nil_when_prior_eval_returns_nil
prior = RPath { |root| root.foo[0].adjacent }
exp = RPath::Named.new(prior, 'a')
assert_nil exp.eval({})
end
end
| 25.035714 | 69 | 0.707561 |
018aa4fd1c680cec07bdd7fe376ed63bfdaf39a6 | 319 | class CreateExecutingCommands < ActiveRecord::Migration
def change
create_table :redmine_chat_telegram_executing_commands do |t|
t.integer :account_id
t.string :name
t.integer :step_number
t.text :data
end
add_index :redmine_chat_telegram_executing_commands, :account_id
end
end
| 26.583333 | 68 | 0.746082 |
ed5cde21ea33668c60351a79c474b31aca387e83 | 4,393 | require_relative '../global/dice'
require_relative '../global/weapon'
require_relative '../global/intro'
require 'yaml'
class Global
include Dice
include Intro
attr_accessor :main_stat
attr_accessor :main_stat_modify
attr_accessor :size
attr_accessor :speed
attr_accessor :languages
attr_accessor :vision
attr_accessor :race
attr_accessor :hit_dice
attr_accessor :hp_max
attr_accessor :hp_current
attr_accessor :damage
attr_accessor :skills
attr_accessor :abilities
attr_accessor :race_abilities
attr_accessor :weapon_proficiency
attr_accessor :armor_proficiency
attr_accessor :skill_proficiency
attr_accessor :magic
attr_accessor :level
attr_accessor :saving_throws
TEXT_GLOBAL = YAML.load_file('global/data/global_text.yml')
def initialize
@main_stat = { STR: 20, DEX: 18, CON: 16, INT: 14, WIS: 12, CHAR: 8}
@main_stat_modify = { STR: 0, DEX: 0, CON: 0, INT: 0, WIS: 0, CHAR: 0}
@size = 'medium'
@speed = 30
@skill_proficiency = []
@race_abilities = []
@languages = [:common]
@hp_max = 1
@hp = 1
@magic = {}
end
def main_stats_display(player)
puts 'Ваши Характеристики:'
main_stat_info = TEXT_GLOBAL['main_stats_info_text']
index = 1
main_stat.each do |key, value|
unless key == :LUCK
if detect_main_stat_modify(player, key, value) < 0
puts "[#{index}] " + "#{main_stat_info[key.to_s.downcase]}: ".color_stat_text[:main_stat][index - 1] +"#{value} " + "|Модификатор|: " + "#{player.main_stat_modify[key]}".red
elsif detect_main_stat_modify(player, key, value) >= 4
puts "[#{index}] " + "#{main_stat_info[key.to_s.downcase]}: ".color_stat_text[:main_stat][index - 1] +"#{value} " + "|Модификатор|: " + "#{player.main_stat_modify[key]}".green
elsif detect_main_stat_modify(player, key, value).between?(2, 3)
puts "[#{index}] " + "#{main_stat_info[key.to_s.downcase]}: ".color_stat_text[:main_stat][index - 1] +"#{value} " + "|Модификатор|: " + "#{player.main_stat_modify[key]}".brown
else
puts "[#{index}] " + "#{main_stat_info[key.to_s.downcase]}: ".color_stat_text[:main_stat][index - 1] +"#{value} " + "|Модификатор|: " + "#{player.main_stat_modify[key]}"
end
index += 1
end
end
puts
player_display_languages(player)
unless player.age.nil?
if player.age >= 100
print 'Ваш возраст: ' + "#{player.age}".brown
puts
else
puts "Ваш возраст: #{player.age}"
end
puts "Ваш размер: #{TEXT_GLOBAL['size'][player.size]}"
puts "Ваша скорость: #{player.speed}"
puts
puts 'Вы владеете следующими рассовыми способностями:'
player.race_abilities.each { |ra| puts ra.magenta }
puts
puts 'Вы владеете следующими навыками:'
player.skill_proficiency.each { |sp| puts sp.cyan }
puts
puts 'Вы владеете следующим оружием:'
player.weapon_proficiency.each { |wp| puts wp.brown }
puts
puts 'Вы владеете следующими магическими навыками:'
player.magic.each do |skill|
puts "#{TEXT_GLOBAL['magic']['cantrip_race']}:"
puts "- #{TEXT_GLOBAL['magic']['count']}: #{skill[1][:count]}"
puts "- #{TEXT_GLOBAL['magic']['main_stat']}: " + "#{skill[1][:main_stat]}".blue
end
puts
end
puts
end
def detect_main_stat_modify(player, key, value)
# main_stat = @main_stat
if key == :LUCK
puts '### Параметр Удачи не имеет Мофификатора ###'
elsif value == 1
player.main_stat_modify[key] = -5
elsif value.between?(2, 3)
player.main_stat_modify[key] = -4
elsif value.between?(4, 5)
player.main_stat_modify[key] = -3
elsif value.between?(6, 7)
player.main_stat_modify[key] = -2
elsif value.between?(8, 9)
player.main_stat_modify[key] = -1
elsif value.between?(10, 11)
player.main_stat_modify[key] = +0
elsif value.between?(12, 13)
player.main_stat_modify[key] = +1
elsif value.between?(14, 15)
player.main_stat_modify[key] = +2
elsif value.between?(16, 17)
player.main_stat_modify[key] = +3
elsif value.between?(18, 19)
player.main_stat_modify[key] = +4
elsif value.between?(20, 21)
player.main_stat_modify[key] = +5
end
player.main_stat_modify[key]
end
end
| 27.803797 | 187 | 0.638288 |
1c22369d0d78a1c5b9be2db8b261e1c5622ee5e7 | 1,539 | class Notcurses < Formula
desc "Blingful character graphics/TUI library"
homepage "https://nick-black.com/dankwiki/index.php/Notcurses"
url "https://github.com/dankamongmen/notcurses/archive/refs/tags/v2.3.15.tar.gz"
sha256 "146e83723e5f5c486b9f16ec11b70ad682e76b6d01f10e4d9c27d07f3de72811"
license "Apache-2.0"
bottle do
sha256 arm64_big_sur: "cec298c56c1b6ae574a91ad64e606bbff7f8f4b1dc3634c4d873d66332d8b5b6"
sha256 big_sur: "d3ccf77415d1575c11c8e1e4c39150a7942e802e29bd7209341d4323a42e609e"
sha256 catalina: "5acb192986f425945fa2fc3dded530b64c48075534d1a78e5889c8a81708d686"
sha256 mojave: "596d4da953dd1c20455ebbf0f97212a3027517cf299a48edcf8acb417a53f81a"
end
depends_on "cmake" => :build
depends_on "doctest" => :build
depends_on "pandoc" => :build
depends_on "pkg-config" => :build
depends_on "ffmpeg"
depends_on "libunistring"
depends_on "ncurses"
depends_on "readline"
uses_from_macos "zlib"
def install
system "cmake", "-S", ".", "-B", "build", *std_cmake_args, "-DCMAKE_INSTALL_RPATH=#{rpath}"
system "cmake", "--build", "build"
system "cmake", "--install", "build"
end
test do
# without the TERM definition, Notcurses is like a small child, lost in a
# horrible mall. of course, if the tests are run in some non-xterm
# environment, this choice might prove unfortunate.
# you have no chance to survive. make your time.
ENV["TERM"] = "xterm"
assert_match "notcurses", shell_output("#{bin}/notcurses-info")
end
end
| 37.536585 | 95 | 0.736842 |
3945b537d0fbe171fbfef5232914fe986b156b42 | 1,223 | class Duti < Formula
desc "Select default apps for documents and URL schemes on macOS"
homepage "https://github.com/moretension/duti/"
url "https://github.com/moretension/duti/archive/duti-1.5.4.tar.gz"
sha256 "3f8f599899a0c3b85549190417e4433502f97e332ce96cd8fa95c0a9adbe56de"
head "https://github.com/moretension/duti.git"
bottle do
cellar :any_skip_relocation
rebuild 1
sha256 "e327eda2392f8a4cc6f05f14848c118d680996ecb065af2f44d05461c2c63e2f" => :mojave
sha256 "61d2281c0c477d98203e6d85c83f7ccb76dddcc86f81a316d2a83df4cef4a64b" => :high_sierra
sha256 "e0178ad9c0f9a10120cc78ff63bbe727f8fc42fb3ed03438593f21381f8bdb3c" => :sierra
end
depends_on "autoconf" => :build
# Fix compilation on macOS 10.14 Mojave
patch do
url "https://github.com/moretension/duti/pull/32.patch?full_index=1"
sha256 "0f6013b156b79aa498881f951172bcd1ceac53807c061f95c5252a8d6df2a21a"
end
def install
system "autoreconf", "-vfi"
system "./configure", "--prefix=#{prefix}"
system "make", "install"
end
test do
assert_match "com.apple.TextEdit", shell_output("#{bin}/duti -l public.text"),
"TextEdit not found among the handlers for public.text"
end
end
| 34.942857 | 93 | 0.751431 |
01dddb76414b19895ed4a186cfee4bc3bfde980a | 176 | class AdminController < ApplicationController
def dashboard
end
def sales
end
def visitors
end
def orders
@orders_roasted
@orders_delivered
end
end
| 11 | 45 | 0.715909 |
b9f8687f25d7b9064261c91c6c6780615f8083e9 | 4,348 | # frozen_string_literal: true
require "rom/schema"
require "rom/attribute"
require_relative "core"
module ROM
module Components
module DSL
# @private
class Schema < Core
key :schemas
option :attributes, default: -> { EMPTY_HASH.dup }
# Defines a relation attribute with its type and options.
#
# When only options are given, type is left as nil. It makes
# sense when it is used alongside a schema inferrer, which will
# populate the type.
#
# @see Components::DSL#schema
#
# @api public
def attribute(name, type_or_options, options = EMPTY_HASH)
if attributes.key?(name)
raise(AttributeAlreadyDefinedError, "Attribute #{name.inspect} already defined")
end
build_attribute_info(name, type_or_options, options).tap do |attr_info|
attributes[name] = attr_info
end
end
# Specify which key(s) should be the primary key
#
# @api public
def primary_key(*names)
names.each do |name|
attributes[name][:type] = attributes[name][:type].meta(primary_key: true)
end
self
end
# @api private
def call
# Evaluate block only if it's not a schema defined by Relation.view DSL
instance_eval(&block) if block && !config.view
enabled_plugins.each_value do |plugin|
plugin.apply unless plugin.applied?
end
configure
components.add(key, config: config, block: config.view ? block : nil)
end
# @api private
# rubocop:disable Metrics/AbcSize
def configure
config.update(attributes: attributes.values)
# TODO: make this simpler
config.update(
relation: relation_id,
inferrer: config.inferrer.with(enabled: config.infer)
)
if !view? && relation?
config.join!({namespace: relation_id}, :right) if config.id != relation_id
provider.config.component.update(dataset: config.dataset) if config.dataset
provider.config.component.update(id: config.as) if config.as
end
provider.config.schema.infer = config.infer
super
end
# rubocop:enable Metrics/AbcSize
private
# Builds a representation of the information needed to create an
# attribute. It returns a hash with `:type` and `:options` keys.
#
# @return [Hash]
#
# @see [Schema.build_attribute_info]
#
# @api private
def build_attribute_info(name, type_or_options, options = EMPTY_HASH)
type, options = if type_or_options.is_a?(::Hash)
[nil, type_or_options]
else
[build_type(type_or_options, options), options]
end
ROM::Schema.build_attribute_info(type, **options, name: name)
end
# Builds a type instance from base type and meta options
#
# @return [Dry::Types::Type] Type instance
#
# @api private
def build_type(type, options = EMPTY_HASH)
meta = ROM::Attribute::META_OPTIONS
.map { |opt| [opt, options[opt]] if options.key?(opt) }
.compact
.to_h
# TODO: this should be probably moved to rom/compat
source = ROM::Relation::Name[relation_id, config.dataset]
base =
if options[:read]
type.meta(source: source, read: options[:read])
elsif type.optional? && type.meta[:read]
type.meta(source: source, read: type.meta[:read].optional)
else
type.meta(source: source)
end
if meta.empty?
base
else
base.meta(meta)
end
end
# @api private
def relation_id
relation? ? provider.config.component.id : config.id
end
# @api private
def relation?
provider.config.component.type == :relation
end
# @api private
def view?
config.view.equal?(true)
end
end
end
end
end
| 28.794702 | 92 | 0.557498 |
1a04e7f546d41ff73a8b8e6973bf48a89ae0a7eb | 738 | class SessionsController < ApplicationController
def new
end
def create
@user = User.find_by(email: params[:session][:email].downcase)
if @user && @user.authenticate(params[:session][:password])
if @user.activated?
log_in @user
params[:session][:remember_me] == "1"?remember(@user):forget(@user)
redirect_back_or @user
else
message = "Account not activated. "
message += "Check your email for the activation link."
flash[:warning] = message
redirect_to root_url
end
else
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
log_out if logged_in?
redirect_to root_url
end
end
| 25.448276 | 75 | 0.639566 |
21f920c6865618816eee5dd3c4a0e89875f37c3e | 930 | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "devise_castle/version"
Gem::Specification.new do |s|
s.name = 'devise_castle'
s.version = DeviseCastle::VERSION.dup
s.platform = Gem::Platform::RUBY
s.email = '[email protected]'
s.homepage = 'https://github.com/castle/devise_castle'
s.summary = 'Devise extension for Castle'
s.description = 'Devise extension for Castle. Secure your authentication stack with real-time monitoring, instantly notifying you and your users on potential account hijacks.'
s.authors = ['Johan Brissmyr', 'Sebastian Wallin']
s.license = 'MIT'
s.require_path = "lib"
s.files = Dir.glob("{app,lib,config}/**/*")
s.add_dependency("devise", ">= 4.0", "< 5")
s.add_dependency("castle-rb", ">= 3", "< 4")
s.add_development_dependency('bundler')
s.add_development_dependency('rake')
s.add_development_dependency('rails', '>= 4', '< 6')
end
| 35.769231 | 177 | 0.688172 |
1afdddc6bd45eab19a5e51ca342525c88600cefc | 161 | require 'singleton'
class Logger
include Singleton
def initialize
@f = File.open 'log.txt', 'a'
end
def log_something wat
@f.puts wat
end
end | 13.416667 | 33 | 0.670807 |
d5876d9dd0a4d058f12e3d58dd1bf903a3783189 | 57,457 | require "test_helper"
class RBS::DefinitionBuilderTest < Test::Unit::TestCase
include TestHelper
AST = RBS::AST
Environment = RBS::Environment
EnvironmentLoader = RBS::EnvironmentLoader
Declarations = RBS::AST::Declarations
TypeName = RBS::TypeName
Namespace = RBS::Namespace
DefinitionBuilder = RBS::DefinitionBuilder
Definition = RBS::Definition
BuiltinNames = RBS::BuiltinNames
Types = RBS::Types
InvalidTypeApplicationError = RBS::InvalidTypeApplicationError
UnknownMethodAliasError = RBS::UnknownMethodAliasError
InvalidVarianceAnnotationError = RBS::InvalidVarianceAnnotationError
def assert_method_definition(method, types, accessibility: nil)
assert_instance_of Definition::Method, method
assert_equal types, method.method_types.map(&:to_s)
assert_equal accessibility, method.accessibility if accessibility
yield method.super if block_given?
end
def assert_ivar_definition(ivar, type)
assert_instance_of Definition::Variable, ivar
type = parse_type(type) if type.is_a?(String)
assert_equal type, ivar.type
end
def test_build_interface_def_alias
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
interface _I1[X]
def i1: (X) -> String
alias i2 i1
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_interface(type_name("::_I1")).tap do |definition|
assert_instance_of Definition, definition
assert_equal type_name("::_I1"), definition.type_name
assert_equal parse_type("::_I1[X]", variables: [:X]), definition.self_type
assert_equal [:X], definition.type_params
assert_equal Set[:i1, :i2], Set.new(definition.methods.keys)
assert_method_definition definition.methods[:i1], ["(X) -> ::String"], accessibility: :public
assert_method_definition definition.methods[:i2], ["(X) -> ::String"], accessibility: :public
end
end
end
end
def test_build_interface_def_overload
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
interface _I1[X]
def i1: (X) -> String
def i1: (X, Integer) -> String
| ...
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_interface(type_name("::_I1")).tap do |definition|
assert_instance_of Definition, definition
assert_equal type_name("::_I1"), definition.type_name
assert_equal parse_type("::_I1[X]", variables: [:X]), definition.self_type
assert_equal [:X], definition.type_params
assert_equal Set[:i1], Set.new(definition.methods.keys)
assert_method_definition definition.methods[:i1],
["(X, ::Integer) -> ::String", "(X) -> ::String"],
accessibility: :public
end
end
end
end
def test_build_interface_def_alias_overload
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
interface _I1[X]
def i1: (X) -> String
alias i2 i1
def i1: (X, Integer) -> String
| ...
def i2: (X, Symbol) -> String
| ...
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_interface(type_name("::_I1")).tap do |definition|
assert_instance_of Definition, definition
assert_equal type_name("::_I1"), definition.type_name
assert_equal parse_type("::_I1[X]", variables: [:X]), definition.self_type
assert_equal [:X], definition.type_params
assert_equal Set[:i1, :i2], Set.new(definition.methods.keys)
assert_method_definition definition.methods[:i1],
["(X, ::Integer) -> ::String", "(X) -> ::String"],
accessibility: :public
assert_method_definition definition.methods[:i2],
["(X, ::Symbol) -> ::String", "(X, ::Integer) -> ::String", "(X) -> ::String"],
accessibility: :public
end
end
end
end
def test_build_interface_include
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
interface _I1[X]
def i1: (X) -> String
end
interface _I2
include _I1[String]
def i2: () -> String
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_interface(type_name("::_I2")).tap do |definition|
assert_instance_of Definition, definition
assert_equal type_name("::_I2"), definition.type_name
assert_equal parse_type("::_I2"), definition.self_type
assert_equal [], definition.type_params
assert_equal Set[:i1, :i2], Set.new(definition.methods.keys)
assert_method_definition definition.methods[:i1],
["(::String) -> ::String"],
accessibility: :public
assert_method_definition definition.methods[:i2],
["() -> ::String"],
accessibility: :public
end
end
end
end
def test_build_interface_include_alias_overload
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
interface _I1[X]
def i1: (X) -> String
def i2: (X) -> String
end
interface _I2
include _I1[String]
def i1: () -> String
| ...
alias i3 i2
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_interface(type_name("::_I2")).tap do |definition|
assert_instance_of Definition, definition
assert_equal type_name("::_I2"), definition.type_name
assert_equal parse_type("::_I2"), definition.self_type
assert_equal [], definition.type_params
assert_equal Set[:i1, :i2, :i3], Set.new(definition.methods.keys)
assert_method_definition definition.methods[:i1],
["() -> ::String", "(::String) -> ::String"],
accessibility: :public
assert_method_definition definition.methods[:i2],
["(::String) -> ::String"],
accessibility: :public
assert_method_definition definition.methods[:i3],
["(::String) -> ::String"],
accessibility: :public
end
end
end
end
def test_build_interface_error
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
interface _I1
def foo: () -> void | ...
end
interface _I2
alias bar baz
end
interface _I3
alias a b
alias b c
alias c a
end
interface _I4
def foo: () -> void
def foo: () -> void
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
assert_raises(RBS::InvalidOverloadMethodError) do
builder.build_interface(type_name("::_I1"))
end
assert_raises(RBS::UnknownMethodAliasError) do
builder.build_interface(type_name("::_I2"))
end
assert_raises(RBS::RecursiveAliasDefinitionError) do
builder.build_interface(type_name("::_I3"))
end
assert_raises(RBS::DuplicatedMethodDefinitionError) do
builder.build_interface(type_name("::_I4"))
end
end
end
end
def test_build_instance_module
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
module Foo[X]
@value: X
def get: () -> X
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Foo")).tap do |definition|
assert_instance_of Definition, definition
assert_equal type_name("::Foo"), definition.type_name
assert_equal parse_type("::Foo[X]", variables: [:X]), definition.self_type
assert_equal [:X], definition.type_params
assert_operator Set[:get], :subset?, Set.new(definition.methods.keys)
assert_method_definition definition.methods[:get], ["() -> X"], accessibility: :public
assert_equal Set[:@value], Set.new(definition.instance_variables.keys)
assert_ivar_definition definition.instance_variables[:@value], parse_type("X", variables: [:X])
end
end
end
end
def test_build_instance_module_include_module
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
module M1[X]
@value: X
def get: () -> X
end
module M2
include M1[String]
def get: (Integer) -> String
| ...
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::M2")).tap do |definition|
assert_instance_of Definition, definition
assert_equal type_name("::M2"), definition.type_name
assert_equal parse_type("::M2"), definition.self_type
assert_equal [], definition.type_params
assert_operator Set[:get], :subset?, Set.new(definition.methods.keys)
assert_method_definition definition.methods[:get], ["(::Integer) -> ::String", "() -> ::String"], accessibility: :public
assert_equal Set[:@value], Set.new(definition.instance_variables.keys)
assert_ivar_definition definition.instance_variables[:@value], "::String"
end
end
end
end
def test_build_instance_module_include_interface
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
interface _I1[X]
def get: () -> X
end
module M2
include _I1[String]
def get: (Integer) -> String
| ...
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::M2")).tap do |definition|
assert_instance_of Definition, definition
assert_equal type_name("::M2"), definition.type_name
assert_equal parse_type("::M2"), definition.self_type
assert_equal [], definition.type_params
assert_operator Set[:get], :subset?, Set.new(definition.methods.keys)
assert_method_definition definition.methods[:get], ["(::Integer) -> ::String", "() -> ::String"], accessibility: :public
assert definition.methods[:get].defs.all? {|td| td.implemented_in == TypeName("::M2") }
end
end
end
end
def test_build_instance_module_self_types
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
interface _StringConvertible
def to_str: () -> String
end
module M : _StringConvertible
alias inspect to_str
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::M")).tap do |definition|
assert_instance_of Definition, definition
assert_equal type_name("::M"), definition.type_name
assert_equal parse_type("::M"), definition.self_type
assert_equal [], definition.type_params
assert_equal Set[:to_str, :inspect], Set.new(definition.methods.keys)
assert_method_definition definition.methods[:to_str], ["() -> ::String"], accessibility: :public
assert_method_definition definition.methods[:inspect], ["() -> ::String"], accessibility: :public
end
end
end
end
def test_build_instance_class_basic_object
SignatureManager.new do |manager|
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::BasicObject")).tap do |definition|
assert_instance_of Definition, definition
assert_equal type_name("::BasicObject"), definition.type_name
assert_equal parse_type("::BasicObject"), definition.self_type
assert_equal [], definition.type_params
assert_equal Set[:__id__, :initialize], Set.new(definition.methods.keys)
assert_method_definition definition.methods[:__id__], ["() -> ::Integer"], accessibility: :public
assert_method_definition definition.methods[:initialize], ["() -> void"], accessibility: :private
assert_empty definition.instance_variables
end
end
end
end
def test_build_instance_class_inherit
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
class Hello
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Hello")).tap do |definition|
assert_instance_of Definition, definition
assert_equal type_name("::Hello"), definition.type_name
assert_equal parse_type("::Hello"), definition.self_type
assert_equal [], definition.type_params
assert_equal Set[:__id__, :initialize, :puts, :to_i, :respond_to_missing?], Set.new(definition.methods.keys)
assert_method_definition definition.methods[:__id__], ["() -> ::Integer"], accessibility: :public
assert_method_definition definition.methods[:initialize], ["() -> void"], accessibility: :private
assert_method_definition definition.methods[:puts], ["(*untyped) -> nil"], accessibility: :private
assert_method_definition definition.methods[:to_i], ["() -> ::Integer"], accessibility: :public
assert_empty definition.instance_variables
end
end
end
end
def test_build_comment_attributes
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
class Hello
# doc1
%a{hello}
def foo: () -> String
| (Integer) -> String
end
class Hello
# doc2
%a{world}
def foo: (String) -> String | ...
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Hello")).tap do |definition|
foo = definition.methods[:foo]
assert_nil foo.super_method
assert_equal [parse_method_type("(::String) -> ::String"),
parse_method_type("() -> ::String"),
parse_method_type("(::Integer) -> ::String")], foo.method_types
assert_equal type_name("::Hello"), foo.defined_in
assert_equal type_name("::Hello"), foo.implemented_in
assert_includes foo.annotations, AST::Annotation.new(string: "hello", location: nil)
assert_includes foo.annotations, AST::Annotation.new(string: "world", location: nil)
assert_includes foo.comments, AST::Comment.new(string: "doc1\n", location: nil)
assert_includes foo.comments, AST::Comment.new(string: "doc2\n", location: nil)
end
end
end
end
def test_build_instance_method_variance
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
class A[out X, unchecked out Y]
def foo: () -> X
def bar: (X) -> void
def baz: (Y) -> void
end
class B[in X, unchecked in Y]
def foo: (X) -> void
def bar: () -> X
def baz: () -> Y
end
class C[Z]
def foo: (Z) -> Z
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
assert_raises(InvalidVarianceAnnotationError) { builder.build_instance(type_name("::A")) }
assert_raises(InvalidVarianceAnnotationError) { builder.build_instance(type_name("::B")) }
builder.build_instance(type_name("::C"))
end
end
end
def test_build_interface_method_variance
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
interface _A[out X, unchecked out Y]
def foo: () -> X
def bar: (X) -> void
def baz: (Y) -> void
end
interface _B[in X, unchecked in Y]
def foo: (X) -> void
def bar: () -> X
def baz: () -> Y
end
interface _C[Z]
def foo: (Z) -> Z
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
assert_raises(InvalidVarianceAnnotationError) { builder.build_interface(type_name("::_A")) }
assert_raises(InvalidVarianceAnnotationError) { builder.build_interface(type_name("::_B")) }
builder.build_interface(type_name("::_C"))
end
end
end
def test_variance_check_ancestors
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
class C[out X]
end
module M[out X]
end
interface _I[out X]
end
class Test0[out X]
end
class Test1[in X] < C[X]
end
class Test2[in X]
include M[X]
end
class Test3[in X]
include _I[X]
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Test0"))
assert_raises(InvalidVarianceAnnotationError) { builder.build_instance(type_name("::Test1")) }.tap do |error|
assert_equal :X, error.param.name
assert_equal "C[X]", error.location.source
end
assert_raises(InvalidVarianceAnnotationError) { builder.build_instance(type_name("::Test2")) }.tap do |error|
assert_equal :X, error.param.name
assert_equal "include M[X]", error.location.source
end
assert_raises(InvalidVarianceAnnotationError) { builder.build_instance(type_name("::Test3")) }.tap do |error|
assert_equal :X, error.param.name
assert_equal "include _I[X]", error.location.source
end
end
end
end
def test_variance_check_methods
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
class Test0[out X, in Y, Z]
def foo: (Y, Z) -> [X, Z]
attr_reader x: X
attr_accessor z: Z
end
class Test1[out X]
def foo: (X) -> void
end
class Test2[in X]
attr_reader x: X
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Test0"))
assert_raises(InvalidVarianceAnnotationError) { builder.build_instance(type_name("::Test1")) }.tap do |error|
assert_equal :X, error.param.name
assert_equal "(X) -> void", error.location.source
end
assert_raises(InvalidVarianceAnnotationError) { builder.build_instance(type_name("::Test2")) }.tap do |error|
assert_equal :X, error.param.name
assert_equal "attr_reader x: X", error.location.source
end
end
end
end
def test_build_one_instance_variance_inheritance
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
class Base[out X]
end
class A[out X] < Base[X]
end
class B[in X] < Base[X]
end
class C[X] < Base[X]
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::A"))
builder.build_instance(type_name("::C"))
assert_raises(InvalidVarianceAnnotationError) { builder.build_instance(type_name("::B")) }
end
end
end
def test_build_variance_validation
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
module M[out X]
end
class A[out X]
include M[X]
end
class B[in X]
include M[X]
end
class C[X]
include M[X]
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::A"))
builder.build_instance(type_name("::C"))
assert_raises(InvalidVarianceAnnotationError) { builder.build_instance(type_name("::B")) }
end
end
end
def test_build_one_singleton_methods
SignatureManager.new do |manager|
manager.files[Pathname("hello.rbs")] = <<EOF
class Hello
def self.foo: () -> Hello
def self.bar: () -> String
end
class Hello
def self.bar: (Symbol) -> String | ...
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_singleton(type_name("::Hello")).yield_self do |definition|
definition.methods[:foo].tap do |method|
assert_instance_of Definition::Method, method
assert_equal [parse_method_type("() -> ::Hello")], method.method_types
assert_equal type_name("::Hello"), method.defined_in
assert_equal type_name("::Hello"), method.implemented_in
end
definition.methods[:bar].tap do |method|
assert_instance_of Definition::Method, method
assert_equal [parse_method_type("(::Symbol) -> ::String"), parse_method_type("() -> ::String")], method.method_types
assert_equal type_name("::Hello"), method.defined_in
assert_equal type_name("::Hello"), method.implemented_in
end
end
end
end
end
def test_build_one_singleton_extend_interface_methods
SignatureManager.new do |manager|
manager.files[Pathname("hello.rbs")] = <<EOF
interface _Helloable[A]
def hello: () -> A
def world: () -> A
end
class Hello
extend _Helloable[Integer]
end
class Hello
def self.world: (Symbol) -> Integer | ...
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_singleton(type_name("::Hello")).yield_self do |definition|
definition.methods[:hello].tap do |method|
assert_instance_of Definition::Method, method
assert_equal [parse_method_type("() -> ::Integer")], method.method_types
assert_equal type_name("::_Helloable"), method.defined_in
assert_equal type_name("::Hello"), method.implemented_in
end
definition.methods[:world].tap do |method|
assert_instance_of Definition::Method, method
assert_equal [parse_method_type("(::Symbol) -> ::Integer"), parse_method_type("() -> ::Integer")], method.method_types
assert_equal type_name("::_Helloable"), method.defined_in
assert_equal type_name("::Hello"), method.implemented_in
end
end
end
end
end
def test_build_one_singleton_variables
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
class Hello[A]
@name: A
@@count: Integer
self.@email: String
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_singleton(type_name("::Hello")).yield_self do |definition|
assert_instance_of Definition, definition
assert_equal [:@email].sort, definition.instance_variables.keys.sort
definition.instance_variables[:@email].yield_self do |variable|
assert_instance_of Definition::Variable, variable
assert_equal parse_type("::String"), variable.type
end
assert_equal [:@@count].sort, definition.class_variables.keys.sort
definition.class_variables[:@@count].yield_self do |variable|
assert_instance_of Definition::Variable, variable
assert_equal parse_type("::Integer"), variable.type
end
end
end
end
end
def test_build_instance
SignatureManager.new do |manager|
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(BuiltinNames::Object.name).yield_self do |definition|
assert_equal Set.new([:__id__, :initialize, :puts, :respond_to_missing?, :to_i]), Set.new(definition.methods.keys)
definition.methods[:__id__].yield_self do |method|
assert_method_definition method, ["() -> ::Integer"], accessibility: :public
end
definition.methods[:initialize].yield_self do |method|
assert_method_definition method, ["() -> void"], accessibility: :private
end
definition.methods[:puts].yield_self do |method|
assert_method_definition method, ["(*untyped) -> nil"], accessibility: :private
end
definition.methods[:respond_to_missing?].yield_self do |method|
assert_method_definition method, ["(::Symbol, bool) -> bool"], accessibility: :private
end
end
end
end
end
def test_build_instance_variables
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
class Hello[A]
@name: A
@@email: String
end
class Foo < Hello[String]
end
class Bar < Foo
@name: String
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Bar")).yield_self do |definition|
assert_instance_of Definition, definition
assert_equal [:@name].sort, definition.instance_variables.keys.sort
definition.instance_variables[:@name].yield_self do |variable|
assert_instance_of Definition::Variable, variable
assert_equal parse_type("::String"), variable.type
assert_equal type_name("::Bar"), variable.declared_in
assert_equal type_name("::Hello"), variable.parent_variable.declared_in
end
assert_equal [:@@email].sort, definition.class_variables.keys.sort
definition.class_variables[:@@email].yield_self do |variable|
assert_instance_of Definition::Variable, variable
assert_equal parse_type("::String"), variable.type
assert_equal type_name("::Hello"), variable.declared_in
end
end
end
end
end
def test_build_singleton
SignatureManager.new do |manager|
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_singleton(BuiltinNames::BasicObject.name).yield_self do |definition|
assert_equal ["() -> ::BasicObject"], definition.methods[:new].method_types.map {|x| x.to_s }
end
builder.build_singleton(BuiltinNames::String.name).yield_self do |definition|
assert_equal ["() -> ::String"], definition.methods[:new].method_types.map {|x| x.to_s }
end
end
end
end
def test_build_singleton_variables
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
class Hello
self.@name: Integer
@@email: String
end
class Foo < Hello
end
class Bar < Foo
self.@name: String
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_singleton(type_name("::Bar")).yield_self do |definition|
assert_instance_of Definition, definition
assert_equal [:@name].sort, definition.instance_variables.keys.sort
definition.instance_variables[:@name].yield_self do |variable|
assert_instance_of Definition::Variable, variable
assert_equal parse_type("::String"), variable.type
assert_equal type_name("::Bar"), variable.declared_in
assert_equal type_name("::Hello"), variable.parent_variable.declared_in
end
assert_equal [:@@email].sort, definition.class_variables.keys.sort
definition.class_variables[:@@email].yield_self do |variable|
assert_instance_of Definition::Variable, variable
assert_equal parse_type("::String"), variable.type
assert_equal type_name("::Hello"), variable.declared_in
end
end
end
end
end
def test_build_alias
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
class Hello
def foo: (String) -> void
alias bar foo
end
interface _World
def hello: () -> bool
alias world hello
end
class Error
alias self.xxx self.yyy
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Hello")).tap do |definition|
assert_instance_of Definition, definition
assert_method_definition definition.methods[:foo], ["(::String) -> void"]
assert_method_definition definition.methods[:bar], ["(::String) -> void"]
end
builder.build_interface(type_name("::_World")).tap do |definition|
assert_instance_of Definition, definition
assert_method_definition definition.methods[:hello], ["() -> bool"]
assert_method_definition definition.methods[:world], ["() -> bool"]
end
assert_raises UnknownMethodAliasError do
builder.build_singleton(type_name("::Error"))
end
end
end
end
def test_build_one_module_instance
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
interface _Each[A, B]
def each: { (A) -> void } -> B
end
module Enumerable2[X, Y] : _Each[X, Y]
def count: -> Integer
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Enumerable2")).yield_self do |definition|
assert_instance_of Definition, definition
assert_equal [:count, :each], definition.methods.keys.sort
assert_method_definition definition.methods[:count], ["() -> ::Integer"]
assert_method_definition definition.methods[:each], ["() { (X) -> void } -> Y"]
end
end
end
end
def test_build_singleton_module
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
interface _Each[A, B]
def each: { (A) -> void } -> B
end
module Enumerable2[X, Y] : _Each[X, Y]
def count: -> Integer
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_singleton(type_name("::Enumerable2")).yield_self do |definition|
assert_instance_of Definition, definition
assert_equal [:__id__, :initialize, :puts, :respond_to_missing?, :to_i], definition.methods.keys.sort
assert_method_definition definition.methods[:__id__], ["() -> ::Integer"]
assert_method_definition definition.methods[:initialize], ["() -> void"]
assert_method_definition definition.methods[:puts], ["(*untyped) -> nil"]
assert_method_definition definition.methods[:respond_to_missing?], ["(::Symbol, bool) -> bool"]
end
end
end
end
def test_attributes
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
class Hello
attr_reader instance_reader: String
attr_writer instance_writer(@writer): Integer
attr_accessor instance_accessor(): Symbol
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Hello")).yield_self do |definition|
assert_instance_of Definition, definition
assert_method_definition definition.methods[:instance_reader], ["() -> ::String"]
assert_ivar_definition definition.instance_variables[:@instance_reader], "::String"
assert_method_definition definition.methods[:instance_writer=], ["(::Integer instance_writer) -> ::Integer"]
assert_ivar_definition definition.instance_variables[:@writer], "::Integer"
assert_method_definition definition.methods[:instance_accessor], ["() -> ::Symbol"]
assert_method_definition definition.methods[:instance_accessor=], ["(::Symbol instance_accessor) -> ::Symbol"]
assert_nil definition.instance_variables[:@instance_accessor]
end
end
end
end
def test_singleton_attributes
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
class Hello
attr_reader self.reader: String
attr_writer self.writer(@writer): Integer
attr_accessor self.accessor(): Symbol
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_singleton(type_name("::Hello")).yield_self do |definition|
assert_instance_of Definition, definition
assert_method_definition definition.methods[:reader], ["() -> ::String"]
assert_ivar_definition definition.instance_variables[:@reader], "::String"
assert_method_definition definition.methods[:writer=], ["(::Integer writer) -> ::Integer"]
assert_ivar_definition definition.instance_variables[:@writer], "::Integer"
assert_method_definition definition.methods[:accessor], ["() -> ::Symbol"]
assert_method_definition definition.methods[:accessor=], ["(::Symbol accessor) -> ::Symbol"]
assert_nil definition.instance_variables[:@accessor]
end
end
end
end
def test_initialize_new
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
class Hello
def initialize: (String) -> void
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Hello")).tap do |definition|
assert_instance_of Definition, definition
assert_method_definition definition.methods[:initialize], ["(::String) -> void"], accessibility: :private
end
builder.build_singleton(type_name("::Hello")).yield_self do |definition|
assert_instance_of Definition, definition
assert_method_definition definition.methods[:new], ["(::String) -> ::Hello"], accessibility: :public
end
end
end
end
def test_initialize_new_override
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
class C0
def initialize: (Integer) -> void
end
class C1 < C0
def self.new: (String) -> untyped
end
class C2 < C1
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_singleton(type_name("::C0")).tap do |definition|
assert_instance_of Definition, definition
assert_method_definition definition.methods[:new], ["(::Integer) -> ::C0"]
end
builder.build_singleton(type_name("::C1")).tap do |definition|
assert_instance_of Definition, definition
assert_method_definition definition.methods[:new], ["(::String) -> untyped"]
end
builder.build_singleton(type_name("::C2")).tap do |definition|
assert_instance_of Definition, definition
assert_method_definition definition.methods[:new], ["(::String) -> untyped"]
end
end
end
end
def test_initialize_new_no_module
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
module M
def initialize: (Integer) -> void
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_singleton(type_name("::M")).tap do |definition|
assert_instance_of Definition, definition
refute_operator definition.methods, :key?, :new
end
end
end
end
def test_initialize_new_generic
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
class Hello[A]
def initialize: [X] () { (X) -> A } -> void
def get: () -> A
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Hello")).yield_self do |definition|
assert_instance_of Definition, definition
assert_method_definition definition.methods[:initialize], ["[X] () { (X) -> A } -> void"]
end
builder.build_singleton(type_name("::Hello")).yield_self do |definition|
assert_instance_of Definition, definition
assert_method_definition definition.methods[:new], ["[A, X] () { (X) -> A } -> ::Hello[A]"]
end
end
end
end
def test_initialize_new_generic_empty
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
class Hello[A]
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Hello")).yield_self do |definition|
assert_instance_of Definition, definition
assert_method_definition definition.methods[:initialize], ["() -> void"]
end
builder.build_singleton(type_name("::Hello")).yield_self do |definition|
assert_instance_of Definition, definition
assert_method_definition definition.methods[:new], ["[A] () -> ::Hello[A]"]
end
end
end
end
def test_initialize_new_generic_rename
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
class Hello[A]
def initialize: [A] () { (A) -> void } -> void
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Hello")).yield_self do |definition|
assert_instance_of Definition, definition
assert_method_definition definition.methods[:initialize], ["[A] () { (A) -> void } -> void"]
end
builder.build_singleton(type_name("::Hello")).yield_self do |definition|
assert_instance_of Definition, definition
definition.methods[:new].tap do |method|
assert_instance_of Definition::Method, method
assert_equal 1, method.method_types.size
# [A, A@1] () { (A@1) -> void } -> ::Hello[A]
assert_match(/\A\[A, A@(\d+)\] \(\) { \(A@\1\) -> void } -> ::Hello\[A\]\Z/, method.method_types[0].to_s)
end
end
end
end
end
def test_build_alias_forward
SignatureManager.new do |manager|
manager.files[Pathname("foo.rbs")] = <<EOF
class Hello
alias foo bar
def bar: () -> Integer
alias self.hoge self.huga
def self.huga: () -> void
end
interface _Person
alias first_name name
def name: () -> String
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Hello")).yield_self do |definition|
assert_instance_of Definition, definition
assert_method_definition definition.methods[:foo], ["() -> ::Integer"]
end
builder.build_singleton(type_name("::Hello")).yield_self do |definition|
assert_instance_of Definition, definition
assert_method_definition definition.methods[:hoge], ["() -> void"]
end
interface_name = type_name("::_Person")
builder.build_interface(interface_name).yield_self do |definition|
assert_instance_of Definition, definition
assert_method_definition definition.methods[:first_name], ["() -> ::String"]
end
end
end
end
def test_definition_method_type_def
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
class Hello
# doc1
%a{hello}
def foo: () -> String
| (Integer) -> String
end
class Hello
# doc2
%a{world}
def foo: (String) -> String | ...
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Hello")).tap do |definition|
foo = definition.methods[:foo]
assert_nil foo.super_method
assert_equal [parse_method_type("(::String) -> ::String"),
parse_method_type("() -> ::String"),
parse_method_type("(::Integer) -> ::String")], foo.method_types
assert_equal type_name("::Hello"), foo.defined_in
assert_equal type_name("::Hello"), foo.implemented_in
assert_includes foo.annotations, AST::Annotation.new(string: "hello", location: nil)
assert_includes foo.annotations, AST::Annotation.new(string: "world", location: nil)
assert_includes foo.comments, AST::Comment.new(string: "doc1\n", location: nil)
assert_includes foo.comments, AST::Comment.new(string: "doc2\n", location: nil)
assert_equal 3, foo.defs.size
foo.defs[0].tap do |defn|
assert_equal parse_method_type("(::String) -> ::String"), defn.type
assert_equal "doc2\n", defn.comment.string
assert_equal ["world"], defn.annotations.map(&:string)
assert_equal type_name("::Hello"), defn.defined_in
assert_equal type_name("::Hello"), defn.implemented_in
end
foo.defs[1].tap do |defn|
assert_equal parse_method_type("() -> ::String"), defn.type
assert_equal "doc1\n", defn.comment.string
assert_equal ["hello"], defn.annotations.map(&:string)
assert_equal type_name("::Hello"), defn.defined_in
assert_equal type_name("::Hello"), defn.implemented_in
end
foo.defs[2].tap do |defn|
assert_equal parse_method_type("(::Integer) -> ::String"), defn.type
assert_equal "doc1\n", defn.comment.string
assert_equal ["hello"], defn.annotations.map(&:string)
assert_equal type_name("::Hello"), defn.defined_in
assert_equal type_name("::Hello"), defn.implemented_in
end
end
end
end
end
def test_definition_method_type_def_interface
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
interface _Hello
# _Hello#foo
%a{_Hello#foo}
def foo: () -> String
end
class Hello
include _Hello
# Hello#foo
%a{Hello#foo}
def foo: (Integer) -> String | ...
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Hello")).tap do |definition|
foo = definition.methods[:foo]
assert_nil foo.super_method
assert_equal [parse_method_type("(::Integer) -> ::String"),
parse_method_type("() -> ::String")], foo.method_types
assert_equal 2, foo.defs.size
foo.defs[0].tap do |defn|
assert_equal parse_method_type("(::Integer) -> ::String"), defn.type
assert_equal "Hello#foo\n", defn.comment.string
assert_equal ["Hello#foo"], defn.annotations.map(&:string)
assert_equal type_name("::Hello"), defn.defined_in
assert_equal type_name("::Hello"), defn.implemented_in
end
foo.defs[1].tap do |defn|
assert_equal parse_method_type("() -> ::String"), defn.type
assert_equal "_Hello#foo\n", defn.comment.string
assert_equal ["_Hello#foo"], defn.annotations.map(&:string)
assert_equal type_name("::_Hello"), defn.defined_in
assert_equal type_name("::Hello"), defn.implemented_in
end
end
end
end
end
def test_build_with_unknown_super_class
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
class A < B
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
error = assert_raises RBS::NoSuperclassFoundError do
builder.build_instance(type_name("::A"))
end
assert_equal type_name("B"), error.type_name
assert_raises RBS::NoSuperclassFoundError do
builder.build_singleton(type_name("::A"))
end
end
end
end
def test_build_instance_with_unknown_mixin
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
class A
include _Foo
end
class C
extend Bar
end
class D
prepend Baz
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
assert_raises RBS::NoMixinFoundError do
builder.build_instance(type_name("::A"))
end.tap do |error|
assert_equal type_name("_Foo"), error.type_name
assert_instance_of RBS::AST::Members::Include, error.member
end
assert_raises RBS::NoMixinFoundError do
builder.build_singleton(type_name("::C"))
end.tap do |error|
assert_equal type_name("Bar"), error.type_name
end
assert_raises RBS::NoMixinFoundError do
builder.build_instance(type_name("::D"))
end.tap do |error|
assert_equal type_name("Baz"), error.type_name
end
end
end
end
def test_build_absent_namespace
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
class Hello::World
end
interface Hello::_World
end
type Hello::world = 30
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
assert_raises RBS::NoTypeFoundError do
builder.build_instance(type_name("::Hello::World"))
end
assert_raises RBS::NoTypeFoundError do
builder.build_singleton(type_name("::Hello::World"))
end
assert_raises RBS::NoTypeFoundError do
builder.build_interface(type_name("::Hello::_World"))
end
assert_raises RBS::NoTypeFoundError do
builder.expand_alias(type_name("::Hello::world"))
end
end
end
end
def test_definition_method_type_def_overload_from_super
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
class World
def foo: () -> String
end
class Hello < World
def foo: (Integer) -> String | ...
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Hello")).tap do |definition|
foo = definition.methods[:foo]
assert_equal ["(::Integer) -> ::String", "() -> ::String"], foo.method_types.map(&:to_s)
end
end
end
end
def test_definition_method_type_def_overload_from_super_no_super
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
class Hello
def foo: (Integer) -> String | ...
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
assert_raises RBS::InvalidOverloadMethodError do
builder.build_instance(type_name("::Hello"))
end
end
end
end
def test_new_from_included_initialize
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
class Hello
include World
end
module World
def initialize: (String, Integer) -> void
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Hello")).tap do |definition|
initalize = definition.methods[:initialize]
assert_equal ["(::String, ::Integer) -> void"], initalize.method_types.map(&:to_s)
end
builder.build_singleton(type_name("::Hello")).tap do |definition|
new = definition.methods[:new]
assert_equal ["(::String, ::Integer) -> ::Hello"], new.method_types.map(&:to_s)
end
end
end
end
def test_definition_variance_initialize
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
class Hello[out T]
def get: () -> T
def initialize: (T value) -> void
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Hello"))
end
end
end
def test_overload_super_method
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
class C1
def f: () -> void
def f: () -> Integer | ...
end
module M2
def f: () -> String
end
class C2
include M2
def f: () -> Integer | ...
end
interface _I3
def f: () -> String
end
class C3
include _I3
def f: () -> Integer | ...
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::C1")).tap do |definition|
assert_instance_of Definition, definition
definition.methods[:f].tap do |f|
assert_instance_of Definition::Method, f
assert_nil f.super_method
end
end
builder.build_instance(type_name("::C2")).tap do |definition|
assert_instance_of Definition, definition
definition.methods[:f].tap do |f|
assert_instance_of Definition::Method, f
refute_nil f.super_method
assert_equal type_name("::M2"), f.super_method.defined_in
end
end
builder.build_instance(type_name("::C3")).tap do |definition|
assert_instance_of Definition, definition
definition.methods[:f].tap do |f|
assert_instance_of Definition::Method, f
assert_nil f.super_method
end
end
end
end
end
def test_duplicated_methods_from_interfaces
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
interface _I1
def foo: () -> void
end
interface _I2
def foo: () -> String
end
class Hello
include _I1
include _I2
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
assert_raises RBS::DuplicatedInterfaceMethodDefinitionError do
builder.build_instance(type_name("::Hello"))
end
end
end
end
def test_duplicated_methods_from_interfaces2
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
interface _I1
def foo: () -> void
end
class Hello
include _I1
def foo: () -> String
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
assert_raises RBS::DuplicatedMethodDefinitionError do
builder.build_instance(type_name("::Hello"))
end
end
end
end
def test_include_interface_super
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
interface _I1
def foo: () -> void
end
class C0
include _I1
end
class C1
def foo: () -> void
end
class C2 < C1
include _I1
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::C0")).tap do |defn|
defn.methods[:foo].tap do |foo|
assert_equal type_name("::_I1"), foo.defined_in
assert_equal type_name("::C0"), foo.implemented_in
assert_nil foo.super_method
end
end
builder.build_instance(type_name("::C2")).tap do |defn|
defn.methods[:foo].tap do |foo|
assert_equal type_name("::_I1"), foo.defined_in
assert_equal type_name("::C2"), foo.implemented_in
assert_equal type_name("::C1"), foo.super_method.defined_in
end
end
end
end
end
def test_interface_alias
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
interface _I1
def foo: () -> void
end
class C0
include _I1
alias bar foo
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::C0")).tap do |defn|
defn.methods[:bar].tap do |bar|
assert_equal defn.methods[:foo], bar.alias_of
assert_equal type_name("::C0"), bar.defined_in
assert_equal type_name("::C0"), bar.implemented_in
assert_nil bar.super_method
end
end
end
end
end
def test_self_type_interface_methods
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
interface _I1
def a: () -> void
end
module M0 : _I1
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::M0")).tap do |defn|
defn.methods[:a].tap do |a|
assert_equal type_name("::_I1"), a.defined_in
assert_nil a.implemented_in
assert_nil a.super_method
end
end
end
end
end
def test_self_type_interface_methods_error
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
interface _I1
def a: () -> void
end
module M0 : _I1
def a: (Integer) -> String
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::M0")).tap do |definition|
definition.methods[:a].tap do |a|
assert_equal type_name("::M0"), a.defined_in
assert_equal type_name("::M0"), a.implemented_in
assert_equal type_name("::_I1"), a.super_method.defined_in
end
end
end
end
end
def test_self_type_interface_methods_error2
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
interface _I1
def a: () -> void
end
interface _I2
def a: () -> Integer
end
module M0 : _I1, _I2
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::M0")).tap do |definition|
definition.methods[:a].tap do |a|
assert_equal type_name("::_I2"), a.defined_in
assert_nil a.implemented_in
assert_nil a.super_method
assert_method_definition a, ["() -> ::Integer"]
end
end
end
end
end
def test_self_type_interface_methods_overload
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
interface _I1
def a: () -> void
end
module M0 : _I1
def a: (Integer) -> String | ...
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::M0")).tap do |definition|
definition.methods[:a].tap do |a|
assert_equal [type_name("::M0"), type_name("::_I1")], a.defs.map(&:defined_in)
assert_equal [type_name("::M0"), type_name("::M0")], a.defs.map(&:implemented_in)
assert_equal type_name("::_I1"), a.super_method.defined_in
end
end
end
end
end
def test_mixed_module_methods_building
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
class Foo
def foo: () -> void
end
module M0 : Foo
def bar: () -> void
end
class Bar
include M0 # Broken include, but RBS cannot detect it.
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::M0")).tap do |definition|
assert_operator definition.methods, :key?, :foo
assert_operator definition.methods, :key?, :bar
end
builder.build_instance(type_name("::Bar")).tap do |definition|
refute_operator definition.methods, :key?, :foo # foo is not defined in M0
assert_operator definition.methods, :key?, :bar
end
end
end
end
def test_generic_class_open
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
class Foo[A]
def foo: () -> A
end
class Foo[B]
def bar: () -> B
attr_reader Bar: B
@bar: B
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Foo")).tap do |definition|
assert_equal [parse_method_type("() -> A", variables: [:A])],
definition.methods[:foo].method_types
assert_equal [parse_method_type("() -> A", variables: [:A])],
definition.methods[:bar].method_types
assert_equal [parse_method_type("() -> A", variables: [:A])],
definition.methods[:Bar].method_types
assert_equal Types::Variable.build(:A),
definition.instance_variables[:@bar].type
assert_equal Types::Variable.build(:A),
definition.instance_variables[:@Bar].type
end
end
end
end
def test_generic_class_interface
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
class Foo[A]
def foo: () -> A
end
interface _Baz[Y]
def baz: () -> Y
end
class Foo[C]
include _Baz[C]
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Foo")).tap do |definition|
assert_equal [parse_method_type("() -> A", variables: [:A])],
definition.methods[:foo].method_types
assert_equal [parse_method_type("() -> A", variables: [:A])],
definition.methods[:baz].method_types
end
end
end
end
def test_generic_class_module
SignatureManager.new do |manager|
manager.files.merge!(Pathname("foo.rbs") => <<-EOF)
class Foo[A]
def foo: () -> A
end
class Foo[B]
include Bar[B]
end
module Bar[Y]
def bar: () -> Y
@bar: Y
end
EOF
manager.build do |env|
builder = DefinitionBuilder.new(env: env)
builder.build_instance(type_name("::Foo")).tap do |definition|
assert_equal [parse_method_type("() -> A", variables: [:A])],
definition.methods[:foo].method_types
assert_equal [parse_method_type("() -> A", variables: [:A])],
definition.methods[:bar].method_types
assert_equal Types::Variable.build(:A),
definition.instance_variables[:@bar].type
end
end
end
end
end
| 29.450026 | 130 | 0.63571 |
ffcc03620b010ff4109d30c5ec50a388183364ff | 921 | Pod::Spec.new do |s|
s.name = "CWUtils"
s.version = "0.15.2"
s.summary = "iOS 어플리케이션 개발용 유틸리티 모음"
s.description = "RxSwift 를 기반으로 하고 있음. (Dependancy : RxSwift, RxCocoa, RxOptional)"
s.homepage = "https://github.com/iamchiwon/CWUtils"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "iamchiwon" => "[email protected]" }
s.swift_versions = '5'
s.ios.deployment_target = '10.0'
s.source = { :git => "https://github.com/iamchiwon/CWUtils.git", :tag => s.version.to_s }
s.source_files = "CWUtils/Classes/**/*"
# s.resource_bundles = {
# 'CWUtils' => ['CWUtils/Assets/*.png']
# }
s.dependency "RxSwift"
s.dependency "RxCocoa"
s.dependency "RxSwiftExt"
s.dependency "RxOptional"
s.dependency "RxViewController"
s.dependency "SnapKit"
s.dependency "Reusable"
s.dependency "Then"
s.dependency "Kingfisher"
end
| 29.709677 | 97 | 0.617807 |
d5c0d8a5632b3ce8958c5a38b77feeacf0555249 | 143 | class AddSentColumnToApproval < ActiveRecord::Migration[5.0]
def change
add_column :approvals, :sent, :boolean, default: false
end
end
| 23.833333 | 60 | 0.755245 |
d50ae3140ae18caa4183a3adafe00fb24344a704 | 164 | default["pimon"]["listen_interface"] = "0.0.0.0"
default["pimon"]["port"] = 80
default["pimon"]["number_of_stats"] = 6
default["pimon"]["time_period_in_secs"] = 30
| 32.8 | 48 | 0.676829 |
e81db24d7cb2a750a86cd8279462b4eafbb45122 | 1,496 | module Formtastic
module Inputs
# Outputs a simple `<label>` with a `<textarea>` wrapped in the standard
# `<li>` wrapper. This is the default input choice for database columns of the `:text` type,
# but can forced on any text-like input with `:as => :text`.
#
# @example Full form context and output
#
# <%= semantic_form_for(@user) do |f| %>
# <%= f.inputs do %>
# <%= f.input :first_name, :as => :string %>
# <% end %>
# <% end %>
#
# <form...>
# <fieldset>
# <ol>
# <li class="string">
# <label for="user_first_name">First name</label>
# <input type="text" id="user_first_name" name="user[first_name]">
# </li>
# </ol>
# </fieldset>
# </form>
#
# @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documetation of all possible options.
class TextInput
include Base
def input_html_options
{
:cols => builder.default_text_area_width,
:rows => builder.default_text_area_height,
:placeholder => placeholder_text
}.merge(super)
end
def to_html
input_wrapping do
label_html <<
builder.text_area(method, input_html_options)
end
end
def placeholder_text
localized_string(method, options[:placeholder], :placeholder)
end
end
end
end | 28.769231 | 116 | 0.548797 |
e27340979c3adc733b5375cc4c653d11b997ea68 | 135 | class AddAuthorIdToSquirrelPosts < ActiveRecord::Migration
def change
add_column :squirrel_posts, :author_id, :integer
end
end
| 22.5 | 58 | 0.792593 |
e9578d0625c55ebcd4622e1d93088b6f50b78632 | 3,910 | module ApplicationController::Timelines
SELECT_EVENT_TYPE = [[N_('Management Events'), 'timeline'], [N_('Policy Events'), 'policy_timeline']].freeze
DateOptions = Struct.new(
:end_date,
:days,
:end,
:start,
:typ
) do
def update_from_params(params)
self.typ = params[:tl_typ] if params[:tl_typ]
self.days = params[:tl_days] if params[:tl_days]
self.end_date = params[:miq_date_1] || params[:miq_date]
end
def update_start_end(sdate, edate)
if !sdate.nil? && !edate.nil?
self.start = [sdate.year.to_s, (sdate.month - 1).to_s, sdate.day.to_s].join(", ")
self.end = [edate.year.to_s, (edate.month - 1).to_s, edate.day.to_s].join(", ")
self.end_date ||= [edate.month, edate.day, edate.year].join("/")
else
self.start = self.end = nil
end
self.days ||= "7"
end
end
ManagementEventsOptions = Struct.new(
:levels,
:categories
) do
def update_from_params(params)
self.levels = params[:tl_levels]&.map(&:to_sym) || group_levels
self.categories = {}
params.fetch(:tl_categories, []).each do |category_display_name|
group_data = event_groups[events[category_display_name]]
category = {
:display_name => category_display_name,
:include_set => [],
:exclude_set => [],
:regexes => []
}
group_levels.each do |lvl|
next unless group_data[lvl]
strings, regexes = group_data[lvl].partition { |typ| typ.kind_of?(String) }
if levels.include?(lvl)
category[:include_set].push(*strings)
category[:regexes].push(*regexes)
else
category[:exclude_set].push(*strings)
end
end
next if category[:include_set].empty? && category[:regexes].empty?
categories[events[category_display_name]] = category
end
end
def events
@events ||= event_groups.each_with_object({}) do |egroup, hash|
gname, list = egroup
hash[list[:name].to_s] = gname
end
end
def drop_cache
@events = @event_groups = @lvl_text_value = nil
end
def levels_text_and_value
@lvl_text_value ||= group_levels.map { |level| [level.to_s.titleize, level] }
end
private
def event_groups
@event_groups ||= EmsEvent.event_groups
end
def group_levels
EmsEvent::GROUP_LEVELS
end
end
PolicyEventsOptions = Struct.new(
:categories,
:result
) do
def update_from_params(params)
self.result = params[:tl_result] || "success"
self.categories = {}
params.fetch(:tl_categories, []).each do |category|
categories[category] = {
:display_name => category,
:include_set => events[category],
:exclude_set => [],
:regexes => []
}
end
end
def events
@events ||= MiqEventDefinitionSet.all.each_with_object({}) do |event, hash|
hash[event.description] = event.members.collect(&:name)
end
end
def drop_cache
@events = @fltr_cache = nil
end
end
Options = Struct.new(
:date,
:model,
:management,
:policy,
:tl_show
) do
def initialize(*args)
super
self.date = DateOptions.new
self.management = ManagementEventsOptions.new
self.policy = PolicyEventsOptions.new
end
def management_events?
tl_show == 'timeline'
end
def policy_events?
tl_show == 'policy_timeline'
end
def evt_type
management_events? ? :event_streams : :policy_events
end
def categories
(policy_events? ? policy : management).categories
end
def get_set(name)
categories.values.flat_map { |v| v[name] }
end
def drop_cache
[policy, management].each(&:drop_cache)
end
end
end
| 25.225806 | 110 | 0.598721 |
e2d2e0fbc3bdc9ef90fcba3c59a717c0df6849a2 | 120 | class AuthorsController < ApplicationController
def index
end
def show
@author = Author.find(params[:id])
end
end | 15 | 47 | 0.758333 |
6a2c751f2e24d0dd7dfa6343fa512854a474f86f | 1,148 | require_relative "./../../test_helper"
require_relative "./../../helpers/with_server"
require "test/unit"
require "json"
require "bibliotheca-client/client"
class TestOperations < Test::Unit::TestCase
extend WithServer
setup do
@auth_header = Bibliotheca::Client.class_variable_get(:@@auth_header)
Bibliotheca::Client.config url: "http://#{server.address}:#{server.port}"
@token = "valid_token"
@client = Bibliotheca::Client.new @token
@iv_token = "invalid_token"
@iv_client = Bibliotheca::Client.new @iv_token
end
test "logout" do
lmd = -> req, res {
if req[@auth_header] == @token
res.status = 204
else
res.status = 400
end
}
server.with_mount(Bibliotheca::Paths::LOGOUT, lmd) do
res = @client.logout
assert res.success?
res = @iv_client.logout
assert_false res.success?
end
end
test "ping" do
lmd = -> _, res {
res.status = 204
}
server.with_mount(Bibliotheca::Paths::PING, lmd) do
res = @client.ping
assert res.success?
res = @iv_client.ping
assert res.success?
end
end
end
| 20.872727 | 77 | 0.632404 |
abc019cb6abf13baf1a1b84a88df40e672c5932f | 667 | cask "alt-tab" do
version "4.18.0"
sha256 "c04e2c68c5ffcaa5ad5a637499e2cff998f035926032dc6e1ce17a9ac6589bd4"
url "https://github.com/lwouis/alt-tab-macos/releases/download/v#{version}/AltTab-#{version}.zip"
appcast "https://github.com/lwouis/alt-tab-macos/releases.atom"
name "alt-tab"
homepage "https://github.com/lwouis/alt-tab-macos"
auto_updates true
depends_on macos: ">= :sierra"
app "AltTab.app"
uninstall quit: "com.lwouis.alt-tab-macos"
zap trash: [
"~/Library/Caches/com.lwouis.alt-tab-macos",
"~/Library/Cookies/com.lwouis.alt-tab-macos.binarycookies",
"~/Library/Preferences/com.lwouis.alt-tab-macos.plist",
]
end
| 29 | 99 | 0.722639 |
e2d9d290ec73dec3a3a6e23fc76c81846f40f841 | 12,873 | # == Schema Information
#
# Table name: transactions
#
# id :integer not null, primary key
# starter_id :string(255) not null
# starter_uuid :binary(16) not null
# listing_id :integer not null
# listing_uuid :binary(16) not null
# conversation_id :integer
# automatic_confirmation_after_days :integer not null
# community_id :integer not null
# community_uuid :binary(16) not null
# created_at :datetime not null
# updated_at :datetime not null
# starter_skipped_feedback :boolean default(FALSE)
# author_skipped_feedback :boolean default(FALSE)
# last_transition_at :datetime
# current_state :string(255)
# commission_from_seller :integer
# minimum_commission_cents :integer default(0)
# minimum_commission_currency :string(255)
# payment_gateway :string(255) default("none"), not null
# listing_quantity :integer default(1)
# listing_author_id :string(255) not null
# listing_author_uuid :binary(16) not null
# listing_title :string(255)
# unit_type :string(32)
# unit_price_cents :integer
# unit_price_currency :string(8)
# unit_tr_key :string(64)
# unit_selector_tr_key :string(64)
# payment_process :string(31) default("none")
# delivery_method :string(31) default("none")
# shipping_price_cents :integer
# availability :string(32) default("none")
# booking_uuid :binary(16)
# deleted :boolean default(FALSE)
# commission_from_buyer :integer
# minimum_buyer_fee_cents :integer default(0)
# minimum_buyer_fee_currency :string(3)
#
# Indexes
#
# community_starter_state (community_id,starter_id,current_state)
# index_transactions_on_community_id (community_id)
# index_transactions_on_conversation_id (conversation_id)
# index_transactions_on_deleted (deleted)
# index_transactions_on_last_transition_at (last_transition_at)
# index_transactions_on_listing_author_id (listing_author_id)
# index_transactions_on_listing_id (listing_id)
# index_transactions_on_listing_id_and_current_state (listing_id,current_state)
# index_transactions_on_starter_id (starter_id)
# transactions_on_cid_and_deleted (community_id,deleted)
#
class Transaction < ApplicationRecord
include ExportTransaction
# While initiated is technically not a finished state it also
# doesn't have any payment data to track against, so removing person
# is still safe.
FINISHED_TX_STATES = ['initiated', 'free', 'rejected', 'confirmed', 'canceled', 'errored'].freeze
attr_accessor :contract_agreed
belongs_to :community
belongs_to :listing
has_many :transaction_transitions, dependent: :destroy, foreign_key: :transaction_id, inverse_of: :tx
has_one :booking, dependent: :destroy
has_one :shipping_address, dependent: :destroy
belongs_to :starter, class_name: "Person", foreign_key: :starter_id, inverse_of: :starter_transactions
belongs_to :conversation
has_many :testimonials, dependent: :destroy
belongs_to :listing_author, class_name: 'Person'
has_many :stripe_payments, dependent: :destroy
delegate :author, to: :listing
delegate :title, to: :listing, prefix: true
accepts_nested_attributes_for :booking
validates :payment_gateway, presence: true, on: :create
validates :community_uuid, :listing_uuid, :starter_id, :starter_uuid, presence: true, on: :create
validates :listing_quantity, numericality: {only_integer: true, greater_than_or_equal_to: 1}, on: :create
validates :listing_title, :listing_author_id, :listing_author_uuid, presence: true, on: :create
validates :unit_type, inclusion: ["hour", "day", "night", "week", "month", "custom", "unit", nil, :hour, :day, :night, :week, :month, :custom, :unit], on: :create
validates :availability, inclusion: ["none", "booking", :none, :booking], on: :create
validates :delivery_method, inclusion: ["none", "shipping", "pickup", nil, :none, :shipping, :pickup], on: :create
validates :payment_process, inclusion: [:none, :postpay, :preauthorize], on: :create
validates :payment_gateway, inclusion: [:paypal, :checkout, :braintree, :stripe, :none], on: :create
validates :commission_from_seller, numericality: {only_integer: true}, on: :create
validates :automatic_confirmation_after_days, numericality: {only_integer: true}, on: :create
monetize :minimum_commission_cents, with_model_currency: :minimum_commission_currency
monetize :unit_price_cents, with_model_currency: :unit_price_currency
monetize :shipping_price_cents, allow_nil: true, with_model_currency: :unit_price_currency
monetize :minimum_buyer_fee_cents, with_model_currency: :minimum_buyer_fee_currency
scope :exist, -> { where(deleted: false) }
scope :for_person, -> (person){
where('listing_author_id = ? OR starter_id = ?', person.id, person.id)
}
scope :availability_blocking, -> do
where(current_state: ['payment_intent_requires_action', 'preauthorized', 'paid', 'confirmed', 'canceled', 'dismissed', 'disputed'])
end
scope :non_free, -> { where('current_state <> ?', ['free']) }
scope :by_community, -> (community_id) { where(community_id: community_id) }
scope :with_payment_conversation, -> {
left_outer_joins(:conversation).merge(Conversation.payment)
}
scope :with_payment_conversation_latest, -> (sort_direction) {
with_payment_conversation.order(Arel.sql(
"GREATEST(COALESCE(transactions.last_transition_at, 0),
COALESCE(conversations.last_message_at, 0)) #{sort_direction}"))
}
scope :for_csv_export, -> {
includes(:starter, :booking, :testimonials, :transaction_transitions, :conversation => [{:messages => :sender}, :listing, :participants], :listing => :author)
}
scope :for_testimonials, -> {
includes(:testimonials, testimonials: [:author, :receiver], listing: :author)
.where(current_state: ['confirmed', 'canceled', 'dismissed'])
}
scope :search_by_party_or_listing_title, ->(pattern) {
joins(:starter, :listing_author)
.where("listing_title like :pattern
OR (#{Person.search_by_pattern_sql('people')})
OR (#{Person.search_by_pattern_sql('listing_authors_transactions')})", pattern: pattern)
}
scope :search_for_testimonials, ->(community, pattern) do
with_testimonial_ids = by_community(community.id)
.left_outer_joins(testimonials: [:author, :receiver])
.where("
testimonials.text like :pattern
OR #{Person.search_by_pattern_sql('people')}
OR #{Person.search_by_pattern_sql('receivers_testimonials')}
", pattern: pattern).select("`transactions`.`id`")
for_testimonials.joins(:listing, :starter, :listing_author)
.where("
`listings`.`title` like :pattern
OR #{Person.search_by_pattern_sql('people')}
OR #{Person.search_by_pattern_sql('listing_authors_transactions')}
OR `transactions`.`id` IN (#{with_testimonial_ids.to_sql})
", pattern: pattern).distinct
end
scope :paid_or_confirmed, -> { where(current_state: ['paid', 'confirmed']) }
scope :skipped_feedback, -> { where('starter_skipped_feedback OR author_skipped_feedback') }
scope :waiting_feedback, -> {
where("NOT starter_skipped_feedback AND NOT #{Testimonial.with_tx_starter.select('1').arel.exists.to_sql}
OR NOT author_skipped_feedback AND NOT #{Testimonial.with_tx_author.select('1').arel.exists.to_sql}")
}
scope :unfinished, -> { where.not(current_state: FINISHED_TX_STATES) }
# We include deleted transactions on purpose. They might be in a
# state where e.g. IPN message causes them to proceed so removing
# user data would be unwise.
scope :unfinished_for_person, -> (person) { unfinished.for_person(person) }
def booking_uuid_object
if self[:booking_uuid].nil?
nil
else
UUIDUtils.parse_raw(self[:booking_uuid])
end
end
def booking_uuid_object=(uuid)
self.booking_uuid = UUIDUtils.raw(uuid)
end
def community_uuid_object
if self[:community_uuid].nil?
nil
else
UUIDUtils.parse_raw(self[:community_uuid])
end
end
def starter_uuid_object
if self[:starter_uuid].nil?
nil
else
UUIDUtils.parse_raw(self[:starter_uuid])
end
end
def listing_author_uuid_object
if self[:listing_author_uuid].nil?
nil
else
UUIDUtils.parse_raw(self[:listing_author_uuid])
end
end
def starter_uuid=(value)
write_attribute(:starter_uuid, UUIDUtils::RAW.call(value))
end
def listing_uuid=(value)
write_attribute(:listing_uuid, UUIDUtils::RAW.call(value))
end
def community_uuid=(value)
write_attribute(:community_uuid, UUIDUtils::RAW.call(value))
end
def listing_author_uuid=(value)
write_attribute(:listing_author_uuid, UUIDUtils::RAW.call(value))
end
def booking_uuid=(value)
write_attribute(:booking_uuid, UUIDUtils::RAW.call(value))
end
def status
current_state
end
def has_feedback_from?(person)
if author == person
testimonial_from_author.present?
else
testimonial_from_starter.present?
end
end
def feedback_skipped_by?(person)
if author == person
author_skipped_feedback?
else
starter_skipped_feedback?
end
end
def testimonial_from_author
testimonials.find { |testimonial| testimonial.author_id == author.id }
end
def testimonial_from_starter
testimonials.find { |testimonial| testimonial.author_id == starter.id }
end
# TODO This assumes that author is seller (which is true for all offers, sell, give, rent, etc.)
# Change it so that it looks for TransactionProcess.author_is_seller
def seller
author
end
# TODO This assumes that author is seller (which is true for all offers, sell, give, rent, etc.)
# Change it so that it looks for TransactionProcess.author_is_seller
def buyer
starter
end
def participations
[author, starter]
end
def payer
starter
end
def payment_receiver
author
end
def with_type(&block)
block.call(:listing_conversation)
end
def latest_activity
(transaction_transitions + conversation.messages).max
end
# Give person (starter or listing author) and get back the other
#
# Note: I'm not sure whether we want to have this method or not but at least it makes refactoring easier.
def other_party(person)
person == starter ? listing.author : starter
end
def unit_type
Maybe(read_attribute(:unit_type)).to_sym.or_else(nil)
end
def item_total
unit_price * listing_quantity
end
def payment_gateway
read_attribute(:payment_gateway)&.to_sym
end
def payment_process
read_attribute(:payment_process)&.to_sym
end
def commission
[(item_total * (commission_from_seller / 100.0) unless commission_from_seller.nil?),
(minimum_commission unless minimum_commission.nil? || minimum_commission.zero?),
Money.new(0, item_total.currency)]
.compact
.max
end
def buyer_commission
[(item_total * (commission_from_buyer / 100.0) unless commission_from_buyer.nil?),
(minimum_buyer_fee unless minimum_buyer_fee.nil? || minimum_buyer_fee.zero?),
Money.new(0, item_total.currency)]
.compact
.max
end
def waiting_testimonial_from?(person_id)
if starter_id == person_id && starter_skipped_feedback
false
elsif listing_author_id == person_id && author_skipped_feedback
false
else
testimonials.detect{|t| t.author_id == person_id}.nil?
end
end
def mark_as_seen_by_current(person_id)
self.conversation
.participations
.where("person_id = '#{person_id}'")
.update_all(is_read: true) # rubocop:disable Rails/SkipsModelValidations
end
def payment_total
unit_price = self.unit_price || 0
quantity = self.listing_quantity || 1
shipping_price = self.shipping_price || 0
(unit_price * quantity) + shipping_price + buyer_commission
end
def last_transition_by_admin?
transition = transaction_transitions.last
transition && transition[:metadata] && transition[:metadata]['executed_by_admin']
end
end
| 37.313043 | 164 | 0.681271 |
ab579318d4b728a754b6ca32479703ea78e06a62 | 16,572 | # frozen_string_literal: true
require 'spec_helper'
describe 'php', type: :class do
on_supported_os.each do |os, facts|
context "on #{os}" do
let :facts do
facts
end
php_cli_package = case facts[:os]['name']
when 'Debian'
case facts[:os]['release']['major']
when '11'
'php7.4-cli'
when '10'
'php7.3-cli'
else
'php5-cli'
end
when 'Ubuntu'
case facts[:os]['release']['major']
when '20.04'
'php7.4-cli'
when '18.04'
'php7.2-cli'
else
'php5-cli'
end
end
php_fpm_package = case facts[:os]['name']
when 'Debian'
case facts[:os]['release']['major']
when '11'
'php7.4-fpm'
when '10'
'php7.3-fpm'
else
'php5-fpm'
end
when 'Ubuntu'
case facts[:os]['release']['major']
when '20.04'
'php7.4-fpm'
when '18.04'
'php7.2-fpm'
else
'php5-fpm'
end
end
php_dev_package = case facts[:os]['name']
when 'Debian'
case facts[:os]['release']['major']
when '11'
'php7.4-dev'
when '10'
'php7.3-dev'
else
'php5-dev'
end
when 'Ubuntu'
case facts[:os]['release']['major']
when '20.04'
'php7.4-dev'
when '18.04'
'php7.2-dev'
else
'php5-dev'
end
end
describe 'works without params' do
it { is_expected.to compile.with_all_deps }
end
describe 'when called with no parameters' do # rubocop: disable RSpec/EmptyExampleGroup
case facts[:osfamily]
when 'Suse', 'RedHat', 'CentOS'
it { is_expected.to contain_class('php::global') }
end
case facts[:osfamily]
when 'Debian'
it { is_expected.not_to contain_class('php::global') }
it { is_expected.to contain_class('php::fpm') }
it { is_expected.to contain_package('php-pear').with_ensure('present') }
it { is_expected.to contain_class('php::composer') }
it { is_expected.to contain_package(php_cli_package).with_ensure('present') }
it { is_expected.to contain_package(php_fpm_package).with_ensure('present') }
it { is_expected.to contain_package(php_dev_package).with_ensure('present') }
when 'Suse'
it { is_expected.to contain_package('php5').with_ensure('present') }
it { is_expected.to contain_package('php5-devel').with_ensure('present') }
it { is_expected.to contain_package('php5-pear').with_ensure('present') }
it { is_expected.not_to contain_package('php5-cli') }
it { is_expected.not_to contain_package('php5-dev') }
it { is_expected.not_to contain_package('php-pear') }
when 'RedHat', 'CentOS'
it { is_expected.to contain_package('php-cli').with_ensure('present') }
it { is_expected.to contain_package('php-common').with_ensure('present') }
end
end
describe 'when called with extensions' do
let(:params) { { extensions: { xml: {} } } }
it { is_expected.to contain_php__extension('xml').with_ensure('present') }
end
describe 'when called with ensure absent and extensions' do
extensions = { xml: {} }
let(:params) { { ensure: 'absent', extensions: extensions } }
it { is_expected.to contain_php__extension('xml').with_ensure('absent') }
case facts[:osfamily]
when 'Debian'
it { is_expected.to contain_package(php_cli_package).with_ensure('absent') }
it { is_expected.to contain_package(php_fpm_package).with_ensure('absent') }
it { is_expected.to contain_package(php_dev_package).with_ensure('absent') }
when 'Suse'
it { is_expected.to contain_package('php5').with_ensure('absent') }
it { is_expected.to contain_package('php5-devel').with_ensure('absent') }
when 'RedHat', 'CentOS'
it { is_expected.to contain_package('php-cli').with_ensure('absent') }
it { is_expected.to contain_package('php-common').with_ensure('absent') }
end
end
describe 'when called with package_prefix parameter' do # rubocop: disable RSpec/EmptyExampleGroup
package_prefix = 'myphp-'
let(:params) { { package_prefix: package_prefix } }
case facts[:osfamily]
when 'Suse', 'RedHat', 'CentOS'
it { is_expected.to contain_class('php::global') }
end
case facts[:osfamily]
when 'Debian', 'RedHat', 'CentOS'
it { is_expected.to contain_package("#{package_prefix}cli").with_ensure('present') }
end
case facts[:osfamily]
when 'Debian'
it { is_expected.not_to contain_class('php::global') }
it { is_expected.to contain_class('php::fpm') }
it { is_expected.to contain_class('php::composer') }
it { is_expected.to contain_package('php-pear').with_ensure('present') }
it { is_expected.to contain_package("#{package_prefix}dev").with_ensure('present') }
it { is_expected.to contain_package("#{package_prefix}fpm").with_ensure('present') }
when 'Suse'
it { is_expected.to contain_package('php5').with_ensure('present') }
it { is_expected.to contain_package("#{package_prefix}devel").with_ensure('present') }
it { is_expected.to contain_package("#{package_prefix}pear").with_ensure('present') }
it { is_expected.not_to contain_package("#{package_prefix}cli").with_ensure('present') }
it { is_expected.not_to contain_package("#{package_prefix}dev") }
it { is_expected.not_to contain_package('php-pear') }
when 'RedHat', 'CentOS'
it { is_expected.to contain_package("#{package_prefix}common").with_ensure('present') }
end
end
describe 'when called with fpm_user parameter' do
let(:params) { { fpm_user: 'nginx' } }
it { is_expected.to contain_class('php::fpm').with(user: 'nginx') }
it { is_expected.to contain_php__fpm__pool('www').with(user: 'nginx') }
dstfile = case facts[:osfamily]
when 'Debian'
case facts[:os]['name']
when 'Debian'
case facts[:os]['release']['major']
when '11'
'/etc/php/7.4/fpm/pool.d/www.conf'
when '10'
'/etc/php/7.3/fpm/pool.d/www.conf'
else
'/etc/php5/fpm/pool.d/www.conf'
end
when 'Ubuntu'
case facts[:os]['release']['major']
when '20.04'
'/etc/php/7.4/fpm/pool.d/www.conf'
when '18.04'
'/etc/php/7.2/fpm/pool.d/www.conf'
else
'/etc/php5/fpm/pool.d/www.conf'
end
end
when 'Archlinux'
'/etc/php/php-fpm.d/www.conf'
when 'Suse'
'/etc/php5/fpm/pool.d/www.conf'
when 'RedHat'
'/etc/php-fpm.d/www.conf'
when 'FreeBSD'
'/usr/local/etc/php-fpm.d/www.conf'
end
it { is_expected.to contain_file(dstfile).with_content(%r{user = nginx}) }
end
describe 'when called with fpm_group parameter' do
let(:params) { { fpm_group: 'nginx' } }
it { is_expected.to contain_class('php::fpm').with(group: 'nginx') }
it { is_expected.to contain_php__fpm__pool('www').with(group: 'nginx') }
dstfile = case facts[:osfamily]
when 'Debian'
case facts[:os]['name']
when 'Debian'
case facts[:os]['release']['major']
when '11'
'/etc/php/7.4/fpm/pool.d/www.conf'
when '10'
'/etc/php/7.3/fpm/pool.d/www.conf'
else
'/etc/php5/fpm/pool.d/www.conf'
end
when 'Ubuntu'
case facts[:os]['release']['major']
when '20.04'
'/etc/php/7.4/fpm/pool.d/www.conf'
when '18.04'
'/etc/php/7.2/fpm/pool.d/www.conf'
else
'/etc/php5/fpm/pool.d/www.conf'
end
end
when 'Archlinux'
'/etc/php/php-fpm.d/www.conf'
when 'Suse'
'/etc/php5/fpm/pool.d/www.conf'
when 'RedHat'
'/etc/php-fpm.d/www.conf'
when 'FreeBSD'
'/usr/local/etc/php-fpm.d/www.conf'
end
it { is_expected.to contain_file(dstfile).with_content(%r{group = nginx}) }
end
describe 'when configured with a pool with apparmor_hat parameter' do
let(:params) { { fpm_pools: { 'www' => { 'apparmor_hat' => 'www' } } } }
it { is_expected.to contain_php__fpm__pool('www').with(apparmor_hat: 'www') }
dstfile = case facts[:osfamily]
when 'Debian'
case facts[:os]['name']
when 'Debian'
case facts[:os]['release']['major']
when '11'
'/etc/php/7.4/fpm/pool.d/www.conf'
when '10'
'/etc/php/7.3/fpm/pool.d/www.conf'
else
'/etc/php5/fpm/pool.d/www.conf'
end
when 'Ubuntu'
case facts[:os]['release']['major']
when '20.04'
'/etc/php/7.4/fpm/pool.d/www.conf'
when '18.04'
'/etc/php/7.2/fpm/pool.d/www.conf'
else
'/etc/php5/fpm/pool.d/www.conf'
end
end
when 'Archlinux'
'/etc/php/php-fpm.d/www.conf'
when 'Suse'
'/etc/php5/fpm/pool.d/www.conf'
when 'RedHat'
'/etc/php-fpm.d/www.conf'
when 'FreeBSD'
'/usr/local/etc/php-fpm.d/www.conf'
end
it { is_expected.to contain_file(dstfile).with_content(%r{apparmor_hat = www}) }
end
describe 'when fpm is disabled' do
let(:params) { { fpm: false } }
it { is_expected.not_to contain_class('php::fpm') }
end
describe 'when composer is disabled' do
let(:params) { { composer: false } }
it { is_expected.not_to contain_class('php::composer') }
end
if facts[:osfamily] == 'RedHat' || facts[:osfamily] == 'CentOS'
describe 'when called with valid settings parameter types' do
let(:params) do
{
'settings' =>
{
'PHP/memory_limit' => '300M',
'PHP/safe_mode_include_dir' => :undef,
'PHP/error_reporting' => '',
'PHP/max_execution_time' => 60
}
}
end
it { is_expected.to contain_php__config__setting('/etc/php.ini: PHP/memory_limit').with_value('300M') }
it { is_expected.to contain_ini_setting('/etc/php.ini: PHP/safe_mode_include_dir').with_ensure('absent') }
it { is_expected.to contain_php__config__setting('/etc/php.ini: PHP/error_reporting').with_value('') }
it { is_expected.to contain_php__config__setting('/etc/php.ini: PHP/max_execution_time').with_value(60) }
end
describe 'when called with cli_settings parameter' do
let(:params) do
{
'settings' => { 'PHP/memory_limit' => '300M' },
'cli_settings' => { 'PHP/memory_limit' => '1000M' }
}
end
it { is_expected.to contain_php__config__setting('/etc/php.ini: PHP/memory_limit').with_value('300M') }
it { is_expected.to contain_php__config__setting('/etc/php-fpm.ini: PHP/memory_limit').with_value('300M') }
it { is_expected.to contain_php__config__setting('/etc/php-cli.ini: PHP/memory_limit').with_value('1000M') }
end
describe 'when called with global option for rhscl_mode' do
describe 'when called with mode "remi"' do
scl_php_version = 'php56'
rhscl_mode = 'remi'
let(:pre_condition) do
"class {'::php::globals':
php_version => '#{scl_php_version}',
rhscl_mode => '#{rhscl_mode}'
}"
end
let(:params) do
{ settings: { 'Date/date.timezone' => 'Europe/Berlin' } }
end
it { is_expected.to contain_class('php::global') }
it { is_expected.to contain_package("#{scl_php_version}-php-cli").with_ensure('present') }
it { is_expected.to contain_package("#{scl_php_version}-php-common").with_ensure('present') }
it { is_expected.to contain_php__config('global').with(file: "/etc/opt/#{rhscl_mode}/#{scl_php_version}/php.ini") }
it { is_expected.not_to contain_php__config('cli') }
# see: https://github.com/voxpupuli/puppet-php/blob/master/lib/puppet/parser/functions/to_hash_settings.rb
it { is_expected.to contain_php__config__setting("/etc/opt/#{rhscl_mode}/#{scl_php_version}/php.ini: Date/date.timezone").with_value('Europe/Berlin') }
end
describe 'when called with mode "rhscl"' do
scl_php_version = 'rh-php56'
rhscl_mode = 'rhscl'
let(:pre_condition) do
"class {'::php::globals':
php_version => '#{scl_php_version}',
rhscl_mode => '#{rhscl_mode}'
}"
end
let(:params) do
{ settings: { 'Date/date.timezone' => 'Europe/Berlin' } }
end
it { is_expected.to contain_class('php::global') }
it { is_expected.to contain_package("#{scl_php_version}-php-cli").with_ensure('present') }
it { is_expected.to contain_package("#{scl_php_version}-php-common").with_ensure('present') }
it { is_expected.to contain_php__config('global').with(file: "/etc/opt/rh/#{scl_php_version}/php.ini") }
it { is_expected.to contain_php__config('cli').with(file: "/etc/opt/rh/#{scl_php_version}/php-cli.ini") }
it { is_expected.to contain_php__config__setting("/etc/opt/rh/#{scl_php_version}/php.ini: Date/date.timezone").with_value('Europe/Berlin') }
end
end
end
describe 'when called with pool_purge => true and fpm_pools => {}' do
let(:params) { { pool_purge: true, fpm_pools: {} } }
it { is_expected.to contain_class('php::fpm').with(pool_purge: true) }
it { is_expected.not_to contain_php__fpm__pool('www') }
end
end
end
end
| 42.821705 | 163 | 0.493483 |
79052c0de706c0fab8d6b42fb7153fee11107433 | 1,416 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'cancannible/version'
Gem::Specification.new do |spec|
spec.name = "cancannible"
spec.version = Cancannible::VERSION
spec.authors = ["Paul Gallagher"]
spec.email = ["[email protected]"]
spec.summary = "Dynamic, configurable permissions for CanCan"
spec.description = "Extends CanCan with dynamic, inheritable permissions stored in a database, with caching and multi-tenant refinements"
spec.homepage = "https://github.com/evendis/cancannible"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
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_runtime_dependency "activesupport", "~> 6.1"
spec.add_runtime_dependency "activemodel", "~> 6.1"
spec.add_runtime_dependency "cancancan"
spec.add_development_dependency "activerecord", "~> 6.1"
spec.add_development_dependency "sqlite3", ">= 1.3.2"
spec.add_development_dependency "bundler"
spec.add_development_dependency "rake"
spec.add_development_dependency "rdoc"
spec.add_development_dependency "rspec"
spec.add_development_dependency "guard-rspec"
spec.add_development_dependency "rb-fsevent"
end
| 40.457143 | 141 | 0.711864 |
bb8c447bdbf3c596017570cdd7112e31350b8e99 | 747 | Pod::Spec.new do |s|
s.name = "Annotated"
s.version = "0.1.0"
s.summary = "Easy String Annotation"
s.description = <<-DESC
Annotate your Strings, render them in NSAttributedString or Text
DESC
s.homepage = "https://github.com/jegnux/Annotated"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Jérôme Alves" => "[email protected]" }
s.social_media_url = ""
s.ios.deployment_target = "11.0"
s.osx.deployment_target = "10.10"
s.watchos.deployment_target = "2.0"
s.tvos.deployment_target = "11.0"
s.source = { :git => "https://github.com/jegnux/Annotated.git", :tag => s.version.to_s }
s.source_files = "Sources/**/*"
s.frameworks = "Foundation"
end
| 37.35 | 96 | 0.606426 |
1c0d33511fdcf90401c7c9fed8d59382c080e9ba | 4,133 | describe 'create latest matrix (latest pact revision/latest verification for provider version)', migration: true do
before do
PactBroker::Database.migrate(50)
end
def shorten_row row
"#{row[:consumer_name]}#{row[:consumer_version_number]} #{row[:provider_name]}#{row[:provider_version_number] || '?'} (r#{row[:pact_revision_number]}/n#{row[:verification_number] || '?'})"
end
let(:now) { DateTime.new(2018, 2, 2) }
let!(:consumer) { create(:pacticipants, {name: 'C', created_at: now, updated_at: now}) }
let!(:provider) { create(:pacticipants, {name: 'P', created_at: now, updated_at: now}) }
let!(:consumer_version_1) { create(:versions, {number: '1', order: 1, pacticipant_id: consumer[:id], created_at: now, updated_at: now}) }
let!(:consumer_version_2) { create(:versions, {number: '2', order: 2, pacticipant_id: consumer[:id], created_at: now, updated_at: now}) }
let!(:provider_version_1) { create(:versions, {number: '1', order: 1, pacticipant_id: provider[:id], created_at: now, updated_at: now}) }
let!(:provider_version_2) { create(:versions, {number: '2', order: 2, pacticipant_id: provider[:id], created_at: now, updated_at: now}) }
let!(:pact_version_1) { create(:pact_versions, {content: {some: 'json'}.to_json, sha: '1', consumer_id: consumer[:id], provider_id: provider[:id], created_at: now}) }
let!(:pact_version_2) { create(:pact_versions, {content: {some: 'json other'}.to_json, sha: '2', consumer_id: consumer[:id], provider_id: provider[:id], created_at: now}) }
let!(:pact_version_3) { create(:pact_versions, {content: {some: 'json more'}.to_json, sha: '3', consumer_id: consumer[:id], provider_id: provider[:id], created_at: now}) }
let!(:pact_publication_1) do
create(:pact_publications, {
consumer_version_id: consumer_version_1[:id],
provider_id: provider[:id],
revision_number: 1,
pact_version_id: pact_version_1[:id],
created_at: now
})
end
let!(:pact_publication_2) do
create(:pact_publications, {
consumer_version_id: consumer_version_1[:id],
provider_id: provider[:id],
revision_number: 2,
pact_version_id: pact_version_2[:id],
created_at: now
})
end
# C2 P? (r1/n?)
let!(:pact_publication_3) do
create(:pact_publications, {
consumer_version_id: consumer_version_2[:id],
provider_id: provider[:id],
revision_number: 1,
pact_version_id: pact_version_3[:id],
created_at: now
})
end
# C1 P3 (r1n3)
let!(:verification_1) do
create(:verifications, {
number: 1,
success: true,
provider_version_id: provider_version_1[:id],
pact_version_id: pact_version_1[:id],
execution_date: now,
created_at: now
})
end
# C1 P3 (r1n1)
let!(:verification_2) do
create(:verifications, {
number: 1,
success: true,
provider_version_id: provider_version_1[:id],
pact_version_id: pact_version_2[:id],
execution_date: now,
created_at: now
})
end
# include
let!(:verification_3) do
create(:verifications, {
number: 2,
success: true,
provider_version_id: provider_version_1[:id],
pact_version_id: pact_version_2[:id],
execution_date: now,
created_at: now
})
end
# include
let!(:verification_4) do
create(:verifications, {
number: 3,
success: true,
provider_version_id: provider_version_2[:id],
pact_version_id: pact_version_2[:id],
execution_date: now,
created_at: now
})
end
# C1 P1 (r1/n1) this pact version is overwritten by r2
# C1 P1 (r2/n1) this verification is overwritten by n2
# C1 P1 (r2/n2)
# C1 P2 (r2/n3)
# C2 P? (r1/n?)
it "only includes the latest pact revisions and latest verifications" do
rows = database[:latest_matrix].order(:verification_id).all.collect{|row| shorten_row(row) }
expect(rows).to include "C1 P1 (r2/n2)"
expect(rows).to include "C1 P2 (r2/n3)"
expect(rows).to include "C2 P? (r1/n?)"
expect(rows).to_not include "C1 P1 (r2/n1)"
expect(database[:latest_matrix].count).to eq 3
end
end
| 36.254386 | 192 | 0.664408 |
33ec5eeffaf5536140cb8517c1c911de88076c99 | 1,139 | #
# Be sure to run `pod lib lint LanguageManger-iOS.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'LanguageManager-iOS'
s.version = '1.2.5'
s.summary = 'Language manager used to handle change app language'
s.description = <<-DESC
Language manager used to handle change app language without restart the app.
DESC
s.homepage = 'https://github.com/lienghongky/LanguageManager-iOS'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Abedalkareem' => '[email protected]' }
s.source = { :git => 'https://github.com/lienghongky/LanguageManager-iOS.git', :tag => s.version.to_s }
s.swift_version = '5.0'
s.social_media_url = 'https://twitter.com/AbedalkareemOmr'
s.ios.deployment_target = '9.0'
s.tvos.deployment_target = '13.0'
s.source_files = 'LanguageManager-iOS/Classes/**/*'
end
| 36.741935 | 115 | 0.646181 |
ed047beda4e3639075905a969f7defd106184cbc | 861 | require 'test_helper'
class TestStore
def initialize
@test_hash = {}
end
def write(uid, value)
@test_hash[uid] = value
end
def read(uid)
@test_hash[uid]
end
end
class ConfigurationTest < Minitest::Test
def test_configuration_defaults
assert_nil ActiveWaiter.configuration.layout
end
def test_configuration_layout
ActiveWaiter.configure do |config|
config.layout = 'layouts/application'
end
assert_equal "layouts/application", ActiveWaiter.configuration.layout
ensure
ActiveWaiter.configuration = nil
end
def test_configuration_store
test_store = TestStore.new
ActiveWaiter.configure do |config|
config.store = test_store
end
ActiveWaiter.write("abcdef", "test")
assert_equal "test", test_store.read("abcdef")
ensure
ActiveWaiter.configuration = nil
end
end
| 19.568182 | 73 | 0.722416 |
015331461276f490c6a05e9cfaf7e169b65c4916 | 563 | class CreateServices < ActiveRecord::Migration
def change
create_table :services do |t|
t.belongs_to :location
t.text :audience
t.text :description
t.text :eligibility
t.text :fees
t.text :how_to_apply
t.text :name
t.text :short_desc
t.text :urls
t.text :wait
t.text :funding_sources
t.text :service_areas, array: true, default: []
t.text :keywords
t.timestamps
end
add_index :services, :location_id
add_index :services, :service_areas, using: 'gin'
end
end
| 23.458333 | 53 | 0.634103 |
bfad98515764cbe64ed41ec89a30a232c21ca1b8 | 560 | require 'jump_back/options_parser'
module JumpBack
module Redirection
def save_referer
session[:jump_back_stored_referer] ||= request.referer
end
def return_to_referer(path=root_path, options={})
options = OptionsParser.new(path: path, options: options, default: root_path)
session[:jump_back_stored_referer] ? redirect_to(clear_referer, options.redirect_options) : redirect_to(options.path, options.redirect_options)
end
def clear_referer
session.delete(:jump_back_stored_referer)
end
end
end | 28 | 149 | 0.7375 |
5dbcb491d7902f31240060b45d5b148ea9a85252 | 60 | class Instrument < ApplicationRecord
belongs_to :user
end
| 15 | 36 | 0.816667 |
39581cf27c9cb54147ac578f5ed98d0ac63a0b4e | 1,789 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Cosmosdb::Mgmt::V2021_01_15
module Models
#
# The read-only access keys for the given database account.
#
class DatabaseAccountListReadOnlyKeysResult
include MsRestAzure
# @return [String] Base 64 encoded value of the primary read-only key.
attr_accessor :primary_readonly_master_key
# @return [String] Base 64 encoded value of the secondary read-only key.
attr_accessor :secondary_readonly_master_key
#
# Mapper for DatabaseAccountListReadOnlyKeysResult class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'DatabaseAccountListReadOnlyKeysResult',
type: {
name: 'Composite',
class_name: 'DatabaseAccountListReadOnlyKeysResult',
model_properties: {
primary_readonly_master_key: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'primaryReadonlyMasterKey',
type: {
name: 'String'
}
},
secondary_readonly_master_key: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'secondaryReadonlyMasterKey',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 29.816667 | 78 | 0.580212 |
e99d787f21038e0f33b7e27559ef8fe3a3a3efa3 | 6,245 | module ActiveMerchant #:nodoc:
module Billing #:nodoc:
class PayboxDirectGateway < Gateway
class_attribute :live_url_backup
self.test_url = 'https://preprod-ppps.paybox.com/PPPS.php'
self.live_url = 'https://ppps.paybox.com/PPPS.php'
self.live_url_backup = 'https://ppps1.paybox.com/PPPS.php'
# Payment API Version
API_VERSION = '00103'
# Transactions hash
TRANSACTIONS = {
:authorization => '00001',
:capture => '00002',
:purchase => '00003',
:unreferenced_credit => '00004',
:void => '00005',
:refund => '00014'
}
CURRENCY_CODES = {
'AUD'=> '036',
'CAD'=> '124',
'CZK'=> '203',
'DKK'=> '208',
'HKD'=> '344',
'ICK'=> '352',
'JPY'=> '392',
'NOK'=> '578',
'SGD'=> '702',
'SEK'=> '752',
'CHF'=> '756',
'GBP'=> '826',
'USD'=> '840',
'EUR'=> '978'
}
SUCCESS_CODES = ['00000']
UNAVAILABILITY_CODES = ['00001', '00097', '00098']
SUCCESS_MESSAGE = 'The transaction was approved'
FAILURE_MESSAGE = 'The transaction failed'
# Money is referenced in cents
self.money_format = :cents
self.default_currency = 'EUR'
# The countries the gateway supports merchants from as 2 digit ISO country codes
self.supported_countries = ['FR']
# The card types supported by the payment gateway
self.supported_cardtypes = [:visa, :master, :american_express, :diners_club, :jcb]
# The homepage URL of the gateway
self.homepage_url = 'http://www.paybox.com/'
# The name of the gateway
self.display_name = 'Paybox Direct'
def initialize(options = {})
requires!(options, :login, :password)
super
end
def authorize(money, creditcard, options = {})
post = {}
add_invoice(post, options)
add_creditcard(post, creditcard)
add_amount(post, money, options)
commit('authorization', money, post)
end
def purchase(money, creditcard, options = {})
post = {}
add_invoice(post, options)
add_creditcard(post, creditcard)
add_amount(post, money, options)
commit('purchase', money, post)
end
def capture(money, authorization, options = {})
requires!(options, :order_id)
post = {}
add_invoice(post, options)
add_amount(post, money, options)
post[:numappel] = authorization[0, 10]
post[:numtrans] = authorization[10, 10]
commit('capture', money, post)
end
def void(identification, options = {})
requires!(options, :order_id, :amount)
post ={}
add_invoice(post, options)
add_reference(post, identification)
add_amount(post, options[:amount], options)
post[:porteur] = '000000000000000'
post[:dateval] = '0000'
commit('void', options[:amount], post)
end
def credit(money, identification, options = {})
ActiveMerchant.deprecated CREDIT_DEPRECATION_MESSAGE
refund(money, identification, options)
end
def refund(money, identification, options = {})
post = {}
add_invoice(post, options)
add_reference(post, identification)
add_amount(post, money, options)
commit('refund', money, post)
end
private
def add_invoice(post, options)
post[:reference] = options[:order_id]
end
def add_creditcard(post, creditcard)
post[:porteur] = creditcard.number
post[:dateval] = expdate(creditcard)
post[:cvv] = creditcard.verification_value if creditcard.verification_value?
end
def add_reference(post, identification)
post[:numappel] = identification[0, 10]
post[:numtrans] = identification[10, 10]
end
def add_amount(post, money, options)
post[:montant] = ('0000000000' + (money ? amount(money) : ''))[-10..-1]
post[:devise] = CURRENCY_CODES[options[:currency] || currency(money)]
end
def parse(body)
results = {}
body.split(/&/).each do |pair|
key, val = pair.split(/\=/)
results[key.downcase.to_sym] = CGI.unescape(val) if val
end
results
end
def commit(action, money = nil, parameters = nil)
request_data = post_data(action, parameters)
response = parse(ssl_post(test? ? self.test_url : self.live_url, request_data))
response = parse(ssl_post(self.live_url_backup, request_data)) if service_unavailable?(response) && !test?
Response.new(success?(response), message_from(response), response.merge(
:timestamp => parameters[:dateq]),
:test => test?,
:authorization => response[:numappel].to_s + response[:numtrans].to_s,
:fraud_review => false,
:sent_params => parameters.delete_if { |key, value| ['porteur', 'dateval', 'cvv'].include?(key.to_s) }
)
end
def success?(response)
SUCCESS_CODES.include?(response[:codereponse])
end
def service_unavailable?(response)
UNAVAILABILITY_CODES.include?(response[:codereponse])
end
def message_from(response)
success?(response) ? SUCCESS_MESSAGE : (response[:commentaire] || FAILURE_MESSAGE)
end
def post_data(action, parameters = {})
parameters.update(
:version => API_VERSION,
:type => TRANSACTIONS[action.to_sym],
:dateq => Time.now.strftime('%d%m%Y%H%M%S'),
:numquestion => unique_id(parameters[:order_id]),
:site => @options[:login].to_s[0, 7],
:rang => @options[:rang] || @options[:login].to_s[7..-1],
:cle => @options[:password],
:pays => '',
:archivage => parameters[:order_id]
)
parameters.collect { |key, value| "#{key.to_s.upcase}=#{CGI.escape(value.to_s)}" }.join('&')
end
def unique_id(seed = 0)
randkey = "#{seed}#{Time.now.usec}".to_i % 2147483647 # Max paybox value for the question number
"0000000000#{randkey}"[-10..-1]
end
end
end
end
| 31.225 | 114 | 0.584628 |
28e1fce2b67a58f0322b5487e233fbd29ed79a08 | 4,265 | #--
# This file is part of the X12Parser library that provides tools to
# manipulate X12 messages using Ruby native syntax.
#
# http://x12parser.rubyforge.org
#
# Copyright (C) 2012 P&D Technical Solutions, LLC.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#++
#
require 'x12'
require 'test/unit'
class Test999Factory < Test::Unit::TestCase
def setup
@parser = X12::Parser.new('999.xml')
@msg = "ISA*00* *00* *27*PPPPPP *27*XXXXXX *100914*1025*^*00501*000000218*0*T*:~GS*FA*PPPPPP*XXXXXX*20100914*10251463*3*X*005010X231A1~ST*999*3001*005010X231A1~AK1*HC*2145001*005010X222A1~AK2*837*000000001*005010X222A1~IK5*A~AK9*A*1*1*1~SE*6*3001~GE*1*3~IEA*1*000000218~"
end
def teardown
#nothing
end
def set_header(r)
r.ISA.AuthorizationInformationQualifier = "00"
r.ISA.AuthorizationInformation = " "
r.ISA.SecurityInformationQualifier = "00"
r.ISA.SecurityInformation = " "
r.ISA.InterchangeIdQualifier1 = "27"
r.ISA.InterchangeSenderId = "PPPPPP "
r.ISA.InterchangeIdQualifier2 = "27"
r.ISA.InterchangeReceiverId = "XXXXXX "
r.ISA.InterchangeDate = "100914"
r.ISA.InterchangeTime = "1025"
r.ISA.InterchangeControlStandardsIdentifier = "^"
r.ISA.InterchangeControlVersionNumber = "00501"
r.ISA.InterchangeControlNumber = "000000218"
r.ISA.AcknowledgmentRequested = "0"
r.ISA.UsageIndicator = "T"
r.ISA.ComponentElementSeparator = ":"
r.GS.FunctionalIdentifierCode = "FA"
r.GS.ApplicationSendersCode = "PPPPPP"
r.GS.ApplicationReceiversCode = "XXXXXX"
r.GS.Date = "20100914"
r.GS.Time = "10251463"
r.GS.GroupControlNumber = "3"
r.GS.ResponsibleAgencyCode = "X"
r.GS.VersionReleaseIndustryIdentifierCode = "005010X231A1"
r.ST.TransactionSetIdentifierCode = 999
r.ST.TransactionSetControlNumber = '3001'
r.ST.ImplementationConventionReference = "005010X231A1"
return r
end
def set_trailer(r, count)
r.SE.NumberOfIncludedSegments = count
r.SE.TransactionSetControlNumber = "3001"
r.GE.NumberOfTransactionSetsIncluded = "1"
r.GE.GroupControlNumber = "3"
r.IEA.NumberOfIncludedFunctionalGroups = "1"
r.IEA.InterchangeControlNumber = "000000218"
return r
end
def test_all
@r = @parser.factory('999')
@r = set_header(@r)
#count both the ST and SE segments
@seg_count = 2
@r.AK1 {|a|
a.FunctionalIdentifierCode = "HC"
a.GroupControlNumber = "2145001"
a.VersionReleaseIndustryIdentifierCode = "005010X222A1"
}
@seg_count += 1
@r.L1000 {|a|
a.AK2.TransactionSetIdentifierCode = "837"
a.AK2.TransactionSetControlNumber = "000000001"
a.AK2.ImplementationConventionReference = "005010X222A1"
@seg_count += 1
a.IK5.TransactionSetAcknowledgmentCode = "A"
@seg_count += 1
}
@r.AK9 {|a|
a.FunctionalGroupAcknowledgeCode = "A"
a.NumberOfTransactionSetsIncluded = "1"
a.NumberOfReceivedTransactionSets = "1"
a.NumberOfAcceptedTransactionSets = "1"
}
@seg_count += 1
@r = set_trailer(@r, @seg_count)
assert_equal(@msg, @r.render)
end
def test_timing
start = Time::now
X12::TEST_REPEAT.times do
test_all
end
finish = Time::now
puts sprintf("Factories per second, 999: %.2f, elapsed: %.1f", X12::TEST_REPEAT.to_f/(finish-start), finish-start)
end # test_timing
end | 33.320313 | 309 | 0.67034 |
91628ccfba7216fcb37dd89303cee268a29b622b | 2,904 | require "spec_helper"
require "httpi/auth/config"
describe HTTPI::Auth::Config do
let(:auth) { HTTPI::Auth::Config.new }
describe "#basic" do
it "lets you specify the basic auth credentials" do
auth.basic "username", "password"
auth.basic.should == ["username", "password"]
end
it "also accepts an Array of credentials" do
auth.basic ["username", "password"]
auth.basic.should == ["username", "password"]
end
it "sets the authentication type to :basic" do
auth.basic "username", "password"
auth.type.should == :basic
end
end
describe "#basic?" do
it "should default to return false" do
auth.should_not be_basic
end
it "should return true for HTTP basic auth" do
auth.basic "username", "password"
auth.should be_basic
end
end
describe "#digest" do
it "lets you specify the digest auth credentials" do
auth.digest "username", "password"
auth.digest.should == ["username", "password"]
end
it "also accepts an Array of credentials" do
auth.digest ["username", "password"]
auth.digest.should == ["username", "password"]
end
it "sets the authentication type to :digest" do
auth.digest "username", "password"
auth.type.should == :digest
end
end
describe "#digest?" do
it "should default to return false" do
auth.should_not be_digest
end
it "should return true for HTTP digest auth" do
auth.digest "username", "password"
auth.should be_digest
end
end
describe "#http?" do
it "should default to return false" do
auth.should_not be_http
end
it "should return true for HTTP basic auth" do
auth.basic "username", "password"
auth.should be_http
end
it "should return true for HTTP digest auth" do
auth.digest "username", "password"
auth.should be_http
end
end
describe "#ssl" do
it "should return the HTTPI::Auth::SSL object" do
auth.ssl.should be_a(HTTPI::Auth::SSL)
end
end
describe "#ssl?" do
it "should default to return false" do
auth.should_not be_ssl
end
it "should return true for SSL client auth" do
auth.ssl.cert_key_file = "spec/fixtures/client_key.pem"
auth.ssl.cert_file = "spec/fixtures/client_cert.pem"
auth.should be_ssl
end
end
describe "#type" do
it "should return the authentication type" do
auth.basic "username", "password"
auth.type.should == :basic
end
end
describe "#credentials" do
it "return the credentials for HTTP basic auth" do
auth.basic "username", "basic"
auth.credentials.should == ["username", "basic"]
end
it "return the credentials for HTTP digest auth" do
auth.digest "username", "digest"
auth.credentials.should == ["username", "digest"]
end
end
end
| 24.610169 | 61 | 0.642218 |
7a7b4453609264de5d6be82a3756cf78118d388f | 2,226 | # frozen_string_literal: true
module Hyrax
##
# Provides tools for interpreting form input as a visibility.
#
# @since 3.0.0
class VisibilityIntention
PUBLIC = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC
PRIVATE = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE
LEASE_REQUEST = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_LEASE
EMBARGO_REQUEST = Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_EMBARGO
##
# @!attribute [rw] after
# @return [String] the visibility requested after the embargo/lease release
# @!attribute [rw] during
# @return [String] the visibility requested while the embargo/lease is in effect
# @!attribute [rw] release_date
# @return [String]
# @!attribute [rw] visibility
# @return [String]
attr_accessor :after, :during, :release_date, :visibility
##
# @param [String] after
# @param [String] during
# @param [String] release_date
# @param [String] visibility
def initialize(visibility: PRIVATE, release_date: nil, during: nil, after: nil)
self.after = after
self.during = during
self.release_date = release_date
self.visibility = visibility
end
##
# @return [Array] the parameters for the requested embargo
def embargo_params
return [] unless wants_embargo?
raise ArgumentError unless valid_embargo?
[release_date, (during || PRIVATE), (after || PUBLIC)]
end
##
# @return [Array] the parameters for the requested embargo
def lease_params
return [] unless wants_lease?
raise ArgumentError unless valid_lease?
[release_date, (during || PUBLIC), (after || PRIVATE)]
end
##
# @return [Boolean]
def valid_embargo?
wants_embargo? && release_date.present?
end
##
# @return [Boolean]
def wants_embargo?
visibility == EMBARGO_REQUEST
end
##
# @return [Boolean]
def valid_lease?
wants_lease? && release_date.present?
end
##
# @return [Boolean]
def wants_lease?
visibility == LEASE_REQUEST
end
end
end
| 28.177215 | 87 | 0.651393 |
386238a8478c5faa977f498f3077ced9c6cd5ee3 | 2,005 | module SSHKit
module Sudo
module Backend
module Netssh
private
def execute_command!(cmd)
output.log_command_start(cmd)
cmd.started = true
exit_status = nil
with_ssh do |ssh|
ssh.open_channel do |chan|
chan.request_pty
chan.exec cmd.to_command do |_ch, _success|
chan.on_data do |ch, data|
cmd.on_stdout(ch, data)
output.log_command_data(cmd, :stdout, data)
end
chan.on_extended_data do |ch, _type, data|
cmd.on_stderr(ch, data)
output.log_command_data(cmd, :stderr, data)
end
chan.on_request("exit-status") do |_ch, data|
exit_status = data.read_long
end
#chan.on_request("exit-signal") do |ch, data|
# # TODO: This gets called if the program is killed by a signal
# # might also be a worthwhile thing to report
# exit_signal = data.read_string.to_i
# warn ">>> " + exit_signal.inspect
# output.log_command_killed(cmd, exit_signal)
#end
chan.on_open_failed do |_ch|
# TODO: What do do here?
# I think we should raise something
end
chan.on_process do |_ch|
# TODO: I don't know if this is useful
end
chan.on_eof do |_ch|
# TODO: chan sends EOF before the exit status has been
# writtend
end
end
chan.wait
end
ssh.loop
end
# Set exit_status and log the result upon completion
if exit_status
cmd.exit_status = exit_status
output.log_command_exit(cmd)
end
end
end
end
end
end
| 34.568966 | 80 | 0.487781 |
26682621735bca53955fb317967f7d0059ede7c7 | 3,971 | require 'raindrops'
require 'cdo/aws/metrics'
require 'honeybadger'
require 'concurrent/timer_task'
module Cdo
# UnicornListener extends the Raindrops::Middleware class,
# which instruments a Rack application to collect the number of
# currently-executing requests using an atomic counter shared across
# all Unicorn worker-processes.
#
# Every :interval seconds (default 1), metrics are collected.
# Once :report_count metrics (default 60) have been collected, they are asynchronously reported to CloudWatch.
#
# The following metrics are collected and reported:
# `active` - the number of active TCP/socket connections
# `queued` - the number of queued TCP/socket requests
# `calling` - the maximum number of currently-executing requests at any point during the interval.
#
# The :listeners option accepts an array of strings (TCP or Unix domain socket names).
# By default, all listeners used by the Unicorn master process are monitored.
#
# Any errors are forwarded to Honeybadger for logging and notifying.
class UnicornListener < Raindrops::Middleware
def initialize(app, opts = {})
# Track max_calling using a modified Stats implementation.
opts[:stats] ||= StatsWithMax.new
# Disable the reporting endpoint with an empty-string :path by default.
opts[:path] ||= ''
super(app, opts)
@metrics = %i(active queued calling).map {|name| [name, []]}.to_h
@report_count = opts[:report_count] || 60
interval = opts[:interval] || 1
spawn_reporting_task(interval) unless interval.zero?
end
def shutdown
@task && @task.shutdown
end
def spawn_reporting_task(interval)
@task ||= Concurrent::TimerTask.new(execution_interval: interval, &method(:collect_metrics)).
with_observer {|_, _, ex| Honeybadger.notify(ex) if ex}.
execute
end
# Periodically collect unicorn-listener metrics,
# reporting every time `report_count` metrics have been collected.
def collect_metrics(*_)
stat_values = collect_listener_stats + [@stats.max_calling.tap {@stats.max_calling = 0}]
@metrics.zip(stat_values) {|stat, val| stat[1] << {timestamp: Time.now, value: val}}
report!(@metrics) if @metrics.values.first.count >= @report_count
end
# Collect current snapshot of tcp/unix listener stats.
def collect_listener_stats
stats = {}
stats.merge! Raindrops::Linux.tcp_listener_stats(@tcp.uniq) if @tcp
stats.merge! Raindrops::Linux.unix_listener_stats(@unix.uniq) if @unix
%i(active queued).map do |name|
stats.values.map(&name).inject(:+)
end
end
# Report all stats as CloudWatch metrics, then clear the collection.
# @param metrics [Hash]
def report!(metrics)
metric_data = metrics.map do |name, stat|
stat.reject {|datum| datum[:value].nil?}.map do |datum|
{
metric_name: name,
dimensions: [
{name: "Environment", value: CDO.rack_env},
{name: "Host", value: CDO.pegasus_hostname}
],
timestamp: datum[:timestamp],
value: datum[:value],
unit: 'Count',
storage_resolution: 1
}
end
end.flatten
metrics.values.map(&:clear)
Cdo::Metrics.push('Unicorn', metric_data)
end
end
# Extends Raindrops::Middleware::Stats (which defines :calling and :writing)
# with an additional :max_calling atomic counter.
# This allows us to record the peak number of currently-executing
# worker-processes at any point, which a one-second sampling interval
# might not otherwise capture.
#
# rubocop:disable Style/StructInheritance
class StatsWithMax < Raindrops::Struct.new(:calling, :writing, :max_calling)
# Override incr_calling to keep max_calling updated.
def incr_calling
calling = super
self.max_calling = calling if calling > max_calling
end
end
end
| 38.182692 | 112 | 0.679174 |
7a5663cfd744f931e9007c3964fc0bd46de6aea8 | 1,053 | class Highlight < Formula
desc "Convert source code to formatted text with syntax highlighting"
homepage "http://www.andre-simon.de/doku/highlight/en/highlight.html"
url "http://www.andre-simon.de/zip/highlight-3.33.tar.bz2"
sha256 "64b530354feccabc3e8eeec02a0341be0625509db1fa5dd201c4d07e4d845c3c"
head "svn://svn.code.sf.net/p/syntaxhighlight/code/highlight/"
bottle do
sha256 "0e0b5a6ce08ef6e007e442ad27fdaf8e8229c28f5d03fa7b23d3388218dd3303" => :sierra
sha256 "eff4f5323affe30dcc734277971442c8bb8dff968c56e44cb23c85da5e0efab4" => :el_capitan
sha256 "30b5bc8958c29900e3f23ad788d8c04b0dd0a1423fe6ea10d2b930fc59bbdfe3" => :yosemite
end
depends_on "pkg-config" => :build
depends_on "boost"
depends_on "lua"
def install
conf_dir = etc/"highlight/" # highlight needs a final / for conf_dir
system "make", "PREFIX=#{prefix}", "conf_dir=#{conf_dir}"
system "make", "PREFIX=#{prefix}", "conf_dir=#{conf_dir}", "install"
end
test do
system bin/"highlight", doc/"examples/highlight_pipe.php"
end
end
| 37.607143 | 92 | 0.756885 |
b94d3beb76cdeda9639f8a45ae575e08343f532f | 678 | cask 'termius-beta' do
version '5.12.0'
sha256 '629060c853ef4ffab88098f2bf3fbeb0e5b9ee55b659ce278d300a4267860c72'
url 'https://www.termius.com/beta/download/mac/Termius+Beta.dmg'
name 'Termius Beta'
homepage 'https://www.termius.com/beta-program'
app 'Termius Beta.app'
zap trash: [
'~/.termius',
'~/Library/Application Support/Termius Beta',
'~/Library/Saved Application State/com.termius-beta.mac.savedState',
'/Library/Preferences/com.termius-beta.mac.helper.plist',
'/Library/Preferences/com.termius-beta.mac.plist',
'~/Library/Logs/Termius Beta',
]
end
| 33.9 | 83 | 0.640118 |
f83186e13b3d91ef62299b499b962306d975208e | 356 | require 'contentful/management'
require 'contentful_migrations/utils'
require 'contentful_migrations/version'
require 'contentful_migrations/migration_content_type'
require 'contentful_migrations/migration_proxy'
require 'contentful_migrations/migration'
require 'contentful_migrations/migrator'
load 'tasks/contentful_migrations.rake' if defined?(Rails)
| 35.6 | 58 | 0.867978 |
d53556b086604e3e249453af0da0cea5dd0429ff | 219 | # frozen_string_literal: true
require_relative "spec_helper"
require_relative "../lib/my_module"
describe MyModule do
it "extends with OpencBot methods" do
described_class.should respond_to :save_data
end
end
| 19.909091 | 48 | 0.794521 |
f849830b99d147f80c05724f4a8e81b695e71a48 | 4,795 | # -*- coding: binary -*-
module Rex
module Proto
module Kerberos
module Model
# This class provides a representation of an Authenticator, sent with a
# ticket to the server to certify the client's knowledge of the encryption
# key in the ticket.
class Authenticator < Element
# @!attribute vno
# @return [Fixnum] The authenticator version number
attr_accessor :vno
# @!attribute crealm
# @return [String] The realm in which the client is registered
attr_accessor :crealm
# @!attribute cname
# @return [Rex::Proto::Kerberos::Model::PrincipalName] The name part of the client's principal
# identifier
attr_accessor :cname
# @!attribute checksum
# @return [Rex::Proto::Kerberos::Model::Checksum] The checksum of the application data that
# accompanies the KRB_AP_REQ.
attr_accessor :checksum
# @!attribute cusec
# @return [Fixnum] The microsecond part of the client's timestamp
attr_accessor :cusec
# @!attribute ctime
# @return [Time] The current time of the client's host
attr_accessor :ctime
# @!attribute subkey
# @return [Rex::Proto::Kerberos::Model::EncryptionKey] the client's choice for an encryption
# key which is to be used to protect this specific application session
attr_accessor :subkey
# Rex::Proto::Kerberos::Model::Authenticator decoding isn't supported
#
# @raise [NotImplementedError]
def decode(input)
raise ::NotImplementedError, 'Authenticator decoding not supported'
end
# Encodes the Rex::Proto::Kerberos::Model::Authenticator into an ASN.1 String
#
# @return [String]
def encode
elems = []
elems << OpenSSL::ASN1::ASN1Data.new([encode_vno], 0, :CONTEXT_SPECIFIC)
elems << OpenSSL::ASN1::ASN1Data.new([encode_crealm], 1, :CONTEXT_SPECIFIC)
elems << OpenSSL::ASN1::ASN1Data.new([encode_cname], 2, :CONTEXT_SPECIFIC)
elems << OpenSSL::ASN1::ASN1Data.new([encode_checksum], 3, :CONTEXT_SPECIFIC) if checksum
elems << OpenSSL::ASN1::ASN1Data.new([encode_cusec], 4, :CONTEXT_SPECIFIC)
elems << OpenSSL::ASN1::ASN1Data.new([encode_ctime], 5, :CONTEXT_SPECIFIC)
elems << OpenSSL::ASN1::ASN1Data.new([encode_subkey], 6, :CONTEXT_SPECIFIC) if subkey
seq = OpenSSL::ASN1::Sequence.new(elems)
seq_asn1 = OpenSSL::ASN1::ASN1Data.new([seq], AUTHENTICATOR, :APPLICATION)
seq_asn1.to_der
end
# Encrypts the Rex::Proto::Kerberos::Model::Authenticator
#
# @param etype [Fixnum] the crypto schema to encrypt
# @param key [String] the key to encrypt
# @return [String] the encrypted result
# @raise [NotImplementedError] if the encryption schema isn't supported
def encrypt(etype, key)
data = self.encode
res = ''
case etype
when RC4_HMAC
res = encrypt_rc4_hmac(data, key, 7)
else
raise ::NotImplementedError, 'EncryptedData schema is not supported'
end
res
end
private
# Encodes the vno field
#
# @return [OpenSSL::ASN1::Integer]
def encode_vno
bn = OpenSSL::BN.new(vno.to_s)
int = OpenSSL::ASN1::Integer.new(bn)
int
end
# Encodes the crealm field
#
# @return [OpenSSL::ASN1::GeneralString]
def encode_crealm
OpenSSL::ASN1::GeneralString.new(crealm)
end
# Encodes the cname field
#
# @return [String]
def encode_cname
cname.encode
end
# Encodes the checksum field
#
# @return [String]
def encode_checksum
checksum.encode
end
# Encodes the cusec field
#
# @return [OpenSSL::ASN1::Integer]
def encode_cusec
bn = OpenSSL::BN.new(cusec.to_s)
int = OpenSSL::ASN1::Integer.new(bn)
int
end
# Encodes the ctime field
#
# @return [OpenSSL::ASN1::GeneralizedTime]
def encode_ctime
OpenSSL::ASN1::GeneralizedTime.new(ctime)
end
# Encodes the subkey field
#
# @return [String]
def encode_subkey
subkey.encode
end
end
end
end
end
end | 33.531469 | 106 | 0.559958 |
e9a5888e093a07e977e3b08aa7e02cee5e55b312 | 93 | collection roles
attributes :id, :name, :color, :billable, :technical, :show_in_team, :admin
| 31 | 75 | 0.752688 |
0818c6f7c07e58b5e5ef7e0bf936346f45c16676 | 1,779 | Pod::Spec.new do |s|
s.name = "CocoaExtension"
s.version = "2.1.0"
s.summary = "Foundation/UIKit extension kit. It is category based and looks familiar to Foundation/UIKit. It includes many common snippets as shortcut."
s.description = <<-DESC
This library includes small Foundation/Cocoa/UIKit extensions. This library does not includes high-level data structure, algorithm or frameworks, but collection of code snippets.
* Many common snippets in a method call.
* Looks like native foundation methods - It follows Apple Coding Guideline and Foundation naming convention.
See document on [Github] (http://youknowone.github.com/FoundationExtension)
Try FoundationExtension for Foundation extensions.
For iOS, UIKitExtension is available too.
DESC
s.homepage = "https://github.com/youknowone/FoundationExtension"
s.license = "2-clause BSD"
s.author = { "Jeong YunWon" => "[email protected]" }
s.social_media_url = "http://twitter.com/youknowone_"
s.source = { :git => "https://github.com/youknowone/FoundationExtension.git", :tag => s.version }
s.dependency "cdebug", "~> 1.2"
s.requires_arc = true
s.static_framework = true
s.osx.deployment_target = '10.9'
s.ios.deployment_target = '9.0'
s.tvos.deployment_target = '9.0'
s.watchos.deployment_target = '2.0'
s.subspec "CocoaExtension" do |ss|
ss.osx.deployment_target = '10.9'
ss.source_files = "CocoaExtension/*.{h,m}"
ss.public_header_files = "CocoaExtension/*.h"
ss.header_dir = "CocoaExtension"
ss.frameworks = "Cocoa", "QuartzCore"
ss.dependency "FoundationExtension"
end
end
| 48.081081 | 198 | 0.659921 |
91f593b5a58586237ea41632b6a62aa94e2f80d3 | 1,628 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Rumale::NeuralNetwork::MLPRegressor do
let(:x) { two_clusters_dataset[0] }
let(:single_target) { x[true, 0] + x[true, 1]**2 }
let(:multi_target) { Numo::DFloat[x[true, 0].to_a, (x[true, 1]**2).to_a].transpose.dot(Numo::DFloat[[0.6, 0.4], [0.8, 0.2]]) }
let(:n_samples) { x.shape[0] }
let(:n_features) { x.shape[1] }
let(:n_outputs) { y.shape[1] }
let(:estimator) { described_class.new(hidden_units: [128, 128], max_iter: 100, verbose: false, random_seed: 1).fit(x, y) }
let(:predicted) { estimator.predict(x) }
let(:score) { estimator.score(x, y) }
let(:copied) { Marshal.load(Marshal.dump(estimator)) }
shared_examples 'regression' do
it 'fits model for given dataset.', :aggregate_failures do
expect(predicted).to be_a(Numo::DFloat)
expect(predicted).to be_contiguous
expect(predicted.ndim).to eq(y.ndim)
expect(predicted.shape[0]).to eq(n_samples)
expect(score).to be > 0.98
end
end
shared_examples 'dump and load model' do
it 'dumps and restores itself using Marshal module.', :aggregate_failures do
expect(estimator.class).to eq(copied.class)
expect(estimator.params).to eq(copied.params)
expect(score).to eq(copied.score(x, y))
end
end
context 'when single regression problem' do
let(:y) { single_target }
it_behaves_like 'regression'
it_behaves_like 'dump and load model'
end
context 'when multiple regression problem' do
let(:y) { multi_target }
it_behaves_like 'regression'
it_behaves_like 'dump and load model'
end
end
| 33.22449 | 128 | 0.679975 |
61ac78d29996c449fd4eeb0f48a14a8d12a6b70f | 1,178 | # 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.
#
# This file is the source Rails uses to define your schema when running `rails
# db:schema:load`. When creating a new database, `rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2020_10_19_233635) do
create_table "list_items", force: :cascade do |t|
t.string "content"
t.string "list_id", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "lists", force: :cascade do |t|
t.string "name"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
end
| 40.62069 | 86 | 0.750424 |
f87e1949005bfe7a33fbdecba981f9984e4ad93b | 170 | class ChangeProxyDepositRequestPidToGenericFileId < ActiveRecord::Migration[4.2]
def change
rename_column :proxy_deposit_requests, :pid, :generic_file_id
end
end
| 28.333333 | 80 | 0.817647 |
33dd59e65f18569042231a35e04265d29afd3b34 | 3,832 | module Togodb
class DatabaseList
class DataTables < Togodb::DataTables
include ActionView::Helpers::NumberHelper
include Togodb::Management
class << self
def columns
[
{
name: 'name',
label: 'Name',
method: 'name_text',
prop: '{"sClass": "left"}'
},
{
name: 'enabled',
label: 'Access',
method: 'access_text',
prop: '{"sClass": "center"}'
},
{
name: nil,
label: 'Action',
method: 'action_text',
prop: '{"sClass": "center", "bSortable": false}'
},
{
name: 'num_records',
label: 'Num records',
method: 'numrecords_text',
prop: '{"sClass": "right"}'
},
{
name: 'created_at',
label: 'Date created',
method: 'created_text',
prop: '{"sClass": "center"}'
},
{
name: 'creator_id',
label: 'Creator',
method: 'creator_text',
prop: '{"sClass": "left"}'
}
]
end
end
def initialize(datatables_params)
super(datatables_params)
@records = tables
end
def list_records
conditions = list_conditions
if conditions == false
@filtered_total = 0
[]
else
@filtered_total = TogodbTable.where(list_conditions).count
TogodbTable.joins(ar_joins).select(ar_select).where(conditions).offset(list_offset).limit(list_limit).order(list_orders)
end
end
def list_orders
if num_sort_columns == 0
['name ASC']
else
orders = []
num_sort_columns.times { |i|
if sort_field(i) == 'creator_id'
orders << "togodb_users.login #{sort_dir(i)}"
else
orders << "#{sort_field(i)} #{sort_dir(i)}"
end
}
orders
end
end
def ar_select
'togodb_users.login,togodb_tables.id,' + columns.select { |c| c[:name] }.map { |c| "togodb_tables.#{c[:name]}" }.join(',')
end
def ar_joins
'LEFT OUTER JOIN togodb_users ON togodb_tables.creator_id = togodb_users.id'
end
def name_text(table)
table.id
end
def access_text(table)
table.enabled? ? 'Public' : 'Private'
end
def creator_text(table)
begin
table.creator.login
rescue
'[Unknown]'
end
end
def numrecords_text(table)
begin
number_with_delimiter(table.num_records)
rescue ActiveRecord::StatementInvalid
'[Unknown]'
end
end
def created_text(table)
begin
table.created_at.to_s
rescue
'[Unknown]'
end
end
def action_text(table)
actions = []
if allow_execute?(@current_user, table)
actions << "<a href=\"/config/#{table.name}\">Config</a>"
end
if admin_user?(@current_user, table)
actions << "<a href=\"/config/copy/#{table.name}\">Copy</a>"
actions << "<a href=\"/append/db/#{table.name}\">Append</a>"
actions << %|<a id="togodb-dblist-delete-db-link-#{table.id}" href="#" onclick="show_delete_db_confirm_dialog('#{table.id}', '#{table.name}'); return false;">Delete</a>|
end
''
end
def total_size
@records.size
end
end
end
end
| 26.427586 | 179 | 0.471033 |
089066dd2010bd834c584da79fe604d3929bb256 | 662 | require 'spec_helper'
require 'cfn-model'
require 'cfn-nag/custom_rules/ElasticLoadBalancerAccessLoggingRule'
describe ElasticLoadBalancerAccessLoggingRule do
context 'two load balancers without access logging enabled' do
it 'returns offending logical resource id' do
cfn_model = CfnParser.new.parse read_test_template('json/elasticloadbalancing_loadbalancer/two_load_balancers_with_no_logging.json')
actual_logical_resource_ids = ElasticLoadBalancerAccessLoggingRule.new.audit_impl cfn_model
expected_logical_resource_ids = %w(elb1 elb2)
expect(actual_logical_resource_ids).to eq expected_logical_resource_ids
end
end
end
| 38.941176 | 138 | 0.824773 |
bff6defc24165635f5f1361739bd99cfe3cb7945 | 969 | require 'minitest/autorun'
require_relative '../libtoc.rb'
class LibTocTest < MiniTest::Unit::TestCase
def test_basic
options = {}
options[:bullets] = true
toc = md_to_toc( File.read(__dir__ + '/test.md'), options )
assert toc.include?("* Top-level topic (Heading 2)")
assert toc.include?("* First sub-sub-sub-sub-topic (Heading 6)")
end
def test_skip_heading
options = {}
options[:bullets] = true
options[:scanmarker] = true
toc = md_to_toc( File.read(__dir__ + '/test.md'), options )
refute toc.include?("* Top-level topic (Heading 2)")
assert toc.include?("* First sub-sub-sub-sub-topic (Heading 6)")
end
def test_ignore_code
options = {}
toc = md_to_toc( File.read(__dir__ + '/test.md'), options )
refute toc.include?("Top-level topic that should not be counted")
assert toc.include?("Top-level topic")
end
end
| 26.916667 | 73 | 0.607843 |
d593618fc0ae0aa862731d1176c56a8616702f4b | 1,492 | class Backupmyapp
class Transfer
MAX_RETRY_ATTEMPTS = 4
def initialize(config, server)
@connection = Net::SCP.start(config[:domain], config[:user], :password => config[:password])
@failed_downloads = @failed_uploads = Array.new
@server = server
end
def upload(file)
puts "Uploading #{file.path}"
begin
d = @connection.upload(file.path, file.remote_path, :preserve => true)
d.wait
rescue
@failed_uploads << file unless @failed_uploads.include?(file)
end
end
def download(file)
puts "Downloading #{file.remote_path}"
begin
FileUtils.mkdir_p(file.local_folder)
d = @connection.download(file.remote_path, file.path, :preserve => true)
d.wait
rescue
@failed_downloads << file unless @failed_downloads.include?(file)
end
end
def upload_collection(collection, try = 0)
collection.each { |file| upload(file) }
retry_failed_uploads("upload", try)
end
def download_collection(collection, try = 0)
collection.each { |file| download(file) }
retry_failed_uploads("download", try)
end
def retry_failed_uploads(action, try)
instance_eval %Q{
try += 1
if try < MAX_RETRY_ATTEMPTS
#{action}_collection(@failed_#{action}s, try) && @failed_#{action}s.any?
else
@server.#{action}_error(@failed_#{action}s)
end
}
end
end
end | 28.150943 | 98 | 0.616622 |
283f5f13e824d9f7a2a169d4416ad7543ea8710b | 243 | class CreatePosts < ActiveRecord::Migration[5.1]
def change
create_table :posts do |t|
t.string :title
t.text :body
t.attachment :photo
t.references :user, foriegn_key: true
t.timestamps
end
end
end
| 17.357143 | 48 | 0.63786 |
18192e24d7bf79547c94e18a61e5d7786799b5a3 | 2,370 | class ApplicationHelper::Toolbar::MiqAeDomainCenter < ApplicationHelper::Toolbar::Basic
button_group('miq_ae_domain_vmdb', [
select(
:miq_ae_domain_vmdb_choice,
'fa fa-cog fa-lg',
t = N_('Configuration'),
t,
:items => [
button(
:miq_ae_domain_edit,
'pficon pficon-edit fa-lg',
t = N_('Edit this Domain'),
t,
:klass => ApplicationHelper::Button::MiqAeDomainEdit),
button(
:miq_ae_domain_delete,
'pficon pficon-delete fa-lg',
t = N_('Remove this Domain'),
t,
:confirm => N_("Are you sure you want to remove this Domain?"),
:klass => ApplicationHelper::Button::MiqAeDomainDelete),
button(
:miq_ae_domain_unlock,
'fa fa-check fa-lg',
t = N_('Unlock this Domain'),
t,
:klass => ApplicationHelper::Button::MiqAeDomainUnlock),
button(
:miq_ae_domain_lock,
'fa fa-ban fa-lg',
t = N_('Lock this Domain'),
t,
:klass => ApplicationHelper::Button::MiqAeDomainLock),
button(
:miq_ae_git_refresh,
'fa fa-lg fa-refresh',
t = N_('Refresh with a new branch or tag'),
t,
:klass => ApplicationHelper::Button::MiqAeGitRefresh),
separator,
button(
:miq_ae_namespace_new,
'pficon pficon-add-circle-o fa-lg',
t = N_('Add a New Namespace'),
t,
:klass => ApplicationHelper::Button::MiqAeDefault),
button(
:miq_ae_namespace_edit,
'pficon pficon-edit fa-lg',
N_('Select a single Namespace to edit'),
N_('Edit Selected Namespace'),
:url_parms => "main_div",
:enabled => false,
:onwhen => "1",
:klass => ApplicationHelper::Button::MiqAeNamespaceEdit),
button(
:miq_ae_namespace_delete,
'pficon pficon-delete fa-lg',
N_('Remove selected Namespaces'),
N_('Remove Namespaces'),
:url_parms => "main_div",
:confirm => N_("Are you sure you want to remove the selected Namespaces?"),
:enabled => false,
:onwhen => "1+",
:klass => ApplicationHelper::Button::MiqAeDefault),
]
),
])
end
| 33.857143 | 87 | 0.537975 |
f733440b461c8ecfc1d014152f73bd0d6e81dc2e | 5,190 | # SOAP4R - XML Literal EncodingStyle handler library
# Copyright (C) 2001, 2003-2005 NAKAMURA, Hiroshi <[email protected]>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
# either the dual license version in 2003, or any later version.
require 'action_web_service/soap/encodingstyle/handler'
module SOAP
module EncodingStyle
class LiteralHandler < Handler
Namespace = SOAP::LiteralNamespace
add_handler
def initialize(charset = nil)
super(charset)
@textbuf = ''
end
###
## encode interface.
#
def encode_data(generator, ns, data, parent)
attrs = {}
name = generator.encode_name(ns, data, attrs)
data.extraattr.each do |k, v|
# ToDo: check generator.attributeformdefault here
if k.is_a?(XSD::QName)
if k.namespace
SOAPGenerator.assign_ns(attrs, ns, k.namespace)
k = ns.name(k)
else
k = k.name
end
end
attrs[k] = v
end
case data
when SOAPRawString
generator.encode_tag(name, attrs)
generator.encode_rawstring(data.to_s)
when XSD::XSDString
generator.encode_tag(name, attrs)
str = data.to_s
str = XSD::Charset.encoding_to_xml(str, @charset) if @charset
generator.encode_string(str)
when XSD::XSDAnySimpleType
generator.encode_tag(name, attrs)
generator.encode_string(data.to_s)
when SOAPStruct
generator.encode_tag(name, attrs)
data.each do |key, value|
generator.encode_child(ns, value, data)
end
when SOAPArray
generator.encode_tag(name, attrs)
data.traverse do |child, *rank|
data.position = nil
generator.encode_child(ns, child, data)
end
when SOAPElement
# passes 2 times for simplifying namespace definition
data.each do |key, value|
if value.elename.namespace
SOAPGenerator.assign_ns(attrs, ns, value.elename.namespace)
end
end
generator.encode_tag(name, attrs)
generator.encode_rawstring(data.text) if data.text
data.each do |key, value|
generator.encode_child(ns, value, data)
end
else
raise EncodingStyleError.new(
"unknown object:#{data} in this encodingStyle")
end
end
def encode_data_end(generator, ns, data, parent)
name = generator.encode_name_end(ns, data)
cr = (data.is_a?(SOAPCompoundtype) or
(data.is_a?(SOAPElement) and !data.text))
generator.encode_tag_end(name, cr)
end
###
## decode interface.
#
class SOAPTemporalObject
attr_accessor :parent
def initialize
@parent = nil
end
end
class SOAPUnknown < SOAPTemporalObject
def initialize(handler, elename, extraattr)
super()
@handler = handler
@elename = elename
@extraattr = extraattr
end
def as_element
o = SOAPElement.decode(@elename)
o.parent = @parent
o.extraattr.update(@extraattr)
@handler.decode_parent(@parent, o)
o
end
def as_string
o = SOAPString.decode(@elename)
o.parent = @parent
o.extraattr.update(@extraattr)
@handler.decode_parent(@parent, o)
o
end
def as_nil
o = SOAPNil.decode(@elename)
o.parent = @parent
o.extraattr.update(@extraattr)
@handler.decode_parent(@parent, o)
o
end
end
def decode_tag(ns, elename, attrs, parent)
@textbuf = ''
o = SOAPUnknown.new(self, elename, decode_attrs(ns, attrs))
o.parent = parent
o
end
def decode_tag_end(ns, node)
o = node.node
if o.is_a?(SOAPUnknown)
newnode = if /\A\s*\z/ =~ @textbuf
o.as_element
else
o.as_string
end
node.replace_node(newnode)
o = node.node
end
decode_textbuf(o)
@textbuf = ''
end
def decode_text(ns, text)
# @textbuf is set at decode_tag_end.
@textbuf << text
end
def decode_attrs(ns, attrs)
extraattr = {}
attrs.each do |key, value|
qname = ns.parse_local(key)
extraattr[qname] = value
end
extraattr
end
def decode_prologue
end
def decode_epilogue
end
def decode_parent(parent, node)
return unless parent.node
case parent.node
when SOAPUnknown
newparent = parent.node.as_element
node.parent = newparent
parent.replace_node(newparent)
decode_parent(parent, node)
when SOAPElement
parent.node.add(node)
node.parent = parent.node
when SOAPStruct
parent.node.add(node.elename.name, node)
node.parent = parent.node
when SOAPArray
if node.position
parent.node[*(decode_arypos(node.position))] = node
parent.node.sparse = true
else
parent.node.add(node)
end
node.parent = parent.node
else
raise EncodingStyleError.new("illegal parent: #{parent.node}")
end
end
private
def decode_textbuf(node)
if node.is_a?(XSD::XSDString)
if @charset
node.set(XSD::Charset.encoding_from_xml(@textbuf, @charset))
else
node.set(@textbuf)
end
else
# Nothing to do...
end
end
end
LiteralHandler.new
end
end
| 22.863436 | 74 | 0.649518 |
d5eb4abe7e43177157fdf0a32235cdb67d5464c6 | 286 | # frozen_string_literal: true
class TestChannel < ApplicationCable::Channel # :nodoc:
periodically :refresh, every: 1.second
def subscribed
@bad_var = 'bad'
stream_from 'all' do |msg|
transmit msg
end
end
def follow
@another_var = 'not_good'
end
end
| 15.888889 | 55 | 0.674825 |
7910aad128eb8d1532366af1cbe317876cc2936e | 542 | module HasHierarchy
module OrmAdapter
module Mongoid
def ancestors
tree_scope.where(path_part_column.in => path_parts)
end
def siblings
tree_scope.where(:parent_id => parent_id, :id.ne => id)
end
def subtree
tree_scope.or({ id: id }, descendants_conditions)
end
def descendants
tree_scope.where(descendants_conditions)
end
protected
def descendants_conditions
{ path_column => /^#{path_for_children}/ }
end
end
end
end
| 19.357143 | 63 | 0.621771 |
28ae846adabec494f832d4e3904499bab27aeade | 804 | require File.dirname(__FILE__) + '/spec_helper'
describe Exceptional do
describe "with no configuration" do
before(:each) do
Exceptional.stub!(:to_stderr) # Don't print error when testing
end
it "should raise a remoting exception if not authenticated" do
exception_data = mock(Exceptional::ExceptionData,
:message => "Something bad has happened",
:backtrace => ["/app/controllers/buggy_controller.rb:29:in `index'"],
:class => Exception,
:to_hash => { :message => "Something bad has happened" })
Exceptional.api_key.should == nil
Exceptional.should_receive(:authenticated?).once.and_return(false)
lambda { Exceptional.post_exception(exception_data) }.should raise_error(Exceptional::Config::ConfigurationException)
end
end
end | 36.545455 | 123 | 0.707711 |
910800307a83a22bbbee28bc0d0462ee872a69f3 | 146 | class CreateCalendars < ActiveRecord::Migration
def change
create_table :calendars do |t|
t.timestamps null: false
end
end
end
| 16.222222 | 47 | 0.705479 |
bf99422083e899bad0226e43144f7a91eb7a7b4e | 13,335 | # frozen_string_literal: true
module Sapience
# rubocop:disable ClassLength
class Base
# Class name to be logged
attr_accessor :name, :filter, :log_hooks
include Sapience::LogMethods
# Set the logging level for this logger
#
# Note: This level is only for this particular instance. It does not override
# the log level in any logging instance or the default log level
# Sapience.config.default_level
#
# Must be one of the values in Sapience::LEVELS, or
# nil if this logger instance should use the global default level
def level=(level)
@level_index = Sapience.config.level_to_index(level)
@level = Sapience.config.index_to_level(@level_index)
end
# Returns the current log level if set, otherwise it returns the global
# default log level
def level
@level || Sapience.config.default_level
end
# TODO: Move this to logger.rb?
# Implement the log level calls
# logger.debug(message, hash|exception=nil, &block)
#
# Implement the log level query
# logger.debug?
#
# Parameters:
# message
# [String] text message to be logged
# Should always be supplied unless the result of the supplied block returns
# a string in which case it will become the logged message
# Default: nil
#
# payload
# [Hash|Exception] Optional hash payload or an exception to be logged
# Default: nil
#
# exception
# [Exception] Optional exception to be logged
# Allows both an exception and a payload to be logged
# Default: nil
#
# Examples:
# require 'sapience'
#
# # Enable trace level logging
# Sapience.config.default_level = :info
#
# # Log to screen
# Sapience.add_appender(:stream, io: STDOUT, formatter: :color)
#
# # And log to a file at the same time
# Sapience.add_appender(:stream, file_name: 'application.log', formatter: :color)
#
# logger = Sapience['MyApplication']
# logger.debug("Only display this if log level is set to Debug or lower")
#
# # Log information along with a text message
# logger.info("Request received", user: "joe", duration: 100)
#
# # Log an exception
# logger.info("Parsing received XML", exc)
#
# :nodoc:
def tagged(*tags, &block)
Sapience.tagged(*tags, &block)
end
# :nodoc:
alias with_tags tagged
# :nodoc:
def tags
Sapience.tags
end
# :nodoc:
def push_tags(*tags)
Sapience.push_tags(*tags)
end
alias tags= push_tags
# :nodoc:
def pop_tags(quantity = 1)
Sapience.pop_tags(quantity)
end
# :nodoc:
def silence(new_level = :error, &block)
Sapience.silence(new_level, &block)
end
# :nodoc:
def fast_tag(tag, &block)
Sapience.fast_tag(tag, &block)
end
# Returns [Sapience::Formatters::Default] formatter default for this subscriber
def default_formatter
Sapience::Formatters::Default.new
end
def app_name
Sapience.app_name
end
# Allow host name to be set globally or per subscriber
def host
Sapience.config.host
end
# Thread specific context information to be logged with every log entry
#
# Add a payload to all log calls on This Thread within the supplied block
#
# logger.with_payload(tracking_number: 12345) do
# logger.debug('Hello World')
# end
#
# If a log call already includes a pyload, this payload will be merged with
# the supplied payload, with the supplied payload taking precedence
#
# logger.with_payload(tracking_number: 12345) do
# logger.debug('Hello World', result: 'blah')
# end
def with_payload(payload)
current_payload = self.payload
Thread.current[:sapience_payload] = current_payload ? current_payload.merge(payload) : payload
yield
ensure
Thread.current[:sapience_payload] = current_payload
end
# Returns [Hash] payload to be added to every log entry in the current scope
# on this thread.
# Returns nil if no payload is currently set
def payload
Thread.current[:sapience_payload]
end
protected
# Write log data to underlying data storage
def log(_log_)
fail NotImplementedError, "Logging Appender must implement #log(log)"
end
private
# Initializer for Abstract Class Sapience::Base
#
# Parameters
# klass [String]
# Name of the class, module, or other identifier for which the log messages
# are being logged
#
# level [Symbol]
# Only allow log entries of this level or higher to be written to this appender
# For example if set to :warn, this appender would only log :warn and :fatal
# log messages when other appenders could be logging :info and lower
#
# filter [Regexp|Proc]
# RegExp: Only include log messages where the class name matches the supplied
# regular expression. All other messages will be ignored
# Proc: Only include log messages where the supplied Proc returns true
# The Proc must return true or false
# rubocop:disable AbcSize, PerceivedComplexity, CyclomaticComplexity, LineLength
def initialize(klass, level = nil, filter = nil, log_hooks = [])
# Support filtering all messages to this logger using a Regular Expression
# or Proc
fail ArgumentError, ":filter must be a Regexp or Proc" unless filter.nil? || filter.is_a?(Regexp) || filter.is_a?(Proc)
@filter = filter.is_a?(Regexp) ? filter.freeze : filter
@name = klass if klass.is_a?(String)
@name ||= klass.name if klass.respond_to?(:name)
@name ||= klass.class.name
@log_hooks = log_hooks
if level.nil?
# Allow the global default level to determine this loggers log level
@level_index = nil
@level = nil
else
self.level = level
end
end
# rubocop:enable AbcSize, PerceivedComplexity, CyclomaticComplexity, LineLength
# Return the level index for fast comparisons
# Returns the global default level index if the level has not been explicitly
# set for this instance
def level_index
@level_index || Sapience.config.default_level_index
end
# Whether to log the supplied message based on the current filter if any
def include_message?(log)
return true if @filter.nil?
if @filter.is_a?(Regexp)
!(@filter =~ log.name).nil?
elsif @filter.is_a?(Proc)
@filter.call(log) == true
end
end
# Whether the log message should be logged for the current logger or appender
def should_log?(log)
# Ensure minimum log level is met, and check filter
(level_index <= (log.level_index || 0)) && include_message?(log)
end
# TODO: Move this to logger.rb?
# Log message at the specified level
# rubocop:disable AbcSize, PerceivedComplexity, CyclomaticComplexity, LineLength
def log_internal(level, index, message = nil, payload = nil, exception = nil)
# Exception being logged?
if exception.nil? && payload.nil? && message.respond_to?(:backtrace) && message.respond_to?(:message)
exception = message
message = nil
elsif exception.nil? && payload && payload.respond_to?(:backtrace) && payload.respond_to?(:message)
exception = payload
payload = nil
end
# Add result of block as message or payload if not nil
if block_given? && (result = yield)
if result.is_a?(String)
message = message.nil? ? result : "#{message} -- #{result}"
elsif message.nil? && result.is_a?(Hash)
message = result
elsif payload && payload.respond_to?(:merge) # rubocop: disable Style/SafeNavigation
payload.merge(result)
else
payload = result
end
end
# Add scoped payload
if self.payload
payload = payload.nil? ? self.payload : self.payload.merge(payload)
end
merged_tags = merge_tags_with_payload(payload)
# Add caller stack trace
backtrace = extract_backtrace if index >= Sapience.config.backtrace_level_index
log = Log.new(level, Thread.current.name, name, message, payload, Time.now, nil, merged_tags, index, exception, nil, backtrace)
# Logging Hash only?
# logger.info(name: 'value')
if payload.nil? && exception.nil? && message.is_a?(Hash)
payload = message.dup
min_duration = payload.delete(:min_duration) || 0.0
log.exception = payload.delete(:exception)
log.message = payload.delete(:message)
log.metric = payload.delete(:metric)
log.metric_amount = payload.delete(:metric_amount) || 1
if (duration = payload.delete(:duration))
return false if duration <= min_duration
log.duration = duration
end
log.payload = payload unless payload.empty?
end
log_hooks.each { |h| h.call(log) }
self.log(log) if include_message?(log)
end
# rubocop:enable AbcSize, PerceivedComplexity, CyclomaticComplexity, LineLength
SELF_PATTERN = File.join("lib", "sapience")
def merge_tags_with_payload(payload = {})
merged_tags = tags.dup
if payload.is_a?(Hash)
payload_tags = payload.delete(:tags) || []
merged_tags.concat(payload_tags) unless payload_tags.empty?
end
merged_tags.uniq
end
# Extract the callers backtrace leaving out Sapience
def extract_backtrace
stack = caller
while (first = stack.first) && first.include?(SELF_PATTERN)
stack.shift
end
stack
end
# Measure the supplied block and log the message
# rubocop:disable AbcSize, PerceivedComplexity, CyclomaticComplexity, LineLength
def measure_internal(level, index, message, params)
params.dup
start = Time.now
exception = nil
begin
if block_given?
result =
if (silence_level = params[:silence])
# In case someone accidentally sets `silence: true` instead of `silence: :error`
silence_level = :error if silence_level == true
silence(silence_level) { yield(params) }
else
yield(params)
end
exception = params[:exception]
result
end
rescue Exception => exc # rubocop:disable RescueException
exception = exc
ensure
end_time = Time.now
# Extract options after block completes so that block can modify any of the options
log_exception = params[:log_exception] || :partial
on_exception_level = params[:on_exception_level]
min_duration = params[:min_duration] || 0.0
payload = params[:payload]
metric = params[:metric]
duration =
if block_given?
1000.0 * (end_time - start)
else
params[:duration] || fail("Mandatory block missing when :duration option is not supplied")
end
# Add scoped payload
if self.payload
payload = payload.nil? ? self.payload : self.payload.merge(payload)
end
merged_tags = merge_tags_with_payload(payload)
if exception
logged_exception = exception
backtrace = nil
case log_exception
when :full
# On exception change the log level
if on_exception_level
level = on_exception_level
index = Sapience.config.level_to_index(level)
end
when :partial
# On exception change the log level
if on_exception_level
level = on_exception_level
index = Sapience.config.level_to_index(level)
end
message = "#{message} -- Exception: #{exception.class}: #{exception.message}"
logged_exception = nil
backtrace = exception.backtrace
else
# Log the message with its duration but leave out the exception that was raised
logged_exception = nil
backtrace = exception.backtrace
end
log = Log.new(level, Thread.current.name, name, message, payload, end_time, duration, merged_tags, index, logged_exception, metric, backtrace) # rubocop:disable LineLength
self.log(log) if include_message?(log)
fail exception
elsif duration >= min_duration
# Only log if the block took longer than 'min_duration' to complete
# Add caller stack trace
backtrace = extract_backtrace if index >= Sapience.config.backtrace_level_index
log = Log.new(level, Thread.current.name, name, message, payload, end_time, duration, merged_tags, index, nil, metric, backtrace) # rubocop:disable LineLength
self.log(log) if include_message?(log)
end
end
end
# rubocop:enable AbcSize, PerceivedComplexity, CyclomaticComplexity, LineLength
end
# rubocop:enable ClassLength
end
| 34.457364 | 181 | 0.632696 |
bfd4581b0878e776af22aab0ae3c8f9f679809d9 | 747 | module Rouge
module Themes
class Atelier Estuary < Base16
name 'base16.Atelier Estuary'
# author Bram de Haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/estuary)
light!
palette base00: "#22221b"
palette base01: "#302f27"
palette base02: "#5f5e4e"
palette base03: "#6c6b5a"
palette base04: "#878573"
palette base05: "#929181"
palette base06: "#e7e6df"
palette base07: "#f4f3ec"
palette base08: "#ba6236"
palette base09: "#ae7313"
palette base0A: "#a5980d"
palette base0B: "#7d9726"
palette base0C: "#5b9d48"
palette base0D: "#36a166"
palette base0E: "#5f9182"
palette base0F: "#9d6c7c"
end
end
end
| 27.666667 | 102 | 0.626506 |
1dac57c1cc24fa53103785c24aa321756eeaeeb9 | 987 | class EntriesController < ApplicationController
#GET /forums/:forum_id/entries
def index
forum_id = params[:forum_id]
@entries = Entry.where(:forum_id => forum_id)
entries = []
@entries.each do |entry|
entries.push(
{
id_tag: entry.user.id_tag,
content: entry.content,
timestamp: entry.created_at
}
)
end
render status: :ok, json: entries
end
#POST /forums/:forum_id/entries
def create
content = params[:content]
user_id = params[:user_id]
forum_id = params[:forum_id]
#TODO: Store through forums
@entry = Entry.new do |e|
e.content = content
e.forum_id = forum_id
e.user_id = user_id
end
if @entry.save
render status: :ok, json: {
message: 'Entry created successfully'
}
else
render status: :internal_server_error, json: {
errors: @entry.errors
}.to_json
end
end
end
| 19.352941 | 52 | 0.586626 |
1d8e36200c8bb0bbfc76a5d6adcb1622deb805df | 162 | # frozen_string_literal: true
class AddIsDryRunToFlagLogs < ActiveRecord::Migration[5.0]
def change
add_column :flag_logs, :is_dry_run, :boolean
end
end
| 20.25 | 58 | 0.771605 |
1a43505d7c37faba7a39a792a09c6d9e82469cf8 | 3,708 | require 'rubygems/command'
require 'rubygems/local_remote_options'
require 'rubygems/version_option'
require 'rubygems/source_info_cache'
class Gem::Commands::DependencyCommand < Gem::Command
include Gem::LocalRemoteOptions
include Gem::VersionOption
def initialize
super 'dependency',
'Show the dependencies of an installed gem',
:version => Gem::Requirement.default, :domain => :local
add_version_option
add_platform_option
add_option('-R', '--[no-]reverse-dependencies',
'Include reverse dependencies in the output') do
|value, options|
options[:reverse_dependencies] = value
end
add_option('-p', '--pipe',
"Pipe Format (name --version ver)") do |value, options|
options[:pipe_format] = value
end
add_local_remote_options
end
def arguments # :nodoc:
"GEMNAME name of gem to show dependencies for"
end
def defaults_str # :nodoc:
"--local --version '#{Gem::Requirement.default}' --no-reverse-dependencies"
end
def usage # :nodoc:
"#{program_name} GEMNAME"
end
def execute
options[:args] << '.' if options[:args].empty?
specs = {}
source_indexes = []
if local? then
source_indexes << Gem::SourceIndex.from_installed_gems
end
if remote? then
Gem::SourceInfoCache.cache_data.map do |_, sice|
source_indexes << sice.source_index
end
end
options[:args].each do |name|
new_specs = nil
source_indexes.each do |source_index|
new_specs = find_gems(name, source_index)
end
say "No match found for #{name} (#{options[:version]})" if
new_specs.empty?
specs = specs.merge new_specs
end
terminate_interaction 1 if specs.empty?
reverse = Hash.new { |h, k| h[k] = [] }
if options[:reverse_dependencies] then
specs.values.each do |source_index, spec|
reverse[spec.full_name] = find_reverse_dependencies spec, source_index
end
end
if options[:pipe_format] then
specs.values.sort_by { |_, spec| spec }.each do |_, spec|
unless spec.dependencies.empty?
spec.dependencies.each do |dep|
say "#{dep.name} --version '#{dep.version_requirements}'"
end
end
end
else
response = ''
specs.values.sort_by { |_, spec| spec }.each do |_, spec|
response << print_dependencies(spec)
unless reverse[spec.full_name].empty? then
response << " Used by\n"
reverse[spec.full_name].each do |sp, dep|
response << " #{sp} (#{dep})\n"
end
end
response << "\n"
end
say response
end
end
def print_dependencies(spec, level = 0)
response = ''
response << ' ' * level + "Gem #{spec.full_name}\n"
unless spec.dependencies.empty? then
spec.dependencies.each do |dep|
response << ' ' * level + " #{dep}\n"
end
end
response
end
# Retuns list of [specification, dep] that are satisfied by spec.
def find_reverse_dependencies(spec, source_index)
result = []
source_index.each do |name, sp|
sp.dependencies.each do |dep|
dep = Gem::Dependency.new(*dep) unless Gem::Dependency === dep
if spec.name == dep.name and
dep.version_requirements.satisfied_by?(spec.version) then
result << [sp.full_name, dep]
end
end
end
result
end
def find_gems(name, source_index)
specs = {}
spec_list = source_index.search name, options[:version]
spec_list.each do |spec|
specs[spec.full_name] = [source_index, spec]
end
specs
end
end
| 24.556291 | 79 | 0.617853 |
edb52c4cbcc9b3671e9aea32b1de29eb3d7eb7df | 12,164 | #!/usr/bin/env ruby
# encoding: UTF-8
#
# Copyright © 2012-2014 Cask Data, Inc.
#
# Licensed 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 'thin'
require 'sinatra/base'
require 'json'
require 'rest_client'
require 'socket'
require 'resolv'
require_relative 'api'
require_relative 'tenantmanager'
require_relative 'provisioner'
require_relative 'cli'
require_relative 'logging'
require_relative 'config'
require_relative 'constants'
require_relative 'workerlauncher'
require_relative 'rest-helper'
module Coopr
# top-level class for provisioner
class Provisioner
include Logging
attr_accessor :tenantmanagers, :provisioner_id, :server_uri
def initialize(options, config)
@options = options
@config = config
@tenantmanagers = {}
@terminating_tenants = []
@server_uri = config.get('provisioner.server.uri')
pid = Process.pid
host = Socket.gethostname.downcase.split('.').first
@provisioner_id = "master-#{host}-#{pid}"
log.info "provisioner #{@provisioner_id} initialized"
@registered = false
Logging.process_name = @provisioner_id
Coopr::RestHelper.cert_path = config.get(TRUST_CERT_PATH)
Coopr::RestHelper.cert_pass = config.get(TRUST_CERT_PASS)
end
# invoked from bin/provisioner
def self.run(options)
# read configuration
config = Config.new(options)
config.load
# initialize logging
Logging.configure(config.get(PROVISIONER_LOG_DIR) ? "#{config.get(PROVISIONER_LOG_DIR)}/provisioner.log" : nil)
Logging.level = config.get(PROVISIONER_LOG_LEVEL)
Logging.shift_age = config.get(PROVISIONER_LOG_ROTATION_SHIFT_AGE)
Logging.shift_size = config.get(PROVISIONER_LOG_ROTATION_SHIFT_SIZE)
Logging.log.debug 'Provisioner starting up'
config.properties.each do |k, v|
Logging.log.debug " #{k}: #{v}"
end
# daemonize
daemonize if config.get(PROVISIONER_DAEMONIZE)
pg = Coopr::Provisioner.new(options, config)
if options[:register]
pg.register_plugins
else
pg.run
end
end
# main run block
def run
begin
@status = 'STARTING'
Thread.abort_on_exception = true
# start the api server
spawn_sinatra_thread
# wait for sinatra to fully initialize
sleep 1 until Api.running?
# register our own signal handlers
setup_signal_traps
# spawn the heartbeat, signal-handler, and resource threads
spawn_heartbeat_thread
spawn_signal_thread
spawn_resource_thread
# heartbeat thread will update status to 'OK'
# wait for signal_handler to exit in response to signals
@signal_thread.join
# kill the other threads
[@heartbeat_thread, @sinatra_thread, @resource_thread].each do |t|
t.kill
t.join
end
log.info "provisioner gracefully shut down"
exit
rescue RuntimeError => e
log.error "Exception raised in thread: #{e.inspect}, shutting down..."
# if signal_handler thread alive, use it to shutdown gracefully
if @signal_thread && @signal_thread.alive?
Process.kill('TERM', 0)
@signal_thread.join
[@heartbeat_thread, @sinatra_thread, @resource_thread].each do |t|
t.kill if t.alive?
end
log.info "provisioner forced graceful shutdown"
exit 1
else
# last resort, kill entire process group
Process.kill('TERM', -Process.getpgrp)
log.info "provisioner forced shutdown"
exit 1
end
end
end
def spawn_sinatra_thread
@sinatra_thread = Thread.new {
# set reference to provisioner
Api.set :provisioner, self
# set bind settings
bind_ip = @config.get(PROVISIONER_BIND_IP)
bind_port = @config.get(PROVISIONER_BIND_PORT)
Api.set :bind, bind_ip
Api.set :port, bind_port
# let sinatra take over from here
Api.run!
}
end
def setup_signal_traps
@signals = Array.new
%w(CLD TERM INT).each do |signal|
Signal.trap(signal) do
@signals << signal
end
end
end
def spawn_signal_thread
@signal_thread = Thread.new {
log.info "started signal processing thread"
loop {
log.debug "reaping #{@signals.size} signals: #{@signals}" unless @signals.empty?
signals_processed = {}
unless @signals.empty?
sig = @signals.shift
next if signals_processed.key?(sig)
log.debug "processing signal: #{sig}"
case sig
when 'CLD'
verify_tenants
when 'TERM', 'INT'
unless @shutting_down
# begin shutdown procedure
@shutting_down = true
tenantmanagers.each do |k, v|
v.delete
end
# wait for all workers to shut down
Process.waitall
unregister_from_server
# exit thread
Thread.current.kill
end
end
signals_processed[sig] = true
end
sleep 1
}
}
end
def spawn_heartbeat_thread
@heartbeat_thread = Thread.new {
log.info "starting heartbeat thread"
loop {
register_with_server unless @registered
uri = "#{@server_uri}/v2/provisioners/#{provisioner_id}/heartbeat"
begin
json = heartbeat.to_json
resp = Coopr::RestHelper.post("#{uri}", json, :'Coopr-UserID' => "admin")
unless resp.code == 200
if(resp.code == 404)
log.warn "Response code #{resp.code} when sending heartbeat, re-registering provisioner"
register_with_server
else
log.warn "Response code #{resp.code}, #{resp.to_str} when sending heartbeat to coopr server #{uri}"
end
end
rescue => e
log.error "Caught exception sending heartbeat to coopr server #{uri}: #{e.message}"
end
sleep 10
}
}
end
def spawn_resource_thread
@resource_thread = Thread.new {
log.info "starting resource thread"
loop {
@tenantmanagers.each do |id, tmgr|
if tmgr.resource_sync_needed? && tmgr.num_workers == 0
# handle stacked sync calls, last one wins
while tmgr.resource_sync_needed?
log.debug "resource thread invoking sync for tenant #{tmgr.id}"
tmgr.sync
end
log.debug "done syncing tenant #{tmgr.id}, resuming workers"
tmgr.resume
end
end
sleep 1
}
}
end
def register_with_server
uri = "#{@server_uri}/v2/provisioners/#{@provisioner_id}"
data = {}
data['id'] = @provisioner_id
data['capacityTotal'] = @config.get(PROVISIONER_CAPACITY)
data['host'] = @config.get(PROVISIONER_REGISTER_IP) || local_ip
data['port'] = @config.get(PROVISIONER_BIND_PORT)
log.info "Registering with server at #{uri}: #{data.to_json}"
begin
resp = Coopr::RestHelper.put("#{uri}", data.to_json, :'Coopr-UserID' => "admin")
if(resp.code == 200)
log.info "Successfully registered"
@registered = true
# announce provisioner is ready
@status = 'OK'
else
log.warn "Response code #{resp.code}, #{resp.to_str} when registering with coopr server #{uri}"
end
rescue => e
log.error "Caught exception when registering with server #{uri}: #{e.message}"
end
end
def register_plugins
worker_launcher = WorkerLauncher.new(@config)
worker_launcher.provisioner = @provisioner_id
worker_launcher.name = "plugin-registration-worker"
worker_launcher.register = true
worker_cmd = worker_launcher.cmd
log.debug "launching worker to register plugins: #{worker_cmd}"
exec(worker_cmd)
end
def unregister_from_server
uri = "#{@server_uri}/v2/provisioners/#{@provisioner_id}"
log.info "Unregistering with server at #{uri}"
begin
resp = Coopr::RestHelper.delete("#{uri}", :'Coopr-UserID' => "admin")
if(resp.code == 200)
log.info "Successfully unregistered"
else
log.warn "Response code #{resp.code}, #{resp.to_str} when unregistering with coopr server #{uri}"
end
rescue => e
log.error "Caught exception when unregistering with coopr server #{uri}: #{e.message}"
end
end
def self.daemonize
Process.daemon
end
# api method to add or edit tenant
def add_tenant(tenantspec)
unless tenantspec.instance_of?(TenantSpec)
raise ArgumentError, "only instances of TenantSpec can be added to provisioner", caller
end
# validate input
id = tenantspec.id
log.debug "Adding/Editing tenant: #{id}"
fail "cannot add a TenantManager without an id: #{tenantmgr.inspect}" if id.nil?
tenantmgr = TenantManager.new(tenantspec, @config, @provisioner_id)
if @tenantmanagers.key? id
# edit tenant
log.debug "Editing tenant: #{id}"
@tenantmanagers[id].update(tenantmgr)
else
# new tenant
log.debug "Adding new tenant: #{id}"
#tenantmgr.spawn
tenantmgr.resource_sync_needed
@tenantmanagers[id] = tenantmgr
end
end
# api method to delete tenant for given id
def delete_tenant(id)
# if no workers currently running, just delete
if @tenantmanagers[id].num_workers == 0
@tenantmanagers.delete(id)
else
# instruct tenant to send kill signal to its workers
@tenantmanagers[id].delete
# we mark this tenant as deleting. when its num_workers reaches 0 it can be deleted from @tenantmanagers
@terminating_tenants.push(id)
end
end
# check running tenants and their workers, called after a CLD signal processed
def verify_tenants
@tenantmanagers.each do |k, v|
# update worker counts
v.verify_workers
# has this tenant been deleted?
if (@terminating_tenants.include?(k) && v.num_workers == 0)
@tenantmanagers.delete(k)
@terminating_tenants.delete(k)
end
end
end
# get current heartbeat data
def heartbeat
hb = {}
hb['usage'] = {}
@tenantmanagers.each do |id, tm|
hb['usage'][id] = tm.num_workers
end
hb
end
# get current status
def status
@status ||= 'UNKNOWN'
end
# determine ip to register with server from routing info
# http://coderrr.wordpress.com/2008/05/28/get-your-local-ip-address/
def local_ip
begin
server_ip = Resolv.getaddress( @server_uri.sub(%r{^https?://}, '').split(':').first ) rescue '127.0.0.1'
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
UDPSocket.open do |s|
s.connect server_ip, 1
s.addr.last
end
rescue => e
log.error "Unable to determine provisioner.register.ip, defaulting to 127.0.0.1. Please set it explicitly. "\
"Server may not be able to connect to this provisioner: #{e.inspect}"
'127.0.0.1'
ensure
Socket.do_not_reverse_lookup = orig
end
end
end
end
| 32.437333 | 125 | 0.617642 |
388a8b3367230cab66ca140f411e8385ec2ac2d7 | 333 | class Author < ActiveRecord::Base
set_table_name "users"
has_one :address, :foreign_key => 'user_id'
has_one :working_topic, :as => :writer, :class_name => 'Topic'
has_one :country, :through => :address
has_one :living_country, :through => :address, :source => :country
should_bypass_all_callbacks_and_validations
end | 33.3 | 68 | 0.72973 |
b93a76a3b24da77b628ad74d601652f179d106e6 | 6,331 | # frozen_string_literal: true
require "formula"
require "keg"
require "cli/parser"
require "cask/cmd"
require "cask/caskroom"
module Homebrew
module_function
def outdated_args
Homebrew::CLI::Parser.new do
usage_banner <<~EOS
`outdated` [<options>] [<formula>|<cask>]
List installed casks and formulae that have an updated version available. By default, version
information is displayed in interactive shells, and suppressed otherwise.
EOS
switch "-q", "--quiet",
description: "List only the names of outdated kegs (takes precedence over `--verbose`)."
switch "-v", "--verbose",
description: "Include detailed version information."
switch "--formula",
description: "Only output outdated formulae."
switch "--cask",
description: "Only output outdated casks."
flag "--json",
description: "Print output in JSON format. There are two versions: v1 and v2. " \
"v1 is deprecated and is currently the default if no version is specified. " \
"v2 prints outdated formulae and casks. "
switch "--fetch-HEAD",
description: "Fetch the upstream repository to detect if the HEAD installation of the "\
"formula is outdated. Otherwise, the repository's HEAD will only be checked for "\
"updates when a new stable or development version has been released."
switch "--greedy",
description: "Print outdated casks with `auto_updates` or `version :latest`."
conflicts "--quiet", "--verbose", "--json"
conflicts "--formula", "--cask"
end
end
def outdated
args = outdated_args.parse
case json_version(args.json)
when :v1, :default
# TODO: enable for next major/minor release
# odeprecated "brew outdated --json#{json_version == :v1 ? "=v1" : ""}", "brew outdated --json=v2"
outdated = if args.formula? || !args.cask?
outdated_formulae args: args
else
outdated_casks args: args
end
puts JSON.generate(json_info(outdated, args: args))
when :v2
formulae, casks = if args.formula?
[outdated_formulae(args: args), []]
elsif args.cask?
[[], outdated_casks(args: args)]
else
outdated_formulae_casks args: args
end
json = {
"formulae" => json_info(formulae, args: args),
"casks" => json_info(casks, args: args),
}
puts JSON.generate(json)
outdated = formulae + casks
else
outdated = if args.formula?
outdated_formulae args: args
elsif args.cask?
outdated_casks args: args
else
outdated_formulae_casks(args: args).flatten
end
print_outdated(outdated, args: args)
end
Homebrew.failed = args.named.present? && outdated.present?
end
def print_outdated(formulae_or_casks, args:)
formulae_or_casks.each do |formula_or_cask|
if formula_or_cask.is_a?(Formula)
f = formula_or_cask
if verbose?
outdated_kegs = f.outdated_kegs(fetch_head: args.fetch_HEAD?)
current_version = if f.alias_changed?
latest = f.latest_formula
"#{latest.name} (#{latest.pkg_version})"
elsif f.head? && outdated_kegs.any? { |k| k.version.to_s == f.pkg_version.to_s }
# There is a newer HEAD but the version number has not changed.
"latest HEAD"
else
f.pkg_version.to_s
end
outdated_versions = outdated_kegs.group_by { |keg| Formulary.from_keg(keg).full_name }
.sort_by { |full_name, _kegs| full_name }
.map do |full_name, kegs|
"#{full_name} (#{kegs.map(&:version).join(", ")})"
end.join(", ")
pinned_version = " [pinned at #{f.pinned_version}]" if f.pinned?
puts "#{outdated_versions} < #{current_version}#{pinned_version}"
else
puts f.full_installed_specified_name
end
else
c = formula_or_cask
puts c.outdated_info(args.greedy?, verbose?, false)
end
end
end
def json_info(formulae_or_casks, args:)
formulae_or_casks.map do |formula_or_cask|
if formula_or_cask.is_a?(Formula)
f = formula_or_cask
outdated_versions = f.outdated_kegs(fetch_head: args.fetch_HEAD?).map(&:version)
current_version = if f.head? && outdated_versions.any? { |v| v.to_s == f.pkg_version.to_s }
"HEAD"
else
f.pkg_version.to_s
end
{ name: f.full_name,
installed_versions: outdated_versions.map(&:to_s),
current_version: current_version,
pinned: f.pinned?,
pinned_version: f.pinned_version }
else
c = formula_or_cask
c.outdated_info(args.greedy?, verbose?, true)
end
end
end
def verbose?
($stdout.tty? || super) && !quiet?
end
def json_version(version)
version_hash = {
nil => nil,
true => :default,
"v1" => :v1,
"v2" => :v2,
}
raise UsageError, "invalid JSON version: #{version}" unless version_hash.include?(version)
version_hash[version]
end
def outdated_formulae(args:)
select_outdated((args.resolved_formulae.presence || Formula.installed), args: args).sort
end
def outdated_casks(args:)
if args.named.present?
select_outdated(args.named.uniq.map(&Cask::CaskLoader.method(:load)), args: args)
else
select_outdated(Cask::Caskroom.casks, args: args)
end
end
def outdated_formulae_casks(args:)
formulae, casks = args.resolved_formulae_casks
if formulae.blank? && casks.blank?
formulae = Formula.installed
casks = Cask::Caskroom.casks
end
[select_outdated(formulae, args: args).sort, select_outdated(casks, args: args)]
end
def select_outdated(formulae_or_casks, args:)
formulae_or_casks.select do |formula_or_cask|
if formula_or_cask.is_a?(Formula)
formula_or_cask.outdated?(fetch_head: args.fetch_HEAD?)
else
formula_or_cask.outdated?(args.greedy?)
end
end
end
end
| 30.882927 | 108 | 0.611278 |
870e5e9ee946dfce35ff2a20ea885558ec813ecb | 2,459 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
# General Settings
config.app_domain = 'localhost:3000'
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
if Rails.root.join('tmp/caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => 'public, max-age=172800'
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
# Email
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.default_url_options = { host: config.app_domain }
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: '587',
enable_starttls_auto: true,
user_name: '[email protected]',
password: 'MockingJay',
authentication: :plain,
domain: 'localhost:3000'
}
end
| 32.355263 | 85 | 0.751525 |
e2a16f0a63da62131a35bece4ead426849a38225 | 4,948 | require 'rails_helper'
RSpec.describe AlmaAdapter::ScsbDumpRecord do
let(:host_record) do
file = file_fixture("alma/scsb_dump_fixtures/host.xml").to_s
MARC::XMLReader.new(file, external_encoding: 'UTF-8').first
end
let(:bad_host_record) do
file = file_fixture("alma/scsb_dump_fixtures/bad-host.xml").to_s
MARC::XMLReader.new(file, external_encoding: 'UTF-8').first
end
let(:host_record_uncached) do
file = file_fixture("alma/scsb_dump_fixtures/host-id-not-in-cache.xml").to_s
MARC::XMLReader.new(file, external_encoding: 'UTF-8').first
end
let(:constituent_record) do
file = file_fixture("alma/scsb_dump_fixtures/constituent.xml").to_s
MARC::XMLReader.new(file, external_encoding: 'UTF-8').first
end
let(:bad_constituent_record) do
file = file_fixture("alma/scsb_dump_fixtures/bad-constituent.xml").to_s
MARC::XMLReader.new(file, external_encoding: 'UTF-8').first
end
let(:non_boundwith_record) do
file = file_fixture("alma/scsb_dump_fixtures/notboundwith.xml").to_s
MARC::XMLReader.new(file, external_encoding: 'UTF-8').first
end
it "is a MARC Record" do
expect(host_record).to be_a MARC::Record
expect(constituent_record).to be_a MARC::Record
end
describe "#boundwith?" do
context "with a host record" do
it "returns true" do
expect(described_class.new(marc_record: host_record).boundwith?).to be true
end
end
context "with a constituent record" do
it "returns true" do
expect(described_class.new(marc_record: constituent_record).boundwith?).to be true
end
end
context "with a non-boundwith record" do
it "returns false" do
expect(described_class.new(marc_record: non_boundwith_record).boundwith?).to be false
end
end
end
describe "#constituent?" do
context "with a host record" do
it "returns false" do
expect(described_class.new(marc_record: host_record).constituent?).to be false
end
end
context "with a constituent record" do
it "returns true" do
expect(described_class.new(marc_record: constituent_record).constituent?).to be true
end
end
context "with a malformed constituent record" do
it "returns false" do
expect(described_class.new(marc_record: bad_constituent_record).constituent?).to be false
end
end
end
describe "#host?" do
context "with a host record" do
it "returns true" do
expect(described_class.new(marc_record: host_record).host?).to be true
end
end
context "with a malformed host record" do
it "returns false" do
expect(described_class.new(marc_record: bad_host_record).host?).to be false
end
end
context "with a constituent record" do
it "returns false" do
expect(described_class.new(marc_record: constituent_record).host?).to be false
end
end
end
describe "#cache" do
it "caches a record in the database" do
described_class.new(marc_record: host_record).cache
record = CachedMarcRecord.find_by(bib_id: "99121886293506421")
expect(record.bib_id).to eq "99121886293506421"
expect(record.marc).to include("<subfield code")
end
end
context "with methods that make use of cached marc records" do
before do
PublishingJobFileService.new(path: "spec/fixtures/files/alma/scsb_dump_fixtures/cacheable_scsb_records.tar.gz").cache
end
describe "#host_record" do
it "retrieves a host record from the cache" do
record = described_class.new(marc_record: constituent_record).host_record
expect(record.id).to eq "99116515383506421"
end
end
describe "#constituent_record" do
context "with no skipped records" do
let(:missing_constituent_ids) { ["9929455783506421", "9929455793506421", "9929455773506421"] }
it "retrieves all constituent records from the cache" do
records = described_class.new(marc_record: host_record).constituent_records
expect(records.map { |r| r.marc_record["001"].value }).to contain_exactly(*missing_constituent_ids)
end
end
context "with skipped records" do
let(:missing_constituent_ids) { ["9929455783506421", "9929455793506421"] }
it "retrieves non-skipped constituent records from the cache" do
records = described_class.new(marc_record: host_record).constituent_records(skip_ids: ["9929455773506421"])
expect(records.map { |r| r.marc_record["001"].value }).to contain_exactly(*missing_constituent_ids)
end
end
end
context "with records missing from the cache" do
it "raises an exception" do
expect { described_class.new(marc_record: host_record_uncached).constituent_records }.to raise_error(AlmaAdapter::ScsbDumpRecord::CacheMiss, "9929455783506421,9998765433506421,9912345673506421")
end
end
end
end
| 33.432432 | 202 | 0.703517 |
bf814e9f405721a3ec335e523a865a2b077700d0 | 3,024 | # frozen_string_literal: true
require_relative 'argument_string_builder'
require_relative 'extensions/object_extensions'
require_relative 'errors/command_line_argument_error'
# The Jekyll module contains everything related to Jekyll.
module Jekyll
# The Jekyll::PlantUml module contains everything related to Jekyll::PlantUml.
module PlantUml
# The Jekyll::PlantUml::Arguments class contains the arguments parsed from
# the command line by Jekyll::PlantUml::ArgumentParser
class Arguments
attr_reader :command, :ignore_urls, :log_level, :environment, :profile, :site_url
def initialize(args)
args.must_be_a! :non_empty, Hash
@args = args
@command = find_command(args)
@verify = args.value_for('--verify')
@dry_run = args.value_for('--dry-run')
@ignore_urls = args.value_for('--ignore-url')
@site_url = args.value_for('--site-url')
@log_level = args.value_for('--log-level')
@profile = args.value_for('--profile')
@environment = args.value_for('--env')
end
def verify?
@verify
end
def dry_run?
@dry_run
end
def profile?
@profile
end
def inspect
@args.inspect
end
def to_s
builder = ArgumentStringBuilder.new(self)
builder.to_s
end
def self.default
Arguments.new({
'build' => false,
'serve' => false,
'deploy' => false,
'--verify' => false,
'--dry-run' => false,
'--ignore-url' => false,
'--site-url' => nil,
'--log-level' => nil,
'--env' => nil,
'--profile' => false
})
end
private
def find_command(args)
return 'build' if args.value_for('build') == true
return 'serve' if args.value_for('serve') == true
return 'deploy' if args.value_for('deploy') == true
# Alias CommandLineArgumentError to save line length
clae = CommandLineArgumentError
# If Arguments.default invoked the constructor, we shouldn't raise
raise clae, 'Unknown command' unless invoked_by_default?
end
def invoked_by_default?
# Find the caller location that matches Arguments.default
loc = caller_locations.find { |l| location_is_arguments_default?(l) }
# If we find Arguments.default in the caller locations, return true
!loc.nil?
end
def location_is_arguments_default?(location)
path = location.absolute_path
label = location.base_label
# If the path of the caller location is equal to this file's path
# and the caller location's base label (method name) is equal to
# 'default', return true.
path == __FILE__ && label == 'default'
end
end
end
end
| 30.24 | 87 | 0.58168 |
6269424ce180e0f75a16050f3df66c9686ec4788 | 689 | Pod::Spec.new do |s|
s.name = "RemoteImageServiceForMDCDemos"
s.version = "121.0.0"
s.summary = "A helper image class for the MDC demos."
s.description = "This spec is made for use in the MDC demos. It gets images via url."
s.homepage = "https://github.com/material-components/material-components-ios"
s.license = "Apache 2.0"
s.authors = { 'Apple platform engineering at Google' => '[email protected]' }
s.source = { :git => "https://github.com/material-components/material-components-ios.git", :tag => "v#{s.version}" }
s.source_files = "RemoteImageService/*.{h,m}"
s.public_header_files = "RemoteImageService/*.h"
end
| 53 | 124 | 0.661829 |
28d51cd0936182e11802db9060c7fd953a87a259 | 3,925 | class User < ActiveRecord::Base
has_many :microposts, dependent: :destroy
has_many :active_relationships, class_name: "Relationship",
foreign_key: "follower_id",
dependent: :destroy
has_many :passive_relationships, class_name: "Relationship",
foreign_key: "followed_id",
dependent: :destroy
has_many :following, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower
attr_accessor :remember_token, :activation_token, :reset_token
before_save :downcase_email
before_create :create_activation_digest
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
has_secure_password
validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
# Returns the hash digest of the given string.
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
def User.new_token
SecureRandom.urlsafe_base64
end
# Remembers a user in the database for use in persistent sessions.
def remember
self.remember_token = User.new_token
update_attribute(:remember_digest, User.digest(remember_token))
end
# Returns true if the given token matches the digest.
def authenticated?(attribute, token)
digest = send("#{attribute}_digest")
return false if digest.nil?
BCrypt::Password.new(digest).is_password?(token)
end
# Forgets a user.
def forget
update_attribute(:remember_digest, nil)
end
# Activates an account.
def activate
update_attribute(:activated, true)
update_attribute(:activated_at, Time.zone.now)
end
# Sends activation email.
def send_activation_email
UserMailer.account_activation(self).deliver_now
end
# Sets the password reset attributes.
def create_reset_digest
self.reset_token = User.new_token
update_attribute(:reset_digest, User.digest(reset_token))
update_attribute(:reset_sent_at, Time.zone.now)
end
# Sends password reset email.
def send_password_reset_email
UserMailer.password_reset(self).deliver_now
end
# Returns true if a password reset has expired.
def password_reset_expired?
reset_sent_at < 2.hours.ago
end
# Defines a proto-feed.
# See "Following users" for the full implementation.
# Returns a user's status feed.
def feed
following_ids = "SELECT followed_id FROM relationships
WHERE follower_id = :user_id"
Micropost.where("user_id IN (#{following_ids})
OR user_id = :user_id", user_id: id)
end
# Follows a user.
def follow(other_user)
active_relationships.create(followed_id: other_user.id)
end
# Unfollows a user.
def unfollow(other_user)
active_relationships.find_by(followed_id: other_user.id).destroy
end
# Returns true if the current user is following the other user.
def following?(other_user)
following.include?(other_user)
end
private
# Converts email to all lower-case.
def downcase_email
self.email = email.downcase
end
# Creates and assigns the activation token and digest.
def create_activation_digest
self.activation_token = User.new_token
self.activation_digest = User.digest(activation_token)
end
end
| 32.438017 | 138 | 0.654777 |
e2d38dc9903515299d33b021adc0dfe39ef2feb4 | 2,226 | # frozen_string_literal: true
# Note: initial thinking behind `icon_name` is for it to do triple duty:
# 1. one of our svg icon names, such as `external-link` or a new one `bug`
# 2. if it's an absolute url, then url to a user uploaded icon/image
# 3. an emoji, with the format of `:smile:`
module WorkItems
class Type < ApplicationRecord
self.table_name = 'work_item_types'
include CacheMarkdownField
# Base types need to exist on the DB on app startup
# This constant is used by the DB seeder
BASE_TYPES = {
issue: { name: 'Issue', icon_name: 'issue-type-issue', enum_value: 0 },
incident: { name: 'Incident', icon_name: 'issue-type-incident', enum_value: 1 },
test_case: { name: 'Test Case', icon_name: 'issue-type-test-case', enum_value: 2 }, ## EE-only
requirement: { name: 'Requirement', icon_name: 'issue-type-requirements', enum_value: 3 }, ## EE-only
task: { name: 'Task', icon_name: 'issue-type-task', enum_value: 4 }
}.freeze
cache_markdown_field :description, pipeline: :single_line
enum base_type: BASE_TYPES.transform_values { |value| value[:enum_value] }
belongs_to :namespace, optional: true
has_many :work_items, class_name: 'Issue', foreign_key: :work_item_type_id, inverse_of: :work_item_type
before_validation :strip_whitespace
# TODO: review validation rules
# https://gitlab.com/gitlab-org/gitlab/-/issues/336919
validates :name, presence: true
validates :name, uniqueness: { case_sensitive: false, scope: [:namespace_id] }
validates :name, length: { maximum: 255 }
validates :icon_name, length: { maximum: 255 }
scope :default, -> { where(namespace: nil) }
scope :order_by_name_asc, -> { order(arel_table[:name].lower.asc) }
scope :by_type, ->(base_type) { where(base_type: base_type) }
def self.default_by_type(type)
find_by(namespace_id: nil, base_type: type)
end
def self.default_issue_type
default_by_type(:issue)
end
def self.allowed_types_for_issues
base_types.keys.excluding('task')
end
def default?
namespace.blank?
end
private
def strip_whitespace
name&.strip!
end
end
end
| 33.727273 | 107 | 0.680144 |
e224d3456a95fcb233249c3949da4f094d2a73b7 | 4,735 | # frozen_string_literal: true
module ActiveRecord
module Associations
# = Active Record Has Many Association
# This is the proxy that handles a has many association.
#
# If the association has a <tt>:through</tt> option further specialization
# is provided by its child HasManyThroughAssociation.
class HasManyAssociation < CollectionAssociation #:nodoc:
include ForeignAssociation
def handle_dependency
case options[:dependent]
when :restrict_with_exception
raise ActiveRecord::DeleteRestrictionError.new(reflection.name) unless empty?
when :restrict_with_error
unless empty?
record = owner.class.human_attribute_name(reflection.name).downcase
owner.errors.add(:base, :'restrict_dependent_destroy.has_many', record: record)
throw(:abort)
end
when :destroy
# No point in executing the counter update since we're going to destroy the parent anyway
load_target.each { |t| t.destroyed_by_association = reflection }
destroy_all
else
delete_all
end
end
def insert_record(record, validate = true, raise = false)
set_owner_attributes(record)
super
end
def empty?
if reflection.has_cached_counter?
size.zero?
else
super
end
end
private
# Returns the number of records in this collection.
#
# If the association has a counter cache it gets that value. Otherwise
# it will attempt to do a count via SQL, bounded to <tt>:limit</tt> if
# there's one. Some configuration options like :group make it impossible
# to do an SQL count, in those cases the array count will be used.
#
# That does not depend on whether the collection has already been loaded
# or not. The +size+ method is the one that takes the loaded flag into
# account and delegates to +count_records+ if needed.
#
# If the collection is empty the target is set to an empty array and
# the loaded flag is set to true as well.
def count_records
count = if reflection.has_cached_counter?
owner._read_attribute(reflection.counter_cache_column).to_i
else
scope.count(:all)
end
# If there's nothing in the database and @target has no new records
# we are certain the current target is an empty array. This is a
# documented side-effect of the method that may avoid an extra SELECT.
(@target ||= []) && loaded! if count == 0
[association_scope.limit_value, count].compact.min
end
def update_counter(difference, reflection = reflection())
if reflection.has_cached_counter?
owner.increment!(reflection.counter_cache_column, difference)
end
end
def update_counter_in_memory(difference, reflection = reflection())
if reflection.counter_must_be_updated_by_has_many?
counter = reflection.counter_cache_column
owner.increment(counter, difference)
owner.send(:clear_attribute_change, counter) # eww
end
end
def delete_count(method, scope)
if method == :delete_all
scope.delete_all
else
scope.update_all(reflection.foreign_key => nil)
end
end
def delete_or_nullify_all_records(method)
count = delete_count(method, scope)
update_counter(-count)
end
# Deletes the records according to the <tt>:dependent</tt> option.
def delete_records(records, method)
if method == :destroy
records.each(&:destroy!)
update_counter(-records.length) unless reflection.inverse_updates_counter_cache?
else
scope = self.scope.where(reflection.klass.primary_key => records)
update_counter(-delete_count(method, scope))
end
end
def concat_records(records, *)
update_counter_if_success(super, records.length)
end
def _create_record(attributes, *)
if attributes.is_a?(Array)
super
else
update_counter_if_success(super, 1)
end
end
def update_counter_if_success(saved_successfully, difference)
if saved_successfully
update_counter_in_memory(difference)
end
saved_successfully
end
def difference(a, b)
a - b
end
def intersection(a, b)
a & b
end
end
end
end
| 32.881944 | 99 | 0.622598 |
08c4910303f1cc3d41f584a77a5e378507e80149 | 1,133 | require 'test_helper'
class UsersIndexTest < ActionDispatch::IntegrationTest
def setup
@user = users(:lana)
@admin = users(:michael)
@non_admin = users(:archer)
end
test "index including pagination" do
log_in_as(@user)
get users_path
assert_template 'users/index'
assert_select 'div.pagination', count: 2
User.paginate(page: 1).each do |user|
assert_select 'a[href=?]', user_path(user), text: user.name
end
end
test "index as admin including pagination and delete links" do
log_in_as(@admin)
get users_path
assert_template 'users/index'
assert_select 'div.pagination'
first_page_of_users = User.paginate(page: 1)
first_page_of_users.each do |user|
assert_select 'a[href=?]', user_path(user), text: user.name
unless user == @admin
assert_select 'a[href=?]', user_path(user), text: 'delete'
end
end
assert_difference 'User.count', -1 do
delete user_path(@non_admin)
end
end
test "index as non-admin" do
log_in_as(@non_admin)
get users_path
assert_select 'a', text: 'delete', count: 0
end
end | 25.75 | 66 | 0.672551 |
e84a83966db8bd6490051b9327a3bc153e1e0889 | 1,847 | #!/usr/bin/env ruby
Dir.chdir(File.dirname(__FILE__))
require "optparse"
require "sqlite3" if RUBY_ENGINE != "jruby"
begin
args = {
:filename => "benchmark.rhtml"
}
OptionParser.new do |opts|
opts.banner = "Usage: benchmark.rb [options]"
opts.on("-f FILENAME", "--file FILENAME", "The filename that should be requested from the server.") do |t|
args[:filename] = t
end
opts.on("-k PATH", "--knjrbfw PATH", "The path of knjrbfw if it should not be loaded from gems.") do |path|
args[:knjrbfw_path] = path
end
end.parse!
end
db_path = "#{File.dirname(__FILE__)}/benchmark_db.sqlite3"
appserver_args = {
:debug => false,
:port => 15081,
:doc_root => "#{File.dirname(__FILE__)}/../pages",
:db_args => {
:type => "sqlite3",
:path => db_path,
:return_keys => "symbols"
}
}
require "rubygems"
require "erubis"
require "#{args[:knjrbfw_path]}/knjrbfw.rb"
require "../hayabusa.rb"
if args[:knjrbfw_path]
appserver_args[:knjrbfw_path] = args[:knjrbfw_path]
else
require "knjrbfw"
end
require "knj/autoload"
appsrv = Hayabusa.new(appserver_args)
appsrv.start
count_requests = 0
1.upto(50) do |count_thread|
Knj::Thread.new(count_thread) do |count_thread|
print "Thread #{count_thread} started.\n"
http = Http2.new(
:host => "localhost",
:port => 15081,
:user_agent => "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.1; debugid:#{count_thread}) Gecko/20060111 Firefox/3.6.0.1",
:debug => false
)
loop do
resp = http.get(:url => args[:filename])
count_requests += 1
raise "Invalid code: #{resp.code}\n" if resp.code.to_i != 200
end
end
end
loop do
last_count = count_requests
sleep 1
counts_betw = count_requests - last_count
print "#{counts_betw} /sec\n"
end
appsrv.join | 22.52439 | 139 | 0.642664 |
bfcf1ca734b3ae5819744c3589f073148853715a | 2,429 | require 'monitor'
require 'riemann/client/tcp_socket'
module Riemann
class Client
class TCP < Client
attr_accessor :host, :port, :socket
# Public: Set a socket factory -- an object responding
# to #call(options) that returns a Socket object
def self.socket_factory=(factory)
@socket_factory = factory
end
# Public: Return a socket factory
def self.socket_factory
@socket_factory || proc { |options| TcpSocket.connect(options) }
end
def initialize(options = {})
@options = options
@locket = Monitor.new
end
def socket
@locket.synchronize do
if @pid && @pid != Process.pid
close
end
return @socket if connected?
@socket = self.class.socket_factory.call(@options)
@pid = Process.pid
return @socket
end
end
def close
@locket.synchronize do
@socket.close if connected?
@socket = nil
end
end
def connected?
@locket.synchronize do
[email protected]? && [email protected]?
end
end
# Read a message from a stream
def read_message(s)
if buffer = s.read(4) and buffer.size == 4
length = buffer.unpack('N').first
begin
str = s.read length
message = Riemann::Message.decode str
rescue => e
puts "Message was #{str.inspect}"
raise
end
unless message.ok
puts "Failed"
raise ServerError, message.error
end
message
else
raise InvalidResponse, "unexpected EOF"
end
end
def send_recv(message)
with_connection do |s|
s.write(message.encode_with_length)
read_message(s)
end
end
alias send_maybe_recv send_recv
# Yields a connection in the block.
def with_connection
tries = 0
@locket.synchronize do
begin
tries += 1
yield(socket)
rescue IOError, Errno::EPIPE, Errno::ECONNREFUSED, InvalidResponse, Timeout::Error, Riemann::Client::TcpSocket::Error
close
raise if tries > 3
retry
rescue Exception
close
raise
end
end
end
end
end
end
| 22.915094 | 127 | 0.540552 |
1c43b736a328f244428d8b40351c6e6d983cea91 | 1,517 | require File.expand_path('../helper', __FILE__)
class VisualOpsTest < Service::TestCase
def setup
@stubs = Faraday::Adapter::Test::Stubs.new
@data = {'username' => 'someuser', 'app_list' => 'abc123, madeira:master, xyz456:devel', 'consumer_token' => 'madeira-visualops'}
end
def test_push
svc = service :push, @data
@stubs.post "/v1/github" do |env|
assert_equal 'api.visualops.io', env[:url].host
body = JSON.parse(env[:body])
assert_equal 'someuser', body['config']['username']
assert_equal 'madeira-visualops', body['config']['consumer_token']
assert_equal ['abc123','madeira'], body['config']['app_list']
[200, {}, '']
end
svc.receive_event
end
def test_develop
svc = service :push, @data,
payload.update("ref" => "refs/heads/devel")
@stubs.post "/v1/github" do |env|
assert_equal 'api.visualops.io', env[:url].host
body = JSON.parse(env[:body])
assert_equal 'someuser', body['config']['username']
assert_equal 'madeira-visualops', body['config']['consumer_token']
assert_equal ['xyz456'], body['config']['app_list']
[200, {}, '']
end
svc.receive_event
end
def test_other_branch
svc = service :push, @data,
payload.update("ref" => "refs/heads/no-such-branch")
@stubs.post "/v1/github" do |env|
raise "This should not be called"
end
svc.receive_event
end
def service(*args)
super Service::VisualOps, *args
end
end
| 27.089286 | 133 | 0.624258 |
e8e6c00fd531768535986b5470becc6c61dd3de8 | 561 | Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
root 'welcome#landing_page'
get '/courses/cheapest', to: 'courses#cheapest'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
post '/logout', to: 'sessions#destroy'
resources :users do
resources :courses, only: [:index]
end
resources :courses do
resources :reviews, only: [:new]
end
resources :reviews
get 'auth/:provider/callback' => 'sessions#omniauth'
end
| 22.44 | 102 | 0.686275 |
d5fbf9ce3a104a2ba80f2ac043be3589edd3400c | 2,367 | # This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require 'engine_cart'
EngineCart.load_application!
require 'sipity'
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
RSpec.configure do |config|
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
end
| 41.526316 | 86 | 0.747782 |
26fcc97d5652ab402c030c50bb013d0e8894caf7 | 2,929 | require 'beaker-rspec'
def ldapsearch(cmd, exit_codes = [0,1], &block)
shell("ldapsearch #{cmd}", :acceptable_exit_codes => exit_codes, &block)
end
hosts.each do |host|
# Install Puppet
install_puppet()
# Install ruby-augeas
case fact('osfamily')
when 'Debian'
install_package host, 'libaugeas-ruby'
when 'RedHat'
install_package host, 'ruby-devel'
install_package host, 'augeas-devel'
on host, 'gem install ruby-augeas --no-ri --no-rdoc'
else
puts 'Sorry, this osfamily is not supported.'
exit
end
end
RSpec.configure do |c|
# Project root
proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..'))
# Readable test descriptions
c.formatter = :documentation
# Configure all nodes in nodeset
c.before :suite do
# Install module and dependencies
puppet_module_install(:source => proj_root, :module_name => 'openldap')
# Set up Certificates
pp = <<-EOS
$ssldir = '/var/lib/puppet/ssl'
Exec {
path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
}
exec { "puppet cert generate ${::fqdn}":
creates => [
"${ssldir}/private_keys/${::fqdn}.pem",
"${ssldir}/certs/${::fqdn}.pem",
],
}
file { '/etc/ldap':
ensure => directory,
}
file { '/etc/ldap/ssl':
ensure => directory,
}
if $::osfamily == 'Debian' {
# OpenLDAP is linked towards GnuTLS on Debian so we have to convert the key
package { 'gnutls-bin':
ensure => present,
}
->
exec { "certtool -k < ${ssldir}/private_keys/${::fqdn}.pem > /etc/ldap/ssl/${::fqdn}.key":
creates => "/etc/ldap/ssl/${::fqdn}.key",
require => [
File['/etc/ldap/ssl'],
Exec["puppet cert generate ${::fqdn}"],
],
before => File["/etc/ldap/ssl/${::fqdn}.key"],
}
} else {
File <| title == "/etc/ldap/ssl/${::fqdn}.key" |> {
source => "${ssldir}/private_keys/${::fqdn}.pem",
}
}
file { "/etc/ldap/ssl/${::fqdn}.key":
ensure => file,
mode => '0644',
}
file { "/etc/ldap/ssl/${::fqdn}.crt":
ensure => file,
mode => '0644',
source => "${ssldir}/certs/${::fqdn}.pem",
}
file { '/etc/ldap/ssl/ca.pem':
ensure => file,
mode => '0644',
source => "${ssldir}/certs/ca.pem",
}
EOS
apply_manifest_on(hosts, pp, :catch_failures => false)
hosts.each do |host|
on host, puppet('module','install','herculesteam-augeasproviders_core'), { :acceptable_exit_codes => [0,1] }
on host, puppet('module','install','herculesteam-augeasproviders_shellvar'), { :acceptable_exit_codes => [0,1] }
on host, puppet('module','install','puppetlabs-stdlib'), { :acceptable_exit_codes => [0,1] }
end
end
end
| 29.887755 | 118 | 0.556504 |
6179e54f1fec95d04a954e423c89c6f12825fe91 | 835 | Pod::Spec.new do |s|
s.name = 'YLProgressBar'
s.version = '0.0.1'
s.platform = :ios
s.license = 'MIT'
s.summary = 'Custom progress bar for iOS (4.0 or over) with an animated background'
s.homepage = 'https://github.com/YannickL/YLProgressBar'
s.authors = {'Yannick Loriot' => 'http://yannickloriot.com'}
s.source = { :git => 'https://github.com/lexrus/YLProgressBar.git',
:commit => '58c106e5b502f28da0d8bf641531bcf7f4c69c5a' }
s.source_files = ['YLProgressBar/YLProgressBar.{h,m}', 'YLProgressBar/ARCMacro.h']
s.clean_paths = ['YLProgressBar.xcodeproj', 'YLProgressBar/Resources', 'YLProgressBar/en.lproj',
'YLAppDelegate.*', 'YLBackgroundView.*', 'YLProgressBar-Info.plist',
'YLProgressBar-Prefix.pch', 'YLViewController.h', 'main.m']
end
| 52.1875 | 98 | 0.649102 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.