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
287f8fee9bbd4a040bf1d4d96740dfd5b92518b7
2,393
# Run Coverage report require 'simplecov' SimpleCov.start do add_filter 'spec/dummy' add_group 'Controllers', 'app/controllers' add_group 'Helpers', 'app/helpers' add_group 'Mailers', 'app/mailers' add_group 'Models', 'app/models' add_group 'Views', 'app/views' add_group 'Libraries', 'lib/spree' end # Configure Rails Environment ENV['RAILS_ENV'] = 'test' require File.expand_path('../dummy/config/environment.rb', __FILE__) require 'rspec/rails' require 'ffaker' # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[File.join(File.dirname(__FILE__), 'support/**/*.rb')].each { |f| require f } # Requires factories and other useful helpers defined in spree_core. require 'spree/testing_support/authorization_helpers' require 'spree/testing_support/capybara_ext' require 'spree/testing_support/controller_requests' require 'spree/testing_support/factories' require 'spree/testing_support/url_helpers' require 'spree_snippets/factories' RSpec.configure do |config| # Infer an example group's spec type from the file location. config.infer_spec_type_from_file_location! # == URL Helpers # # Allows access to Spree's routes in specs: # # visit spree.admin_path # current_path.should eql(spree.products_path) config.include Spree::TestingSupport::UrlHelpers # == Requests support # # Adds convenient methods to request Spree's controllers # spree_get :index config.include Spree::TestingSupport::ControllerRequests, type: :controller # == Mock Framework # # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr config.mock_with :rspec config.color = true config.default_formatter = 'doc' # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" # Capybara javascript drivers require transactional fixtures set to false, and we use DatabaseCleaner # to cleanup after each test instead. Without transactional fixtures set to false the records created # to setup a test will be unavailable to the browser, which runs under a separate server instance. config.use_transactional_fixtures = false config.fail_fast = ENV['FAIL_FAST'] || false config.order = 'random' end
32.337838
104
0.75888
085d89820335ac2e52dad8bdd2a6c2e9ea86438b
3,598
#!/usr/bin/env ruby # -*- coding: binary -*- $:.unshift(File.join(File.dirname(__FILE__), '..', '..', '..')) require 'test/unit' require 'rex/proto/http' class Rex::Proto::Http::Response::UnitTest < Test::Unit::TestCase Klass = Rex::Proto::Http::Response def test_deflate h = Klass.new h.body = 'hi mom' h.compress = 'deflate' assert_equal( "HTTP/1.1 200 OK\r\n" + "Content-Length: 14\r\n" + "Content-Encoding: deflate\r\n\r\n" + "x\234\313\310T\310\315\317\005\000\a\225\002;", h.to_s, 'deflate' ) end def test_gzip h = Klass.new h.body = 'hi mom' h.compress = 'gzip' srand(0) response = h.to_s http_header = response.slice!(0,63) assert_equal( "HTTP/1.1 200 OK\r\n" + "Content-Length: 26\r\n"+ "Content-Encoding: gzip\r\n\r\n", http_header, 'http headers' ) assert_equal("\x1f\x8b\x08\x00", response.slice!(0,4), 'gzip headers') # skip the next 6 bytes as it is host & time specific (zlib's example gun does, so why not us too?) response.slice!(0,6) assert_equal("\xcb\xc8\x54\xc8\xcd\xcf\x05\x00\x68\xa4\x1c\xf0\x06\x00\x00\x00", response, 'gzip data') end def test_to_s h = Klass.new h.headers['Foo'] = 'Fishing' h.headers['Chicken'] = 47 assert_equal( "HTTP/1.1 200 OK\r\n" + "Content-Length: 0\r\n" + "Foo: Fishing\r\n" + "Chicken: 47\r\n\r\n", h.to_s, 'to_s w/o body') h.body = 'hi mom' assert_equal( "HTTP/1.1 200 OK\r\n" + "Content-Length: 6\r\n" + "Foo: Fishing\r\n" + "Chicken: 47\r\n\r\nhi mom", h.to_s, 'to_s w/ body') end def test_chunked h = Klass.new h.headers['Foo'] = 'Fishing' h.headers['Chicken'] = 47 h.auto_cl = false h.transfer_chunked = true assert_equal( "HTTP/1.1 200 OK\r\n" + "Transfer-Encoding: chunked\r\n" + "Foo: Fishing\r\n" + "Chicken: 47\r\n\r\n0\r\n\r\n", h.to_s, 'chunked w/o body' ) srand(0) h.body = Rex::Text.rand_text_alphanumeric(100) assert_equal( "HTTP/1.1 200 OK\r\n" + "Transfer-Encoding: chunked\r\n" + "Foo: Fishing\r\n" + "Chicken: 47\r\n\r\n" + "5\r\nsv1AD\r\n7\r\n7DnJTVy\r\n5\r\nkXGYY\r\n5\r\nM6Bmn\r\n4\r\nXuYR\r\n5\r\nlZNIJ\r\n5\r\nUzQzF\r\n9\r\nPvASjYxzd\r\n5\r\nTTOng\r\n4\r\nBJ5g\r\n8\r\nfK0XjLy3\r\n6\r\nciAAk1\r\n6\r\nFmo0RP\r\n1\r\nE\r\n2\r\npq\r\n6\r\n6f4BBn\r\n4\r\np5jm\r\n1\r\n3\r\n6\r\nLuSbAO\r\n1\r\nj\r\n2\r\n1M\r\n3\r\n5qU\r\n0\r\n\r\n", h.to_s, 'random chunk sizes' ) h.chunk_max_size = 1 h.body = 'hi mom' assert_equal( "HTTP/1.1 200 OK\r\n" + "Transfer-Encoding: chunked\r\n" + "Foo: Fishing\r\n" + "Chicken: 47\r\n\r\n" + "1\r\nh\r\n1\r\ni\r\n1\r\n \r\n1\r\nm\r\n1\r\no\r\n1\r\nm\r\n0\r\n\r\n", h.to_s, '1 byte chunks' ) h.chunk_min_size = 2 assert_equal( "HTTP/1.1 200 OK\r\n" + "Transfer-Encoding: chunked\r\n" + "Foo: Fishing\r\n" + "Chicken: 47\r\n\r\n" + "2\r\nhi\r\n2\r\n m\r\n2\r\nom\r\n0\r\n\r\n", h.to_s, '2 byte chunks' ) h = Klass.new(200, 'OK', '1.0') h.body = 'hi mom' h.auto_cl = false h.transfer_chunked = true assert_raise(Rex::RuntimeError, 'chunked encoding via 1.0') { h.to_s } end def test_from_s h = Klass.new h.from_s( "HTTP/1.0 404 File not found\r\n" + "Lucifer: Beast\r\n" + "HoHo: Satan\r\n" + "Eat: Babies\r\n" + "\r\n") assert_equal(404, h.code) assert_equal('File not found', h.message) assert_equal('1.0', h.proto) assert_equal("HTTP/1.0 404 File not found\r\n", h.cmd_string) h.code = 470 assert_equal("HTTP/1.0 470 File not found\r\n", h.cmd_string) assert_equal('Babies', h['Eat']) end end
23.827815
313
0.611451
e28000142d5da28f90d7b8e0ed168c2f64ac4e63
299
module Buildable def perform(payload_data) payload = Payload.new(payload_data) build_runner = BuildRunner.new(payload) build_runner.run rescue Resque::TermException retry_job rescue => exception Raven.capture_exception(exception, payload: { data: payload_data }) end end
24.916667
71
0.745819
f72f0db4edfa0ef243b0a93ebfe03bcff4c8c59b
1,452
# frozen_string_literal: true # WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE require 'aws-sdk-core' require 'aws-sigv4' require_relative 'aws-sdk-licensemanager/types' require_relative 'aws-sdk-licensemanager/client_api' require_relative 'aws-sdk-licensemanager/client' require_relative 'aws-sdk-licensemanager/errors' require_relative 'aws-sdk-licensemanager/resource' require_relative 'aws-sdk-licensemanager/customizations' # This module provides support for AWS License Manager. This module is available in the # `aws-sdk-licensemanager` gem. # # # Client # # The {Client} class provides one method for each API operation. Operation # methods each accept a hash of request parameters and return a response # structure. # # license_manager = Aws::LicenseManager::Client.new # resp = license_manager.create_license_configuration(params) # # See {Client} for more information. # # # Errors # # Errors returned from AWS License Manager are defined in the # {Errors} module and all extend {Errors::ServiceError}. # # begin # # do stuff # rescue Aws::LicenseManager::Errors::ServiceError # # rescues all AWS License Manager API errors # end # # See {Errors} for more information. # # @!group service module Aws::LicenseManager GEM_VERSION = '1.18.0' end
27.396226
87
0.758264
e8b9f25344bc79f57e763899cd507fd42c02dbf8
1,195
class Swiftformat < Formula desc "Formatting tool for reformatting Swift code" homepage "https://github.com/nicklockwood/SwiftFormat" url "https://github.com/nicklockwood/SwiftFormat/archive/0.40.4.tar.gz" sha256 "0e11500bf82390b8ac3065c480ab561763adc4096e6f04d0c277d6df5b294b74" head "https://github.com/nicklockwood/SwiftFormat.git", :shallow => false bottle do cellar :any_skip_relocation sha256 "7c0d9893b89f200319bfd4cfe8fe3cf942f85f2914c236b18ec9b67ffe1e6e34" => :mojave sha256 "885e505fd201bc1055af6a4a3a077590675886eb897893b8762b390d162d3521" => :high_sierra sha256 "ab6f2c65661b1cec3958d7e0687e79e05a271af17d30e5082312bc454b4352d2" => :sierra end depends_on :macos depends_on :xcode => ["9.2", :build] if OS.mac? def install xcodebuild "-project", "SwiftFormat.xcodeproj", "-scheme", "SwiftFormat (Command Line Tool)", "CODE_SIGN_IDENTITY=", "SYMROOT=build", "OBJROOT=build" bin.install "build/Release/swiftformat" end test do (testpath/"potato.swift").write <<~EOS struct Potato { let baked: Bool } EOS system "#{bin}/swiftformat", "#{testpath}/potato.swift" end end
33.194444
93
0.725523
385528d74df4a9910b0e28ff2cb0b5f6adb52ace
1,869
class UsersController < ApplicationController before_action :logged_in_user, only: [:index, :edit, :update, :destroy, :following, :followers] before_action :correct_user, only: [:edit, :update] before_action :admin_user, only: :destroy def index @users = User.where(activated: true).paginate(page: params[:page]) end def show @user = User.find(params[:id]) @microposts = @user.microposts.paginate(page: params[:page]) redirect_to root_url and return unless @user.activated? end def new @user = User.new end def create @user = User.new(user_params) if @user.save @user.send_activation_email flash[:info] = "Please check your email to activate your account." redirect_to root_url else render 'new' end end def edit end def update if @user.update_attributes(user_params) flash[:success] = "Profile updated" redirect_to @user else render 'edit' end end def destroy User.find(params[:id]).destroy flash[:success] = "User deleted" redirect_to users_url end def following @title = "Following" @user = User.find(params[:id]) @users = @user.following.paginate(page: params[:page]) render 'show_follow' end def followers @title = "Followers" @user = User.find(params[:id]) @users = @user.followers.paginate(page: params[:page]) render 'show_follow' end private def user_params params.require(:user).permit(:name, :email, :password, :password_confirmation) end # 正しいユーザーかどうか確認 def correct_user @user = User.find(params[:id]) redirect_to(root_url) unless current_user?(@user) end # 管理者かどうか確認 def admin_user redirect_to(root_url) unless current_user.admin? end end
22.792683
73
0.638844
1a29502892f159f5ed6cc65ea0a80a9bdb8a6a8c
254
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure end module Azure::CDN end module Azure::CDN::Mgmt end module Azure::CDN::Mgmt::V2017_10_12 end
28.222222
70
0.775591
6a142573aec1bc1d36b2595bdd44885cd4cd1d60
938
require 'spec_helper' describe 'vim::default' do let(:chef_run) do ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '12.04', file_cache_path: '/var/chef/cache') do |node| node.set['vim']['source']['version'] = 'foo_version_1' end.converge(described_recipe) end it 'should default to install_method = "package"' do chef_run.converge(described_recipe) expect(chef_run.node['vim']['install_method']).to eq('package') end it 'should include the vim::package recipe when install_method = "package"' do chef_run.converge(described_recipe) expect(chef_run).to include_recipe('vim::package') end it 'should include the vim::source recipe when install_method = "source"' do chef_run.node.set['vim']['install_method'] = 'source' chef_run.converge(described_recipe) expect(chef_run).to include_recipe('vim::source') end end
33.5
80
0.668443
03e3dd49feae7b18dc83816d32f5429fbcec3fca
1,369
Pod::Spec.new do |s| s.name = "ZappCrashlogsPluginMsAppCenter" s.version = '3.0.0' s.summary = "ZappCrashlogsPluginMsAppCenter" s.description = <<-DESC ZappCrashlogsPluginMsAppCenter container. DESC s.homepage = "https://github.com/applicaster/ZappCrashlogsPluginMsAppCenter-iOS" s.license = 'CMPS' s.author = "Applicaster LTD." s.source = { :git => "[email protected]:applicaster/ZappCrashlogsPluginMsAppCenter-iOS.git", :tag => s.version.to_s } s.platform = :ios, '10.0' s.requires_arc = true s.static_framework = true s.public_header_files = 'ZappCrashlogsPluginMsAppCenter/**/*.h' s.source_files = 'ZappCrashlogsPluginMsAppCenter/**/*.{h,m,swift}' s.resources = [ "ZappCrashlogsPluginMsAppCenter/**/*.xcassets", "ZappCrashlogsPluginMsAppCenter/**/*.storyboard", "ZappCrashlogsPluginMsAppCenter/**/*.xib", "ZappCrashlogsPluginMsAppCenter/**/*.png"] s.xcconfig = { 'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES', 'ENABLE_BITCODE' => 'YES', 'SWIFT_VERSION' => '5.1' } s.dependency 'ZappCrashlogsPluginsSDK', '~> 3.0.0' s.dependency 'AppCenter/Crashes', '~> 2.3.0' end
41.484848
126
0.595325
4ac6725b1703b4d5191caf1292c0de550d776506
9,628
require 'spec_helper' describe FactoryGirl::Factory do before do @name = :user @class = define_class('User') @factory = FactoryGirl::Factory.new(@name) FactoryGirl.register_factory(@factory) end it "has a factory name" do @factory.name.should == @name end it "has a build class" do @factory.build_class.should == @class end it "passes a custom creation block" do strategy = stub("strategy", result: nil, add_observer: true) FactoryGirl::Strategy::Build.stubs(new: strategy) block = -> {} factory = FactoryGirl::Factory.new(:object) factory.to_create(&block) factory.run(FactoryGirl::Strategy::Build, {}) strategy.should have_received(:result).with(instance_of(FactoryGirl::Evaluation)) end it "returns associations" do factory = FactoryGirl::Factory.new(:post) FactoryGirl.register_factory(FactoryGirl::Factory.new(:admin)) factory.declare_attribute(FactoryGirl::Declaration::Association.new(:author, {})) factory.declare_attribute(FactoryGirl::Declaration::Association.new(:editor, {})) factory.declare_attribute(FactoryGirl::Declaration::Implicit.new(:admin, factory)) factory.associations.each do |association| association.should be_association end factory.associations.to_a.length.should == 3 end it "includes associations from the parent factory" do association_on_parent = FactoryGirl::Declaration::Association.new(:association_on_parent, {}) association_on_child = FactoryGirl::Declaration::Association.new(:association_on_child, {}) factory = FactoryGirl::Factory.new(:post) factory.declare_attribute(association_on_parent) FactoryGirl.register_factory(factory) child_factory = FactoryGirl::Factory.new(:child_post, parent: :post) child_factory.declare_attribute(association_on_child) child_factory.associations.map(&:name).should == [:association_on_parent, :association_on_child] end describe "when overriding generated attributes with a hash" do before do @name = :name @value = 'The price is right!' @hash = { @name => @value } end it "returns the overridden value in the generated attributes" do declaration = FactoryGirl::Declaration::Static.new(@name, 'The price is wrong, Bob!') @factory.declare_attribute(declaration) result = @factory.run(FactoryGirl::Strategy::AttributesFor, @hash) result[@name].should == @value end it "does not call a lazy attribute block for an overridden attribute" do declaration = FactoryGirl::Declaration::Dynamic.new(@name, false, -> { flunk }) @factory.declare_attribute(declaration) @factory.run(FactoryGirl::Strategy::AttributesFor, @hash) end it "overrides a symbol parameter with a string parameter" do declaration = FactoryGirl::Declaration::Static.new(@name, 'The price is wrong, Bob!') @factory.declare_attribute(declaration) @hash = { @name.to_s => @value } result = @factory.run(FactoryGirl::Strategy::AttributesFor, @hash) result[@name].should == @value end end describe "overriding an attribute with an alias" do before do @factory.declare_attribute(FactoryGirl::Declaration::Static.new(:test, 'original')) FactoryGirl.aliases << [/(.*)_alias/, '\1'] @result = @factory.run(FactoryGirl::Strategy::AttributesFor, test_alias: 'new') end it "uses the passed in value for the alias" do @result[:test_alias].should == 'new' end it "discards the predefined value for the attribute" do @result[:test].should be_nil end end it "guesses the build class from the factory name" do @factory.build_class.should == User end it "creates a new factory using the class of the parent" do child = FactoryGirl::Factory.new(:child, parent: @factory.name) child.compile child.build_class.should == @factory.build_class end it "creates a new factory while overriding the parent class" do child = FactoryGirl::Factory.new(:child, class: String, parent: @factory.name) child.compile child.build_class.should == String end end describe FactoryGirl::Factory, "when defined with a custom class" do subject { FactoryGirl::Factory.new(:author, class: Float) } its(:build_class) { should == Float } end describe FactoryGirl::Factory, "when given a class that overrides #to_s" do let(:overriding_class) { Overriding::Class } before do define_class("Overriding") define_class("Overriding::Class") do def self.to_s "Overriding" end end end subject { FactoryGirl::Factory.new(:overriding_class, class: Overriding::Class) } it "sets build_class correctly" do subject.build_class.should == overriding_class end end describe FactoryGirl::Factory, "when defined with a class instead of a name" do let(:factory_class) { ArgumentError } let(:name) { :argument_error } subject { FactoryGirl::Factory.new(factory_class) } its(:name) { should == name } its(:build_class) { should == factory_class } end describe FactoryGirl::Factory, "when defined with a custom class name" do subject { FactoryGirl::Factory.new(:author, class: :argument_error) } its(:build_class) { should == ArgumentError } end describe FactoryGirl::Factory, "with a name ending in s" do let(:name) { :business } let(:business_class) { Business } before { define_class('Business') } subject { FactoryGirl::Factory.new(name) } its(:name) { should == name } its(:build_class) { should == business_class } end describe FactoryGirl::Factory, "with a string for a name" do let(:name) { :string } subject { FactoryGirl::Factory.new(name.to_s) } its(:name) { should == name } end describe FactoryGirl::Factory, "for namespaced class" do let(:name) { :settings } let(:settings_class) { Admin::Settings } before do define_class("Admin") define_class("Admin::Settings") end context "with a namespaced class with Namespace::Class syntax" do subject { FactoryGirl::Factory.new(name, class: "Admin::Settings") } it "sets build_class correctly" do subject.build_class.should == settings_class end end context "with a namespaced class with namespace/class syntax" do subject { FactoryGirl::Factory.new(name, class: "admin/settings") } it "sets build_class correctly" do subject.build_class.should == settings_class end end end describe FactoryGirl::Factory, "human names" do context "factory name without underscores" do subject { FactoryGirl::Factory.new(:user) } its(:names) { should == [:user] } its(:human_names) { should == ["user"] } end context "factory name with underscores" do subject { FactoryGirl::Factory.new(:happy_user) } its(:names) { should == [:happy_user] } its(:human_names) { should == ["happy user"] } end context "factory name with big letters" do subject { FactoryGirl::Factory.new(:LoL) } its(:names) { should == [:LoL] } its(:human_names) { should == ["lol"] } end context "factory name with aliases" do subject { FactoryGirl::Factory.new(:happy_user, aliases: [:gleeful_user, :person]) } its(:names) { should == [:happy_user, :gleeful_user, :person] } its(:human_names) { should == ["happy user", "gleeful user", "person"] } end end describe FactoryGirl::Factory, "running a factory" do subject { FactoryGirl::Factory.new(:user) } let(:attribute) { FactoryGirl::Attribute::Static.new(:name, "value", false) } let(:declaration) { FactoryGirl::Declaration::Static.new(:name, "value", false) } let(:strategy) { stub("strategy", result: "result", add_observer: true) } let(:attributes) { [attribute] } let(:attribute_list) { stub('attribute-list', declarations: [declaration], to_a: attributes) } before do define_model("User", name: :string) FactoryGirl::Declaration::Static.stubs(new: declaration) declaration.stubs(to_attributes: attributes) FactoryGirl::Strategy::Build.stubs(new: strategy) subject.declare_attribute(declaration) end it "creates the right strategy using the build class when running" do subject.run(FactoryGirl::Strategy::Build, {}) FactoryGirl::Strategy::Build.should have_received(:new).once end it "returns the result from the strategy when running" do subject.run(FactoryGirl::Strategy::Build, {}).should == "result" end it "calls the block and returns the result" do block_run = nil block = ->(result) { block_run = "changed" } subject.run(FactoryGirl::Strategy::Build, { }, &block) block_run.should == "changed" end end describe FactoryGirl::Factory, "#with_traits" do subject { FactoryGirl::Factory.new(:user) } let(:admin_trait) { FactoryGirl::Trait.new(:admin) } let(:female_trait) { FactoryGirl::Trait.new(:female) } let(:admin_definition) { admin_trait.definition } let(:female_definition) { female_trait.definition } before do FactoryGirl.register_trait(admin_trait) FactoryGirl.register_trait(female_trait) end it "returns a factory with the correct definitions" do subject.with_traits([:admin, :female]).definition_list[1, 2].should == [admin_definition, female_definition] end it "doesn't modify the original factory's processing order" do subject.with_traits([:admin, :female]) subject.definition_list.should == [subject.definition] end end
34.141844
112
0.686955
21af2f684e9b763ed4abe5de45803314c38106b6
156
require 'doogle/tft_diagonal_in_option' class Doogle::OledDiagonalInOption < Doogle::TftDiagonalInOption def self.type_key 'oled_displays' end end
19.5
64
0.801282
01dd9b25129aa494b950855fd71f131e41aa5192
159
class AddRefToAssignmentSubmission < ActiveRecord::Migration[5.1] def change add_reference :assignment_submissions, :project, foreign_key:true end end
26.5
69
0.805031
f81f386c3eda49b8628b59b7577af3feea94a48f
113
ENV['RACK_ENV'] = 'test' require 'rubygems' require 'bundler' Bundler.require :test require_relative './base'
12.555556
25
0.725664
7aede6278927d1e3bf69b279251e780887dcb8d9
1,756
require 'plugin_routes' require 'camaleon_cms/engine' Rails.application.routes.draw do scope PluginRoutes.system_info["relative_url_root"] do scope '(:locale)', locale: /#{PluginRoutes.all_locales}/, :defaults => { } do # frontend namespace :plugins do namespace 'social_shortcode' do get 'index' => 'front#index' end end end #Admin Panel scope :admin, as: 'admin', path: PluginRoutes.system_info['admin_path_name'] do namespace 'plugins' do namespace 'social_shortcode' do controller :admin do get :index get :settings post :save_settings end end end end # main routes #scope 'social_shortcode', module: 'plugins/social_shortcode/', as: 'social_shortcode' do # Here my routes for main routes #end end end require 'plugin_routes' require 'camaleon_cms/engine' Rails.application.routes.draw do scope PluginRoutes.system_info["relative_url_root"] do scope '(:locale)', locale: /#{PluginRoutes.all_locales}/, :defaults => { } do # frontend namespace :plugins do namespace 'social_shortcode' do get 'index' => 'front#index' end end end #Admin Panel scope :admin, as: 'admin', path: PluginRoutes.system_info['admin_path_name'] do namespace 'plugins' do namespace 'social_shortcode' do controller :admin do get :index get :settings post :save_settings end end end end # main routes #scope 'social_shortcode', module: 'plugins/social_shortcode/', as: 'social_shortcode' do # Here my routes for main routes #end end end
27.015385
93
0.620729
5d1d6aa53d09af0f029b8df8bc2fbf4044d55aaa
212
# frozen_string_literal: true Rails.application.routes.draw do devise_for :accounts # TODO: Add root route as needed/necessary # unauthenticated :user do # root to: 'static_pages#landing' # end end
19.272727
44
0.735849
87323724abad7aa47f97c9ae1815eaa606950573
1,211
require 'rb-inotify' module Blimp module Sources class GitWatcher def initialize @notifier = INotify::Notifier.new @watchers = {} end def watch(git_source, &block) raise ArgumentError, "block must not be nil" if block.nil? ws = [] begin ws << notifier.watch(git_source.head_path, :close_write) {|event| print "Calling block" block.call } print "#{self} is watching #{git_source.head_path}" rescue Errno::ENOENT end begin ws << notifier.watch(File.join(git_source.path, "packed-refs"), :close_write) {|event| print "Calling block" block.call } print "#{self} is watching #{git_source.path}/packed-refs" rescue Errno::ENOENT end raise RuntimeError, "Neither a packed nor an unpacked ref was found" if ws.empty? watchers[git_source] = ws end def unwatch(git_source) watchers[git_source].each {|w| w.close } end def process notifier.process end protected attr_reader :notifier attr_reader :watchers end end end
24.714286
96
0.57308
62de5658e895cec90ad7e709fb9884a1f80caed4
3,819
# Copyright 2015, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. require "googleauth/compute_engine" require "googleauth/default_credentials" module Google # Module Auth provides classes that provide Google-specific authorization # used to access Google APIs. module Auth NOT_FOUND_ERROR = <<~ERROR_MESSAGE.freeze Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information ERROR_MESSAGE module_function # Obtains the default credentials implementation to use in this # environment. # # Use this to obtain the Application Default Credentials for accessing # Google APIs. Application Default Credentials are described in detail # at https://cloud.google.com/docs/authentication/production. # # If supplied, scope is used to create the credentials instance, when it can # be applied. E.g, on google compute engine and for user credentials the # scope is ignored. # # @param scope [string|array|nil] the scope(s) to access # @param options [Hash] Connection options. These may be used to configure # the `Faraday::Connection` used for outgoing HTTP requests. For # example, if a connection proxy must be used in the current network, # you may provide a connection with with the needed proxy options. # The following keys are recognized: # * `:default_connection` The connection object to use for token # refresh requests. # * `:connection_builder` A `Proc` that creates and returns a # connection to use for token refresh requests. # * `:connection` The connection to use to determine whether GCE # metadata credentials are available. def get_application_default scope = nil, options = {} creds = DefaultCredentials.from_env(scope, options) || DefaultCredentials.from_well_known_path(scope, options) || DefaultCredentials.from_system_default_path(scope, options) return creds unless creds.nil? unless GCECredentials.on_gce? options # Clear cache of the result of GCECredentials.on_gce? GCECredentials.unmemoize_all raise NOT_FOUND_ERROR end GCECredentials.new options.merge(scope: scope) end end end
46.573171
81
0.737628
1853efde3502e774f254fb83bc2012425092d663
17,090
# frozen_string_literal: true require 'spec_helper' describe Gitlab::Ci::Config::Entry::Job do let(:entry) { described_class.new(config, name: :rspec) } describe '.nodes' do context 'when filtering all the entry/node names' do subject { described_class.nodes.keys } let(:result) do %i[before_script script stage type after_script cache image services only except rules variables artifacts environment coverage retry] end it { is_expected.to match_array result } end end describe '.matching?' do subject { described_class.matching?(name, config) } context 'when config is not a hash' do let(:name) { :rspec } let(:config) { 'string' } it { is_expected.to be_falsey } end context 'when config is a regular job' do let(:name) { :rspec } let(:config) do { script: 'ls -al' } end it { is_expected.to be_truthy } end context 'when config is a bridge job' do let(:name) { :rspec } let(:config) do { trigger: 'other-project' } end it { is_expected.to be_falsey } end context 'when config is a hidden job' do let(:name) { '.rspec' } let(:config) do { script: 'ls -al' } end it { is_expected.to be_falsey } end end describe 'validations' do before do entry.compose! end context 'when entry config value is correct' do let(:config) { { script: 'rspec' } } describe '#valid?' do it 'is valid' do expect(entry).to be_valid end end context 'when job name is empty' do let(:entry) { described_class.new(config, name: ''.to_sym) } it 'reports error' do expect(entry.errors).to include "job name can't be blank" end end context 'when delayed job' do context 'when start_in is specified' do let(:config) { { script: 'echo', when: 'delayed', start_in: '1 day' } } it { expect(entry).to be_valid } end end context 'when has needs' do let(:config) do { stage: 'test', script: 'echo', needs: ['another-job'] } end it { expect(entry).to be_valid } context 'when has dependencies' do let(:config) do { stage: 'test', script: 'echo', dependencies: ['another-job'], needs: ['another-job'] } end it { expect(entry).to be_valid } end end end context 'when entry value is not correct' do context 'incorrect config value type' do let(:config) { ['incorrect'] } describe '#errors' do it 'reports error about a config type' do expect(entry.errors) .to include 'job config should be a hash' end end end context 'when config is empty' do let(:config) { {} } describe '#valid' do it 'is invalid' do expect(entry).not_to be_valid end end end context 'when unknown keys detected' do let(:config) { { unknown: true } } describe '#valid' do it 'is not valid' do expect(entry).not_to be_valid end end end context 'when script is not provided' do let(:config) { { stage: 'test' } } it 'returns error about missing script entry' do expect(entry).not_to be_valid expect(entry.errors).to include "job script can't be blank" end end context 'when extends key is not a string' do let(:config) { { extends: 123 } } it 'returns error about wrong value type' do expect(entry).not_to be_valid expect(entry.errors).to include "job extends should be an array of strings or a string" end end context 'when parallel value is not correct' do context 'when it is not a numeric value' do let(:config) { { parallel: true } } it 'returns error about invalid type' do expect(entry).not_to be_valid expect(entry.errors).to include 'job parallel is not a number' end end context 'when it is lower than two' do let(:config) { { parallel: 1 } } it 'returns error about value too low' do expect(entry).not_to be_valid expect(entry.errors) .to include 'job parallel must be greater than or equal to 2' end end context 'when it is bigger than 50' do let(:config) { { parallel: 51 } } it 'returns error about value too high' do expect(entry).not_to be_valid expect(entry.errors) .to include 'job parallel must be less than or equal to 50' end end context 'when it is not an integer' do let(:config) { { parallel: 1.5 } } it 'returns error about wrong value' do expect(entry).not_to be_valid expect(entry.errors).to include 'job parallel must be an integer' end end context 'when it uses both "when:" and "rules:"' do let(:config) do { script: 'echo', when: 'on_failure', rules: [{ if: '$VARIABLE', when: 'on_success' }] } end it 'returns an error about when: being combined with rules' do expect(entry).not_to be_valid expect(entry.errors).to include 'job config key may not be used with `rules`: when' end end end context 'when delayed job' do context 'when start_in is specified' do let(:config) { { script: 'echo', when: 'delayed', start_in: '1 day' } } it 'returns error about invalid type' do expect(entry).to be_valid end end context 'when start_in is empty' do let(:config) { { when: 'delayed', start_in: nil } } it 'returns error about invalid type' do expect(entry).not_to be_valid expect(entry.errors).to include 'job start in should be a duration' end end context 'when start_in is not formatted as a duration' do let(:config) { { when: 'delayed', start_in: 'test' } } it 'returns error about invalid type' do expect(entry).not_to be_valid expect(entry.errors).to include 'job start in should be a duration' end end context 'when start_in is longer than one day' do let(:config) { { when: 'delayed', start_in: '2 days' } } it 'returns error about exceeding the limit' do expect(entry).not_to be_valid expect(entry.errors).to include 'job start in should not exceed the limit' end end end context 'when only: is used with rules:' do let(:config) { { only: ['merge_requests'], rules: [{ if: '$THIS' }] } } it 'returns error about mixing only: with rules:' do expect(entry).not_to be_valid expect(entry.errors).to include /may not be used with `rules`/ end context 'and only: is blank' do let(:config) { { only: nil, rules: [{ if: '$THIS' }] } } it 'returns error about mixing only: with rules:' do expect(entry).not_to be_valid expect(entry.errors).to include /may not be used with `rules`/ end end context 'and rules: is blank' do let(:config) { { only: ['merge_requests'], rules: nil } } it 'returns error about mixing only: with rules:' do expect(entry).not_to be_valid expect(entry.errors).to include /may not be used with `rules`/ end end end context 'when except: is used with rules:' do let(:config) { { except: { refs: %w[master] }, rules: [{ if: '$THIS' }] } } it 'returns error about mixing except: with rules:' do expect(entry).not_to be_valid expect(entry.errors).to include /may not be used with `rules`/ end context 'and except: is blank' do let(:config) { { except: nil, rules: [{ if: '$THIS' }] } } it 'returns error about mixing except: with rules:' do expect(entry).not_to be_valid expect(entry.errors).to include /may not be used with `rules`/ end end context 'and rules: is blank' do let(:config) { { except: { refs: %w[master] }, rules: nil } } it 'returns error about mixing except: with rules:' do expect(entry).not_to be_valid expect(entry.errors).to include /may not be used with `rules`/ end end end context 'when only: and except: are both used with rules:' do let(:config) do { only: %w[merge_requests], except: { refs: %w[master] }, rules: [{ if: '$THIS' }] } end it 'returns errors about mixing both only: and except: with rules:' do expect(entry).not_to be_valid expect(entry.errors).to include /may not be used with `rules`/ expect(entry.errors).to include /may not be used with `rules`/ end context 'when only: and except: as both blank' do let(:config) do { only: nil, except: nil, rules: [{ if: '$THIS' }] } end it 'returns errors about mixing both only: and except: with rules:' do expect(entry).not_to be_valid expect(entry.errors).to include /may not be used with `rules`/ expect(entry.errors).to include /may not be used with `rules`/ end end context 'when rules: is blank' do let(:config) do { only: %w[merge_requests], except: { refs: %w[master] }, rules: nil } end it 'returns errors about mixing both only: and except: with rules:' do expect(entry).not_to be_valid expect(entry.errors).to include /may not be used with `rules`/ expect(entry.errors).to include /may not be used with `rules`/ end end end context 'when start_in specified without delayed specification' do let(:config) { { start_in: '1 day' } } it 'returns error about invalid type' do expect(entry).not_to be_valid expect(entry.errors).to include 'job start in must be blank' end end context 'when has dependencies' do context 'that are not a array of strings' do let(:config) do { script: 'echo', dependencies: 'build-job' } end it 'returns error about invalid type' do expect(entry).not_to be_valid expect(entry.errors).to include 'job dependencies should be an array of strings' end end end context 'when has needs' do context 'that are not a array of strings' do let(:config) do { stage: 'test', script: 'echo', needs: 'build-job' } end it 'returns error about invalid type' do expect(entry).not_to be_valid expect(entry.errors).to include 'job needs should be an array of strings' end end context 'when have dependencies that are not subset of needs' do let(:config) do { stage: 'test', script: 'echo', dependencies: ['another-job'], needs: ['build-job'] } end it 'returns error about invalid data' do expect(entry).not_to be_valid expect(entry.errors).to include 'job dependencies the another-job should be part of needs' end end context 'when stage: is missing' do let(:config) do { script: 'echo', needs: ['build-job'] } end it 'returns error about invalid data' do expect(entry).not_to be_valid expect(entry.errors).to include 'job config missing required keys: stage' end end end end end describe '#relevant?' do it 'is a relevant entry' do entry = described_class.new({ script: 'rspec' }, name: :rspec) expect(entry).to be_relevant end end describe '#compose!' do let(:specified) do double('specified', 'specified?' => true, value: 'specified') end let(:unspecified) { double('unspecified', 'specified?' => false) } let(:default) { double('default', '[]' => unspecified) } let(:deps) { double('deps', 'default' => default, '[]' => unspecified) } context 'when job config overrides default config' do before do entry.compose!(deps) end let(:config) do { script: 'rspec', image: 'some_image', cache: { key: 'test' } } end it 'overrides default config' do expect(entry[:image].value).to eq(name: 'some_image') expect(entry[:cache].value).to eq(key: 'test', policy: 'pull-push') end end context 'when job config does not override default config' do before do allow(default).to receive('[]').with(:image).and_return(specified) entry.compose!(deps) end let(:config) { { script: 'ls', cache: { key: 'test' } } } it 'uses config from default entry' do expect(entry[:image].value).to eq 'specified' expect(entry[:cache].value).to eq(key: 'test', policy: 'pull-push') end end end context 'when composed' do before do entry.compose! end describe '#value' do before do entry.compose! end context 'when entry is correct' do let(:config) do { before_script: %w[ls pwd], script: 'rspec', after_script: %w[cleanup] } end it 'returns correct value' do expect(entry.value) .to eq(name: :rspec, before_script: %w[ls pwd], script: %w[rspec], stage: 'test', ignore: false, after_script: %w[cleanup], only: { refs: %w[branches tags] }, variables: {}) end end end end describe '#manual_action?' do context 'when job is a manual action' do let(:config) { { script: 'deploy', when: 'manual' } } it 'is a manual action' do expect(entry).to be_manual_action end end context 'when job is not a manual action' do let(:config) { { script: 'deploy' } } it 'is not a manual action' do expect(entry).not_to be_manual_action end end end describe '#delayed?' do context 'when job is a delayed' do let(:config) { { script: 'deploy', when: 'delayed' } } it 'is a delayed' do expect(entry).to be_delayed end end context 'when job is not a delayed' do let(:config) { { script: 'deploy' } } it 'is not a delayed' do expect(entry).not_to be_delayed end end end describe '#ignored?' do context 'when job is a manual action' do context 'when it is not specified if job is allowed to fail' do let(:config) do { script: 'deploy', when: 'manual' } end it 'is an ignored job' do expect(entry).to be_ignored end end context 'when job is allowed to fail' do let(:config) do { script: 'deploy', when: 'manual', allow_failure: true } end it 'is an ignored job' do expect(entry).to be_ignored end end context 'when job is not allowed to fail' do let(:config) do { script: 'deploy', when: 'manual', allow_failure: false } end it 'is not an ignored job' do expect(entry).not_to be_ignored end end end context 'when job is not a manual action' do context 'when it is not specified if job is allowed to fail' do let(:config) { { script: 'deploy' } } it 'is not an ignored job' do expect(entry).not_to be_ignored end end context 'when job is allowed to fail' do let(:config) { { script: 'deploy', allow_failure: true } } it 'is an ignored job' do expect(entry).to be_ignored end end context 'when job is not allowed to fail' do let(:config) { { script: 'deploy', allow_failure: false } } it 'is not an ignored job' do expect(entry).not_to be_ignored end end end end end
28.530885
102
0.548742
87232caeb2036a880d768c22fea61c8206776af1
3,939
module Fastlane module Actions class UpdateAppIdentifierAction < Action def self.run(params) require 'plist' require 'xcodeproj' info_plist_key = 'INFOPLIST_FILE' identifier_key = 'PRODUCT_BUNDLE_IDENTIFIER' # Read existing plist file info_plist_path = File.join(params[:xcodeproj], '..', params[:plist_path]) UI.user_error!("Couldn't find info plist file at path '#{params[:plist_path]}'") unless File.exist?(info_plist_path) plist = Plist.parse_xml(info_plist_path) # Check if current app identifier product bundle identifier if plist['CFBundleIdentifier'] == "$(#{identifier_key})" # Load .xcodeproj project_path = params[:xcodeproj] project = Xcodeproj::Project.open(project_path) # Fetch the build configuration objects configs = project.objects.select { |obj| obj.isa == 'XCBuildConfiguration' && !obj.build_settings[identifier_key].nil? } UI.user_error!("Info plist uses $(#{identifier_key}), but xcodeproj does not") unless configs.count > 0 configs = configs.select { |obj| obj.build_settings[info_plist_key] == params[:plist_path] } UI.user_error!("Xcodeproj doesn't have configuration with info plist #{params[:plist_path]}.") unless configs.count > 0 # For each of the build configurations, set app identifier configs.each do |c| c.build_settings[identifier_key] = params[:app_identifier] end # Write changes to the file project.save UI.success("Updated #{params[:xcodeproj]} 💾.") else # Update plist value plist['CFBundleIdentifier'] = params[:app_identifier] # Write changes to file plist_string = Plist::Emit.dump(plist) File.write(info_plist_path, plist_string) UI.success("Updated #{params[:plist_path]} 💾.") end end ##################################################### # @!group Documentation ##################################################### def self.is_supported?(platform) [:ios].include?(platform) end def self.description "Update the project's bundle identifier" end def self.available_options [ FastlaneCore::ConfigItem.new(key: :xcodeproj, env_name: "FL_UPDATE_APP_IDENTIFIER_PROJECT_PATH", description: "Path to your Xcode project", default_value: Dir['*.xcodeproj'].first, verify_block: proc do |value| UI.user_error!("Please pass the path to the project, not the workspace") unless value.end_with?(".xcodeproj") UI.user_error!("Could not find Xcode project") unless File.exist?(value) end), FastlaneCore::ConfigItem.new(key: :plist_path, env_name: "FL_UPDATE_APP_IDENTIFIER_PLIST_PATH", description: "Path to info plist, relative to your Xcode project", verify_block: proc do |value| UI.user_error!("Invalid plist file") unless value[-6..-1].casecmp(".plist").zero? end), FastlaneCore::ConfigItem.new(key: :app_identifier, env_name: 'FL_UPDATE_APP_IDENTIFIER', description: 'The app Identifier you want to set', default_value: ENV['PRODUCE_APP_IDENTIFIER']) ] end def self.authors ['squarefrog', 'tobiasstrebitzer'] end end end end
43.285714
150
0.543031
b9b20da64c75685078c60f749632596477277e77
186
Rails.application.routes.draw do root "articles#index" resources :articles # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
31
102
0.77957
1cb715534cc5e2a347eb54a130eed4754b7f133c
928
require 'bundler/setup' require 'rspec' require 'zxcvbnjs' Dir[Pathname.new(File.expand_path('../', __FILE__)).join('support/**/*.rb')].each {|f| require f} RSpec.configure do |config| config.include JsHelpers end TEST_PASSWORDS = [ 'zxcvbn', 'qwER43@!', 'Tr0ub4dour&3', 'correcthorsebatterystaple', 'coRrecth0rseba++ery9.23.2007staple$', 'D0g..................', 'abcdefghijk987654321', 'neverforget13/3/1997', '1qaz2wsx3edc', 'temppass22', 'briansmith', 'briansmith4mayor', 'password1', 'viking', 'thx1138', 'ScoRpi0ns', 'do you know', 'ryanhunter2000', 'rianhunter2000', 'asdfghju7654rewq', 'AOEUIDHG&*()LS_', '12345678', 'defghi6789', 'rosebud', 'Rosebud', 'ROSEBUD', 'rosebuD', 'ros3bud99', 'r0s3bud99', 'R0$38uD99', 'verlineVANDERMARK', 'eheuczkqyq', 'rWibMFACxAUGZmxhVncy', 'Ba9ZyWABu99[BK#6MBgbH88Tofv)vs$w', 'qwER43@!', 'Obama!123' ]
16.280702
97
0.639009
1c736b5f824060d4cd234019c050e2f9061c34b8
288
module AtoTk module Common WEIGHTS = {8 => [10, 7, 8, 4, 6, 3, 5, 1], 9 => [10, 7, 8, 4, 6, 3, 5, 2, 1], 11 => [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]} end end # Require everything from the atotk directory. Dir[File.expand_path('../atotk/*.rb', __FILE__)].each{|f| require f }
26.181818
128
0.555556
f8fa376f833dbd9caff92e2220c4a57585157616
4,847
# frozen_string_literal: true module Integrations class Github < Integration include Gitlab::Routing include ActionView::Helpers::UrlHelper prop_accessor :token, :repository_url boolean_accessor :static_context delegate :api_url, :owner, :repository_name, to: :remote_project validates :token, presence: true, if: :activated? validates :repository_url, public_url: true, allow_blank: true default_value_for :pipeline_events, true def initialize_properties self.properties ||= { static_context: true } end def title 'GitHub' end def description s_("GithubIntegration|Obtain statuses for commits and pull requests.") end def help return unless project docs_link = link_to _('What is repository mirroring?'), help_page_url('user/project/repository/repository_mirroring') s_("GithubIntegration|This requires mirroring your GitHub repository to this project. %{docs_link}" % { docs_link: docs_link }).html_safe end def self.to_param 'github' end def fields learn_more_link_url = help_page_path('user/project/integrations/github', anchor: 'static-or-dynamic-status-check-names') learn_more_link_start = '<a href="%{url}" target="_blank" rel="noopener noreferrer">'.html_safe % { url: learn_more_link_url } static_context_field_help = s_('GithubIntegration|Select this if you want GitHub to mark status checks as "Required". %{learn_more_link_start}Learn more%{learn_more_link_end}.').html_safe % { learn_more_link_start: learn_more_link_start, learn_more_link_end: '</a>'.html_safe } token_url = 'https://github.com/settings/tokens' token_link_start = '<a href="%{url}" target="_blank" rel="noopener noreferrer">'.html_safe % { url: token_url } token_field_help = s_('GithubIntegration|Create a %{token_link_start}personal access token%{token_link_end} with %{status_html} access granted and paste it here.').html_safe % { token_link_start: token_link_start, token_link_end: '</a>'.html_safe, status_html: '<code>repo:status</code>'.html_safe } [ { type: 'password', name: "token", required: true, placeholder: "8d3f016698e...", non_empty_password_title: s_('ProjectService|Enter new token'), non_empty_password_help: s_('ProjectService|Leave blank to use your current token.'), help: token_field_help }, { type: 'text', name: "repository_url", title: s_('GithubIntegration|Repository URL'), required: true, placeholder: 'https://github.com/owner/repository' }, { type: 'checkbox', name: "static_context", title: s_('GithubIntegration|Static status check names (optional)'), checkbox_label: s_('GithubIntegration|Enable static status check names'), help: static_context_field_help } ] end def self.supported_events %w(pipeline) end def testable? project&.ci_pipelines&.any? end def execute(data) return if disabled? || invalid? || irrelevant_result?(data) status_message = StatusMessage.from_pipeline_data(project, self, data) update_status(status_message) end def test(data) begin result = execute(data) context = result[:context] by_user = result.dig(:creator, :login) result = "Status for #{context} updated by #{by_user}" if context && by_user rescue StandardError => error return { success: false, result: error } end { success: true, result: result } end private def irrelevant_result?(data) !external_pull_request_pipeline?(data) && external_pull_request_pipelines_exist_for_sha?(data) end def external_pull_request_pipeline?(data) id = data.dig(:object_attributes, :id) external_pull_request_pipelines.id_in(id).exists? end def external_pull_request_pipelines_exist_for_sha?(data) sha = data.dig(:object_attributes, :sha) return false if sha.nil? external_pull_request_pipelines.for_sha(sha).exists? end def external_pull_request_pipelines @external_pull_request_pipelines ||= project .ci_pipelines .external_pull_request_event end def remote_project RemoteProject.new(repository_url) end def disabled? project.disabled_integrations.include?(to_param) end def update_status(status_message) notifier.notify(status_message.sha, status_message.status, status_message.status_options) end def notifier StatusNotifier.new(token, remote_repo_path, api_endpoint: api_url) end def remote_repo_path "#{owner}/#{repository_name}" end end end
32.313333
305
0.68104
6225f8d25a224c22c9b2fa2c9ceb3e50d3f46cf1
110,335
# WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE module Aws::DirectoryService # @api private module ClientApi include Seahorse::Model AcceptSharedDirectoryRequest = Shapes::StructureShape.new(name: 'AcceptSharedDirectoryRequest') AcceptSharedDirectoryResult = Shapes::StructureShape.new(name: 'AcceptSharedDirectoryResult') AccessDeniedException = Shapes::StructureShape.new(name: 'AccessDeniedException') AccessUrl = Shapes::StringShape.new(name: 'AccessUrl') AddIpRoutesRequest = Shapes::StructureShape.new(name: 'AddIpRoutesRequest') AddIpRoutesResult = Shapes::StructureShape.new(name: 'AddIpRoutesResult') AddTagsToResourceRequest = Shapes::StructureShape.new(name: 'AddTagsToResourceRequest') AddTagsToResourceResult = Shapes::StructureShape.new(name: 'AddTagsToResourceResult') AddedDateTime = Shapes::TimestampShape.new(name: 'AddedDateTime') AliasName = Shapes::StringShape.new(name: 'AliasName') Attribute = Shapes::StructureShape.new(name: 'Attribute') AttributeName = Shapes::StringShape.new(name: 'AttributeName') AttributeValue = Shapes::StringShape.new(name: 'AttributeValue') Attributes = Shapes::ListShape.new(name: 'Attributes') AuthenticationFailedException = Shapes::StructureShape.new(name: 'AuthenticationFailedException') AvailabilityZone = Shapes::StringShape.new(name: 'AvailabilityZone') AvailabilityZones = Shapes::ListShape.new(name: 'AvailabilityZones') CancelSchemaExtensionRequest = Shapes::StructureShape.new(name: 'CancelSchemaExtensionRequest') CancelSchemaExtensionResult = Shapes::StructureShape.new(name: 'CancelSchemaExtensionResult') CidrIp = Shapes::StringShape.new(name: 'CidrIp') CidrIps = Shapes::ListShape.new(name: 'CidrIps') ClientException = Shapes::StructureShape.new(name: 'ClientException') CloudOnlyDirectoriesLimitReached = Shapes::BooleanShape.new(name: 'CloudOnlyDirectoriesLimitReached') Computer = Shapes::StructureShape.new(name: 'Computer') ComputerName = Shapes::StringShape.new(name: 'ComputerName') ComputerPassword = Shapes::StringShape.new(name: 'ComputerPassword') ConditionalForwarder = Shapes::StructureShape.new(name: 'ConditionalForwarder') ConditionalForwarders = Shapes::ListShape.new(name: 'ConditionalForwarders') ConnectDirectoryRequest = Shapes::StructureShape.new(name: 'ConnectDirectoryRequest') ConnectDirectoryResult = Shapes::StructureShape.new(name: 'ConnectDirectoryResult') ConnectPassword = Shapes::StringShape.new(name: 'ConnectPassword') ConnectedDirectoriesLimitReached = Shapes::BooleanShape.new(name: 'ConnectedDirectoriesLimitReached') CreateAliasRequest = Shapes::StructureShape.new(name: 'CreateAliasRequest') CreateAliasResult = Shapes::StructureShape.new(name: 'CreateAliasResult') CreateComputerRequest = Shapes::StructureShape.new(name: 'CreateComputerRequest') CreateComputerResult = Shapes::StructureShape.new(name: 'CreateComputerResult') CreateConditionalForwarderRequest = Shapes::StructureShape.new(name: 'CreateConditionalForwarderRequest') CreateConditionalForwarderResult = Shapes::StructureShape.new(name: 'CreateConditionalForwarderResult') CreateDirectoryRequest = Shapes::StructureShape.new(name: 'CreateDirectoryRequest') CreateDirectoryResult = Shapes::StructureShape.new(name: 'CreateDirectoryResult') CreateLogSubscriptionRequest = Shapes::StructureShape.new(name: 'CreateLogSubscriptionRequest') CreateLogSubscriptionResult = Shapes::StructureShape.new(name: 'CreateLogSubscriptionResult') CreateMicrosoftADRequest = Shapes::StructureShape.new(name: 'CreateMicrosoftADRequest') CreateMicrosoftADResult = Shapes::StructureShape.new(name: 'CreateMicrosoftADResult') CreateSnapshotBeforeSchemaExtension = Shapes::BooleanShape.new(name: 'CreateSnapshotBeforeSchemaExtension') CreateSnapshotRequest = Shapes::StructureShape.new(name: 'CreateSnapshotRequest') CreateSnapshotResult = Shapes::StructureShape.new(name: 'CreateSnapshotResult') CreateTrustRequest = Shapes::StructureShape.new(name: 'CreateTrustRequest') CreateTrustResult = Shapes::StructureShape.new(name: 'CreateTrustResult') CreatedDateTime = Shapes::TimestampShape.new(name: 'CreatedDateTime') CustomerId = Shapes::StringShape.new(name: 'CustomerId') CustomerUserName = Shapes::StringShape.new(name: 'CustomerUserName') DeleteAssociatedConditionalForwarder = Shapes::BooleanShape.new(name: 'DeleteAssociatedConditionalForwarder') DeleteConditionalForwarderRequest = Shapes::StructureShape.new(name: 'DeleteConditionalForwarderRequest') DeleteConditionalForwarderResult = Shapes::StructureShape.new(name: 'DeleteConditionalForwarderResult') DeleteDirectoryRequest = Shapes::StructureShape.new(name: 'DeleteDirectoryRequest') DeleteDirectoryResult = Shapes::StructureShape.new(name: 'DeleteDirectoryResult') DeleteLogSubscriptionRequest = Shapes::StructureShape.new(name: 'DeleteLogSubscriptionRequest') DeleteLogSubscriptionResult = Shapes::StructureShape.new(name: 'DeleteLogSubscriptionResult') DeleteSnapshotRequest = Shapes::StructureShape.new(name: 'DeleteSnapshotRequest') DeleteSnapshotResult = Shapes::StructureShape.new(name: 'DeleteSnapshotResult') DeleteTrustRequest = Shapes::StructureShape.new(name: 'DeleteTrustRequest') DeleteTrustResult = Shapes::StructureShape.new(name: 'DeleteTrustResult') DeregisterEventTopicRequest = Shapes::StructureShape.new(name: 'DeregisterEventTopicRequest') DeregisterEventTopicResult = Shapes::StructureShape.new(name: 'DeregisterEventTopicResult') DescribeConditionalForwardersRequest = Shapes::StructureShape.new(name: 'DescribeConditionalForwardersRequest') DescribeConditionalForwardersResult = Shapes::StructureShape.new(name: 'DescribeConditionalForwardersResult') DescribeDirectoriesRequest = Shapes::StructureShape.new(name: 'DescribeDirectoriesRequest') DescribeDirectoriesResult = Shapes::StructureShape.new(name: 'DescribeDirectoriesResult') DescribeDomainControllersRequest = Shapes::StructureShape.new(name: 'DescribeDomainControllersRequest') DescribeDomainControllersResult = Shapes::StructureShape.new(name: 'DescribeDomainControllersResult') DescribeEventTopicsRequest = Shapes::StructureShape.new(name: 'DescribeEventTopicsRequest') DescribeEventTopicsResult = Shapes::StructureShape.new(name: 'DescribeEventTopicsResult') DescribeSharedDirectoriesRequest = Shapes::StructureShape.new(name: 'DescribeSharedDirectoriesRequest') DescribeSharedDirectoriesResult = Shapes::StructureShape.new(name: 'DescribeSharedDirectoriesResult') DescribeSnapshotsRequest = Shapes::StructureShape.new(name: 'DescribeSnapshotsRequest') DescribeSnapshotsResult = Shapes::StructureShape.new(name: 'DescribeSnapshotsResult') DescribeTrustsRequest = Shapes::StructureShape.new(name: 'DescribeTrustsRequest') DescribeTrustsResult = Shapes::StructureShape.new(name: 'DescribeTrustsResult') Description = Shapes::StringShape.new(name: 'Description') DesiredNumberOfDomainControllers = Shapes::IntegerShape.new(name: 'DesiredNumberOfDomainControllers') DirectoryAlreadySharedException = Shapes::StructureShape.new(name: 'DirectoryAlreadySharedException') DirectoryConnectSettings = Shapes::StructureShape.new(name: 'DirectoryConnectSettings') DirectoryConnectSettingsDescription = Shapes::StructureShape.new(name: 'DirectoryConnectSettingsDescription') DirectoryDescription = Shapes::StructureShape.new(name: 'DirectoryDescription') DirectoryDescriptions = Shapes::ListShape.new(name: 'DirectoryDescriptions') DirectoryEdition = Shapes::StringShape.new(name: 'DirectoryEdition') DirectoryId = Shapes::StringShape.new(name: 'DirectoryId') DirectoryIds = Shapes::ListShape.new(name: 'DirectoryIds') DirectoryLimitExceededException = Shapes::StructureShape.new(name: 'DirectoryLimitExceededException') DirectoryLimits = Shapes::StructureShape.new(name: 'DirectoryLimits') DirectoryName = Shapes::StringShape.new(name: 'DirectoryName') DirectoryNotSharedException = Shapes::StructureShape.new(name: 'DirectoryNotSharedException') DirectoryShortName = Shapes::StringShape.new(name: 'DirectoryShortName') DirectorySize = Shapes::StringShape.new(name: 'DirectorySize') DirectoryStage = Shapes::StringShape.new(name: 'DirectoryStage') DirectoryType = Shapes::StringShape.new(name: 'DirectoryType') DirectoryUnavailableException = Shapes::StructureShape.new(name: 'DirectoryUnavailableException') DirectoryVpcSettings = Shapes::StructureShape.new(name: 'DirectoryVpcSettings') DirectoryVpcSettingsDescription = Shapes::StructureShape.new(name: 'DirectoryVpcSettingsDescription') DisableRadiusRequest = Shapes::StructureShape.new(name: 'DisableRadiusRequest') DisableRadiusResult = Shapes::StructureShape.new(name: 'DisableRadiusResult') DisableSsoRequest = Shapes::StructureShape.new(name: 'DisableSsoRequest') DisableSsoResult = Shapes::StructureShape.new(name: 'DisableSsoResult') DnsIpAddrs = Shapes::ListShape.new(name: 'DnsIpAddrs') DomainController = Shapes::StructureShape.new(name: 'DomainController') DomainControllerId = Shapes::StringShape.new(name: 'DomainControllerId') DomainControllerIds = Shapes::ListShape.new(name: 'DomainControllerIds') DomainControllerLimitExceededException = Shapes::StructureShape.new(name: 'DomainControllerLimitExceededException') DomainControllerStatus = Shapes::StringShape.new(name: 'DomainControllerStatus') DomainControllerStatusReason = Shapes::StringShape.new(name: 'DomainControllerStatusReason') DomainControllers = Shapes::ListShape.new(name: 'DomainControllers') EnableRadiusRequest = Shapes::StructureShape.new(name: 'EnableRadiusRequest') EnableRadiusResult = Shapes::StructureShape.new(name: 'EnableRadiusResult') EnableSsoRequest = Shapes::StructureShape.new(name: 'EnableSsoRequest') EnableSsoResult = Shapes::StructureShape.new(name: 'EnableSsoResult') EndDateTime = Shapes::TimestampShape.new(name: 'EndDateTime') EntityAlreadyExistsException = Shapes::StructureShape.new(name: 'EntityAlreadyExistsException') EntityDoesNotExistException = Shapes::StructureShape.new(name: 'EntityDoesNotExistException') EventTopic = Shapes::StructureShape.new(name: 'EventTopic') EventTopics = Shapes::ListShape.new(name: 'EventTopics') ExceptionMessage = Shapes::StringShape.new(name: 'ExceptionMessage') GetDirectoryLimitsRequest = Shapes::StructureShape.new(name: 'GetDirectoryLimitsRequest') GetDirectoryLimitsResult = Shapes::StructureShape.new(name: 'GetDirectoryLimitsResult') GetSnapshotLimitsRequest = Shapes::StructureShape.new(name: 'GetSnapshotLimitsRequest') GetSnapshotLimitsResult = Shapes::StructureShape.new(name: 'GetSnapshotLimitsResult') InsufficientPermissionsException = Shapes::StructureShape.new(name: 'InsufficientPermissionsException') InvalidNextTokenException = Shapes::StructureShape.new(name: 'InvalidNextTokenException') InvalidParameterException = Shapes::StructureShape.new(name: 'InvalidParameterException') InvalidPasswordException = Shapes::StructureShape.new(name: 'InvalidPasswordException') InvalidTargetException = Shapes::StructureShape.new(name: 'InvalidTargetException') IpAddr = Shapes::StringShape.new(name: 'IpAddr') IpAddrs = Shapes::ListShape.new(name: 'IpAddrs') IpRoute = Shapes::StructureShape.new(name: 'IpRoute') IpRouteInfo = Shapes::StructureShape.new(name: 'IpRouteInfo') IpRouteLimitExceededException = Shapes::StructureShape.new(name: 'IpRouteLimitExceededException') IpRouteStatusMsg = Shapes::StringShape.new(name: 'IpRouteStatusMsg') IpRouteStatusReason = Shapes::StringShape.new(name: 'IpRouteStatusReason') IpRoutes = Shapes::ListShape.new(name: 'IpRoutes') IpRoutesInfo = Shapes::ListShape.new(name: 'IpRoutesInfo') LastUpdatedDateTime = Shapes::TimestampShape.new(name: 'LastUpdatedDateTime') LaunchTime = Shapes::TimestampShape.new(name: 'LaunchTime') LdifContent = Shapes::StringShape.new(name: 'LdifContent') Limit = Shapes::IntegerShape.new(name: 'Limit') ListIpRoutesRequest = Shapes::StructureShape.new(name: 'ListIpRoutesRequest') ListIpRoutesResult = Shapes::StructureShape.new(name: 'ListIpRoutesResult') ListLogSubscriptionsRequest = Shapes::StructureShape.new(name: 'ListLogSubscriptionsRequest') ListLogSubscriptionsResult = Shapes::StructureShape.new(name: 'ListLogSubscriptionsResult') ListSchemaExtensionsRequest = Shapes::StructureShape.new(name: 'ListSchemaExtensionsRequest') ListSchemaExtensionsResult = Shapes::StructureShape.new(name: 'ListSchemaExtensionsResult') ListTagsForResourceRequest = Shapes::StructureShape.new(name: 'ListTagsForResourceRequest') ListTagsForResourceResult = Shapes::StructureShape.new(name: 'ListTagsForResourceResult') LogGroupName = Shapes::StringShape.new(name: 'LogGroupName') LogSubscription = Shapes::StructureShape.new(name: 'LogSubscription') LogSubscriptions = Shapes::ListShape.new(name: 'LogSubscriptions') ManualSnapshotsLimitReached = Shapes::BooleanShape.new(name: 'ManualSnapshotsLimitReached') NextToken = Shapes::StringShape.new(name: 'NextToken') Notes = Shapes::StringShape.new(name: 'Notes') OrganizationalUnitDN = Shapes::StringShape.new(name: 'OrganizationalUnitDN') OrganizationsException = Shapes::StructureShape.new(name: 'OrganizationsException') OwnerDirectoryDescription = Shapes::StructureShape.new(name: 'OwnerDirectoryDescription') Password = Shapes::StringShape.new(name: 'Password') PortNumber = Shapes::IntegerShape.new(name: 'PortNumber') RadiusAuthenticationProtocol = Shapes::StringShape.new(name: 'RadiusAuthenticationProtocol') RadiusDisplayLabel = Shapes::StringShape.new(name: 'RadiusDisplayLabel') RadiusRetries = Shapes::IntegerShape.new(name: 'RadiusRetries') RadiusSettings = Shapes::StructureShape.new(name: 'RadiusSettings') RadiusSharedSecret = Shapes::StringShape.new(name: 'RadiusSharedSecret') RadiusStatus = Shapes::StringShape.new(name: 'RadiusStatus') RadiusTimeout = Shapes::IntegerShape.new(name: 'RadiusTimeout') RegisterEventTopicRequest = Shapes::StructureShape.new(name: 'RegisterEventTopicRequest') RegisterEventTopicResult = Shapes::StructureShape.new(name: 'RegisterEventTopicResult') RejectSharedDirectoryRequest = Shapes::StructureShape.new(name: 'RejectSharedDirectoryRequest') RejectSharedDirectoryResult = Shapes::StructureShape.new(name: 'RejectSharedDirectoryResult') RemoteDomainName = Shapes::StringShape.new(name: 'RemoteDomainName') RemoteDomainNames = Shapes::ListShape.new(name: 'RemoteDomainNames') RemoveIpRoutesRequest = Shapes::StructureShape.new(name: 'RemoveIpRoutesRequest') RemoveIpRoutesResult = Shapes::StructureShape.new(name: 'RemoveIpRoutesResult') RemoveTagsFromResourceRequest = Shapes::StructureShape.new(name: 'RemoveTagsFromResourceRequest') RemoveTagsFromResourceResult = Shapes::StructureShape.new(name: 'RemoveTagsFromResourceResult') ReplicationScope = Shapes::StringShape.new(name: 'ReplicationScope') RequestId = Shapes::StringShape.new(name: 'RequestId') ResetUserPasswordRequest = Shapes::StructureShape.new(name: 'ResetUserPasswordRequest') ResetUserPasswordResult = Shapes::StructureShape.new(name: 'ResetUserPasswordResult') ResourceId = Shapes::StringShape.new(name: 'ResourceId') RestoreFromSnapshotRequest = Shapes::StructureShape.new(name: 'RestoreFromSnapshotRequest') RestoreFromSnapshotResult = Shapes::StructureShape.new(name: 'RestoreFromSnapshotResult') SID = Shapes::StringShape.new(name: 'SID') SchemaExtensionId = Shapes::StringShape.new(name: 'SchemaExtensionId') SchemaExtensionInfo = Shapes::StructureShape.new(name: 'SchemaExtensionInfo') SchemaExtensionStatus = Shapes::StringShape.new(name: 'SchemaExtensionStatus') SchemaExtensionStatusReason = Shapes::StringShape.new(name: 'SchemaExtensionStatusReason') SchemaExtensionsInfo = Shapes::ListShape.new(name: 'SchemaExtensionsInfo') SecurityGroupId = Shapes::StringShape.new(name: 'SecurityGroupId') SelectiveAuth = Shapes::StringShape.new(name: 'SelectiveAuth') Server = Shapes::StringShape.new(name: 'Server') Servers = Shapes::ListShape.new(name: 'Servers') ServiceException = Shapes::StructureShape.new(name: 'ServiceException') ShareDirectoryRequest = Shapes::StructureShape.new(name: 'ShareDirectoryRequest') ShareDirectoryResult = Shapes::StructureShape.new(name: 'ShareDirectoryResult') ShareLimitExceededException = Shapes::StructureShape.new(name: 'ShareLimitExceededException') ShareMethod = Shapes::StringShape.new(name: 'ShareMethod') ShareStatus = Shapes::StringShape.new(name: 'ShareStatus') ShareTarget = Shapes::StructureShape.new(name: 'ShareTarget') SharedDirectories = Shapes::ListShape.new(name: 'SharedDirectories') SharedDirectory = Shapes::StructureShape.new(name: 'SharedDirectory') Snapshot = Shapes::StructureShape.new(name: 'Snapshot') SnapshotId = Shapes::StringShape.new(name: 'SnapshotId') SnapshotIds = Shapes::ListShape.new(name: 'SnapshotIds') SnapshotLimitExceededException = Shapes::StructureShape.new(name: 'SnapshotLimitExceededException') SnapshotLimits = Shapes::StructureShape.new(name: 'SnapshotLimits') SnapshotName = Shapes::StringShape.new(name: 'SnapshotName') SnapshotStatus = Shapes::StringShape.new(name: 'SnapshotStatus') SnapshotType = Shapes::StringShape.new(name: 'SnapshotType') Snapshots = Shapes::ListShape.new(name: 'Snapshots') SsoEnabled = Shapes::BooleanShape.new(name: 'SsoEnabled') StageReason = Shapes::StringShape.new(name: 'StageReason') StartDateTime = Shapes::TimestampShape.new(name: 'StartDateTime') StartSchemaExtensionRequest = Shapes::StructureShape.new(name: 'StartSchemaExtensionRequest') StartSchemaExtensionResult = Shapes::StructureShape.new(name: 'StartSchemaExtensionResult') StartTime = Shapes::TimestampShape.new(name: 'StartTime') StateLastUpdatedDateTime = Shapes::TimestampShape.new(name: 'StateLastUpdatedDateTime') SubnetId = Shapes::StringShape.new(name: 'SubnetId') SubnetIds = Shapes::ListShape.new(name: 'SubnetIds') SubscriptionCreatedDateTime = Shapes::TimestampShape.new(name: 'SubscriptionCreatedDateTime') Tag = Shapes::StructureShape.new(name: 'Tag') TagKey = Shapes::StringShape.new(name: 'TagKey') TagKeys = Shapes::ListShape.new(name: 'TagKeys') TagLimitExceededException = Shapes::StructureShape.new(name: 'TagLimitExceededException') TagValue = Shapes::StringShape.new(name: 'TagValue') Tags = Shapes::ListShape.new(name: 'Tags') TargetId = Shapes::StringShape.new(name: 'TargetId') TargetType = Shapes::StringShape.new(name: 'TargetType') TopicArn = Shapes::StringShape.new(name: 'TopicArn') TopicName = Shapes::StringShape.new(name: 'TopicName') TopicNames = Shapes::ListShape.new(name: 'TopicNames') TopicStatus = Shapes::StringShape.new(name: 'TopicStatus') Trust = Shapes::StructureShape.new(name: 'Trust') TrustDirection = Shapes::StringShape.new(name: 'TrustDirection') TrustId = Shapes::StringShape.new(name: 'TrustId') TrustIds = Shapes::ListShape.new(name: 'TrustIds') TrustPassword = Shapes::StringShape.new(name: 'TrustPassword') TrustState = Shapes::StringShape.new(name: 'TrustState') TrustStateReason = Shapes::StringShape.new(name: 'TrustStateReason') TrustType = Shapes::StringShape.new(name: 'TrustType') Trusts = Shapes::ListShape.new(name: 'Trusts') UnshareDirectoryRequest = Shapes::StructureShape.new(name: 'UnshareDirectoryRequest') UnshareDirectoryResult = Shapes::StructureShape.new(name: 'UnshareDirectoryResult') UnshareTarget = Shapes::StructureShape.new(name: 'UnshareTarget') UnsupportedOperationException = Shapes::StructureShape.new(name: 'UnsupportedOperationException') UpdateConditionalForwarderRequest = Shapes::StructureShape.new(name: 'UpdateConditionalForwarderRequest') UpdateConditionalForwarderResult = Shapes::StructureShape.new(name: 'UpdateConditionalForwarderResult') UpdateNumberOfDomainControllersRequest = Shapes::StructureShape.new(name: 'UpdateNumberOfDomainControllersRequest') UpdateNumberOfDomainControllersResult = Shapes::StructureShape.new(name: 'UpdateNumberOfDomainControllersResult') UpdateRadiusRequest = Shapes::StructureShape.new(name: 'UpdateRadiusRequest') UpdateRadiusResult = Shapes::StructureShape.new(name: 'UpdateRadiusResult') UpdateSecurityGroupForDirectoryControllers = Shapes::BooleanShape.new(name: 'UpdateSecurityGroupForDirectoryControllers') UpdateTrustRequest = Shapes::StructureShape.new(name: 'UpdateTrustRequest') UpdateTrustResult = Shapes::StructureShape.new(name: 'UpdateTrustResult') UseSameUsername = Shapes::BooleanShape.new(name: 'UseSameUsername') UserDoesNotExistException = Shapes::StructureShape.new(name: 'UserDoesNotExistException') UserName = Shapes::StringShape.new(name: 'UserName') UserPassword = Shapes::StringShape.new(name: 'UserPassword') VerifyTrustRequest = Shapes::StructureShape.new(name: 'VerifyTrustRequest') VerifyTrustResult = Shapes::StructureShape.new(name: 'VerifyTrustResult') VpcId = Shapes::StringShape.new(name: 'VpcId') AcceptSharedDirectoryRequest.add_member(:shared_directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "SharedDirectoryId")) AcceptSharedDirectoryRequest.struct_class = Types::AcceptSharedDirectoryRequest AcceptSharedDirectoryResult.add_member(:shared_directory, Shapes::ShapeRef.new(shape: SharedDirectory, location_name: "SharedDirectory")) AcceptSharedDirectoryResult.struct_class = Types::AcceptSharedDirectoryResult AddIpRoutesRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) AddIpRoutesRequest.add_member(:ip_routes, Shapes::ShapeRef.new(shape: IpRoutes, required: true, location_name: "IpRoutes")) AddIpRoutesRequest.add_member(:update_security_group_for_directory_controllers, Shapes::ShapeRef.new(shape: UpdateSecurityGroupForDirectoryControllers, location_name: "UpdateSecurityGroupForDirectoryControllers")) AddIpRoutesRequest.struct_class = Types::AddIpRoutesRequest AddIpRoutesResult.struct_class = Types::AddIpRoutesResult AddTagsToResourceRequest.add_member(:resource_id, Shapes::ShapeRef.new(shape: ResourceId, required: true, location_name: "ResourceId")) AddTagsToResourceRequest.add_member(:tags, Shapes::ShapeRef.new(shape: Tags, required: true, location_name: "Tags")) AddTagsToResourceRequest.struct_class = Types::AddTagsToResourceRequest AddTagsToResourceResult.struct_class = Types::AddTagsToResourceResult Attribute.add_member(:name, Shapes::ShapeRef.new(shape: AttributeName, location_name: "Name")) Attribute.add_member(:value, Shapes::ShapeRef.new(shape: AttributeValue, location_name: "Value")) Attribute.struct_class = Types::Attribute Attributes.member = Shapes::ShapeRef.new(shape: Attribute) AvailabilityZones.member = Shapes::ShapeRef.new(shape: AvailabilityZone) CancelSchemaExtensionRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) CancelSchemaExtensionRequest.add_member(:schema_extension_id, Shapes::ShapeRef.new(shape: SchemaExtensionId, required: true, location_name: "SchemaExtensionId")) CancelSchemaExtensionRequest.struct_class = Types::CancelSchemaExtensionRequest CancelSchemaExtensionResult.struct_class = Types::CancelSchemaExtensionResult CidrIps.member = Shapes::ShapeRef.new(shape: CidrIp) Computer.add_member(:computer_id, Shapes::ShapeRef.new(shape: SID, location_name: "ComputerId")) Computer.add_member(:computer_name, Shapes::ShapeRef.new(shape: ComputerName, location_name: "ComputerName")) Computer.add_member(:computer_attributes, Shapes::ShapeRef.new(shape: Attributes, location_name: "ComputerAttributes")) Computer.struct_class = Types::Computer ConditionalForwarder.add_member(:remote_domain_name, Shapes::ShapeRef.new(shape: RemoteDomainName, location_name: "RemoteDomainName")) ConditionalForwarder.add_member(:dns_ip_addrs, Shapes::ShapeRef.new(shape: DnsIpAddrs, location_name: "DnsIpAddrs")) ConditionalForwarder.add_member(:replication_scope, Shapes::ShapeRef.new(shape: ReplicationScope, location_name: "ReplicationScope")) ConditionalForwarder.struct_class = Types::ConditionalForwarder ConditionalForwarders.member = Shapes::ShapeRef.new(shape: ConditionalForwarder) ConnectDirectoryRequest.add_member(:name, Shapes::ShapeRef.new(shape: DirectoryName, required: true, location_name: "Name")) ConnectDirectoryRequest.add_member(:short_name, Shapes::ShapeRef.new(shape: DirectoryShortName, location_name: "ShortName")) ConnectDirectoryRequest.add_member(:password, Shapes::ShapeRef.new(shape: ConnectPassword, required: true, location_name: "Password")) ConnectDirectoryRequest.add_member(:description, Shapes::ShapeRef.new(shape: Description, location_name: "Description")) ConnectDirectoryRequest.add_member(:size, Shapes::ShapeRef.new(shape: DirectorySize, required: true, location_name: "Size")) ConnectDirectoryRequest.add_member(:connect_settings, Shapes::ShapeRef.new(shape: DirectoryConnectSettings, required: true, location_name: "ConnectSettings")) ConnectDirectoryRequest.add_member(:tags, Shapes::ShapeRef.new(shape: Tags, location_name: "Tags")) ConnectDirectoryRequest.struct_class = Types::ConnectDirectoryRequest ConnectDirectoryResult.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "DirectoryId")) ConnectDirectoryResult.struct_class = Types::ConnectDirectoryResult CreateAliasRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) CreateAliasRequest.add_member(:alias, Shapes::ShapeRef.new(shape: AliasName, required: true, location_name: "Alias")) CreateAliasRequest.struct_class = Types::CreateAliasRequest CreateAliasResult.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "DirectoryId")) CreateAliasResult.add_member(:alias, Shapes::ShapeRef.new(shape: AliasName, location_name: "Alias")) CreateAliasResult.struct_class = Types::CreateAliasResult CreateComputerRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) CreateComputerRequest.add_member(:computer_name, Shapes::ShapeRef.new(shape: ComputerName, required: true, location_name: "ComputerName")) CreateComputerRequest.add_member(:password, Shapes::ShapeRef.new(shape: ComputerPassword, required: true, location_name: "Password")) CreateComputerRequest.add_member(:organizational_unit_distinguished_name, Shapes::ShapeRef.new(shape: OrganizationalUnitDN, location_name: "OrganizationalUnitDistinguishedName")) CreateComputerRequest.add_member(:computer_attributes, Shapes::ShapeRef.new(shape: Attributes, location_name: "ComputerAttributes")) CreateComputerRequest.struct_class = Types::CreateComputerRequest CreateComputerResult.add_member(:computer, Shapes::ShapeRef.new(shape: Computer, location_name: "Computer")) CreateComputerResult.struct_class = Types::CreateComputerResult CreateConditionalForwarderRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) CreateConditionalForwarderRequest.add_member(:remote_domain_name, Shapes::ShapeRef.new(shape: RemoteDomainName, required: true, location_name: "RemoteDomainName")) CreateConditionalForwarderRequest.add_member(:dns_ip_addrs, Shapes::ShapeRef.new(shape: DnsIpAddrs, required: true, location_name: "DnsIpAddrs")) CreateConditionalForwarderRequest.struct_class = Types::CreateConditionalForwarderRequest CreateConditionalForwarderResult.struct_class = Types::CreateConditionalForwarderResult CreateDirectoryRequest.add_member(:name, Shapes::ShapeRef.new(shape: DirectoryName, required: true, location_name: "Name")) CreateDirectoryRequest.add_member(:short_name, Shapes::ShapeRef.new(shape: DirectoryShortName, location_name: "ShortName")) CreateDirectoryRequest.add_member(:password, Shapes::ShapeRef.new(shape: Password, required: true, location_name: "Password")) CreateDirectoryRequest.add_member(:description, Shapes::ShapeRef.new(shape: Description, location_name: "Description")) CreateDirectoryRequest.add_member(:size, Shapes::ShapeRef.new(shape: DirectorySize, required: true, location_name: "Size")) CreateDirectoryRequest.add_member(:vpc_settings, Shapes::ShapeRef.new(shape: DirectoryVpcSettings, location_name: "VpcSettings")) CreateDirectoryRequest.add_member(:tags, Shapes::ShapeRef.new(shape: Tags, location_name: "Tags")) CreateDirectoryRequest.struct_class = Types::CreateDirectoryRequest CreateDirectoryResult.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "DirectoryId")) CreateDirectoryResult.struct_class = Types::CreateDirectoryResult CreateLogSubscriptionRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) CreateLogSubscriptionRequest.add_member(:log_group_name, Shapes::ShapeRef.new(shape: LogGroupName, required: true, location_name: "LogGroupName")) CreateLogSubscriptionRequest.struct_class = Types::CreateLogSubscriptionRequest CreateLogSubscriptionResult.struct_class = Types::CreateLogSubscriptionResult CreateMicrosoftADRequest.add_member(:name, Shapes::ShapeRef.new(shape: DirectoryName, required: true, location_name: "Name")) CreateMicrosoftADRequest.add_member(:short_name, Shapes::ShapeRef.new(shape: DirectoryShortName, location_name: "ShortName")) CreateMicrosoftADRequest.add_member(:password, Shapes::ShapeRef.new(shape: Password, required: true, location_name: "Password")) CreateMicrosoftADRequest.add_member(:description, Shapes::ShapeRef.new(shape: Description, location_name: "Description")) CreateMicrosoftADRequest.add_member(:vpc_settings, Shapes::ShapeRef.new(shape: DirectoryVpcSettings, required: true, location_name: "VpcSettings")) CreateMicrosoftADRequest.add_member(:edition, Shapes::ShapeRef.new(shape: DirectoryEdition, location_name: "Edition")) CreateMicrosoftADRequest.add_member(:tags, Shapes::ShapeRef.new(shape: Tags, location_name: "Tags")) CreateMicrosoftADRequest.struct_class = Types::CreateMicrosoftADRequest CreateMicrosoftADResult.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "DirectoryId")) CreateMicrosoftADResult.struct_class = Types::CreateMicrosoftADResult CreateSnapshotRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) CreateSnapshotRequest.add_member(:name, Shapes::ShapeRef.new(shape: SnapshotName, location_name: "Name")) CreateSnapshotRequest.struct_class = Types::CreateSnapshotRequest CreateSnapshotResult.add_member(:snapshot_id, Shapes::ShapeRef.new(shape: SnapshotId, location_name: "SnapshotId")) CreateSnapshotResult.struct_class = Types::CreateSnapshotResult CreateTrustRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) CreateTrustRequest.add_member(:remote_domain_name, Shapes::ShapeRef.new(shape: RemoteDomainName, required: true, location_name: "RemoteDomainName")) CreateTrustRequest.add_member(:trust_password, Shapes::ShapeRef.new(shape: TrustPassword, required: true, location_name: "TrustPassword")) CreateTrustRequest.add_member(:trust_direction, Shapes::ShapeRef.new(shape: TrustDirection, required: true, location_name: "TrustDirection")) CreateTrustRequest.add_member(:trust_type, Shapes::ShapeRef.new(shape: TrustType, location_name: "TrustType")) CreateTrustRequest.add_member(:conditional_forwarder_ip_addrs, Shapes::ShapeRef.new(shape: DnsIpAddrs, location_name: "ConditionalForwarderIpAddrs")) CreateTrustRequest.add_member(:selective_auth, Shapes::ShapeRef.new(shape: SelectiveAuth, location_name: "SelectiveAuth")) CreateTrustRequest.struct_class = Types::CreateTrustRequest CreateTrustResult.add_member(:trust_id, Shapes::ShapeRef.new(shape: TrustId, location_name: "TrustId")) CreateTrustResult.struct_class = Types::CreateTrustResult DeleteConditionalForwarderRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) DeleteConditionalForwarderRequest.add_member(:remote_domain_name, Shapes::ShapeRef.new(shape: RemoteDomainName, required: true, location_name: "RemoteDomainName")) DeleteConditionalForwarderRequest.struct_class = Types::DeleteConditionalForwarderRequest DeleteConditionalForwarderResult.struct_class = Types::DeleteConditionalForwarderResult DeleteDirectoryRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) DeleteDirectoryRequest.struct_class = Types::DeleteDirectoryRequest DeleteDirectoryResult.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "DirectoryId")) DeleteDirectoryResult.struct_class = Types::DeleteDirectoryResult DeleteLogSubscriptionRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) DeleteLogSubscriptionRequest.struct_class = Types::DeleteLogSubscriptionRequest DeleteLogSubscriptionResult.struct_class = Types::DeleteLogSubscriptionResult DeleteSnapshotRequest.add_member(:snapshot_id, Shapes::ShapeRef.new(shape: SnapshotId, required: true, location_name: "SnapshotId")) DeleteSnapshotRequest.struct_class = Types::DeleteSnapshotRequest DeleteSnapshotResult.add_member(:snapshot_id, Shapes::ShapeRef.new(shape: SnapshotId, location_name: "SnapshotId")) DeleteSnapshotResult.struct_class = Types::DeleteSnapshotResult DeleteTrustRequest.add_member(:trust_id, Shapes::ShapeRef.new(shape: TrustId, required: true, location_name: "TrustId")) DeleteTrustRequest.add_member(:delete_associated_conditional_forwarder, Shapes::ShapeRef.new(shape: DeleteAssociatedConditionalForwarder, location_name: "DeleteAssociatedConditionalForwarder")) DeleteTrustRequest.struct_class = Types::DeleteTrustRequest DeleteTrustResult.add_member(:trust_id, Shapes::ShapeRef.new(shape: TrustId, location_name: "TrustId")) DeleteTrustResult.struct_class = Types::DeleteTrustResult DeregisterEventTopicRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) DeregisterEventTopicRequest.add_member(:topic_name, Shapes::ShapeRef.new(shape: TopicName, required: true, location_name: "TopicName")) DeregisterEventTopicRequest.struct_class = Types::DeregisterEventTopicRequest DeregisterEventTopicResult.struct_class = Types::DeregisterEventTopicResult DescribeConditionalForwardersRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) DescribeConditionalForwardersRequest.add_member(:remote_domain_names, Shapes::ShapeRef.new(shape: RemoteDomainNames, location_name: "RemoteDomainNames")) DescribeConditionalForwardersRequest.struct_class = Types::DescribeConditionalForwardersRequest DescribeConditionalForwardersResult.add_member(:conditional_forwarders, Shapes::ShapeRef.new(shape: ConditionalForwarders, location_name: "ConditionalForwarders")) DescribeConditionalForwardersResult.struct_class = Types::DescribeConditionalForwardersResult DescribeDirectoriesRequest.add_member(:directory_ids, Shapes::ShapeRef.new(shape: DirectoryIds, location_name: "DirectoryIds")) DescribeDirectoriesRequest.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken")) DescribeDirectoriesRequest.add_member(:limit, Shapes::ShapeRef.new(shape: Limit, location_name: "Limit")) DescribeDirectoriesRequest.struct_class = Types::DescribeDirectoriesRequest DescribeDirectoriesResult.add_member(:directory_descriptions, Shapes::ShapeRef.new(shape: DirectoryDescriptions, location_name: "DirectoryDescriptions")) DescribeDirectoriesResult.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken")) DescribeDirectoriesResult.struct_class = Types::DescribeDirectoriesResult DescribeDomainControllersRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) DescribeDomainControllersRequest.add_member(:domain_controller_ids, Shapes::ShapeRef.new(shape: DomainControllerIds, location_name: "DomainControllerIds")) DescribeDomainControllersRequest.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken")) DescribeDomainControllersRequest.add_member(:limit, Shapes::ShapeRef.new(shape: Limit, location_name: "Limit")) DescribeDomainControllersRequest.struct_class = Types::DescribeDomainControllersRequest DescribeDomainControllersResult.add_member(:domain_controllers, Shapes::ShapeRef.new(shape: DomainControllers, location_name: "DomainControllers")) DescribeDomainControllersResult.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken")) DescribeDomainControllersResult.struct_class = Types::DescribeDomainControllersResult DescribeEventTopicsRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "DirectoryId")) DescribeEventTopicsRequest.add_member(:topic_names, Shapes::ShapeRef.new(shape: TopicNames, location_name: "TopicNames")) DescribeEventTopicsRequest.struct_class = Types::DescribeEventTopicsRequest DescribeEventTopicsResult.add_member(:event_topics, Shapes::ShapeRef.new(shape: EventTopics, location_name: "EventTopics")) DescribeEventTopicsResult.struct_class = Types::DescribeEventTopicsResult DescribeSharedDirectoriesRequest.add_member(:owner_directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "OwnerDirectoryId")) DescribeSharedDirectoriesRequest.add_member(:shared_directory_ids, Shapes::ShapeRef.new(shape: DirectoryIds, location_name: "SharedDirectoryIds")) DescribeSharedDirectoriesRequest.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken")) DescribeSharedDirectoriesRequest.add_member(:limit, Shapes::ShapeRef.new(shape: Limit, location_name: "Limit")) DescribeSharedDirectoriesRequest.struct_class = Types::DescribeSharedDirectoriesRequest DescribeSharedDirectoriesResult.add_member(:shared_directories, Shapes::ShapeRef.new(shape: SharedDirectories, location_name: "SharedDirectories")) DescribeSharedDirectoriesResult.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken")) DescribeSharedDirectoriesResult.struct_class = Types::DescribeSharedDirectoriesResult DescribeSnapshotsRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "DirectoryId")) DescribeSnapshotsRequest.add_member(:snapshot_ids, Shapes::ShapeRef.new(shape: SnapshotIds, location_name: "SnapshotIds")) DescribeSnapshotsRequest.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken")) DescribeSnapshotsRequest.add_member(:limit, Shapes::ShapeRef.new(shape: Limit, location_name: "Limit")) DescribeSnapshotsRequest.struct_class = Types::DescribeSnapshotsRequest DescribeSnapshotsResult.add_member(:snapshots, Shapes::ShapeRef.new(shape: Snapshots, location_name: "Snapshots")) DescribeSnapshotsResult.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken")) DescribeSnapshotsResult.struct_class = Types::DescribeSnapshotsResult DescribeTrustsRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "DirectoryId")) DescribeTrustsRequest.add_member(:trust_ids, Shapes::ShapeRef.new(shape: TrustIds, location_name: "TrustIds")) DescribeTrustsRequest.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken")) DescribeTrustsRequest.add_member(:limit, Shapes::ShapeRef.new(shape: Limit, location_name: "Limit")) DescribeTrustsRequest.struct_class = Types::DescribeTrustsRequest DescribeTrustsResult.add_member(:trusts, Shapes::ShapeRef.new(shape: Trusts, location_name: "Trusts")) DescribeTrustsResult.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken")) DescribeTrustsResult.struct_class = Types::DescribeTrustsResult DirectoryConnectSettings.add_member(:vpc_id, Shapes::ShapeRef.new(shape: VpcId, required: true, location_name: "VpcId")) DirectoryConnectSettings.add_member(:subnet_ids, Shapes::ShapeRef.new(shape: SubnetIds, required: true, location_name: "SubnetIds")) DirectoryConnectSettings.add_member(:customer_dns_ips, Shapes::ShapeRef.new(shape: DnsIpAddrs, required: true, location_name: "CustomerDnsIps")) DirectoryConnectSettings.add_member(:customer_user_name, Shapes::ShapeRef.new(shape: UserName, required: true, location_name: "CustomerUserName")) DirectoryConnectSettings.struct_class = Types::DirectoryConnectSettings DirectoryConnectSettingsDescription.add_member(:vpc_id, Shapes::ShapeRef.new(shape: VpcId, location_name: "VpcId")) DirectoryConnectSettingsDescription.add_member(:subnet_ids, Shapes::ShapeRef.new(shape: SubnetIds, location_name: "SubnetIds")) DirectoryConnectSettingsDescription.add_member(:customer_user_name, Shapes::ShapeRef.new(shape: UserName, location_name: "CustomerUserName")) DirectoryConnectSettingsDescription.add_member(:security_group_id, Shapes::ShapeRef.new(shape: SecurityGroupId, location_name: "SecurityGroupId")) DirectoryConnectSettingsDescription.add_member(:availability_zones, Shapes::ShapeRef.new(shape: AvailabilityZones, location_name: "AvailabilityZones")) DirectoryConnectSettingsDescription.add_member(:connect_ips, Shapes::ShapeRef.new(shape: IpAddrs, location_name: "ConnectIps")) DirectoryConnectSettingsDescription.struct_class = Types::DirectoryConnectSettingsDescription DirectoryDescription.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "DirectoryId")) DirectoryDescription.add_member(:name, Shapes::ShapeRef.new(shape: DirectoryName, location_name: "Name")) DirectoryDescription.add_member(:short_name, Shapes::ShapeRef.new(shape: DirectoryShortName, location_name: "ShortName")) DirectoryDescription.add_member(:size, Shapes::ShapeRef.new(shape: DirectorySize, location_name: "Size")) DirectoryDescription.add_member(:edition, Shapes::ShapeRef.new(shape: DirectoryEdition, location_name: "Edition")) DirectoryDescription.add_member(:alias, Shapes::ShapeRef.new(shape: AliasName, location_name: "Alias")) DirectoryDescription.add_member(:access_url, Shapes::ShapeRef.new(shape: AccessUrl, location_name: "AccessUrl")) DirectoryDescription.add_member(:description, Shapes::ShapeRef.new(shape: Description, location_name: "Description")) DirectoryDescription.add_member(:dns_ip_addrs, Shapes::ShapeRef.new(shape: DnsIpAddrs, location_name: "DnsIpAddrs")) DirectoryDescription.add_member(:stage, Shapes::ShapeRef.new(shape: DirectoryStage, location_name: "Stage")) DirectoryDescription.add_member(:share_status, Shapes::ShapeRef.new(shape: ShareStatus, location_name: "ShareStatus")) DirectoryDescription.add_member(:share_method, Shapes::ShapeRef.new(shape: ShareMethod, location_name: "ShareMethod")) DirectoryDescription.add_member(:share_notes, Shapes::ShapeRef.new(shape: Notes, location_name: "ShareNotes")) DirectoryDescription.add_member(:launch_time, Shapes::ShapeRef.new(shape: LaunchTime, location_name: "LaunchTime")) DirectoryDescription.add_member(:stage_last_updated_date_time, Shapes::ShapeRef.new(shape: LastUpdatedDateTime, location_name: "StageLastUpdatedDateTime")) DirectoryDescription.add_member(:type, Shapes::ShapeRef.new(shape: DirectoryType, location_name: "Type")) DirectoryDescription.add_member(:vpc_settings, Shapes::ShapeRef.new(shape: DirectoryVpcSettingsDescription, location_name: "VpcSettings")) DirectoryDescription.add_member(:connect_settings, Shapes::ShapeRef.new(shape: DirectoryConnectSettingsDescription, location_name: "ConnectSettings")) DirectoryDescription.add_member(:radius_settings, Shapes::ShapeRef.new(shape: RadiusSettings, location_name: "RadiusSettings")) DirectoryDescription.add_member(:radius_status, Shapes::ShapeRef.new(shape: RadiusStatus, location_name: "RadiusStatus")) DirectoryDescription.add_member(:stage_reason, Shapes::ShapeRef.new(shape: StageReason, location_name: "StageReason")) DirectoryDescription.add_member(:sso_enabled, Shapes::ShapeRef.new(shape: SsoEnabled, location_name: "SsoEnabled")) DirectoryDescription.add_member(:desired_number_of_domain_controllers, Shapes::ShapeRef.new(shape: DesiredNumberOfDomainControllers, location_name: "DesiredNumberOfDomainControllers")) DirectoryDescription.add_member(:owner_directory_description, Shapes::ShapeRef.new(shape: OwnerDirectoryDescription, location_name: "OwnerDirectoryDescription")) DirectoryDescription.struct_class = Types::DirectoryDescription DirectoryDescriptions.member = Shapes::ShapeRef.new(shape: DirectoryDescription) DirectoryIds.member = Shapes::ShapeRef.new(shape: DirectoryId) DirectoryLimits.add_member(:cloud_only_directories_limit, Shapes::ShapeRef.new(shape: Limit, location_name: "CloudOnlyDirectoriesLimit")) DirectoryLimits.add_member(:cloud_only_directories_current_count, Shapes::ShapeRef.new(shape: Limit, location_name: "CloudOnlyDirectoriesCurrentCount")) DirectoryLimits.add_member(:cloud_only_directories_limit_reached, Shapes::ShapeRef.new(shape: CloudOnlyDirectoriesLimitReached, location_name: "CloudOnlyDirectoriesLimitReached")) DirectoryLimits.add_member(:cloud_only_microsoft_ad_limit, Shapes::ShapeRef.new(shape: Limit, location_name: "CloudOnlyMicrosoftADLimit")) DirectoryLimits.add_member(:cloud_only_microsoft_ad_current_count, Shapes::ShapeRef.new(shape: Limit, location_name: "CloudOnlyMicrosoftADCurrentCount")) DirectoryLimits.add_member(:cloud_only_microsoft_ad_limit_reached, Shapes::ShapeRef.new(shape: CloudOnlyDirectoriesLimitReached, location_name: "CloudOnlyMicrosoftADLimitReached")) DirectoryLimits.add_member(:connected_directories_limit, Shapes::ShapeRef.new(shape: Limit, location_name: "ConnectedDirectoriesLimit")) DirectoryLimits.add_member(:connected_directories_current_count, Shapes::ShapeRef.new(shape: Limit, location_name: "ConnectedDirectoriesCurrentCount")) DirectoryLimits.add_member(:connected_directories_limit_reached, Shapes::ShapeRef.new(shape: ConnectedDirectoriesLimitReached, location_name: "ConnectedDirectoriesLimitReached")) DirectoryLimits.struct_class = Types::DirectoryLimits DirectoryVpcSettings.add_member(:vpc_id, Shapes::ShapeRef.new(shape: VpcId, required: true, location_name: "VpcId")) DirectoryVpcSettings.add_member(:subnet_ids, Shapes::ShapeRef.new(shape: SubnetIds, required: true, location_name: "SubnetIds")) DirectoryVpcSettings.struct_class = Types::DirectoryVpcSettings DirectoryVpcSettingsDescription.add_member(:vpc_id, Shapes::ShapeRef.new(shape: VpcId, location_name: "VpcId")) DirectoryVpcSettingsDescription.add_member(:subnet_ids, Shapes::ShapeRef.new(shape: SubnetIds, location_name: "SubnetIds")) DirectoryVpcSettingsDescription.add_member(:security_group_id, Shapes::ShapeRef.new(shape: SecurityGroupId, location_name: "SecurityGroupId")) DirectoryVpcSettingsDescription.add_member(:availability_zones, Shapes::ShapeRef.new(shape: AvailabilityZones, location_name: "AvailabilityZones")) DirectoryVpcSettingsDescription.struct_class = Types::DirectoryVpcSettingsDescription DisableRadiusRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) DisableRadiusRequest.struct_class = Types::DisableRadiusRequest DisableRadiusResult.struct_class = Types::DisableRadiusResult DisableSsoRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) DisableSsoRequest.add_member(:user_name, Shapes::ShapeRef.new(shape: UserName, location_name: "UserName")) DisableSsoRequest.add_member(:password, Shapes::ShapeRef.new(shape: ConnectPassword, location_name: "Password")) DisableSsoRequest.struct_class = Types::DisableSsoRequest DisableSsoResult.struct_class = Types::DisableSsoResult DnsIpAddrs.member = Shapes::ShapeRef.new(shape: IpAddr) DomainController.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "DirectoryId")) DomainController.add_member(:domain_controller_id, Shapes::ShapeRef.new(shape: DomainControllerId, location_name: "DomainControllerId")) DomainController.add_member(:dns_ip_addr, Shapes::ShapeRef.new(shape: IpAddr, location_name: "DnsIpAddr")) DomainController.add_member(:vpc_id, Shapes::ShapeRef.new(shape: VpcId, location_name: "VpcId")) DomainController.add_member(:subnet_id, Shapes::ShapeRef.new(shape: SubnetId, location_name: "SubnetId")) DomainController.add_member(:availability_zone, Shapes::ShapeRef.new(shape: AvailabilityZone, location_name: "AvailabilityZone")) DomainController.add_member(:status, Shapes::ShapeRef.new(shape: DomainControllerStatus, location_name: "Status")) DomainController.add_member(:status_reason, Shapes::ShapeRef.new(shape: DomainControllerStatusReason, location_name: "StatusReason")) DomainController.add_member(:launch_time, Shapes::ShapeRef.new(shape: LaunchTime, location_name: "LaunchTime")) DomainController.add_member(:status_last_updated_date_time, Shapes::ShapeRef.new(shape: LastUpdatedDateTime, location_name: "StatusLastUpdatedDateTime")) DomainController.struct_class = Types::DomainController DomainControllerIds.member = Shapes::ShapeRef.new(shape: DomainControllerId) DomainControllers.member = Shapes::ShapeRef.new(shape: DomainController) EnableRadiusRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) EnableRadiusRequest.add_member(:radius_settings, Shapes::ShapeRef.new(shape: RadiusSettings, required: true, location_name: "RadiusSettings")) EnableRadiusRequest.struct_class = Types::EnableRadiusRequest EnableRadiusResult.struct_class = Types::EnableRadiusResult EnableSsoRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) EnableSsoRequest.add_member(:user_name, Shapes::ShapeRef.new(shape: UserName, location_name: "UserName")) EnableSsoRequest.add_member(:password, Shapes::ShapeRef.new(shape: ConnectPassword, location_name: "Password")) EnableSsoRequest.struct_class = Types::EnableSsoRequest EnableSsoResult.struct_class = Types::EnableSsoResult EventTopic.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "DirectoryId")) EventTopic.add_member(:topic_name, Shapes::ShapeRef.new(shape: TopicName, location_name: "TopicName")) EventTopic.add_member(:topic_arn, Shapes::ShapeRef.new(shape: TopicArn, location_name: "TopicArn")) EventTopic.add_member(:created_date_time, Shapes::ShapeRef.new(shape: CreatedDateTime, location_name: "CreatedDateTime")) EventTopic.add_member(:status, Shapes::ShapeRef.new(shape: TopicStatus, location_name: "Status")) EventTopic.struct_class = Types::EventTopic EventTopics.member = Shapes::ShapeRef.new(shape: EventTopic) GetDirectoryLimitsRequest.struct_class = Types::GetDirectoryLimitsRequest GetDirectoryLimitsResult.add_member(:directory_limits, Shapes::ShapeRef.new(shape: DirectoryLimits, location_name: "DirectoryLimits")) GetDirectoryLimitsResult.struct_class = Types::GetDirectoryLimitsResult GetSnapshotLimitsRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) GetSnapshotLimitsRequest.struct_class = Types::GetSnapshotLimitsRequest GetSnapshotLimitsResult.add_member(:snapshot_limits, Shapes::ShapeRef.new(shape: SnapshotLimits, location_name: "SnapshotLimits")) GetSnapshotLimitsResult.struct_class = Types::GetSnapshotLimitsResult IpAddrs.member = Shapes::ShapeRef.new(shape: IpAddr) IpRoute.add_member(:cidr_ip, Shapes::ShapeRef.new(shape: CidrIp, location_name: "CidrIp")) IpRoute.add_member(:description, Shapes::ShapeRef.new(shape: Description, location_name: "Description")) IpRoute.struct_class = Types::IpRoute IpRouteInfo.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "DirectoryId")) IpRouteInfo.add_member(:cidr_ip, Shapes::ShapeRef.new(shape: CidrIp, location_name: "CidrIp")) IpRouteInfo.add_member(:ip_route_status_msg, Shapes::ShapeRef.new(shape: IpRouteStatusMsg, location_name: "IpRouteStatusMsg")) IpRouteInfo.add_member(:added_date_time, Shapes::ShapeRef.new(shape: AddedDateTime, location_name: "AddedDateTime")) IpRouteInfo.add_member(:ip_route_status_reason, Shapes::ShapeRef.new(shape: IpRouteStatusReason, location_name: "IpRouteStatusReason")) IpRouteInfo.add_member(:description, Shapes::ShapeRef.new(shape: Description, location_name: "Description")) IpRouteInfo.struct_class = Types::IpRouteInfo IpRoutes.member = Shapes::ShapeRef.new(shape: IpRoute) IpRoutesInfo.member = Shapes::ShapeRef.new(shape: IpRouteInfo) ListIpRoutesRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) ListIpRoutesRequest.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken")) ListIpRoutesRequest.add_member(:limit, Shapes::ShapeRef.new(shape: Limit, location_name: "Limit")) ListIpRoutesRequest.struct_class = Types::ListIpRoutesRequest ListIpRoutesResult.add_member(:ip_routes_info, Shapes::ShapeRef.new(shape: IpRoutesInfo, location_name: "IpRoutesInfo")) ListIpRoutesResult.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken")) ListIpRoutesResult.struct_class = Types::ListIpRoutesResult ListLogSubscriptionsRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "DirectoryId")) ListLogSubscriptionsRequest.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken")) ListLogSubscriptionsRequest.add_member(:limit, Shapes::ShapeRef.new(shape: Limit, location_name: "Limit")) ListLogSubscriptionsRequest.struct_class = Types::ListLogSubscriptionsRequest ListLogSubscriptionsResult.add_member(:log_subscriptions, Shapes::ShapeRef.new(shape: LogSubscriptions, location_name: "LogSubscriptions")) ListLogSubscriptionsResult.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken")) ListLogSubscriptionsResult.struct_class = Types::ListLogSubscriptionsResult ListSchemaExtensionsRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) ListSchemaExtensionsRequest.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken")) ListSchemaExtensionsRequest.add_member(:limit, Shapes::ShapeRef.new(shape: Limit, location_name: "Limit")) ListSchemaExtensionsRequest.struct_class = Types::ListSchemaExtensionsRequest ListSchemaExtensionsResult.add_member(:schema_extensions_info, Shapes::ShapeRef.new(shape: SchemaExtensionsInfo, location_name: "SchemaExtensionsInfo")) ListSchemaExtensionsResult.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken")) ListSchemaExtensionsResult.struct_class = Types::ListSchemaExtensionsResult ListTagsForResourceRequest.add_member(:resource_id, Shapes::ShapeRef.new(shape: ResourceId, required: true, location_name: "ResourceId")) ListTagsForResourceRequest.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken")) ListTagsForResourceRequest.add_member(:limit, Shapes::ShapeRef.new(shape: Limit, location_name: "Limit")) ListTagsForResourceRequest.struct_class = Types::ListTagsForResourceRequest ListTagsForResourceResult.add_member(:tags, Shapes::ShapeRef.new(shape: Tags, location_name: "Tags")) ListTagsForResourceResult.add_member(:next_token, Shapes::ShapeRef.new(shape: NextToken, location_name: "NextToken")) ListTagsForResourceResult.struct_class = Types::ListTagsForResourceResult LogSubscription.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "DirectoryId")) LogSubscription.add_member(:log_group_name, Shapes::ShapeRef.new(shape: LogGroupName, location_name: "LogGroupName")) LogSubscription.add_member(:subscription_created_date_time, Shapes::ShapeRef.new(shape: SubscriptionCreatedDateTime, location_name: "SubscriptionCreatedDateTime")) LogSubscription.struct_class = Types::LogSubscription LogSubscriptions.member = Shapes::ShapeRef.new(shape: LogSubscription) OwnerDirectoryDescription.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "DirectoryId")) OwnerDirectoryDescription.add_member(:account_id, Shapes::ShapeRef.new(shape: CustomerId, location_name: "AccountId")) OwnerDirectoryDescription.add_member(:dns_ip_addrs, Shapes::ShapeRef.new(shape: DnsIpAddrs, location_name: "DnsIpAddrs")) OwnerDirectoryDescription.add_member(:vpc_settings, Shapes::ShapeRef.new(shape: DirectoryVpcSettingsDescription, location_name: "VpcSettings")) OwnerDirectoryDescription.add_member(:radius_settings, Shapes::ShapeRef.new(shape: RadiusSettings, location_name: "RadiusSettings")) OwnerDirectoryDescription.add_member(:radius_status, Shapes::ShapeRef.new(shape: RadiusStatus, location_name: "RadiusStatus")) OwnerDirectoryDescription.struct_class = Types::OwnerDirectoryDescription RadiusSettings.add_member(:radius_servers, Shapes::ShapeRef.new(shape: Servers, location_name: "RadiusServers")) RadiusSettings.add_member(:radius_port, Shapes::ShapeRef.new(shape: PortNumber, location_name: "RadiusPort")) RadiusSettings.add_member(:radius_timeout, Shapes::ShapeRef.new(shape: RadiusTimeout, location_name: "RadiusTimeout")) RadiusSettings.add_member(:radius_retries, Shapes::ShapeRef.new(shape: RadiusRetries, location_name: "RadiusRetries")) RadiusSettings.add_member(:shared_secret, Shapes::ShapeRef.new(shape: RadiusSharedSecret, location_name: "SharedSecret")) RadiusSettings.add_member(:authentication_protocol, Shapes::ShapeRef.new(shape: RadiusAuthenticationProtocol, location_name: "AuthenticationProtocol")) RadiusSettings.add_member(:display_label, Shapes::ShapeRef.new(shape: RadiusDisplayLabel, location_name: "DisplayLabel")) RadiusSettings.add_member(:use_same_username, Shapes::ShapeRef.new(shape: UseSameUsername, location_name: "UseSameUsername")) RadiusSettings.struct_class = Types::RadiusSettings RegisterEventTopicRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) RegisterEventTopicRequest.add_member(:topic_name, Shapes::ShapeRef.new(shape: TopicName, required: true, location_name: "TopicName")) RegisterEventTopicRequest.struct_class = Types::RegisterEventTopicRequest RegisterEventTopicResult.struct_class = Types::RegisterEventTopicResult RejectSharedDirectoryRequest.add_member(:shared_directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "SharedDirectoryId")) RejectSharedDirectoryRequest.struct_class = Types::RejectSharedDirectoryRequest RejectSharedDirectoryResult.add_member(:shared_directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "SharedDirectoryId")) RejectSharedDirectoryResult.struct_class = Types::RejectSharedDirectoryResult RemoteDomainNames.member = Shapes::ShapeRef.new(shape: RemoteDomainName) RemoveIpRoutesRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) RemoveIpRoutesRequest.add_member(:cidr_ips, Shapes::ShapeRef.new(shape: CidrIps, required: true, location_name: "CidrIps")) RemoveIpRoutesRequest.struct_class = Types::RemoveIpRoutesRequest RemoveIpRoutesResult.struct_class = Types::RemoveIpRoutesResult RemoveTagsFromResourceRequest.add_member(:resource_id, Shapes::ShapeRef.new(shape: ResourceId, required: true, location_name: "ResourceId")) RemoveTagsFromResourceRequest.add_member(:tag_keys, Shapes::ShapeRef.new(shape: TagKeys, required: true, location_name: "TagKeys")) RemoveTagsFromResourceRequest.struct_class = Types::RemoveTagsFromResourceRequest RemoveTagsFromResourceResult.struct_class = Types::RemoveTagsFromResourceResult ResetUserPasswordRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) ResetUserPasswordRequest.add_member(:user_name, Shapes::ShapeRef.new(shape: CustomerUserName, required: true, location_name: "UserName")) ResetUserPasswordRequest.add_member(:new_password, Shapes::ShapeRef.new(shape: UserPassword, required: true, location_name: "NewPassword")) ResetUserPasswordRequest.struct_class = Types::ResetUserPasswordRequest ResetUserPasswordResult.struct_class = Types::ResetUserPasswordResult RestoreFromSnapshotRequest.add_member(:snapshot_id, Shapes::ShapeRef.new(shape: SnapshotId, required: true, location_name: "SnapshotId")) RestoreFromSnapshotRequest.struct_class = Types::RestoreFromSnapshotRequest RestoreFromSnapshotResult.struct_class = Types::RestoreFromSnapshotResult SchemaExtensionInfo.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "DirectoryId")) SchemaExtensionInfo.add_member(:schema_extension_id, Shapes::ShapeRef.new(shape: SchemaExtensionId, location_name: "SchemaExtensionId")) SchemaExtensionInfo.add_member(:description, Shapes::ShapeRef.new(shape: Description, location_name: "Description")) SchemaExtensionInfo.add_member(:schema_extension_status, Shapes::ShapeRef.new(shape: SchemaExtensionStatus, location_name: "SchemaExtensionStatus")) SchemaExtensionInfo.add_member(:schema_extension_status_reason, Shapes::ShapeRef.new(shape: SchemaExtensionStatusReason, location_name: "SchemaExtensionStatusReason")) SchemaExtensionInfo.add_member(:start_date_time, Shapes::ShapeRef.new(shape: StartDateTime, location_name: "StartDateTime")) SchemaExtensionInfo.add_member(:end_date_time, Shapes::ShapeRef.new(shape: EndDateTime, location_name: "EndDateTime")) SchemaExtensionInfo.struct_class = Types::SchemaExtensionInfo SchemaExtensionsInfo.member = Shapes::ShapeRef.new(shape: SchemaExtensionInfo) Servers.member = Shapes::ShapeRef.new(shape: Server) ShareDirectoryRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) ShareDirectoryRequest.add_member(:share_notes, Shapes::ShapeRef.new(shape: Notes, location_name: "ShareNotes")) ShareDirectoryRequest.add_member(:share_target, Shapes::ShapeRef.new(shape: ShareTarget, required: true, location_name: "ShareTarget")) ShareDirectoryRequest.add_member(:share_method, Shapes::ShapeRef.new(shape: ShareMethod, required: true, location_name: "ShareMethod")) ShareDirectoryRequest.struct_class = Types::ShareDirectoryRequest ShareDirectoryResult.add_member(:shared_directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "SharedDirectoryId")) ShareDirectoryResult.struct_class = Types::ShareDirectoryResult ShareTarget.add_member(:id, Shapes::ShapeRef.new(shape: TargetId, required: true, location_name: "Id")) ShareTarget.add_member(:type, Shapes::ShapeRef.new(shape: TargetType, required: true, location_name: "Type")) ShareTarget.struct_class = Types::ShareTarget SharedDirectories.member = Shapes::ShapeRef.new(shape: SharedDirectory) SharedDirectory.add_member(:owner_account_id, Shapes::ShapeRef.new(shape: CustomerId, location_name: "OwnerAccountId")) SharedDirectory.add_member(:owner_directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "OwnerDirectoryId")) SharedDirectory.add_member(:share_method, Shapes::ShapeRef.new(shape: ShareMethod, location_name: "ShareMethod")) SharedDirectory.add_member(:shared_account_id, Shapes::ShapeRef.new(shape: CustomerId, location_name: "SharedAccountId")) SharedDirectory.add_member(:shared_directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "SharedDirectoryId")) SharedDirectory.add_member(:share_status, Shapes::ShapeRef.new(shape: ShareStatus, location_name: "ShareStatus")) SharedDirectory.add_member(:share_notes, Shapes::ShapeRef.new(shape: Notes, location_name: "ShareNotes")) SharedDirectory.add_member(:created_date_time, Shapes::ShapeRef.new(shape: CreatedDateTime, location_name: "CreatedDateTime")) SharedDirectory.add_member(:last_updated_date_time, Shapes::ShapeRef.new(shape: LastUpdatedDateTime, location_name: "LastUpdatedDateTime")) SharedDirectory.struct_class = Types::SharedDirectory Snapshot.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "DirectoryId")) Snapshot.add_member(:snapshot_id, Shapes::ShapeRef.new(shape: SnapshotId, location_name: "SnapshotId")) Snapshot.add_member(:type, Shapes::ShapeRef.new(shape: SnapshotType, location_name: "Type")) Snapshot.add_member(:name, Shapes::ShapeRef.new(shape: SnapshotName, location_name: "Name")) Snapshot.add_member(:status, Shapes::ShapeRef.new(shape: SnapshotStatus, location_name: "Status")) Snapshot.add_member(:start_time, Shapes::ShapeRef.new(shape: StartTime, location_name: "StartTime")) Snapshot.struct_class = Types::Snapshot SnapshotIds.member = Shapes::ShapeRef.new(shape: SnapshotId) SnapshotLimits.add_member(:manual_snapshots_limit, Shapes::ShapeRef.new(shape: Limit, location_name: "ManualSnapshotsLimit")) SnapshotLimits.add_member(:manual_snapshots_current_count, Shapes::ShapeRef.new(shape: Limit, location_name: "ManualSnapshotsCurrentCount")) SnapshotLimits.add_member(:manual_snapshots_limit_reached, Shapes::ShapeRef.new(shape: ManualSnapshotsLimitReached, location_name: "ManualSnapshotsLimitReached")) SnapshotLimits.struct_class = Types::SnapshotLimits Snapshots.member = Shapes::ShapeRef.new(shape: Snapshot) StartSchemaExtensionRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) StartSchemaExtensionRequest.add_member(:create_snapshot_before_schema_extension, Shapes::ShapeRef.new(shape: CreateSnapshotBeforeSchemaExtension, required: true, location_name: "CreateSnapshotBeforeSchemaExtension")) StartSchemaExtensionRequest.add_member(:ldif_content, Shapes::ShapeRef.new(shape: LdifContent, required: true, location_name: "LdifContent")) StartSchemaExtensionRequest.add_member(:description, Shapes::ShapeRef.new(shape: Description, required: true, location_name: "Description")) StartSchemaExtensionRequest.struct_class = Types::StartSchemaExtensionRequest StartSchemaExtensionResult.add_member(:schema_extension_id, Shapes::ShapeRef.new(shape: SchemaExtensionId, location_name: "SchemaExtensionId")) StartSchemaExtensionResult.struct_class = Types::StartSchemaExtensionResult SubnetIds.member = Shapes::ShapeRef.new(shape: SubnetId) Tag.add_member(:key, Shapes::ShapeRef.new(shape: TagKey, required: true, location_name: "Key")) Tag.add_member(:value, Shapes::ShapeRef.new(shape: TagValue, required: true, location_name: "Value")) Tag.struct_class = Types::Tag TagKeys.member = Shapes::ShapeRef.new(shape: TagKey) Tags.member = Shapes::ShapeRef.new(shape: Tag) TopicNames.member = Shapes::ShapeRef.new(shape: TopicName) Trust.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "DirectoryId")) Trust.add_member(:trust_id, Shapes::ShapeRef.new(shape: TrustId, location_name: "TrustId")) Trust.add_member(:remote_domain_name, Shapes::ShapeRef.new(shape: RemoteDomainName, location_name: "RemoteDomainName")) Trust.add_member(:trust_type, Shapes::ShapeRef.new(shape: TrustType, location_name: "TrustType")) Trust.add_member(:trust_direction, Shapes::ShapeRef.new(shape: TrustDirection, location_name: "TrustDirection")) Trust.add_member(:trust_state, Shapes::ShapeRef.new(shape: TrustState, location_name: "TrustState")) Trust.add_member(:created_date_time, Shapes::ShapeRef.new(shape: CreatedDateTime, location_name: "CreatedDateTime")) Trust.add_member(:last_updated_date_time, Shapes::ShapeRef.new(shape: LastUpdatedDateTime, location_name: "LastUpdatedDateTime")) Trust.add_member(:state_last_updated_date_time, Shapes::ShapeRef.new(shape: StateLastUpdatedDateTime, location_name: "StateLastUpdatedDateTime")) Trust.add_member(:trust_state_reason, Shapes::ShapeRef.new(shape: TrustStateReason, location_name: "TrustStateReason")) Trust.add_member(:selective_auth, Shapes::ShapeRef.new(shape: SelectiveAuth, location_name: "SelectiveAuth")) Trust.struct_class = Types::Trust TrustIds.member = Shapes::ShapeRef.new(shape: TrustId) Trusts.member = Shapes::ShapeRef.new(shape: Trust) UnshareDirectoryRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) UnshareDirectoryRequest.add_member(:unshare_target, Shapes::ShapeRef.new(shape: UnshareTarget, required: true, location_name: "UnshareTarget")) UnshareDirectoryRequest.struct_class = Types::UnshareDirectoryRequest UnshareDirectoryResult.add_member(:shared_directory_id, Shapes::ShapeRef.new(shape: DirectoryId, location_name: "SharedDirectoryId")) UnshareDirectoryResult.struct_class = Types::UnshareDirectoryResult UnshareTarget.add_member(:id, Shapes::ShapeRef.new(shape: TargetId, required: true, location_name: "Id")) UnshareTarget.add_member(:type, Shapes::ShapeRef.new(shape: TargetType, required: true, location_name: "Type")) UnshareTarget.struct_class = Types::UnshareTarget UpdateConditionalForwarderRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) UpdateConditionalForwarderRequest.add_member(:remote_domain_name, Shapes::ShapeRef.new(shape: RemoteDomainName, required: true, location_name: "RemoteDomainName")) UpdateConditionalForwarderRequest.add_member(:dns_ip_addrs, Shapes::ShapeRef.new(shape: DnsIpAddrs, required: true, location_name: "DnsIpAddrs")) UpdateConditionalForwarderRequest.struct_class = Types::UpdateConditionalForwarderRequest UpdateConditionalForwarderResult.struct_class = Types::UpdateConditionalForwarderResult UpdateNumberOfDomainControllersRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) UpdateNumberOfDomainControllersRequest.add_member(:desired_number, Shapes::ShapeRef.new(shape: DesiredNumberOfDomainControllers, required: true, location_name: "DesiredNumber")) UpdateNumberOfDomainControllersRequest.struct_class = Types::UpdateNumberOfDomainControllersRequest UpdateNumberOfDomainControllersResult.struct_class = Types::UpdateNumberOfDomainControllersResult UpdateRadiusRequest.add_member(:directory_id, Shapes::ShapeRef.new(shape: DirectoryId, required: true, location_name: "DirectoryId")) UpdateRadiusRequest.add_member(:radius_settings, Shapes::ShapeRef.new(shape: RadiusSettings, required: true, location_name: "RadiusSettings")) UpdateRadiusRequest.struct_class = Types::UpdateRadiusRequest UpdateRadiusResult.struct_class = Types::UpdateRadiusResult UpdateTrustRequest.add_member(:trust_id, Shapes::ShapeRef.new(shape: TrustId, required: true, location_name: "TrustId")) UpdateTrustRequest.add_member(:selective_auth, Shapes::ShapeRef.new(shape: SelectiveAuth, location_name: "SelectiveAuth")) UpdateTrustRequest.struct_class = Types::UpdateTrustRequest UpdateTrustResult.add_member(:request_id, Shapes::ShapeRef.new(shape: RequestId, location_name: "RequestId")) UpdateTrustResult.add_member(:trust_id, Shapes::ShapeRef.new(shape: TrustId, location_name: "TrustId")) UpdateTrustResult.struct_class = Types::UpdateTrustResult VerifyTrustRequest.add_member(:trust_id, Shapes::ShapeRef.new(shape: TrustId, required: true, location_name: "TrustId")) VerifyTrustRequest.struct_class = Types::VerifyTrustRequest VerifyTrustResult.add_member(:trust_id, Shapes::ShapeRef.new(shape: TrustId, location_name: "TrustId")) VerifyTrustResult.struct_class = Types::VerifyTrustResult # @api private API = Seahorse::Model::Api.new.tap do |api| api.version = "2015-04-16" api.metadata = { "apiVersion" => "2015-04-16", "endpointPrefix" => "ds", "jsonVersion" => "1.1", "protocol" => "json", "serviceAbbreviation" => "Directory Service", "serviceFullName" => "AWS Directory Service", "serviceId" => "Directory Service", "signatureVersion" => "v4", "targetPrefix" => "DirectoryService_20150416", "uid" => "ds-2015-04-16", } api.add_operation(:accept_shared_directory, Seahorse::Model::Operation.new.tap do |o| o.name = "AcceptSharedDirectory" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: AcceptSharedDirectoryRequest) o.output = Shapes::ShapeRef.new(shape: AcceptSharedDirectoryResult) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: DirectoryAlreadySharedException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:add_ip_routes, Seahorse::Model::Operation.new.tap do |o| o.name = "AddIpRoutes" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: AddIpRoutesRequest) o.output = Shapes::ShapeRef.new(shape: AddIpRoutesResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: EntityAlreadyExistsException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: DirectoryUnavailableException) o.errors << Shapes::ShapeRef.new(shape: IpRouteLimitExceededException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:add_tags_to_resource, Seahorse::Model::Operation.new.tap do |o| o.name = "AddTagsToResource" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: AddTagsToResourceRequest) o.output = Shapes::ShapeRef.new(shape: AddTagsToResourceResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: TagLimitExceededException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:cancel_schema_extension, Seahorse::Model::Operation.new.tap do |o| o.name = "CancelSchemaExtension" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: CancelSchemaExtensionRequest) o.output = Shapes::ShapeRef.new(shape: CancelSchemaExtensionResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:connect_directory, Seahorse::Model::Operation.new.tap do |o| o.name = "ConnectDirectory" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: ConnectDirectoryRequest) o.output = Shapes::ShapeRef.new(shape: ConnectDirectoryResult) o.errors << Shapes::ShapeRef.new(shape: DirectoryLimitExceededException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:create_alias, Seahorse::Model::Operation.new.tap do |o| o.name = "CreateAlias" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: CreateAliasRequest) o.output = Shapes::ShapeRef.new(shape: CreateAliasResult) o.errors << Shapes::ShapeRef.new(shape: EntityAlreadyExistsException) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:create_computer, Seahorse::Model::Operation.new.tap do |o| o.name = "CreateComputer" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: CreateComputerRequest) o.output = Shapes::ShapeRef.new(shape: CreateComputerResult) o.errors << Shapes::ShapeRef.new(shape: AuthenticationFailedException) o.errors << Shapes::ShapeRef.new(shape: DirectoryUnavailableException) o.errors << Shapes::ShapeRef.new(shape: EntityAlreadyExistsException) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: UnsupportedOperationException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:create_conditional_forwarder, Seahorse::Model::Operation.new.tap do |o| o.name = "CreateConditionalForwarder" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: CreateConditionalForwarderRequest) o.output = Shapes::ShapeRef.new(shape: CreateConditionalForwarderResult) o.errors << Shapes::ShapeRef.new(shape: EntityAlreadyExistsException) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: DirectoryUnavailableException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: UnsupportedOperationException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:create_directory, Seahorse::Model::Operation.new.tap do |o| o.name = "CreateDirectory" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: CreateDirectoryRequest) o.output = Shapes::ShapeRef.new(shape: CreateDirectoryResult) o.errors << Shapes::ShapeRef.new(shape: DirectoryLimitExceededException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:create_log_subscription, Seahorse::Model::Operation.new.tap do |o| o.name = "CreateLogSubscription" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: CreateLogSubscriptionRequest) o.output = Shapes::ShapeRef.new(shape: CreateLogSubscriptionResult) o.errors << Shapes::ShapeRef.new(shape: EntityAlreadyExistsException) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: UnsupportedOperationException) o.errors << Shapes::ShapeRef.new(shape: InsufficientPermissionsException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:create_microsoft_ad, Seahorse::Model::Operation.new.tap do |o| o.name = "CreateMicrosoftAD" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: CreateMicrosoftADRequest) o.output = Shapes::ShapeRef.new(shape: CreateMicrosoftADResult) o.errors << Shapes::ShapeRef.new(shape: DirectoryLimitExceededException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) o.errors << Shapes::ShapeRef.new(shape: UnsupportedOperationException) end) api.add_operation(:create_snapshot, Seahorse::Model::Operation.new.tap do |o| o.name = "CreateSnapshot" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: CreateSnapshotRequest) o.output = Shapes::ShapeRef.new(shape: CreateSnapshotResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: SnapshotLimitExceededException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:create_trust, Seahorse::Model::Operation.new.tap do |o| o.name = "CreateTrust" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: CreateTrustRequest) o.output = Shapes::ShapeRef.new(shape: CreateTrustResult) o.errors << Shapes::ShapeRef.new(shape: EntityAlreadyExistsException) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) o.errors << Shapes::ShapeRef.new(shape: UnsupportedOperationException) end) api.add_operation(:delete_conditional_forwarder, Seahorse::Model::Operation.new.tap do |o| o.name = "DeleteConditionalForwarder" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: DeleteConditionalForwarderRequest) o.output = Shapes::ShapeRef.new(shape: DeleteConditionalForwarderResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: DirectoryUnavailableException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: UnsupportedOperationException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:delete_directory, Seahorse::Model::Operation.new.tap do |o| o.name = "DeleteDirectory" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: DeleteDirectoryRequest) o.output = Shapes::ShapeRef.new(shape: DeleteDirectoryResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:delete_log_subscription, Seahorse::Model::Operation.new.tap do |o| o.name = "DeleteLogSubscription" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: DeleteLogSubscriptionRequest) o.output = Shapes::ShapeRef.new(shape: DeleteLogSubscriptionResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: UnsupportedOperationException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:delete_snapshot, Seahorse::Model::Operation.new.tap do |o| o.name = "DeleteSnapshot" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: DeleteSnapshotRequest) o.output = Shapes::ShapeRef.new(shape: DeleteSnapshotResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:delete_trust, Seahorse::Model::Operation.new.tap do |o| o.name = "DeleteTrust" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: DeleteTrustRequest) o.output = Shapes::ShapeRef.new(shape: DeleteTrustResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) o.errors << Shapes::ShapeRef.new(shape: UnsupportedOperationException) end) api.add_operation(:deregister_event_topic, Seahorse::Model::Operation.new.tap do |o| o.name = "DeregisterEventTopic" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: DeregisterEventTopicRequest) o.output = Shapes::ShapeRef.new(shape: DeregisterEventTopicResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:describe_conditional_forwarders, Seahorse::Model::Operation.new.tap do |o| o.name = "DescribeConditionalForwarders" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: DescribeConditionalForwardersRequest) o.output = Shapes::ShapeRef.new(shape: DescribeConditionalForwardersResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: DirectoryUnavailableException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: UnsupportedOperationException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:describe_directories, Seahorse::Model::Operation.new.tap do |o| o.name = "DescribeDirectories" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: DescribeDirectoriesRequest) o.output = Shapes::ShapeRef.new(shape: DescribeDirectoriesResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: InvalidNextTokenException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:describe_domain_controllers, Seahorse::Model::Operation.new.tap do |o| o.name = "DescribeDomainControllers" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: DescribeDomainControllersRequest) o.output = Shapes::ShapeRef.new(shape: DescribeDomainControllersResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidNextTokenException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) o.errors << Shapes::ShapeRef.new(shape: UnsupportedOperationException) o[:pager] = Aws::Pager.new( limit_key: "limit", tokens: { "next_token" => "next_token" } ) end) api.add_operation(:describe_event_topics, Seahorse::Model::Operation.new.tap do |o| o.name = "DescribeEventTopics" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: DescribeEventTopicsRequest) o.output = Shapes::ShapeRef.new(shape: DescribeEventTopicsResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:describe_shared_directories, Seahorse::Model::Operation.new.tap do |o| o.name = "DescribeSharedDirectories" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: DescribeSharedDirectoriesRequest) o.output = Shapes::ShapeRef.new(shape: DescribeSharedDirectoriesResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidNextTokenException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: UnsupportedOperationException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:describe_snapshots, Seahorse::Model::Operation.new.tap do |o| o.name = "DescribeSnapshots" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: DescribeSnapshotsRequest) o.output = Shapes::ShapeRef.new(shape: DescribeSnapshotsResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: InvalidNextTokenException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:describe_trusts, Seahorse::Model::Operation.new.tap do |o| o.name = "DescribeTrusts" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: DescribeTrustsRequest) o.output = Shapes::ShapeRef.new(shape: DescribeTrustsResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidNextTokenException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) o.errors << Shapes::ShapeRef.new(shape: UnsupportedOperationException) end) api.add_operation(:disable_radius, Seahorse::Model::Operation.new.tap do |o| o.name = "DisableRadius" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: DisableRadiusRequest) o.output = Shapes::ShapeRef.new(shape: DisableRadiusResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:disable_sso, Seahorse::Model::Operation.new.tap do |o| o.name = "DisableSso" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: DisableSsoRequest) o.output = Shapes::ShapeRef.new(shape: DisableSsoResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InsufficientPermissionsException) o.errors << Shapes::ShapeRef.new(shape: AuthenticationFailedException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:enable_radius, Seahorse::Model::Operation.new.tap do |o| o.name = "EnableRadius" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: EnableRadiusRequest) o.output = Shapes::ShapeRef.new(shape: EnableRadiusResult) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: EntityAlreadyExistsException) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:enable_sso, Seahorse::Model::Operation.new.tap do |o| o.name = "EnableSso" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: EnableSsoRequest) o.output = Shapes::ShapeRef.new(shape: EnableSsoResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InsufficientPermissionsException) o.errors << Shapes::ShapeRef.new(shape: AuthenticationFailedException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:get_directory_limits, Seahorse::Model::Operation.new.tap do |o| o.name = "GetDirectoryLimits" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: GetDirectoryLimitsRequest) o.output = Shapes::ShapeRef.new(shape: GetDirectoryLimitsResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:get_snapshot_limits, Seahorse::Model::Operation.new.tap do |o| o.name = "GetSnapshotLimits" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: GetSnapshotLimitsRequest) o.output = Shapes::ShapeRef.new(shape: GetSnapshotLimitsResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:list_ip_routes, Seahorse::Model::Operation.new.tap do |o| o.name = "ListIpRoutes" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: ListIpRoutesRequest) o.output = Shapes::ShapeRef.new(shape: ListIpRoutesResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidNextTokenException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:list_log_subscriptions, Seahorse::Model::Operation.new.tap do |o| o.name = "ListLogSubscriptions" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: ListLogSubscriptionsRequest) o.output = Shapes::ShapeRef.new(shape: ListLogSubscriptionsResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidNextTokenException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:list_schema_extensions, Seahorse::Model::Operation.new.tap do |o| o.name = "ListSchemaExtensions" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: ListSchemaExtensionsRequest) o.output = Shapes::ShapeRef.new(shape: ListSchemaExtensionsResult) o.errors << Shapes::ShapeRef.new(shape: InvalidNextTokenException) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:list_tags_for_resource, Seahorse::Model::Operation.new.tap do |o| o.name = "ListTagsForResource" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: ListTagsForResourceRequest) o.output = Shapes::ShapeRef.new(shape: ListTagsForResourceResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidNextTokenException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:register_event_topic, Seahorse::Model::Operation.new.tap do |o| o.name = "RegisterEventTopic" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: RegisterEventTopicRequest) o.output = Shapes::ShapeRef.new(shape: RegisterEventTopicResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:reject_shared_directory, Seahorse::Model::Operation.new.tap do |o| o.name = "RejectSharedDirectory" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: RejectSharedDirectoryRequest) o.output = Shapes::ShapeRef.new(shape: RejectSharedDirectoryResult) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: DirectoryAlreadySharedException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:remove_ip_routes, Seahorse::Model::Operation.new.tap do |o| o.name = "RemoveIpRoutes" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: RemoveIpRoutesRequest) o.output = Shapes::ShapeRef.new(shape: RemoveIpRoutesResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: DirectoryUnavailableException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:remove_tags_from_resource, Seahorse::Model::Operation.new.tap do |o| o.name = "RemoveTagsFromResource" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: RemoveTagsFromResourceRequest) o.output = Shapes::ShapeRef.new(shape: RemoveTagsFromResourceResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:reset_user_password, Seahorse::Model::Operation.new.tap do |o| o.name = "ResetUserPassword" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: ResetUserPasswordRequest) o.output = Shapes::ShapeRef.new(shape: ResetUserPasswordResult) o.errors << Shapes::ShapeRef.new(shape: DirectoryUnavailableException) o.errors << Shapes::ShapeRef.new(shape: UserDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidPasswordException) o.errors << Shapes::ShapeRef.new(shape: UnsupportedOperationException) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:restore_from_snapshot, Seahorse::Model::Operation.new.tap do |o| o.name = "RestoreFromSnapshot" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: RestoreFromSnapshotRequest) o.output = Shapes::ShapeRef.new(shape: RestoreFromSnapshotResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:share_directory, Seahorse::Model::Operation.new.tap do |o| o.name = "ShareDirectory" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: ShareDirectoryRequest) o.output = Shapes::ShapeRef.new(shape: ShareDirectoryResult) o.errors << Shapes::ShapeRef.new(shape: DirectoryAlreadySharedException) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidTargetException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ShareLimitExceededException) o.errors << Shapes::ShapeRef.new(shape: OrganizationsException) o.errors << Shapes::ShapeRef.new(shape: AccessDeniedException) o.errors << Shapes::ShapeRef.new(shape: UnsupportedOperationException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:start_schema_extension, Seahorse::Model::Operation.new.tap do |o| o.name = "StartSchemaExtension" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: StartSchemaExtensionRequest) o.output = Shapes::ShapeRef.new(shape: StartSchemaExtensionResult) o.errors << Shapes::ShapeRef.new(shape: DirectoryUnavailableException) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: SnapshotLimitExceededException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:unshare_directory, Seahorse::Model::Operation.new.tap do |o| o.name = "UnshareDirectory" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: UnshareDirectoryRequest) o.output = Shapes::ShapeRef.new(shape: UnshareDirectoryResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidTargetException) o.errors << Shapes::ShapeRef.new(shape: DirectoryNotSharedException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:update_conditional_forwarder, Seahorse::Model::Operation.new.tap do |o| o.name = "UpdateConditionalForwarder" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: UpdateConditionalForwarderRequest) o.output = Shapes::ShapeRef.new(shape: UpdateConditionalForwarderResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: DirectoryUnavailableException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: UnsupportedOperationException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:update_number_of_domain_controllers, Seahorse::Model::Operation.new.tap do |o| o.name = "UpdateNumberOfDomainControllers" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: UpdateNumberOfDomainControllersRequest) o.output = Shapes::ShapeRef.new(shape: UpdateNumberOfDomainControllersResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: DirectoryUnavailableException) o.errors << Shapes::ShapeRef.new(shape: DomainControllerLimitExceededException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: UnsupportedOperationException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:update_radius, Seahorse::Model::Operation.new.tap do |o| o.name = "UpdateRadius" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: UpdateRadiusRequest) o.output = Shapes::ShapeRef.new(shape: UpdateRadiusResult) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:update_trust, Seahorse::Model::Operation.new.tap do |o| o.name = "UpdateTrust" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: UpdateTrustRequest) o.output = Shapes::ShapeRef.new(shape: UpdateTrustResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) end) api.add_operation(:verify_trust, Seahorse::Model::Operation.new.tap do |o| o.name = "VerifyTrust" o.http_method = "POST" o.http_request_uri = "/" o.input = Shapes::ShapeRef.new(shape: VerifyTrustRequest) o.output = Shapes::ShapeRef.new(shape: VerifyTrustResult) o.errors << Shapes::ShapeRef.new(shape: EntityDoesNotExistException) o.errors << Shapes::ShapeRef.new(shape: InvalidParameterException) o.errors << Shapes::ShapeRef.new(shape: ClientException) o.errors << Shapes::ShapeRef.new(shape: ServiceException) o.errors << Shapes::ShapeRef.new(shape: UnsupportedOperationException) end) end end end
70.009518
220
0.764753
e2a57999c8df86b4b3945f42d6a8310e0cfa85c5
585
# frozen_string_literal: true if defined?(ChefSpec) # matcher => [methods] { :logstash_config => %w[create delete], :logstash_input => %w[create delete], :logstash_filter => %w[create delete], :logstash_output => %w[create delete], :logstash_service => %w[start stop restart] }.each_pair do |resource, actions| ChefSpec.define_matcher resource actions.each do |action| define_method("#{action}_#{resource}") do |resource_name| ChefSpec::Matchers::ResourceMatcher.new(resource, action.to_sym, resource_name) end end end end
27.857143
87
0.678632
394271feef8c0d50095aa352d1e0d96f412ef785
1,137
# typed: true class PgSearchTest include PgSearch::Model multisearchable against: [:body], update_if: :body_changed? multisearchable against: :body, update_if: :body_changed? multisearchable against: [:title, :body], additional_attributes: -> (article) { { author_id: article.author_id } } pg_search_scope :search_by_title, against: :title pg_search_scope :search_by_full_name, against: [:first_name, :last_name] pg_search_scope :search_by_name, lambda { |name_part, query| raise ArgumentError unless [:first, :last].include?(name_part) { against: name_part, query: query } } pg_search_scope :tasty_search, associated_against: { cheeses: [:kind, :brand], cracker: :kind } pg_search_scope :search_name, against: :name, using: [:tsearch, :trigram, :dmetaphone] pg_search_scope :search_full_text, against: { title: 'A', subtitle: 'B', content: 'C' } pg_search_scope :whose_name_starts_with, against: :name, using: { tsearch: { prefix: true } } pg_search_scope :kinda_spelled_like, against: :name, using: :trigram end
25.840909
88
0.684257
e2a83aec91a5fe589af4e86449960d77d9781b1f
4,450
require 'pathname' Puppet::Type.newtype(:dsc_xscspfstamp) do require Pathname.new(__FILE__).dirname + '../../' + 'puppet/type/base_dsc' require Pathname.new(__FILE__).dirname + '../../puppet_x/puppetlabs/dsc_type_helpers' @doc = %q{ The DSC xSCSPFStamp resource type. Automatically generated from 'xSCSPF/DSCResources/MSFT_xSCSPFStamp/MSFT_xSCSPFStamp.schema.mof' To learn more about PowerShell Desired State Configuration, please visit https://technet.microsoft.com/en-us/library/dn249912.aspx. For more information about built-in DSC Resources, please visit https://technet.microsoft.com/en-us/library/dn249921.aspx. For more information about xDsc Resources, please visit https://github.com/PowerShell/DscResources. } validate do fail('dsc_name is a required attribute') if self[:dsc_name].nil? end def dscmeta_resource_friendly_name; 'xSCSPFStamp' end def dscmeta_resource_name; 'MSFT_xSCSPFStamp' end def dscmeta_module_name; 'xSCSPF' end def dscmeta_module_version; '1.3.1.0' end newparam(:name, :namevar => true ) do end ensurable do newvalue(:exists?) { provider.exists? } newvalue(:present) { provider.create } newvalue(:absent) { provider.destroy } defaultto { :present } end # Name: PsDscRunAsCredential # Type: MSFT_Credential # IsMandatory: False # Values: None newparam(:dsc_psdscrunascredential) do def mof_type; 'MSFT_Credential' end def mof_is_embedded?; true end desc "PsDscRunAsCredential" validate do |value| unless value.kind_of?(Hash) fail("Invalid value '#{value}'. Should be a hash") end PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("Credential", value) end end # Name: Ensure # Type: string # IsMandatory: False # Values: ["Present", "Absent"] newparam(:dsc_ensure) do def mof_type; 'string' end def mof_is_embedded?; false end desc "Ensure - An enumerated value that describes if the SPF stamp exists.\nPresent {default} \nAbsent \n Valid values are Present, Absent." validate do |value| resource[:ensure] = value.downcase unless value.kind_of?(String) fail("Invalid value '#{value}'. Should be a string") end unless ['Present', 'present', 'Absent', 'absent'].include?(value) fail("Invalid value '#{value}'. Valid values are Present, Absent") end end end # Name: Name # Type: string # IsMandatory: True # Values: None newparam(:dsc_name) do def mof_type; 'string' end def mof_is_embedded?; false end desc "Name - Specifies a name for the stamp." isrequired validate do |value| unless value.kind_of?(String) fail("Invalid value '#{value}'. Should be a string") end end end # Name: Servers # Type: string[] # IsMandatory: False # Values: None newparam(:dsc_servers, :array_matching => :all) do def mof_type; 'string[]' end def mof_is_embedded?; false end desc "Servers - Specifies the name of one or more server objects to associate with the new stamp." validate do |value| unless value.kind_of?(Array) || value.kind_of?(String) fail("Invalid value '#{value}'. Should be a string or an array of strings") end end munge do |value| Array(value) end end # Name: SCSPFAdminCredential # Type: MSFT_Credential # IsMandatory: False # Values: None newparam(:dsc_scspfadmincredential) do def mof_type; 'MSFT_Credential' end def mof_is_embedded?; true end desc "SCSPFAdminCredential - Credential with admin permissions to Service Provider Foundation." validate do |value| unless value.kind_of?(Hash) fail("Invalid value '#{value}'. Should be a hash") end PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("SCSPFAdminCredential", value) end end def builddepends pending_relations = super() PuppetX::Dsc::TypeHelpers.ensure_reboot_relationship(self, pending_relations) end end Puppet::Type.type(:dsc_xscspfstamp).provide :powershell, :parent => Puppet::Type.type(:base_dsc).provider(:powershell) do confine :true => (Gem::Version.new(Facter.value(:powershell_version)) >= Gem::Version.new('5.0.10586.117')) defaultfor :operatingsystem => :windows mk_resource_methods end
31.785714
147
0.674607
fffc98b65123b5d2d97b0082c36c8d9f29f2c026
7,828
=begin #Accounting API #No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 2.0.0 Contact: [email protected] Generated by: https://openapi-generator.tech OpenAPI Generator version: 4.0.3 =end require 'time' require 'date' module XeroRuby class ExternalLink # See External link types attr_accessor :link_type # URL for service e.g. http://twitter.com/xeroapi attr_accessor :url attr_accessor :description class EnumAttributeValidator attr_reader :datatype attr_reader :allowable_values def initialize(datatype, allowable_values) @allowable_values = allowable_values.map do |value| case datatype.to_s when /Integer/i value.to_i when /Float/i value.to_f else value end end end def valid?(value) !value || allowable_values.include?(value) end end # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'link_type' => :'LinkType', :'url' => :'Url', :'description' => :'Description' } end # Attribute type mapping. def self.openapi_types { :'link_type' => :'String', :'url' => :'String', :'description' => :'String' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) if (!attributes.is_a?(Hash)) fail ArgumentError, "The input argument (attributes) must be a hash in `XeroRuby::ExternalLink` initialize method" end # check to see if the attribute exists and convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| if (!self.class.attribute_map.key?(k.to_sym)) fail ArgumentError, "`#{k}` is not a valid attribute in `XeroRuby::ExternalLink`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect end h[k.to_sym] = v } if attributes.key?(:'link_type') self.link_type = attributes[:'link_type'] end if attributes.key?(:'url') self.url = attributes[:'url'] end if attributes.key?(:'description') self.description = attributes[:'description'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? link_type_validator = EnumAttributeValidator.new('String', ["Facebook", "GooglePlus", "LinkedIn", "Twitter", "Website"]) return false unless link_type_validator.valid?(@link_type) true end # Custom attribute writer method checking allowed values (enum). # @param [Object] link_type Object to be assigned def link_type=(link_type) validator = EnumAttributeValidator.new('String', ["Facebook", "GooglePlus", "LinkedIn", "Twitter", "Website"]) unless validator.valid?(link_type) fail ArgumentError, "invalid value for \"link_type\", must be one of #{validator.allowable_values}." end @link_type = link_type end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && link_type == o.link_type && url == o.url && description == o.description end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Integer] Hash code def hash [link_type, url, description].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def self.build_from_hash(attributes) new.build_from_hash(attributes) end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.openapi_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(parse_date(value)) when :Date Date._iso8601(parse_date(value)) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :Boolean if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model XeroRuby.const_get(type).build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end # customized data_parser def parse_date(datestring) seconds_since_epoch = datestring.scan(/[0-9]+/)[0].to_i / 1000.0 return Time.at(seconds_since_epoch).to_s end end end
30.341085
200
0.625703
ac110f4f4b3ce78d497e8abd935b27e69e0a32de
330
class Admin::CreateContactListService attr_reader :contact_list def initialize(district_id:) @district_id = district_id end def perform @contact_list = ContactList.create_for_district(@district_id, new_contacts) end private def new_contacts Customer.contactable.for_districts(@district_id) end end
18.333333
79
0.772727
03b930c39f936e93eb2f67cdf7d0a5472498da2a
20,363
# frozen_string_literal: true require 'rails_helper' feature "early allocation", type: :feature do let(:nomis_staff_id) { 485_926 } # any date less than 3 months let(:valid_date) { Time.zone.today - 2.months } let(:prison) { 'LEI' } let(:username) { 'MOIC_POM' } let(:nomis_offender) { build(:nomis_offender, dateOfBirth: date_of_birth, sentence: attributes_for(:sentence_detail, conditionalReleaseDate: release_date)) } let(:nomis_offender_id) { nomis_offender.fetch(:offenderNo) } let(:pom) { build(:pom, staffId: nomis_staff_id) } let(:date_of_birth) { Date.new(1980, 1, 6).to_s } let(:offender_name) { "#{nomis_offender.fetch(:lastName)}, #{nomis_offender.fetch(:firstName)}" } let(:case_alloc) { CaseInformation::NPS } before do create(:case_information, nomis_offender_id: nomis_offender_id, case_allocation: case_alloc) create(:allocation, prison: prison, nomis_offender_id: nomis_offender_id, primary_pom_nomis_id: nomis_staff_id) stub_auth_token stub_offenders_for_prison(prison, [nomis_offender]) stub_offender(nomis_offender) stub_request(:get, "#{ApiHelper::T3}/users/#{username}"). to_return(body: { 'staffId': nomis_staff_id }.to_json) stub_pom(pom) stub_poms(prison, [pom]) stub_pom_emails(nomis_staff_id, []) stub_keyworker(prison, nomis_offender_id, build(:keyworker)) signin_pom_user visit prison_staff_caseload_path(prison, nomis_staff_id) # assert that our setup created a caseload record expect(page).to have_content("Showing 1 - 1 of 1 results") end context 'with switch set false' do let(:test_strategy) { Flipflop::FeatureSet.current.test! } let(:release_date) { Time.zone.today } before do test_strategy.switch!(:early_allocation, false) end after do test_strategy.switch!(:early_allocation, true) end it 'does not show the section' do click_link offender_name expect(page).not_to have_content 'Early allocation eligibility' end end # switch is on by default context 'with switch' do context 'when CRC' do let(:case_alloc) { CaseInformation::CRC } let(:release_date) { Time.zone.today } it 'does not show the section' do click_link offender_name expect(page).not_to have_content 'Early allocation eligibility' end end context 'without existing early allocation' do before do click_link offender_name # Prisoner profile page expect(page).to have_content 'Early allocation referral' click_link 'Start assessment' # Early Allocation start page expect(page).to have_content 'Early allocation assessment process' #expect(page).to have_content 'This case has no saved assessments.' displays_prisoner_information_in_side_panel click_link 'Start new assessment' end context 'when <= 18 months' do let(:release_date) { Time.zone.today + 17.months } scenario 'when first page with just date' do click_button 'Continue' expect(page).to have_css('.govuk-error-message') within '.govuk-error-summary' do expect(all('li').map(&:text)) .to match_array([ "Enter the date of the last OASys risk assessment", ]) end end scenario 'when an immediate error occurs on the second page' do fill_in_date_form click_button 'Continue' expect(page).to have_css('.govuk-error-message') expect(page).to have_css('#early-allocation-high-profile-error') within '.govuk-error-summary' do expect(page).to have_text 'You must say if this case is \'high profile\'' click_link 'You must say if this case is \'high profile\'' # ensure that page is still intact expect(all('li').map(&:text)). to match_array([ "You must say if they are subject to a Serious Crime Prevention Order", "You must say if they were convicted under the Terrorism Act 2000", "You must say if this case is 'high profile'", "You must say if this is a MAPPA level 3 case", "You must say if this will be a CPPC case" ] ) end end context 'when doing eligible happy path' do before do eligible_eligible_answers end scenario 'eligible happy path' do expect { displays_prisoner_information_in_side_panel click_button 'Continue' expect(page).not_to have_css('.govuk-error-message') # selecting any one of these as 'Yes' means that we progress to assessment complete (Yes) expect(page).to have_text('The community probation team will take responsibility') expect(page).to have_text('A new handover date will be calculated automatically') }.to change(EarlyAllocation, :count).by(1) # Early allocation status is updated click_link 'Return to prisoner page' expect(page).to have_text 'Eligible' expect(page).to have_link 'View assessment' # Can view the assessment click_link 'View assessment' expect(page).to have_text 'View previous early allocation assessment' end scenario 'displaying the PDF' do click_button 'Continue' expect(page).not_to have_css('.govuk-error-message') # selecting any one of these as 'Yes' means that we progress to assessment complete (Yes) expect(page).to have_text('The community probation team will take responsibility') click_link 'Save completed assessment (pdf)' created_id = EarlyAllocation.last.id expected_path = "/prisons/#{prison}/prisoners/#{nomis_offender_id}/early_allocations/#{created_id}.pdf" expect(page).to have_current_path(expected_path) end end context 'with stage 2 questions' do before do eligible_discretionary_answers displays_prisoner_information_in_side_panel click_button 'Continue' # make sure that we are displaying stage 2 questions before continuing expect(page).to have_text 'Has the prisoner been held in an extremism' end scenario 'error path' do click_button 'Continue' expect(page).to have_css('.govuk-error-message') expect(page).to have_css('.govuk-error-summary') within '.govuk-error-summary' do expect(all('li').map(&:text)). to match_array([ "You must say if this prisoner has been in an extremism separation centre", "You must say if there is another reason for early allocation", "You must say whether this prisoner presents a risk of serious harm", "You must say if this is a MAPPA level 2 case", "You must say if this prisoner has been identified through the pathfinder process" ] ) end end context 'with discretionary path' do let(:early_allocation_badge) { page.find('#early-allocation-badge') } before do discretionary_discretionary_answers click_button 'Continue' expect(page).not_to have_text 'The community probation team will make a decision' displays_prisoner_information_in_side_panel # Last prompt before end of journey expect(page).to have_text 'Why are you referring this case for early allocation to the community?' click_button 'Continue' # we need to always tick the 'Head of Offender Management' box and fill in the reasons expect(page).to have_css('.govuk-error-message') within '.govuk-error-summary' do expect(all('li').map(&:text)). to match_array([ "You must give a reason for referring this case", "You must say if this referral has been approved", ] ) end expect { complete_form }.to change(EarlyAllocation, :count).by(1) expect(page).to have_text 'The community probation team will make a decision' end scenario 'saving the PDF' do created_id = EarlyAllocation.last.id expected_path = "/prisons/#{prison}/prisoners/#{nomis_offender_id}/early_allocations/#{created_id}.pdf" expect(page).to have_link 'Save completed assessment (pdf)', href: expected_path end scenario 'completing the journey' do # Profile page click_link 'Return to prisoner page' expect(page).to have_content 'Discretionary - the community probation team will make a decision' click_link 'Record community decision' # 'Record community decision' page displays_prisoner_information_in_side_panel click_button('Save') expect(page).to have_css('.govuk-error-message') within '.govuk-error-summary' do expect(all('li').count).to eq(1) end expect(page).to have_text 'You must say whether the community has accepted this case or not' find('label[for=early_allocation_community_decision_true]').click click_button('Save') # Profile page expect(early_allocation_badge.text).to include 'EARLY ALLOCATION APPROVED' expect(page).to have_text 'Eligible - case handover date has been updated' expect(page).to have_link 'View assessment' # View the assessment click_link 'View assessment' expect(page).to have_text 'View previous early allocation assessment' end end scenario 'not eligible due to all answers false' do find('label[for=early-allocation-extremism-separation-field]').click find('label[for=early-allocation-high-risk-of-serious-harm-field]').click find('label[for=early-allocation-mappa-level-2-field]').click find('label[for=early-allocation-pathfinder-process-field]').click find('label[for=early-allocation-other-reason-field]').click click_button 'Continue' expect(page).to have_text 'Not eligible for early allocation' click_link 'Save completed assessment (pdf)' created_id = EarlyAllocation.last.id expected_path = "/prisons/#{prison}/prisoners/#{nomis_offender_id}/early_allocations/#{created_id}.pdf" expect(page).to have_current_path(expected_path) end end end context 'when > 18 months' do let(:release_date) { Time.zone.today + 19.months } context 'when stage 1 happy path - not sent' do before do expect(EarlyAllocationMailer).not_to receive(:auto_early_allocation) end it 'doesnt send the email' do expect { eligible_eligible_answers click_button 'Continue' expect(page).to have_text('The community probation team will take responsibility for this case early') expect(page).to have_text('The assessment has not been sent to the community probation team') }.not_to change(EmailHistory, :count) # Early allocation status is updated click_link 'Return to prisoner page' expect(page).to have_text 'Has saved assessments' expect(page).to have_link 'Check and reassess' end end context 'with discretionary result' do before do expect(EarlyAllocationMailer).not_to receive(:community_early_allocation) end it 'doesnt send the email' do expect { eligible_discretionary_answers click_button 'Continue' discretionary_discretionary_answers click_button 'Continue' complete_form expect(page).to have_text('The assessment has not been sent to the community probation team') }.not_to change(EmailHistory, :count) # Early allocation status is updated click_link 'Return to prisoner page' expect(page).to have_text 'Has saved assessments' expect(page).to have_link 'Check and reassess' end end end end context 'with existing Early Allocation assessments' do context 'when <= 18 months' do let(:release_date) { Time.zone.today + 17.months } context 'when assessment outcome was eligible and was sent to LDU' do before do # Was sent to LDU because created_within_referral_window is true create(:early_allocation, nomis_offender_id: nomis_offender_id, created_within_referral_window: true) click_link offender_name end it 'links to the view page' do click_link 'View assessment' expect(page).to have_text 'View previous early allocation assessment' end it 'does not have a re-assess link' do expect(page).not_to have_link 'Check and reassess' end end context 'when assessment outcome was not eligible' do before do create(:early_allocation, :ineligible, nomis_offender_id: nomis_offender_id, created_within_referral_window: true) click_link offender_name end it 'has a re-assess link' do expect(page).to have_link 'Check and reassess' end end end context 'when > 18 months' do let(:release_date) { Time.zone.today + 19.months } context 'when assessment outcome was eligible' do before do create(:early_allocation, nomis_offender_id: nomis_offender_id, created_within_referral_window: false) click_link offender_name end it 'has a re-assess link' do expect(page).to have_link 'Check and reassess' end end end context 'when reassessing' do let(:release_date) { Time.zone.today + 17.months } before do create(:early_allocation, :ineligible, nomis_offender_id: nomis_offender_id, created_within_referral_window: true) click_link offender_name within '#early_allocation' do click_link 'Check and reassess' end # Early Allocation start page expect(page).not_to have_content 'This case has no saved assessments.' displays_prisoner_information_in_side_panel click_link 'Start new assessment' end it 'creates a new assessment' do expect { eligible_eligible_answers click_button 'Continue' }.to change(EarlyAllocation, :count).by(1) end it 'can do discretionary' do eligible_discretionary_answers click_button 'Continue' expect(page).not_to have_css('.govuk-error-message') end end describe 'Early Allocation start page' do let(:release_date) { Time.zone.today + 19.months } before do create(:early_allocation, :ineligible, created_at: 5.days.ago, nomis_offender_id: nomis_offender_id, created_within_referral_window: false) create(:early_allocation, :eligible, created_at: 3.days.ago, nomis_offender_id: nomis_offender_id, created_within_referral_window: false) create(:early_allocation, :discretionary, created_at: 1.day.ago, nomis_offender_id: nomis_offender_id, created_within_referral_window: false) click_link offender_name within '#early_allocation' do click_link 'Check and reassess' end end it 'displays a list of previous assessments' do table_rows = page.all('#saved_assessments > tbody > tr') expect(page).to have_content 'View saved assessments' # Expect 3 rows in the table expect(table_rows.count).to eq(3) # 1. Discretionary (most recent) expect(table_rows[0]).to have_content 'Discretionary - assessment not sent to the community probation team' # 2. Eligible expect(table_rows[1]).to have_content 'Eligible - assessment not sent to the community probation team' # 3. Not eligible (oldest) expect(table_rows[2]).to have_content 'Not eligible' end describe 'clicking "View" on a previous assessment' do it 'shows you the chosen assessment' do # Click 'View' on the 2nd row of table (should be an 'eligible' assessment) within '#saved_assessments > tbody > tr:nth-child(2)' do click_link 'View' end # We're on the 'View' page expect(page).to have_content 'View previous early allocation assessment' expect(page).to have_content 3.days.ago.strftime('%d/%m/%Y') expect(page).to have_content 'Eligible - assessment not sent to the community probation team' end end end end end def fill_in_date_form fill_in id: 'early_allocation_oasys_risk_assessment_date_3i', with: valid_date.day fill_in id: 'early_allocation_oasys_risk_assessment_date_2i', with: valid_date.month fill_in id: 'early_allocation_oasys_risk_assessment_date_1i', with: valid_date.year click_button 'Continue' end def eligible_eligible_answers fill_in_date_form find('label[for=early-allocation-convicted-under-terrorisom-act-2000-true-field]').click find('label[for=early-allocation-high-profile-field]').click find('label[for=early-allocation-serious-crime-prevention-order-field]').click find('label[for=early-allocation-mappa-level-3-field]').click find('label[for=early-allocation-cppc-case-field]').click end def eligible_discretionary_answers fill_in_date_form find("label[for=early-allocation-convicted-under-terrorisom-act-2000-field]").click find('label[for=early-allocation-high-profile-field]').click find('label[for=early-allocation-serious-crime-prevention-order-field]').click find('label[for=early-allocation-mappa-level-3-field]').click find('label[for=early-allocation-cppc-case-field]').click end def discretionary_discretionary_answers find('label[for=early-allocation-extremism-separation-field]').click find('label[for=early-allocation-high-risk-of-serious-harm-field]').click find('label[for=early-allocation-mappa-level-2-field]').click find('label[for=early-allocation-pathfinder-process-field]').click find('label[for=early-allocation-other-reason-true-field]').click end def complete_form fill_in id: 'early_allocation_reason', with: Faker::Quote.famous_last_words find('label[for=early_allocation_approved]').click click_button 'Continue' end def displays_prisoner_information_in_side_panel expect(page).to have_text('Prisoner information') expect(page).to have_selector('p#prisoner-name', text: offender_name) expect(page).to have_selector('p#date-of-birth', text: '6/01/1980') expect(page).to have_selector('p#nomis-number', text: nomis_offender_id) end end
39.463178
159
0.622109
281feb5c3c2d81cc3170f253073a27480f8ed3fb
606
class I386JosElfGdb < Formula desc "GNU debugger" homepage "https://www.gnu.org/software/gdb/" url "http://ftpmirror.gnu.org/gdb/gdb-8.2.1.tar.xz" mirror "https://ftp.gnu.org/gnu/gdb/gdb-8.2.1.tar.xz" sha256 "0a6a432907a03c5c8eaad3c3cffd50c00a40c3a5e3c4039440624bae703f2202" def install args = %W[ --prefix=#{prefix} --target=i386-jos-elf --disable-werror --with-gdb-datadir=#{pkgshare} ] system "./configure", *args system "make" system "make", "install" rm_rf include rm_rf lib rm_rf share/"locale" rm_rf share/"info" end end
22.444444
75
0.653465
268aca95ff94e17715fabac441f8b0afc369d81a
4,820
module ChildProcess module Windows class ProcessBuilder attr_accessor :leader, :detach, :duplex, :environment, :stdout, :stderr, :cwd attr_reader :stdin def initialize(args) @args = args @detach = false @duplex = false @environment = nil @cwd = nil @stdout = nil @stderr = nil @stdin = nil @flags = 0 @job_ptr = nil @cmd_ptr = nil @env_ptr = nil @cwd_ptr = nil end def start create_command_pointer create_environment_pointer create_cwd_pointer setup_flags setup_io pid = create_process close_handles pid end private def create_command_pointer string = @args.map { |arg| quote_if_necessary(arg.to_s) }.join ' ' @cmd_ptr = FFI::MemoryPointer.from_string string end def create_environment_pointer return unless @environment.kind_of?(Hash) && @environment.any? strings = [] ENV.to_hash.merge(@environment).each do |key, val| next if val.nil? if key.to_s =~ /=|\0/ || val.to_s.include?("\0") raise InvalidEnvironmentVariable, "#{key.inspect} => #{val.inspect}" end strings << "#{key}=#{val}\0" end strings << "\0" # terminate the env block env_str = strings.join @env_ptr = FFI::MemoryPointer.new(:long, env_str.bytesize) @env_ptr.put_bytes 0, env_str, 0, env_str.bytesize end def create_cwd_pointer @cwd_ptr = FFI::MemoryPointer.from_string(@cwd || Dir.pwd) end def create_process ok = Lib.create_process( nil, # application name @cmd_ptr, # command line nil, # process attributes nil, # thread attributes true, # inherit handles @flags, # creation flags @env_ptr, # environment @cwd_ptr, # current directory startup_info, # startup info process_info # process info ) ok or raise LaunchError, Lib.last_error_message process_info[:dwProcessId] end def startup_info @startup_info ||= StartupInfo.new end def process_info @process_info ||= ProcessInfo.new end def setup_flags @flags |= DETACHED_PROCESS if @detach @flags |= CREATE_BREAKAWAY_FROM_JOB if @leader end def setup_io startup_info[:dwFlags] ||= 0 startup_info[:dwFlags] |= STARTF_USESTDHANDLES if @stdout startup_info[:hStdOutput] = std_stream_handle_for(@stdout) end if @stderr startup_info[:hStdError] = std_stream_handle_for(@stderr) end if @duplex read_pipe_ptr = FFI::MemoryPointer.new(:pointer) write_pipe_ptr = FFI::MemoryPointer.new(:pointer) sa = SecurityAttributes.new(:inherit => true) ok = Lib.create_pipe(read_pipe_ptr, write_pipe_ptr, sa, 0) Lib.check_error ok @read_pipe = read_pipe_ptr.read_pointer @write_pipe = write_pipe_ptr.read_pointer Lib.set_handle_inheritance @read_pipe, true Lib.set_handle_inheritance @write_pipe, false startup_info[:hStdInput] = @read_pipe else startup_info[:hStdInput] = std_stream_handle_for(STDIN) end end def std_stream_handle_for(io) handle = Lib.handle_for(io) begin Lib.set_handle_inheritance handle, true rescue ChildProcess::Error # If the IO was set to close on exec previously, this call will fail. # That's probably OK, since the user explicitly asked for it to be # closed (at least I have yet to find other cases where this will # happen...) end handle end def close_handles Lib.close_handle process_info[:hProcess] Lib.close_handle process_info[:hThread] if @duplex @stdin = Lib.io_for(Lib.duplicate_handle(@write_pipe), File::WRONLY) Lib.close_handle @read_pipe Lib.close_handle @write_pipe end end def quote_if_necessary(str) quote = str.start_with?('"') ? "'" : '"' case str when /[\s\\'"]/ [quote, str, quote].join else str end end end # ProcessBuilder end # Windows end # ChildProcess
27.386364
84
0.546266
e24214370448b51c2ade2f34ac47c886c71dd037
258
# begin # # Require the preresolved locked set of gems. # require File.expand_path('../.bundle/environment', __FILE__) # rescue LoadError # # Fallback on doing the resolve at runtime. # require "rubygems" # require "bundler" # Bundler.setup # end
28.666667
64
0.70155
6a89af2df207e88ec62416700fffb0826af21d85
727
require 'spec_helper' require 'core_ext/hash/deep_merge' describe 'Hash#deep_merge' do it 'deep merges a hash into a new one' do lft = { :foo => { :bar => 'bar' } } rgt = { :foo => { :baz => 'baz' } } lft.deep_merge(rgt).should == { :foo => { :bar => 'bar', :baz => 'baz' } } end it 'does not change self' do lft = { :foo => { :bar => 'bar' } } rgt = { :foo => { :baz => 'baz' } } lft.deep_merge(rgt) lft.key?(:baz).should == false end end describe 'Hash#deep_merge!' do it 'deep merges a hash into self' do lft = { :foo => { :bar => 'bar' } } rgt = { :foo => { :baz => 'baz' } } lft.deep_merge!(rgt) lft.should == { :foo => { :bar => 'bar', :baz => 'baz' } } end end
26.925926
78
0.513067
acbc8cd27d2b4707c5ae00911826e5e2775c3465
269
class SnippetRevision < ActiveRecord::Base belongs_to :snippet before_save :increase_number def increase_number snippet = self.snippet self.number = snippet && snippet.last_revision ? snippet.last_revision.number + 1 : 1 return true end end
22.416667
89
0.728625
398e01d744813f1c92fcddefa82e8567701c282e
1,160
class ProcyonDecompiler < Formula desc "Modern decompiler for Java 5 and beyond" homepage "https://bitbucket.org/mstrobel/procyon/wiki/Java%20Decompiler" url "https://bitbucket.org/mstrobel/procyon/downloads/procyon-decompiler-0.5.36.jar" sha256 "74f9f1537113207521a075fafe64bd8265c47a9c73574bbf9fa8854bbf7126bc" revision 1 livecheck do skip "Bitbucket repository is missing" end bottle :unneeded depends_on "openjdk" # bitbucket repo was removed disable! def install libexec.install "procyon-decompiler-#{version}.jar" (bin/"procyon-decompiler").write <<~EOS #!/bin/bash export JAVA_HOME="${JAVA_HOME:-#{Formula["openjdk"].opt_prefix}}" exec "${JAVA_HOME}/bin/java" -jar "#{libexec}/procyon-decompiler-#{version}.jar" "$@" EOS end test do fixture = <<~EOS class T { public static void main(final String[] array) { System.out.println("Hello World!"); } } EOS (testpath/"T.java").write fixture system "#{Formula["openjdk"].bin}/javac", "T.java" fixture.match pipe_output("#{bin}/procyon-decompiler", "T.class") end end
27.619048
91
0.669828
f7d1f7c08fe1ca26c3ca44236105c25ba1b7e3b8
933
class ScopedEventFeed attr_reader :root, :event_subjects, :page, :per def initialize(root_type, root_id, page = 0, per = 20) @root = root_type.classify.constantize.find(root_id) @event_subjects = EventHierarchy.new(root).children @page = page @per = per end def events if @events @events else @events = Event.includes(:subject, :organization, :originating_user) .where(subject: event_subjects) .order('events.created_at desc') .page(page) .per(per) end end def comments if @comments @comments else comment_ids = events.select { |e| e.state_params['comment'].present? } .map { |e| e.state_params['comment']['id'] } comments = Comment.includes(user: [:organizations]).where(id: comment_ids) @comments = comments.each_with_object({}) do |comment, h| h[comment.id] = comment end end end end
26.657143
80
0.631297
33e309106306d645a76740648d923224ef1c4777
7,894
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. require 'date' require 'logger' # rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength module OCI # The properties that define a work request resource. class ContainerEngine::Models::WorkRequestResource ACTION_TYPE_ENUM = [ ACTION_TYPE_CREATED = 'CREATED'.freeze, ACTION_TYPE_UPDATED = 'UPDATED'.freeze, ACTION_TYPE_DELETED = 'DELETED'.freeze, ACTION_TYPE_RELATED = 'RELATED'.freeze, ACTION_TYPE_IN_PROGRESS = 'IN_PROGRESS'.freeze, ACTION_TYPE_FAILED = 'FAILED'.freeze, ACTION_TYPE_UNKNOWN_ENUM_VALUE = 'UNKNOWN_ENUM_VALUE'.freeze ].freeze # The way in which this resource was affected by the work tracked by the work request. # @return [String] attr_reader :action_type # The resource type the work request affects. # @return [String] attr_accessor :entity_type # The OCID of the resource the work request affects. # @return [String] attr_accessor :identifier # The URI path on which the user can issue a GET request to access the resource metadata. # @return [String] attr_accessor :entity_uri # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { # rubocop:disable Style/SymbolLiteral 'action_type': :'actionType', 'entity_type': :'entityType', 'identifier': :'identifier', 'entity_uri': :'entityUri' # rubocop:enable Style/SymbolLiteral } end # Attribute type mapping. def self.swagger_types { # rubocop:disable Style/SymbolLiteral 'action_type': :'String', 'entity_type': :'String', 'identifier': :'String', 'entity_uri': :'String' # rubocop:enable Style/SymbolLiteral } end # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity # rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral # Initializes the object # @param [Hash] attributes Model attributes in the form of hash # @option attributes [String] :action_type The value to assign to the {#action_type} property # @option attributes [String] :entity_type The value to assign to the {#entity_type} property # @option attributes [String] :identifier The value to assign to the {#identifier} property # @option attributes [String] :entity_uri The value to assign to the {#entity_uri} property def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } self.action_type = attributes[:'actionType'] if attributes[:'actionType'] raise 'You cannot provide both :actionType and :action_type' if attributes.key?(:'actionType') && attributes.key?(:'action_type') self.action_type = attributes[:'action_type'] if attributes[:'action_type'] self.entity_type = attributes[:'entityType'] if attributes[:'entityType'] raise 'You cannot provide both :entityType and :entity_type' if attributes.key?(:'entityType') && attributes.key?(:'entity_type') self.entity_type = attributes[:'entity_type'] if attributes[:'entity_type'] self.identifier = attributes[:'identifier'] if attributes[:'identifier'] self.entity_uri = attributes[:'entityUri'] if attributes[:'entityUri'] raise 'You cannot provide both :entityUri and :entity_uri' if attributes.key?(:'entityUri') && attributes.key?(:'entity_uri') self.entity_uri = attributes[:'entity_uri'] if attributes[:'entity_uri'] end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity # rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral # Custom attribute writer method checking allowed values (enum). # @param [Object] action_type Object to be assigned def action_type=(action_type) # rubocop:disable Style/ConditionalAssignment if action_type && !ACTION_TYPE_ENUM.include?(action_type) OCI.logger.debug("Unknown value for 'action_type' [" + action_type + "]. Mapping to 'ACTION_TYPE_UNKNOWN_ENUM_VALUE'") if OCI.logger @action_type = ACTION_TYPE_UNKNOWN_ENUM_VALUE else @action_type = action_type end # rubocop:enable Style/ConditionalAssignment end # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines # Checks equality by comparing each attribute. # @param [Object] other the other object to be compared def ==(other) return true if equal?(other) self.class == other.class && action_type == other.action_type && entity_type == other.entity_type && identifier == other.identifier && entity_uri == other.entity_uri end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines # @see the `==` method # @param [Object] other the other object to be compared def eql?(other) self == other end # rubocop:disable Metrics/AbcSize, Layout/EmptyLines # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [action_type, entity_type, identifier, entity_uri].hash end # rubocop:enable Metrics/AbcSize, Layout/EmptyLines # rubocop:disable Metrics/AbcSize, Layout/EmptyLines # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) public_method("#{key}=").call( attributes[self.class.attribute_map[key]] .map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) } ) end elsif !attributes[self.class.attribute_map[key]].nil? public_method("#{key}=").call( OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]]) ) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # rubocop:enable Metrics/AbcSize, Layout/EmptyLines # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = public_method(attr).call next if value.nil? && !instance_variable_defined?("@#{attr}") hash[param] = _to_hash(value) end hash end private # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end # rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
36.546296
140
0.67735
01ede673b39127d7e990452491aee0f590110401
3,590
require 'spec_helper' require 'cli/public_stemcells' module Bosh::Cli describe PublicStemcells, vcr: { cassette_name: 'promoted-stemcells' } do subject(:public_stemcells) { PublicStemcells.new } describe '#has_stemcell?' do it { should have_stemcell('bosh-stemcell-1001-aws-xen-ubuntu.tgz') } it { should_not have_stemcell('bosh-stemcell-1001-aws-xen-solaris.tgz') } end describe '#find' do subject(:find) { public_stemcells.find('bosh-stemcell-1001-aws-xen-ubuntu.tgz') } it { should be_a(PublicStemcell) } its(:name) { should eq('bosh-stemcell-1001-aws-xen-ubuntu.tgz') } its(:size) { should eq(384139128) } end describe '#all' do subject(:list_of_stemcells) { public_stemcells.all.map(&:name) } it 'returns all promoted bosh-stemcells' do expect(list_of_stemcells.size).to eq(968) end it 'returns the most recent aws stemcells' do expect(list_of_stemcells).to include('bosh-stemcell-1341-aws-xen-ubuntu.tgz') expect(list_of_stemcells).to include('light-bosh-stemcell-1341-aws-xen-ubuntu.tgz') end it 'returns the most recent openstack stemcells' do expect(list_of_stemcells).to include('bosh-stemcell-1341-openstack-kvm-ubuntu.tgz') end it 'returns the most recent vsphere stemcells' do expect(list_of_stemcells).to include('bosh-stemcell-1341-vsphere-esxi-ubuntu.tgz') expect(list_of_stemcells).to include('bosh-stemcell-1341-vsphere-esxi-centos.tgz') end it 'returns legacy stemcells' do expect(list_of_stemcells).to include('bosh-stemcell-aws-0.6.4.tgz') end it 'excludes stemcells with "latest" as their version because these keep changing' do expect(list_of_stemcells).not_to include('latest') end end describe '#recent' do subject(:list_of_stemcells) do public_stemcells.recent.map(&:name) end it 'returns the most recent of each variety of stemcell, except legacy stemcells' do expect(list_of_stemcells).to eq %w[bosh-stemcell-2416-aws-xen-ubuntu.tgz bosh-stemcell-2416-aws-xen-centos.tgz bosh-stemcell-2416-aws-xen-centos-go_agent.tgz bosh-stemcell-2416-aws-xen-ubuntu-go_agent.tgz light-bosh-stemcell-2416-aws-xen-ubuntu.tgz light-bosh-stemcell-2416-aws-xen-centos.tgz light-bosh-stemcell-2416-aws-xen-centos-go_agent.tgz light-bosh-stemcell-2416-aws-xen-ubuntu-go_agent.tgz bosh-stemcell-2416-openstack-kvm-ubuntu.tgz bosh-stemcell-2416-openstack-kvm-centos.tgz bosh-stemcell-2416-vsphere-esxi-ubuntu.tgz bosh-stemcell-2416-vsphere-esxi-centos.tgz bosh-stemcell-2416-vsphere-esxi-centos-go_agent.tgz bosh-stemcell-2416-vsphere-esxi-ubuntu-go_agent.tgz bosh-stemcell-53-warden-boshlite-ubuntu.tgz ] end it 'excludes stemcells with "latest" as their version because these keep changing' do expect(list_of_stemcells).not_to include('latest') end end end end
44.320988
94
0.593036
7980b49c3958282bd2508f296bb92a4af36ce51e
553
require 'test_helper' class LoggerTest < Test::Unit::TestCase context "with connection that has logger" do setup do @output = StringIO.new @logger = Logger.new(@output) MongoMapper.connection = Mongo::Connection.new('127.0.0.1', 27017, :logger => @logger) end should "be able to get access to that logger" do MongoMapper.logger.should == @logger end should "be able to log messages" do MongoMapper.logger.debug 'testing' @output.string.include?('testing').should be_true end end end
27.65
92
0.665461
38767e1ae73e58ec72b54619f8e8df9f8606f8fa
5,103
# This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 2019_06_03_231939) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "activities", force: :cascade do |t| t.string "title" t.boolean "checked" t.bigint "goal_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["goal_id"], name: "index_activities_on_goal_id" end create_table "contacts", force: :cascade do |t| t.string "name" t.string "email" t.text "message" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "csfs", force: :cascade do |t| t.text "what_makes_me_unique" t.text "best_attributes" t.text "essential_atributes" t.text "health_factors" t.bigint "user_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["user_id"], name: "index_csfs_on_user_id" end create_table "goals", force: :cascade do |t| t.string "name" t.float "progress" t.bigint "objective_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["objective_id"], name: "index_goals_on_objective_id" end create_table "missions", force: :cascade do |t| t.string "purpose_of_life" t.text "who_am_i" t.string "why_exist" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.bigint "user_id" t.index ["user_id"], name: "index_missions_on_user_id" end create_table "objectives", force: :cascade do |t| t.string "name" t.boolean "concluded" t.bigint "plan_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "sphere_id" t.index ["plan_id"], name: "index_objectives_on_plan_id" end create_table "plans", force: :cascade do |t| t.text "name" t.integer "selected_mission" t.integer "selected_vision" t.integer "selected_csf" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.bigint "user_id" t.index ["user_id"], name: "index_plans_on_user_id" end create_table "roles", force: :cascade do |t| t.string "name" t.text "description" t.bigint "plan_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["plan_id"], name: "index_roles_on_plan_id" end create_table "spheres", force: :cascade do |t| t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "user_id" t.float "progress" end create_table "swotparts", force: :cascade do |t| t.bigint "plan_id" t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "partname" t.index ["plan_id"], name: "index_swotparts_on_plan_id" end create_table "users", force: :cascade do |t| t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "name" t.integer "selected_plan" t.integer "role" t.index ["email"], name: "index_users_on_email", unique: true t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true end create_table "values", force: :cascade do |t| t.string "name" t.bigint "plan_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["plan_id"], name: "index_values_on_plan_id" end create_table "visions", force: :cascade do |t| t.text "where_im_going" t.text "where_arrive" t.text "how_complete_mission" t.bigint "user_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["user_id"], name: "index_visions_on_user_id" end add_foreign_key "activities", "goals" add_foreign_key "csfs", "users" add_foreign_key "goals", "objectives" add_foreign_key "objectives", "plans" add_foreign_key "plans", "users" add_foreign_key "roles", "plans" add_foreign_key "swotparts", "plans" add_foreign_key "values", "plans" add_foreign_key "visions", "users" end
32.922581
95
0.697825
e2d82f3d191388f73e4f5aee40661fbfe236dc52
1,619
class GitPlus < Formula include Language::Python::Virtualenv desc "Git utilities: git multi, git relation, git old-branches, git recent" homepage "https://github.com/tkrajina/git-plus" url "https://files.pythonhosted.org/packages/73/b5/6cf7f0513fd1ef42b5a3ac0e342b3c4176551f60ad17fc5dbe52329f2b58/git-plus-v0.4.6.tar.gz" sha256 "bcf3a83a2730e8b6f5bc106db00b7b6be5df534cb9543ba7ecc506c535c5158b" license "Apache-2.0" revision OS.mac? ? 1 : 2 head "https://github.com/tkrajina/git-plus.git" livecheck do url :stable end bottle do cellar :any_skip_relocation sha256 "6fbeb0f79fb3149feec139360140b71dc8905336fe3e57979a5555542b14315d" => :big_sur sha256 "e2a53a282b0e444cb0aca6173d8475b803b247b72462605574f28f62d2f7d9b9" => :arm64_big_sur sha256 "77a2c33cfbcaa7eeebf0599197ef9865821df0a513c60f768586049c78795709" => :catalina sha256 "de4043e1cd948c93b60ba863ddc3ed42528e733263efb54f4e4c608cc6fcb148" => :mojave sha256 "774bf600193c1446a6097675f995ec808eada8f45d9b78f735121de23cd3d56c" => :high_sierra sha256 "8ba994c5e972b576f8efe9d01456a0f0910b80918b771b6df1d407eb0ef4d285" => :x86_64_linux end depends_on "[email protected]" def install virtualenv_install_with_resources end test do mkdir "testme" do system "git", "init" system "git", "config", "user.email", "\"[email protected]\"" system "git", "config", "user.name", "\"Test\"" touch "README" system "git", "add", "README" system "git", "commit", "-m", "testing" rm "README" end assert_match "D README", shell_output("#{bin}/git-multi") end end
35.195652
137
0.744287
1c73fe501a67e64137c2fadafb13ea205ecc2fea
876
$LOAD_PATH.unshift File.expand_path('../lib', __FILE__) require 'waylon/version' Gem::Specification.new do |s| s.name = 'waylon' s.version = Waylon::VERSION s.date = '2015-05-11' s.authors = ['Roger Ignazio'] s.email = ['[email protected]'] s.homepage = 'https://github.com/rji/waylon' s.summary = 'Waylon is a dashboard to display the status of your Jenkins builds.' s.description = s.summary s.license = 'Apache License, Version 2.0' s.files = `git ls-files`.split("\n") s.require_paths = ['lib'] s.required_ruby_version = '~> 2.1.0' s.add_runtime_dependency 'sinatra', '~> 1.4.5' s.add_runtime_dependency 'jenkins_api_client', '~> 1.0.1' s.add_runtime_dependency 'deterministic', '~> 0.6.0' s.add_runtime_dependency 'memcached', '~> 1.8.0' end
33.692308
89
0.610731
f74688a53c659bcfa83e9369d6a5bf781ddae257
537
require 'rails_helper' feature 'Reset Password' do let!(:admin) { create(:user, :admin) } scenario 'User exists' do visit '/password_resets/new' fill_in('email', with: admin.email) click_button('Reset Password') expect(page).to have_content('Email sent with password reset instructions') end scenario 'User does not exist' do visit '/password_resets/new' fill_in('email', with: '[email protected]') click_button('Reset Password') expect(page).to have_content('Unknown Email Address') end end
26.85
79
0.702048
ababa7ea53fd6b9eb2a3b42c8229483c2fa8fe8d
113
class UserPagesController < ApplicationController def signup end def login end def account end end
10.272727
49
0.743363
38d0e4086edbfc4f7ea44426388409ccb5d8585c
1,843
xml.h1("class" => "title") do xml << "Posts" end xml.table do xml.thead do xml.tr do xml.th do xml << "\n Title\n " end xml.th do xml << "\n Writer\n " end xml.th do xml << "\n Actions\n " end end end xml.tbody do @posts.each do |post| xml.tr do xml.td do xml << link_to(post().title, edit_post_path(post())) end xml.td do xml << post().author end xml.td do xml << button_to("Delete", { action: "destroy", id: post().id }, method: :delete, data: { confirm: "Are you sure?" }) end end end end end xml.table("class" => "table is-bordered is-striped is-narrow is-hoverable is-fullwidth") do xml.thead do xml.tr end xml.tbody do @posts.each do |post| xml.tr end end end xml.table("class" => "table is-bordered is-striped is-narrow is-hoverable is-fullwidth") do xml.thead do xml.tr do xml.th end end xml.tbody do @posts.each do |post| xml.tr do xml.td do xml << link_to(post.XXX, edit_post_path(post)) end end end end end xml.div("class" => "columns") do xml.div("class" => "column is-half") do xml << simple_form_for(@post || Post.new, defaults: { wrapper: false }) do |form| xml << form.input(:title, label: 'Title') xml << form.input(:author, label: 'Writer') xml << form.input(:published, wrapper: :boolean, label: 'Published') xml << form.input(:credits, as: :numeric, label: 'Credits') xml.div("class" => "field") do xml.div("class" => "control") do xml << form.submit(class: 'button is-link') end end end end end xml << link_to("New Post", new_post_path)
22.753086
127
0.537168
d5bb21c7f1cd8f85115c01c828a74a51aa1ff6d9
2,524
class Composers::CLI attr_accessor :url, :input def call puts "********************** WANT TO LEARN MORE ABOUT COMPOSERS? *******************" start end def to_number(letter) number = letter.tr("A-Z", "1-9a-q").to_i(25) if number > 20 number -= 1 else number end end def start input = nil puts "******************** Type your favorite letter from the alphabet:************* " puts "******************** C'mon it can't be that hard...*************************** " puts "********* Actually, any letter but 'U'! You still have 25 choices! *********** " puts "********** Enter exit to end. Or not, if you're enjoying this :D ************* " input = gets.strip.upcase if input == 'EXIT' puts "Buh-Bye! Remember to listen to some Bach :))" exit! elsif input == "U" puts "******************************** HOW COULD YOU! ******************************" puts "******************************** Outrageous ********************************" puts "****************** I told you not to! You've betrayed me. ********************" puts '' puts '' puts "*************** I'm so nice, I'll still give you another try'. ***************" puts '' puts '' start elsif input.length == 1 @input = to_number(input[0]) Composers::Scraper.list_of_composers(@input) composer_choice elsif input.length > 1 puts "Now, now, try that again." start end puts "Buh-Bye! Remember to listen to some Bach :)" end def composer_choice puts "Now, choose the person you want to learn more about by typing the corresponding number of that composer." num = gets.strip if num.to_i != 0 && num.to_i <= Composers::Scraper.collection.length Composers::Scraper.profile_url(@input, num) Composers::Scraper.composer_profile(@url) # Here is where we are calling the #display_all method. How could we change # this if we were dealing with just an instance of a Composer. We would want something like: # composer = Composer.new or Composer.last or something.. then we could just call # composer.display_all Composers::Composer.display_all puts "Wanna learn more about another composer?" start elsif num == 'exit' puts "Parting is such sweet sorrow that I shall say goodnight till it be morrow." else puts "Hmmm... can you enter that again?" composer_choice end end end
35.549296
115
0.540412
7a1247b6dd4134c33a2a4e0117be25080db99096
2,887
require 'spec_helper' describe 'murano::cfapi' do let(:params) do { :tenant => 'admin', } end shared_examples_for 'murano-cfapi' do it { is_expected.to contain_class('murano::cfapi') } end shared_examples_for 'with default parameters' do it { is_expected.to contain_class('murano::deps') } it { is_expected.to contain_class('murano::params') } it { is_expected.to contain_class('murano::policy') } it { is_expected.to contain_murano_cfapi_config('cfapi/tenant').with_value('admin') } it { is_expected.to contain_murano_cfapi_config('cfapi/bind_host').with_value('<SERVICE DEFAULT>') } it { is_expected.to contain_murano_cfapi_config('cfapi/bind_port').with_value('<SERVICE DEFAULT>') } it { is_expected.to contain_murano_cfapi_config('cfapi/auth_url').with_value('http://127.0.0.1:5000') } it { is_expected.to contain_murano_cfapi_config('cfapi/user_domain_name').with_value('<SERVICE DEFAULT>') } it { is_expected.to contain_murano_cfapi_config('cfapi/project_domain_name').with_value('<SERVICE DEFAULT>') } end shared_examples_for 'with parameters override' do let :params do { :tenant => 'services', :bind_host => '0.0.0.0', :bind_port => 8080, :auth_url => 'http://127.0.0.1:5000/v3/', } end it { is_expected.to contain_class('murano::params') } it { is_expected.to contain_class('murano::policy') } it { is_expected.to contain_murano_cfapi_config('cfapi/tenant').with_value('services') } it { is_expected.to contain_murano_cfapi_config('cfapi/bind_host').with_value('0.0.0.0') } it { is_expected.to contain_murano_cfapi_config('cfapi/bind_port').with_value(8080) } it { is_expected.to contain_murano_cfapi_config('cfapi/auth_url').with_value('http://127.0.0.1:5000/v3/') } end on_supported_os({ :supported_os => OSDefaults.get_supported_os }).each do |os,facts| context "on #{os}" do let (:facts) do facts.merge!(OSDefaults.get_facts({ :concat_basedir => '/var/lib/puppet/concat' })) end it_behaves_like 'murano-cfapi' it_behaves_like 'with default parameters' it_behaves_like 'with parameters override' case facts[:osfamily] when 'RedHat' it_behaves_like 'generic murano service', { :name => 'murano-cfapi', :package_name => 'openstack-murano-cf-api', :service_name => 'murano-cf-api', :extra_params => { :tenant => 'admin', }, } when 'Debian' it_behaves_like 'generic murano service', { :name => 'murano-cfapi', :package_name => 'murano-cfapi', :service_name => 'murano-cfapi', :extra_params => { :tenant => 'admin', }, } end end end end
34.783133
114
0.63353
edde1f755eca1ee4102bd6175cf0b9bc9614b9e3
1,639
# frozen_string_literal: true module ActiveEntity module Type class Serialized < DelegateClass(ActiveModel::Type::Value) # :nodoc: undef to_yaml if method_defined?(:to_yaml) include ActiveModel::Type::Helpers::Mutable attr_reader :subtype, :coder def initialize(subtype, coder) @subtype = subtype @coder = coder super(subtype) end def deserialize(value) if default_value?(value) value else coder.load(super) end end def serialize(value) return if value.nil? unless default_value?(value) super coder.dump(value) end end def inspect Kernel.instance_method(:inspect).bind(self).call end def changed_in_place?(raw_old_value, value) return false if value.nil? raw_new_value = encoded(value) raw_old_value.nil? != raw_new_value.nil? || subtype.changed_in_place?(raw_old_value, raw_new_value) end def accessor ActiveEntity::Store::IndifferentHashAccessor end def assert_valid_value(value) if coder.respond_to?(:assert_valid_value) coder.assert_valid_value(value, action: "serialize") end end def force_equality?(value) coder.respond_to?(:object_class) && value.is_a?(coder.object_class) end private def default_value?(value) value == coder.load(nil) end def encoded(value) unless default_value?(value) coder.dump(value) end end end end end
22.763889
75
0.605247
62b5b48489cca35b74124f540d1a9292ee515788
961
require "logstash/namespace" require "logstash/event" require "logstash/plugin" require "logstash/logging" # This is the base class for logstash codecs. module LogStash::Codecs class Base < LogStash::Plugin include LogStash::Config::Mixin config_name "codec" def initialize(params={}) super config_init(params) register if respond_to?(:register) end public def decode(data) raise "#{self.class}#decode must be overidden" end # def decode alias_method :<<, :decode public def encode(data) raise "#{self.class}#encode must be overidden" end # def encode public def teardown; end; public def on_event(&block) @on_event = block end public def flush(&block) # does nothing by default. # if your codec needs a flush method (like you are spooling things) # you must implement this. end end # class LogStash::Codecs::Base end
20.891304
73
0.655567
e2fd51d2c295f46ec2ed3ae11eefb191f0f8be0b
400
# encoding: UTF-8 require_relative 'spec_helper' describe 'openstack-compute::client' do describe 'redhat' do let(:runner) { ChefSpec::Runner.new(REDHAT_OPTS) } let(:node) { runner.node } let(:chef_run) do runner.converge(described_recipe) end it 'upgrades python-novaclient package' do expect(chef_run).to upgrade_package('python-novaclient') end end end
21.052632
62
0.695
d5f32885409dd7aa1afec4a4945f4aceb6bb5189
517
module HealthSeven::V2_5_1 class MfnM15 < ::HealthSeven::Message attribute :msh, Msh, position: "MSH", require: true attribute :sfts, Array[Sft], position: "SFT", multiple: true attribute :mfi, Mfi, position: "MFI", require: true class MfInvItem < ::HealthSeven::SegmentGroup attribute :mfe, Mfe, position: "MFE", require: true attribute :iim, Iim, position: "IIM", require: true end attribute :mf_inv_items, Array[MfInvItem], position: "MFN_M15.MF_INV_ITEM", require: true, multiple: true end end
43.083333
107
0.723404
79ba45d728e6ca42d0be7bf9d081bea3feed4c98
809
require 'bio-ucsc' describe "Bio::Ucsc::Hg19::WgEncodeUwDnaseHconfPkRep1" do describe "#find_by_interval" do context "given range chr1:1-800,000" do it "returns an array of records" do Bio::Ucsc::Hg19::DBConnection.default Bio::Ucsc::Hg19::DBConnection.connect i = Bio::GenomicInterval.parse("chr1:1-800,000") r = Bio::Ucsc::Hg19::WgEncodeUwDnaseHconfPkRep1.find_all_by_interval(i) r.should have(14).items end it 'returns a record (r.chrom == "chr1")' do Bio::Ucsc::Hg19::DBConnection.default Bio::Ucsc::Hg19::DBConnection.connect i = Bio::GenomicInterval.parse("chr1:1-800,000") r = Bio::Ucsc::Hg19::WgEncodeUwDnaseHconfPkRep1.find_by_interval(i) r.chrom.should == "chr1" end end end end
32.36
79
0.648949
e289f4ce8fbb4078cbde4fe310ff0db7ac09dfe0
1,142
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'version' Gem::Specification.new do |spec| spec.name = 'idempotent-request' spec.version = IdempotentRequest::VERSION spec.authors = ['Dmytro Zakharov'] spec.email = ['[email protected]'] spec.summary = %q{Rack middleware ensuring at most once requests for mutating endpoints.} spec.homepage = 'https://github.com/qonto/idempotent-request' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.add_dependency 'rack', '~> 2.0' spec.add_dependency 'oj', '~> 3.0' spec.add_development_dependency 'bundler', '~> 1.15' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec', '~> 3.0' spec.add_development_dependency 'fakeredis', '~> 0.6' spec.add_development_dependency 'pry', '~> 0.11' end
35.6875
97
0.651489
6ac5bb907061545040cf9bf8a8c50d7a3fd28623
4,399
# frozen_string_literal: true class Projects::MergeRequests::CreationsController < Projects::MergeRequests::ApplicationController include DiffForPath include DiffHelper include RendersCommits skip_before_action :merge_request before_action :whitelist_query_limiting, only: [:create] before_action :authorize_create_merge_request_from! before_action :apply_diff_view_cookie!, only: [:diffs, :diff_for_path] before_action :build_merge_request, except: [:create] def new # n+1: https://gitlab.com/gitlab-org/gitlab-ce/issues/40934 Gitlab::GitalyClient.allow_n_plus_1_calls do define_new_vars end end def create @target_branches ||= [] @merge_request = ::MergeRequests::CreateService.new(project, current_user, merge_request_params).execute if @merge_request.valid? incr_count_webide_merge_request redirect_to(merge_request_path(@merge_request)) else @source_project = @merge_request.source_project @target_project = @merge_request.target_project define_new_vars render action: "new" end end def pipelines @pipelines = @merge_request.all_pipelines Gitlab::PollingInterval.set_header(response, interval: 10_000) render json: { pipelines: PipelineSerializer .new(project: @project, current_user: @current_user) .represent(@pipelines) } end def diffs @diffs = @merge_request.diffs(diff_options) if @merge_request.can_be_created @diff_notes_disabled = true @environment = @merge_request.environments_for(current_user).last render json: { html: view_to_html_string('projects/merge_requests/creations/_diffs', diffs: @diffs, environment: @environment) } end def diff_for_path @diffs = @merge_request.diffs(diff_options) @diff_notes_disabled = true render_diff_for_path(@diffs) end def branch_from # This is always source @source_project = @merge_request.nil? ? @project : @merge_request.source_project if params[:ref].present? @ref = params[:ref] @commit = @repository.commit(Gitlab::Git::BRANCH_REF_PREFIX + @ref) end render layout: false end def branch_to @target_project = selected_target_project if @target_project && params[:ref].present? @ref = params[:ref] @commit = @target_project.commit(Gitlab::Git::BRANCH_REF_PREFIX + @ref) end render layout: false end private def build_merge_request params[:merge_request] ||= ActionController::Parameters.new(source_project: @project) # Gitaly N+1 issue: https://gitlab.com/gitlab-org/gitlab-ce/issues/58096 Gitlab::GitalyClient.allow_n_plus_1_calls do @merge_request = ::MergeRequests::BuildService.new(project, current_user, merge_request_params.merge(diff_options: diff_options)).execute end end def define_new_vars @noteable = @merge_request @target_branches = if @merge_request.target_project @merge_request.target_project.repository.branch_names else [] end @target_project = @merge_request.target_project @source_project = @merge_request.source_project @commits = set_commits_for_rendering(@merge_request.commits) @commit = @merge_request.diff_head_commit # FIXME: We have to assign a presenter to another instance variable # due to class_name checks being made with issuable classes @mr_presenter = @merge_request.present(current_user: current_user) @labels = LabelsFinder.new(current_user, project_id: @project.id).execute set_pipeline_variables end # rubocop: disable CodeReuse/ActiveRecord def selected_target_project if @project.id.to_s == params[:target_project_id] || [email protected]? @project elsif params[:target_project_id].present? MergeRequestTargetProjectFinder.new(current_user: current_user, source_project: @project) .find_by(id: params[:target_project_id]) else @project.forked_from_project end end # rubocop: enable CodeReuse/ActiveRecord def whitelist_query_limiting Gitlab::QueryLimiting.whitelist('https://gitlab.com/gitlab-org/gitlab-ce/issues/42384') end def incr_count_webide_merge_request return if params[:nav_source] != 'webide' Gitlab::UsageDataCounters::WebIdeCounter.increment_merge_requests_count end end
29.92517
143
0.726983
26369487cca222c3185c5955f4f817b653a0cb2b
529
# Deploy related custom tasks namespace :deploy do desc 'Initial Deploy' task :initial do on roles(:app) do before 'deploy:restart', 'puma:start' invoke 'deploy' end end desc 'Restart application' task :restart do on roles(:app), in: :sequence, wait: 5 do invoke 'puma:restart' end end desc 'Deploys the front end' task :front do on roles(:app) do execute "#{shared_path}/scripts/deploy_front.sh #{fetch(:front_path)}" end end after :finishing, :cleanup end
19.592593
76
0.648393
4af47cd8c1b902d9f6c1f4ea513cf7973a33f4ce
280
ITERATIONS = 5_000_000 def harness_input f = FutureImplementation.new f.fulfill 1 f end def harness_sample(input) sum = 0 ITERATIONS.times do sum += input.value end sum end def harness_verify(output) output == ITERATIONS end require 'bench9000/harness'
11.2
30
0.721429
61a44cf95d52a5709abc0c73c6a1bed5a2072557
4,046
$: << '.' require File.dirname(__FILE__) + '/../test_helper' class OrderAddressTest < ActiveSupport::TestCase fixtures :users fixtures :order_addresses, :order_users, :countries # Test if a valid address can be created with success. def test_should_create_address an_address = OrderAddress.new an_address.order_user = order_users(:mustard) an_address.first_name = "Colonel" an_address.last_name = "Mustard" an_address.telephone = "000000000" an_address.address = "After Boddy Mansion at right" an_address.city = "London" an_address.state = "Greater London" an_address.zip = "00000" an_address.country = countries(:GB) assert an_address.save end # Test if a address can be found with success. def test_should_find_address an_address_id = order_addresses(:santa_address).id assert_nothing_raised { OrderAddress.find(an_address_id) } end def test_country_not_nil an_address = OrderAddress.find(order_addresses(:santa_address).id) assert_not_nil an_address.country end # Test if a address can be updated with success. def test_should_update_address an_address = order_addresses(:santa_address) assert an_address.update_attributes(:address => 'After third ice mountain at left') end # Test if a address can be destroyed with success. def test_should_destroy_address an_address = order_addresses(:santa_address) an_address.destroy assert_raise(ActiveRecord::RecordNotFound) { OrderAddress.find(an_address.id) } end # Test if an invalid address really will NOT be created. def test_should_not_create_invalid_address an_address = OrderAddress.new assert !an_address.valid? #assert an_address.errors.invalid?(:order_user_id), "Should have an error in order_user_id" #assert an_address.errors.invalid?(:country_id), "Should have an error in country_id" assert an_address.errors.invalid?(:zip), "Should have an error in zip" assert an_address.errors.invalid?(:telephone), "Should have an error in telephone" assert an_address.errors.invalid?(:first_name), "Should have an error in first_name" assert an_address.errors.invalid?(:last_name), "Should have an error in last_name" assert an_address.errors.invalid?(:address), "Should have an error in address" # An address must have the fields filled. assert_equal "#{ERROR_EMPTY} If you live in a country that doesn't have postal codes please enter '00000'.", an_address.errors.on(:zip) assert_equal ERROR_EMPTY, an_address.errors.on(:telephone) assert_equal ERROR_EMPTY, an_address.errors.on(:first_name) assert_equal ERROR_EMPTY, an_address.errors.on(:last_name) assert_equal ERROR_EMPTY, an_address.errors.on(:address) an_address.address = "P.O. BOX" assert !an_address.valid? assert_equal "Sorry, we don't ship to P.O. boxes", an_address.errors.on(:address) # TODO: The address is being saved even when not associated with an user or a country. # an_address.first_name = "Colonel" # an_address.last_name = "Mustard" # an_address.telephone = "000000000" # an_address.address = "After Boddy Mansion at right" # an_address.zip = "00000" # TODO: Why try to validate P. O. Boxes? assert !an_address.save end # TODO: Get rid of this method if it will not be used. # Test if a shipping address can be found for an user. def test_should_find_shipping_address # find_shipping_address_for_user appears to be a deprecated method, as when # executed it gives an error, and I couldn't find an ocasion where it will be executed. assert_raise(ActiveRecord::StatementInvalid) { OrderAddress.find_shipping_address_for_user(users(:c_norris)) } end # Test if the user's first and last name will be concatenated. def test_should_concatenate_user_first_and_last_name an_address = order_addresses(:santa_address) assert_equal an_address.name, "#{an_address.first_name} #{an_address.last_name}" end end
35.80531
139
0.737519
262a535aac2427a35796929c41fc620a18f42049
15,240
# # Cookbook:: ark # Resource:: Ark # # Author:: Bryan W. Berry <[email protected]> # Copyright:: 2012-2017, Bryan W. Berry # Copyright:: 2016-2017, Chef Software 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. # property :owner, String property :group, [String, Integer], default: 0 property :url, String, required: true property :path, String property :full_path, String property :append_env_path, [true, false], default: false property :checksum, String, regex: /^[a-zA-Z0-9]{64}$/ property :has_binaries, Array, default: [] property :creates, String property :release_file, String, default: '' property :strip_leading_dir, [true, false, NilClass] property :strip_components, Integer, default: 1 property :mode, [Integer, String], default: 0755 property :prefix_root, String property :prefix_home, String property :prefix_bin, String property :version, String property :home_dir, String property :win_install_dir, String property :environment, Hash, default: {} property :autoconf_opts, Array, default: [] property :make_opts, Array, default: [] property :home_dir, String property :autoconf_opts, Array, default: [] property :extension, String property :backup, [FalseClass, Integer], default: 5 unified_mode true ################# # action :install ################# action :install do show_deprecations set_paths directory new_resource.path do recursive true action :create notifies :run, "execute[unpack #{new_resource.release_file}]" end remote_file new_resource.release_file do Chef::Log.debug('DEBUG: new_resource.release_file') source new_resource.url checksum new_resource.checksum if new_resource.checksum action :create notifies :run, "execute[unpack #{new_resource.release_file}]" backup new_resource.backup end # unpack based on file extension execute "unpack #{new_resource.release_file}" do command unpack_command cwd new_resource.path environment new_resource.environment notifies :run, "execute[set owner on #{new_resource.path}]" action :nothing end # set_owner execute "set owner on #{new_resource.path}" do command owner_command action :nothing end if platform_family?('windows') # usually on windows there is no central directory with executables where the applications are linked # so ignore has_binaries for now # Add to PATH permanently on Windows if append_env_path windows_path "#{new_resource.path}/bin" do action :add only_if { new_resource.append_env_path } end else # symlink binaries new_resource.has_binaries.each do |bin| link ::File.join(new_resource.prefix_bin, ::File.basename(bin)) do to ::File.join(new_resource.path, bin) end end # action_link_paths link new_resource.home_dir do to new_resource.path end # This directory doesn't exist by default on MacOS directory '/etc/profile.d' if platform_family?('mac_os_x') # Add to path for interactive bash sessions template "/etc/profile.d/#{new_resource.name}.sh" do cookbook 'ark' source 'add_to_path.sh.erb' owner 'root' group node['root_group'] mode '0755' cookbook 'ark' variables(directory: "#{new_resource.path}/bin") only_if { new_resource.append_env_path } end end # Add to path for the current chef-client converge. bin_path = ::File.join(new_resource.path, 'bin') ruby_block "adding '#{bin_path}' to chef-client ENV['PATH']" do block do ENV['PATH'] = bin_path + ':' + ENV['PATH'] end only_if do new_resource.append_env_path && ENV['PATH'].scan(bin_path).empty? end end end ############## # action :put ############## action :put do show_deprecations set_put_paths directory new_resource.path do recursive true action :create notifies :run, "execute[unpack #{new_resource.release_file}]" end # download remote_file new_resource.release_file do source new_resource.url checksum new_resource.checksum if new_resource.checksum action :create notifies :run, "execute[unpack #{new_resource.release_file}]" backup new_resource.backup end # unpack based on file extension execute "unpack #{new_resource.release_file}" do command unpack_command cwd new_resource.path environment new_resource.environment notifies :run, "execute[set owner on #{new_resource.path}]" action :nothing end # set_owner execute "set owner on #{new_resource.path}" do command owner_command action :nothing end end ########################### # action :dump ########################### action :dump do show_deprecations set_dump_paths directory new_resource.path do recursive true action :create notifies :run, "execute[unpack #{new_resource.release_file}]" end # download remote_file new_resource.release_file do Chef::Log.debug("DEBUG: new_resource.release_file #{new_resource.release_file}") source new_resource.url checksum new_resource.checksum if new_resource.checksum action :create notifies :run, "execute[unpack #{new_resource.release_file}]" end # unpack based on file extension execute "unpack #{new_resource.release_file}" do command dump_command cwd new_resource.path environment new_resource.environment notifies :run, "execute[set owner on #{new_resource.path}]" action :nothing end # set_owner execute "set owner on #{new_resource.path}" do command owner_command action :nothing end end ########################### # action :unzip ########################### action :unzip do show_deprecations set_dump_paths directory new_resource.path do recursive true action :create notifies :run, "execute[unpack #{new_resource.release_file}]" end # download remote_file new_resource.release_file do Chef::Log.debug("DEBUG: new_resource.release_file #{new_resource.release_file}") source new_resource.url checksum new_resource.checksum if new_resource.checksum action :create notifies :run, "execute[unpack #{new_resource.release_file}]" end # unpack based on file extension execute "unpack #{new_resource.release_file}" do command unzip_command cwd new_resource.path environment new_resource.environment notifies :run, "execute[set owner on #{new_resource.path}]" action :nothing end # set_owner execute "set owner on #{new_resource.path}" do command owner_command action :nothing end end ##################### # action :cherry_pick ##################### action :cherry_pick do show_deprecations set_dump_paths Chef::Log.debug("DEBUG: new_resource.creates #{new_resource.creates}") directory new_resource.path do recursive true action :create notifies :run, "execute[cherry_pick #{new_resource.creates} from #{new_resource.release_file}]" end # download remote_file new_resource.release_file do source new_resource.url checksum new_resource.checksum if new_resource.checksum action :create notifies :run, "execute[cherry_pick #{new_resource.creates} from #{new_resource.release_file}]" end execute "cherry_pick #{new_resource.creates} from #{new_resource.release_file}" do command cherry_pick_command creates "#{new_resource.path}/#{new_resource.creates}" notifies :run, "execute[set owner on #{new_resource.path}]" action :nothing end # set_owner execute "set owner on #{new_resource.path}" do command owner_command action :nothing end end ########################### # action :install_with_make ########################### action :install_with_make do show_deprecations set_paths directory new_resource.path do recursive true action :create notifies :run, "execute[unpack #{new_resource.release_file}]" end remote_file new_resource.release_file do Chef::Log.debug('DEBUG: new_resource.release_file') source new_resource.url checksum new_resource.checksum if new_resource.checksum action :create notifies :run, "execute[unpack #{new_resource.release_file}]" end # unpack based on file extension execute "unpack #{new_resource.release_file}" do command unpack_command cwd new_resource.path environment new_resource.environment notifies :run, "execute[set owner on #{new_resource.path}]" notifies :run, "execute[autogen #{new_resource.path}]" notifies :run, "execute[configure #{new_resource.path}]" notifies :run, "execute[make #{new_resource.path}]" notifies :run, "execute[make install #{new_resource.path}]" action :nothing end # set_owner execute "set owner on #{new_resource.path}" do command owner_command action :nothing end execute "autogen #{new_resource.path}" do command './autogen.sh' only_if { ::File.exist? "#{new_resource.path}/autogen.sh" } cwd new_resource.path environment new_resource.environment action :nothing ignore_failure true end execute "configure #{new_resource.path}" do command "./configure #{new_resource.autoconf_opts.join(' ')}" only_if { ::File.exist? "#{new_resource.path}/configure" } cwd new_resource.path environment new_resource.environment action :nothing end execute "make #{new_resource.path}" do command "make #{new_resource.make_opts.join(' ')}" cwd new_resource.path environment new_resource.environment action :nothing end execute "make install #{new_resource.path}" do command "make install #{new_resource.make_opts.join(' ')}" cwd new_resource.path environment new_resource.environment action :nothing end end action :setup_py_build do show_deprecations set_paths directory new_resource.path do recursive true action :create notifies :run, "execute[unpack #{new_resource.release_file}]" end remote_file new_resource.release_file do Chef::Log.debug('DEBUG: new_resource.release_file') source new_resource.url checksum new_resource.checksum if new_resource.checksum action :create notifies :run, "execute[unpack #{new_resource.release_file}]" end # unpack based on file extension execute "unpack #{new_resource.release_file}" do command unpack_command cwd new_resource.path environment new_resource.environment notifies :run, "execute[set owner on #{new_resource.path}]" notifies :run, "execute[python setup.py build #{new_resource.path}]" action :nothing end # set_owner execute "set owner on #{new_resource.path}" do command owner_command action :nothing end execute "python setup.py build #{new_resource.path}" do command "python setup.py build #{new_resource.make_opts.join(' ')}" cwd new_resource.path environment new_resource.environment action :nothing end end action :setup_py_install do show_deprecations set_paths directory new_resource.path do recursive true action :create notifies :run, "execute[unpack #{new_resource.release_file}]" end remote_file new_resource.release_file do Chef::Log.debug('DEBUG: new_resource.release_file') source new_resource.url checksum new_resource.checksum if new_resource.checksum action :create notifies :run, "execute[unpack #{new_resource.release_file}]" end # unpack based on file extension execute "unpack #{new_resource.release_file}" do command unpack_command cwd new_resource.path environment new_resource.environment notifies :run, "execute[set owner on #{new_resource.path}]" notifies :run, "execute[python setup.py install #{new_resource.path}]" action :nothing end # set_owner execute "set owner on #{new_resource.path}" do command owner_command action :nothing end execute "python setup.py install #{new_resource.path}" do command "python setup.py install #{new_resource.make_opts.join(' ')}" cwd new_resource.path environment new_resource.environment action :nothing end end action :setup_py do show_deprecations set_paths directory new_resource.path do recursive true action :create notifies :run, "execute[unpack #{new_resource.release_file}]" end remote_file new_resource.release_file do Chef::Log.debug('DEBUG: new_resource.release_file') source new_resource.url checksum new_resource.checksum if new_resource.checksum action :create notifies :run, "execute[unpack #{new_resource.release_file}]" end # unpack based on file extension execute "unpack #{new_resource.release_file}" do command unpack_command cwd new_resource.path environment new_resource.environment notifies :run, "execute[set owner on #{new_resource.path}]" notifies :run, "execute[python setup.py #{new_resource.path}]" action :nothing end # set_owner execute "set owner on #{new_resource.path}" do command owner_command action :nothing end execute "python setup.py #{new_resource.path}" do command "python setup.py #{new_resource.make_opts.join(' ')}" cwd new_resource.path environment new_resource.environment action :nothing end end action :configure do show_deprecations set_paths directory new_resource.path do recursive true action :create notifies :run, "execute[unpack #{new_resource.release_file}]" end remote_file new_resource.release_file do Chef::Log.debug('DEBUG: new_resource.release_file') source new_resource.url checksum new_resource.checksum if new_resource.checksum action :create notifies :run, "execute[unpack #{new_resource.release_file}]" end # unpack based on file extension execute "unpack #{new_resource.release_file}" do command unpack_command cwd new_resource.path environment new_resource.environment notifies :run, "execute[set owner on #{new_resource.path}]" notifies :run, "execute[autogen #{new_resource.path}]" notifies :run, "execute[configure #{new_resource.path}]" action :nothing end # set_owner execute "set owner on #{new_resource.path}" do command owner_command action :nothing end execute "autogen #{new_resource.path}" do command './autogen.sh' only_if { ::File.exist? "#{new_resource.path}/autogen.sh" } cwd new_resource.path environment new_resource.environment action :nothing ignore_failure true end execute "configure #{new_resource.path}" do command "./configure #{new_resource.autoconf_opts.join(' ')}" only_if { ::File.exist? "#{new_resource.path}/configure" } cwd new_resource.path environment new_resource.environment action :nothing end end action_class do include ::Ark::ProviderHelpers end
28.118081
105
0.715157
111d6e32b324c6a3cc3d5e1a801c6238d8ace704
1,556
class ConditionForeign < ConditionSimple WORDLESS_LANGUAGES = %i[ct cs kr jp de].to_set def initialize(lang, query) @lang = lang.downcase # Support both Gatherer and MCI naming conventions @lang = "ct" if @lang == "tw" @lang = "cs" if @lang == "cn" @lang = @lang.to_sym @lang_match_all = (@lang == :foreign) @query = hard_normalize(query) # For CJK match anywhere # For others match only word boundary if @query == "*" @query_any = true elsif cjk_query? or WORDLESS_LANGUAGES.include?(@lang) @query_regexp = compile_anywhere_match_regexp else @query_regexp = compile_word_match_regexp end end def match?(card) card.foreign_names_normalized.each do |lang, data| next unless @lang_match_all or lang == @lang # I don't think we can have empty here, it would be missing, # but check just in case if @query_any return true unless data.empty? else data.each do |n| return true if n =~ @query_regexp end end end false end def to_s "#{@lang}:#{maybe_quote(@query)}" end private def hard_normalize(s) s.unicode_normalize(:nfd).gsub(/\p{Mn}/, "").downcase end def cjk_query? @query =~ /\p{Han}|\p{Katakana}|\p{Hiragana}|\p{Hangul}/ end def compile_anywhere_match_regexp Regexp.new("(?:" + Regexp.escape(@query) + ")", Regexp::IGNORECASE) end def compile_word_match_regexp Regexp.new("\\b(?:" + Regexp.escape(@query) + ")\\b", Regexp::IGNORECASE) end end
25.508197
77
0.633033
1ddb9cf8d36d27766fae7d2f6faa5a2a28b7a548
2,052
require 'open-uri' require 'json' require 'fileutils' module EyesUtils EYES_ACCESS_KEY_ENV_NAME = 'EYES_ACCESS_KEY'.freeze TMP_UTIL_DIR = File.expand_path('../../../.tmputils', __FILE__).freeze MERGE_UTIL_PATH = "#{TMP_UTIL_DIR}/applitools-merge.jar".freeze REMOTE_JAR_SOURCE = 'https://s3.amazonaws.com/cdo-circle-utils/applitools-merge.jar'.freeze EYES_API_URL = "https://eyes.applitools.com/api/baselines/copybranch?accesskey=$#{EYES_ACCESS_KEY_ENV_NAME}".freeze BASE_MERGE_UTIL_CALL = "java -jar #{MERGE_UTIL_PATH} -url #{EYES_API_URL}".freeze def self.check_eyes_set raise "Must export env var $#{EYES_ACCESS_KEY_ENV_NAME} to run eyes commands." unless ENV[EYES_ACCESS_KEY_ENV_NAME] end def self.ensure_merge_util java_version_output = `java -version 2>&1` raise "Applitools merge util requires Java 1.8 #{Emoji.find_by_alias('sweat_smile').raw}" unless java_version_output =~ /version "1\.8/ unless File.exist? MERGE_UTIL_PATH Kernel.system("wget #{REMOTE_JAR_SOURCE} -O #{MERGE_UTIL_PATH}") end end def self.merge_eyes_baselines(branch, base) ensure_merge_util Kernel.system("#{BASE_MERGE_UTIL_CALL} -n Code.org -s #{branch} -t #{base}") end def self.force_merge_eyes_baselines(branch, base) ensure_merge_util Kernel.system("#{BASE_MERGE_UTIL_CALL} -n Code.org -o true -s #{branch} -t #{base}") end def self.copy_eyes_baselines(branch, base) ensure_merge_util Kernel.system("#{BASE_MERGE_UTIL_CALL} -n Code.org -c true -s #{branch} -t #{base}") end def self.force_copy_eyes_baselines(branch, base) ensure_merge_util Kernel.system("#{BASE_MERGE_UTIL_CALL} -n Code.org -o true -c true -s #{branch} -t #{base}") end def self.delete_eyes_branch(branch) ensure_merge_util Kernel.system("#{BASE_MERGE_UTIL_CALL} -n Code.org -s #{branch} -t #{branch} -d true") end def self.merge_delete_eyes_branch(branch, base) ensure_merge_util Kernel.system("#{BASE_MERGE_UTIL_CALL} -n Code.org -s #{branch} -t #{base} -d true") end end
36.642857
139
0.72807
aba602e94a0d794f171db084afb8418b58b5b703
421
FactoryBot.define do factory :profile do name { FFaker::Name.name } title { FFaker::Lorem.word } portfolio trait :with_photo do after :build do |portfolio| image = File.open(Rails.root.join('features', 'factories', 'images', 'portfolio-photo.png')) portfolio.photo.attach(io: image, filename: "profile-photo.png") end end end end
30.071429
102
0.586698
7a2f2e5623422e2220092b7d3ba31e6a0627cbe5
574
require 'spec_helper' require 'adventofcode/day_11/part_1' RSpec.describe(AdventOfCode::Day11::Part1) do describe('#run') do let(:challenge_input) { load_fixture('day_11.txt') } it('returns the correct answer for example one') do expect(subject.run('abcdefgh')).to eql('abcdffaa') end it('returns the correct answer for example two') do expect(subject.run('ghijklmn')).to eql('ghjaabcc') end it('returns the correct answer for the challenge input') do expect(subject.run(challenge_input)).to eql('hxbxxyzz') end end end
27.333333
63
0.69338
01d6d1283a5385818645604404adbf09303ab988
1,892
step "Install development build of PuppetDB on the PuppetDB server" do os = test_config[:os_families][database.name] case test_config[:install_type] when :git raise "No PUPPETDB_REPO_PUPPETDB set" unless test_config[:repo_puppetdb] case os when :redhat on database, "yum install -y git-core ruby rubygem-rake" when :debian on database, "apt-get install -y git-core ruby rake" else raise "OS #{os} not supported" end on database, "rm -rf #{GitReposDir}/puppetdb" repo = extract_repo_info_from(test_config[:repo_puppetdb].to_s) install_from_git database, GitReposDir, repo if (test_config[:database] == :postgres) install_postgres(database) end install_puppetdb_via_rake(database) start_puppetdb(database) install_puppetdb_termini_via_rake(master, database) when :package Log.notify("Installing puppetdb from package; install mode: '#{test_config[:install_mode].inspect}'") install_puppetdb(database, test_config[:database]) if test_config[:validate_package_version] validate_package_version(database) end install_puppetdb_termini(master, database) # The package should automatically start the service on debian. On redhat, # it doesn't. However, during test runs where we're doing package upgrades, # the redhat package *should* detect that the service was running before the # upgrade, and it should restart it automatically. # # That leaves the case where we're on a redhat box and we're running the # tests as :install only (as opposed to :upgrade). In that case we need # to start the service ourselves here. if test_config[:install_mode] == :install and os == :redhat start_puppetdb(database) else # make sure it got started by the package install/upgrade sleep_until_started(database) end end end
34.4
105
0.718816
3887c22b75327e8d627ffd497841f3444150e34b
6,686
RSpec.describe "Item management", type: :system do before do sign_in(@user) end let!(:url_prefix) { "/#{@organization.to_param}" } it "can create a new item as a user" do visit url_prefix + "/items/new" item_traits = attributes_for(:item) fill_in "Name", with: item_traits[:name] select BaseItem.last.name, from: "Base Item" click_button "Save" expect(page.find(".alert")).to have_content "added" end it "can create a new item with empty attributes as a user" do visit url_prefix + "/items/new" click_button "Save" expect(page.find(".alert")).to have_content "didn't work" end it "can update an existing item as a user" do item = create(:item) visit url_prefix + "/items/#{item.id}/edit" click_button "Save" expect(page.find(".alert")).to have_content "updated" end it "can update an existing item with empty attributes as a user" do item = create(:item) visit url_prefix + "/items/#{item.id}/edit" fill_in "Name", with: "" click_button "Save" expect(page.find(".alert")).to have_content "didn't work" end it "can filter the #index by base item as a user" do Item.delete_all create(:item, base_item: BaseItem.first) create(:item, base_item: BaseItem.last) visit url_prefix + "/items" select BaseItem.first.name, from: "filters_by_base_item" click_button "Filter" within "#tbl_items" do expect(page).to have_css("tbody tr", count: 1) end end it "can include inactive items in the results" do Item.delete_all create(:item, :inactive, name: "Inactive Item") create(:item, :active, name: "Active Item") visit url_prefix + "/items" expect(page).to have_text("Active Item") expect(page).to have_no_text("Inactive Item") page.check('include_inactive_items') click_button "Filter" expect(page).to have_text("Inactive Item") expect(page).to have_text("Active Item") end describe "destroying items" do subject { create(:item, name: "DELETEME", organization: @user.organization) } context "when an item has history" do before do create(:donation, :with_items, item: subject) end it "can be soft-deleted (deactivated) by the user" do expect do visit url_prefix + "/items" expect(page).to have_content(subject.name) within "tr[data-item-id='#{subject.id}']" do accept_confirm do click_on "Delete", match: :first end end page.find(".alert-info") end.to change { Item.count }.by(0).and change { Item.active.count }.by(-1) subject.reload expect(subject).not_to be_active end end context "when an item does not have history" do it "can be fully deleted by the user" do subject expect do visit url_prefix + "/items" expect(page).to have_content(subject.name) within "tr[data-item-id='#{subject.id}']" do accept_confirm do click_on "Delete", match: :first end end page.find(".alert-info") end.to change { Item.count }.by(-1).and change { Item.active.count }.by(-1) expect { subject.reload }.to raise_error(ActiveRecord::RecordNotFound) end end end describe "restoring items" do let!(:item) { create(:item, :inactive, name: "DELETED") } it "allows a user to restore the item" do expect do visit url_prefix + "/items" check "include_inactive_items" click_on "Filter" within "#tbl_items" do expect(page).to have_content(item.name) end within "tr[data-item-id='#{item.id}']" do accept_confirm do click_on "Restore", match: :first end end page.find(".alert-info") end.to change { Item.count }.by(0).and change { Item.active.count }.by(1) item.reload expect(item).to be_active end end describe "Item Table Tabs >" do let(:item_pullups) { create(:item, name: "the most wonderful magical pullups that truly potty train", category: "Magic Toddlers") } let(:item_tampons) { create(:item, name: "blackbeard's rugged tampons", category: "Menstrual Products") } let(:storage_name) { "the poop catcher warehouse" } let(:storage) { create(:storage_location, :with_items, item: item_pullups, item_quantity: num_pullups_in_donation, name: storage_name) } let!(:aux_storage) { create(:storage_location, :with_items, item: item_pullups, item_quantity: num_pullups_second_donation, name: "a secret secondary location") } let(:num_pullups_in_donation) { 666 } let(:num_pullups_second_donation) { 1 } let(:num_tampons_in_donation) { 42 } let(:num_tampons_second_donation) { 17 } let!(:donation_tampons) { create(:donation, :with_items, storage_location: storage, item_quantity: num_tampons_in_donation, item: item_tampons) } let!(:donation_aux_tampons) { create(:donation, :with_items, storage_location: aux_storage, item_quantity: num_tampons_second_donation, item: item_tampons) } before do visit url_prefix + "/items" end # Consolidated these into one to reduce the setup/teardown it "should display items in separate tabs", js: true do tab_items_only_text = page.find("table#tbl_items", visible: true).text expect(tab_items_only_text).not_to have_content "Quantity" expect(tab_items_only_text).to have_content item_pullups.name expect(tab_items_only_text).to have_content item_tampons.name click_link "Items, Quantity, and Location" # href="#sectionC" tab_items_quantity_location_text = page.find("table#tbl_items_location", visible: true).text expect(tab_items_quantity_location_text).to have_content "Quantity" expect(tab_items_quantity_location_text).to have_content storage_name expect(tab_items_quantity_location_text).to have_content num_pullups_in_donation expect(tab_items_quantity_location_text).to have_content num_pullups_second_donation expect(tab_items_quantity_location_text).to have_content num_pullups_in_donation + num_pullups_second_donation expect(tab_items_quantity_location_text).to have_content num_tampons_in_donation expect(tab_items_quantity_location_text).to have_content num_tampons_second_donation expect(tab_items_quantity_location_text).to have_content num_tampons_in_donation + num_tampons_second_donation expect(tab_items_quantity_location_text).to have_content item_pullups.name expect(tab_items_quantity_location_text).to have_content item_tampons.name end end end
40.277108
166
0.685761
abbdaf8e2027987c014d216fd8c30e6b30db5265
1,069
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "workbook_rails/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "workbook_rails" s.version = WorkbookRails::VERSION s.authors = ["Noel Peden"] s.email = ["[email protected]"] s.homepage = "https://github.com/Programatica/workbook_rails" s.summary = "A simple rails plugin to provide an spreadsheet renderer using the workbook gem." s.description = "Workbook_Rails provides a Workbook renderer so you can move all your spreadsheet code from your controller into view files. Partials are supported so you can organize any code into reusable chunks (e.g. cover sheets, common styling, etc.) Now you can keep your controllers thin!" s.files = Dir["{app,config,db,lib}/**/*"] + Dir['[A-Z]*'] s.test_files = Dir["spec/**/*"] s.add_dependency "actionpack", ">= 3.2" s.add_dependency "workbook", ">= 0.4.10" s.add_development_dependency "bundler" s.add_development_dependency "rake" end
42.76
298
0.706268
5d1d4ffad70ab23a642527cd49a8da07c193f88c
1,312
# -*- encoding: utf-8 -*- # stub: rb-inotify 0.9.8 ruby lib Gem::Specification.new do |s| s.name = "rb-inotify".freeze s.version = "0.9.8" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["Nathan Weizenbaum".freeze] s.date = "2017-01-26" s.description = "A Ruby wrapper for Linux's inotify, using FFI".freeze s.email = "[email protected]".freeze s.extra_rdoc_files = ["README.md".freeze] s.files = ["README.md".freeze] s.homepage = "http://github.com/nex3/rb-inotify".freeze s.rubygems_version = "2.6.6".freeze s.summary = "A Ruby wrapper for Linux's inotify, using FFI".freeze s.installed_by_version = "2.6.6" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<ffi>.freeze, [">= 0.5.0"]) s.add_development_dependency(%q<yard>.freeze, [">= 0.4.0"]) else s.add_dependency(%q<ffi>.freeze, [">= 0.5.0"]) s.add_dependency(%q<yard>.freeze, [">= 0.4.0"]) end else s.add_dependency(%q<ffi>.freeze, [">= 0.5.0"]) s.add_dependency(%q<yard>.freeze, [">= 0.4.0"]) end end
35.459459
112
0.65625
bb4b8191216df0805177a3687ebaa9b2caebab10
45
module StandardTasks VERSION = "0.0.1" end
11.25
20
0.711111
1d83caf05d95b15edf0180eb90a66d664be88132
1,152
class Libreplaygain < Formula desc "Library to implement ReplayGain standard for audio" homepage "https://www.musepack.net/" url "https://files.musepack.net/source/libreplaygain_r475.tar.gz" version "r475" sha256 "8258bf785547ac2cda43bb195e07522f0a3682f55abe97753c974609ec232482" bottle do cellar :any rebuild 1 sha256 "13df0590c2056af8071e5c182bc1b73cfd52b6ad7afb561d16a1ac3ddf0df179" => :mojave sha256 "c2d3becfcd2f629fb875b6d6c907505489381e5ea3893b0a882510ebbee9951a" => :high_sierra sha256 "d8f7cfc1bfad75b97271300a16f5c927849b03ff488141423ecf48b25c6ed8c3" => :sierra sha256 "58b52d360c2f37f3ab3a50c4a2fe72b9a370bd951d52939f8853a5ef49fcc322" => :el_capitan sha256 "d47338c5b86daabf3e2e05ab9dd2443c04c1233f3319307e8e5d545b24dcf722" => :yosemite sha256 "dc3f2c3823c5552bddad7b1727b9086dc2fe79e8fa13987b420d1621c97e2bce" => :mavericks sha256 "4ce4390dc0c3ba503381bf256b942207dc706fc2e8e9e464aceb7ecf916f9841" => :mountain_lion end depends_on "cmake" => :build def install system "cmake", ".", *std_cmake_args system "make", "install" include.install "include/replaygain/" end end
41.142857
95
0.802083
ac718d2e5089125a6b7c6ed1089746882109b516
1,166
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{eb_nested_set} s.version = "0.3.5" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Jonas Nicklas"] s.autorequire = %q{eb_nested_set} s.date = %q{2009-02-16} s.description = %q{A cool acts_as_nested_set alternative} s.email = %q{[email protected]} s.extra_rdoc_files = ["README.md", "LICENSE"] s.files = ["LICENSE", "README.md", "Rakefile", "init.rb", "lib/eb_nested_set.rb", "spec/db", "spec/db/test.sqlite3", "spec/directory_spec.rb", "spec/employee_spec.rb", "spec/nested_set_behavior.rb", "spec/spec_helper.rb"] s.has_rdoc = true s.homepage = %q{http://github.com/jnicklas/even_better_nested_set/tree/master} s.require_paths = ["lib"] s.rubygems_version = %q{1.3.1} s.summary = %q{A cool acts_as_nested_set alternative} if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 2 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then else end else end end
37.612903
223
0.700686
4a4cd093435ef1ab35fcc2050a9c01f96699ace5
8,113
require 'spec_helper' describe Issue, "Issuable" do let(:issue) { create(:issue) } let(:user) { create(:user) } describe "Associations" do it { is_expected.to belong_to(:project) } it { is_expected.to belong_to(:author) } it { is_expected.to belong_to(:assignee) } it { is_expected.to have_many(:notes).dependent(:destroy) } it { is_expected.to have_many(:todos).dependent(:destroy) } end describe "Validation" do before do allow(subject).to receive(:set_iid).and_return(false) end it { is_expected.to validate_presence_of(:project) } it { is_expected.to validate_presence_of(:iid) } it { is_expected.to validate_presence_of(:author) } it { is_expected.to validate_presence_of(:title) } it { is_expected.to validate_length_of(:title).is_at_least(0).is_at_most(255) } end describe "Scope" do it { expect(described_class).to respond_to(:opened) } it { expect(described_class).to respond_to(:closed) } it { expect(described_class).to respond_to(:assigned) } end describe ".search" do let!(:searchable_issue) { create(:issue, title: "Searchable issue") } it 'returns notes with a matching title' do expect(described_class.search(searchable_issue.title)). to eq([searchable_issue]) end it 'returns notes with a partially matching title' do expect(described_class.search('able')).to eq([searchable_issue]) end it 'returns notes with a matching title regardless of the casing' do expect(described_class.search(searchable_issue.title.upcase)). to eq([searchable_issue]) end end describe ".full_search" do let!(:searchable_issue) do create(:issue, title: "Searchable issue", description: 'kittens') end it 'returns notes with a matching title' do expect(described_class.full_search(searchable_issue.title)). to eq([searchable_issue]) end it 'returns notes with a partially matching title' do expect(described_class.full_search('able')).to eq([searchable_issue]) end it 'returns notes with a matching title regardless of the casing' do expect(described_class.full_search(searchable_issue.title.upcase)). to eq([searchable_issue]) end it 'returns notes with a matching description' do expect(described_class.full_search(searchable_issue.description)). to eq([searchable_issue]) end it 'returns notes with a partially matching description' do expect(described_class.full_search(searchable_issue.description)). to eq([searchable_issue]) end it 'returns notes with a matching description regardless of the casing' do expect(described_class.full_search(searchable_issue.description.upcase)). to eq([searchable_issue]) end end describe "#today?" do it "returns true when created today" do # Avoid timezone differences and just return exactly what we want allow(Date).to receive(:today).and_return(issue.created_at.to_date) expect(issue.today?).to be_truthy end it "returns false when not created today" do allow(Date).to receive(:today).and_return(Date.yesterday) expect(issue.today?).to be_falsey end end describe "#new?" do it "returns true when created today and record hasn't been updated" do allow(issue).to receive(:today?).and_return(true) expect(issue.new?).to be_truthy end it "returns false when not created today" do allow(issue).to receive(:today?).and_return(false) expect(issue.new?).to be_falsey end it "returns false when record has been updated" do allow(issue).to receive(:today?).and_return(true) issue.touch expect(issue.new?).to be_falsey end end describe '#subscribed?' do context 'user is not a participant in the issue' do before { allow(issue).to receive(:participants).with(user).and_return([]) } it 'returns false when no subcription exists' do expect(issue.subscribed?(user)).to be_falsey end it 'returns true when a subcription exists and subscribed is true' do issue.subscriptions.create(user: user, subscribed: true) expect(issue.subscribed?(user)).to be_truthy end it 'returns false when a subcription exists and subscribed is false' do issue.subscriptions.create(user: user, subscribed: false) expect(issue.subscribed?(user)).to be_falsey end end context 'user is a participant in the issue' do before { allow(issue).to receive(:participants).with(user).and_return([user]) } it 'returns false when no subcription exists' do expect(issue.subscribed?(user)).to be_truthy end it 'returns true when a subcription exists and subscribed is true' do issue.subscriptions.create(user: user, subscribed: true) expect(issue.subscribed?(user)).to be_truthy end it 'returns false when a subcription exists and subscribed is false' do issue.subscriptions.create(user: user, subscribed: false) expect(issue.subscribed?(user)).to be_falsey end end end describe "#to_hook_data" do let(:data) { issue.to_hook_data(user) } let(:project) { issue.project } it "returns correct hook data" do expect(data[:object_kind]).to eq("issue") expect(data[:user]).to eq(user.hook_attrs) expect(data[:object_attributes]).to eq(issue.hook_attrs) expect(data).to_not have_key(:assignee) end context "issue is assigned" do before { issue.update_attribute(:assignee, user) } it "returns correct hook data" do expect(data[:object_attributes]['assignee_id']).to eq(user.id) expect(data[:assignee]).to eq(user.hook_attrs) end end include_examples 'project hook data' include_examples 'deprecated repository hook data' end describe '#card_attributes' do it 'includes the author name' do allow(issue).to receive(:author).and_return(double(name: 'Robert')) allow(issue).to receive(:assignee).and_return(nil) expect(issue.card_attributes). to eq({ 'Author' => 'Robert', 'Assignee' => nil }) end it 'includes the assignee name' do allow(issue).to receive(:author).and_return(double(name: 'Robert')) allow(issue).to receive(:assignee).and_return(double(name: 'Douwe')) expect(issue.card_attributes). to eq({ 'Author' => 'Robert', 'Assignee' => 'Douwe' }) end end describe "votes" do before do author = create :user project = create :empty_project issue.notes.awards.create!(note: "thumbsup", author: author, project: project) issue.notes.awards.create!(note: "thumbsdown", author: author, project: project) end it "returns correct values" do expect(issue.upvotes).to eq(1) expect(issue.downvotes).to eq(1) end end describe ".with_label" do let(:project) { create(:project, :public) } let(:bug) { create(:label, project: project, title: 'bug') } let(:feature) { create(:label, project: project, title: 'feature') } let(:enhancement) { create(:label, project: project, title: 'enhancement') } let(:issue1) { create(:issue, title: "Bugfix1", project: project) } let(:issue2) { create(:issue, title: "Bugfix2", project: project) } let(:issue3) { create(:issue, title: "Feature1", project: project) } before(:each) do issue1.labels << bug issue1.labels << feature issue2.labels << bug issue2.labels << enhancement issue3.labels << feature end it 'finds the correct issue containing just enhancement label' do expect(Issue.with_label(enhancement.title)).to match_array([issue2]) end it 'finds the correct issues containing the same label' do expect(Issue.with_label(bug.title)).to match_array([issue1, issue2]) end it 'finds the correct issues containing only both labels' do expect(Issue.with_label([bug.title, enhancement.title])).to match_array([issue2]) end end end
32.979675
87
0.679034
6a0d1d4aa5a1fcbed780306c12d3d70bfe880728
5,494
# Copyright 2016 Google LLC # # 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 # # https://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 "simplecov" gem "minitest" require "minitest/autorun" require "minitest/focus" require "minitest/rg" require "ostruct" require "json" require "base64" require "google/cloud/logging" require "grpc" ## # Monkey-Patch CallOptions to support Mocks class Google::Gax::CallOptions ## # Minitest Mock depends on === to match same-value objects. # By default, CallOptions objects do not match with ===. # Therefore, we must add this capability. def === other return false unless other.is_a? Google::Gax::CallOptions timeout === other.timeout && retry_options === other.retry_options && page_token === other.page_token && kwargs === other.kwargs end def == other return false unless other.is_a? Google::Gax::CallOptions timeout == other.timeout && retry_options == other.retry_options && page_token == other.page_token && kwargs == other.kwargs end end class MockLogging < Minitest::Spec let(:project) { "test" } let(:default_options) { Google::Gax::CallOptions.new(kwargs: { "google-cloud-resource-prefix" => "projects/#{project}" }) } let(:credentials) { OpenStruct.new(client: OpenStruct.new(updater_proc: Proc.new {})) } let(:logging) { Google::Cloud::Logging::Project.new(Google::Cloud::Logging::Service.new(project, credentials)) } # Register this spec type for when :mock_logging is used. register_spec_type(self) do |desc, *addl| addl.include? :mock_logging end def token_options token Google::Gax::CallOptions.new(kwargs: { "google-cloud-resource-prefix" => "projects/#{project}" }, page_token: token) end def random_entry_hash timestamp = Time.parse "2014-10-02T15:01:23.045123456Z" { log_name: "projects/my-projectid/logs/syslog", resource: random_resource_hash, timestamp: { seconds: timestamp.to_i, nanos: timestamp.nsec }, severity: :DEFAULT, insert_id: "abc123", labels: { "env" => "production", "foo" => "bar" }, text_payload: "payload", http_request: random_http_request_hash, operation: random_operation_hash, trace: "projects/my-projectid/traces/06796866738c859f2f19b7cfb3214824", source_location: random_source_location_hash, trace_sampled: true } end def random_http_request_hash { request_method: "GET", request_url: "http://test.local/foo?bar=baz", request_size: 123, status: 200, response_size: 456, user_agent: "google-cloud/1.0.0", remote_ip: "127.0.0.1", referer: "http://test.local/referer", cache_hit: false, cache_validated_with_origin_server: false } end def random_operation_hash { id: "xyz789", producer: "MyApp.MyClass#my_method", first: false, last: false } end def random_source_location_hash { file: "my_app/my_class.rb", line: 321, function: "#my_method" } end def random_resource_hash { type: "gae_app", labels: { "module_id" => "1", "version_id" => "20150925t173233" } } end def random_resource_descriptor_hash { type: "cloudsql_database", display_name: "Cloud SQL Database", description: "This resource is a Cloud SQL Database", labels: [ { key: "database_id", description: "The ID of the database." }, { key: "zone", value_type: :STRING, description: "The GCP zone in which the database is running." }, { key: "active", value_type: :BOOL, description: "Whether the database is active." }, { key: "max_connections", value_type: :INT64, description: "The maximum number of connections it supports." } ] } end def random_sink_hash timestamp = Time.parse "2014-10-02T15:01:23.045123456Z" { name: "my-severe-errors-to-pubsub", destination: "storage.googleapis.com/a-bucket", filter: "logName:syslog AND severity>=ERROR", output_version_format: :VERSION_FORMAT_UNSPECIFIED, writer_identity: "roles/owner" } end def random_metric_hash { name: "severe_errors", description: "The servere errors metric", filter: "logName:syslog AND severity>=ERROR" } end def project_path "projects/#{project}" end ## # Helper method to loop until block yields true or timeout. def wait_until_true timeout = 5 begin_t = Time.now until yield return :timeout if Time.now - begin_t > timeout sleep 0.1 end :completed end end
27.888325
125
0.620677
d562f2e2665cbd75e75920aecd1897f5943db340
8,007
describe ActiveModel::Errors do before do @klass = Class.new do extend ActiveModel::Naming def initialize @errors = ActiveModel::Errors.new(self) end attr_accessor :name, :email attr_reader :errors def validate! errors.add(:name, "can't be nil") if name.nil? end def read_attribute_for_validation(attr) send(attr) end def self.name 'Person' end def self.human_attribute_name(attr, options = {}) attr end def self.lookup_ancestors [self] end end end describe '#clear' do it 'clears error messages' do person = @klass.new person.validate! person.errors.full_messages.should == ["name can't be nil"] person.errors.clear person.errors.full_messages.should == [] end end describe '#include?' do it 'returns if error messages include an error' do person = @klass.new person.validate! person.errors.messages.should == {:name=>["can't be nil"]} person.errors.include?(:name).should == true person.errors.include?(:age).should == false end end describe '#get' do it 'gets messages' do person = @klass.new person.validate! person.errors.messages.should == {:name=>["can't be nil"]} person.errors.get(:name).should == ["can't be nil"] person.errors.get(:age).should == nil end end describe '#set' do it 'sets messages' do person = @klass.new person.validate! person.errors.get(:name).should == ["can't be nil"] person.errors.set(:name, ["must not be nil"]) person.errors.get(:name).should == ["must not be nil"] end end describe '#delete' do it 'deletes messages' do person = @klass.new person.validate! person.errors.get(:name).should == ["can't be nil"] person.errors.delete(:name).should == ["can't be nil"] person.errors.get(:name).should == nil end end describe '#[]' do it 'returns errors' do person = @klass.new person.validate! person.errors[:name].should == ["can't be nil"] person.errors['name'].should == ["can't be nil"] end end describe '#[]=' do it 'adds error message' do person = @klass.new person.validate! person.errors[:name] = "must be set" person.errors[:name].should == ["can't be nil", "must be set"] end end describe '#each' do it 'yields attribute and error' do person = @klass.new person.errors.add(:name, "can't be nil") person.errors.add(:name, "must be set") errors = [] person.errors.each do |attribute, error| errors << [attribute, error] end errors.should == [ [:name, "can't be nil"], [:name, "must be set"] ] end end describe '#size' do it 'returns number of error messages' do person = @klass.new person.errors.add(:name, "can't be nil") person.errors.size.should == 1 person.errors.add(:name, "must be set") person.errors.size.should == 2 end end describe '#values' do it 'returns all message values' do person = @klass.new person.errors.add(:name, "can't be nil") person.errors.add(:name, "must be set") person.errors.values.should == [["can't be nil", "must be set"]] end end describe '#keys' do it 'returns all message keys' do person = @klass.new person.errors.add(:name, "can't be nil") person.errors.add(:name, "must be set") person.errors.keys.should == [:name] end end describe '#to_a' do it 'returns error messages with the attribute name included' do person = @klass.new person.errors.add(:name, "can't be nil") person.errors.add(:name, "must be set") person.errors.to_a.should == ["name can't be nil", "name must be set"] end end describe '#count' do it 'returns number of error messages' do person = @klass.new person.errors.add(:name, "can't be nil") person.errors.count.should == 1 person.errors.add(:name, "must be set") person.errors.count.should == 2 end end describe '#empty?' do it 'returns if no errors are found' do person = @klass.new person.errors.empty?.should == true person.errors.add(:name, "can't be nil") person.errors.empty?.should == false end end describe '#to_xml' do it 'returns xml formatted representation' do person = @klass.new person.errors.add(:name, "can't be blank") person.errors.add(:name, "must be specified") person.errors.to_xml.should == <<EOS <?xml version=\"1.0\" encoding=\"UTF-8\"?> <errors> <error>name can't be blank</error> <error>name must be specified</error> </errors> EOS end end describe '#as_json' do it 'returns hash for json representation' do person = @klass.new person.errors.add(:name, "can't be nil") person.errors.as_json.should == { name: ["can't be nil"] } person.errors.as_json(full_messages: true) .should == { name: ["name can't be nil"] } end end describe '#to_hash' do it 'returns hash of attributes' do person = @klass.new person.errors.add(:name, "can't be nil") person.errors.to_hash.should == { name: ["can't be nil"] } person.errors.to_hash(true) .should == { name: ["name can't be nil"] } end end describe '#add' do class NameIsInvalid < ActiveModel::StrictValidationFailed end it 'adds message to the error messages on attribute' do person = @klass.new person.errors.add(:name).should == ["is invalid"] person.errors.add(:name, 'must be implemented') .should == ["is invalid", "must be implemented"] person.errors.messages .should == { name: ["is invalid", "must be implemented"] } end it 'raises if strict option is true' do person = @klass.new lambda { person.errors.add(:name, :invalid, strict: true) }.should.raise(ActiveModel::StrictValidationFailed) lambda { person.errors.add(:name, nil, strict: NameIsInvalid) }.should.raise(NameIsInvalid) person.errors.messages.should == {} end end describe '#add_on_empty' do it 'adds an error message on empty attributes' do person = @klass.new person.errors.add_on_empty(:name) person.errors.messages.should == { name: ["can't be empty"] } end end describe '#add_on_blank' do it 'adds an error message on empty attributes' do person = @klass.new person.errors.add_on_blank(:name) person.errors.messages.should == { name: ["can't be blank"] } end end describe '#added?' do it 'adds an error message on empty attributes' do person = @klass.new person.errors.add(:name, :blank) person.errors.added?(:name, :blank).should == true end end describe '#full_messages' do it 'returns all the full error messages' do person = @klass.new person.errors.add(:name, :invalid) person.errors.add(:name, :blank) person.errors.add(:email, :blank) person.errors.full_messages .should == [ "name is invalid", "name can't be blank", "email can't be blank" ] end end describe '#full_messages_for' do it 'returns all the full error messages for attribute' do person = @klass.new person.errors.add(:name, :invalid) person.errors.add(:name, :blank) person.errors.add(:email, :blank) person.errors.full_messages_for(:name) .should == [ "name is invalid", "name can't be blank" ] end end describe '#full_message' do it 'returns a full error message for attribute' do person = @klass.new person.errors.full_message(:name, 'is invalid') .should == "name is invalid" end end end
26.779264
76
0.604471
21d72987422fc33b34763dc7b4a1a808eb84cd11
1,546
require "opencode_theme/version" require 'opencode_theme/base_service' module OpencodeTheme NOOPParser = Proc.new {|data, format| {} } TIMER_RESET = 10 PERMIT_LOWER_LIMIT = 3 CONFIG_FILE = 'config.yml' def self.test? ENV['test'] end def self.critical_permits? @@total_api_calls.to_i - @@current_api_call_count.to_i < PERMIT_LOWER_LIMIT end def self.passed_api_refresh? delta_seconds > TIMER_RESET end def self.delta_seconds Time.now.to_i - @@current_timer.to_i end def self.needs_sleep? critical_permits? && !passed_api_refresh? end def self.sleep if needs_sleep? Kernel.sleep(TIMER_RESET - delta_seconds) @current_timer = nil end end def self.config @config ||= if File.exist? CONFIG_FILE config = YAML.load(File.read(CONFIG_FILE)) config else puts "#{CONFIG_FILE} does not exist!" unless test? {} end end def self.config=(config) @config = config end def self.is_binary_data?(string) if string.respond_to?(:encoding) string.encoding == "US-ASCII" else ( string.count( "^ -~", "^\r\n" ).fdiv(string.size) > 0.3 || string.index( "\x00" ) ) unless string.empty? end end def self.path(type = nil) @path ||= config[:theme_id] ? "/api/themes/#{config[:theme_id]}/assets" : "/api/themes/assets" end def self.ignore_files (config[:ignore_files] || []).compact.map { |r| Regexp.new(r) } end def self.whitelist_files (config[:whitelist_files] || []).compact end end
20.891892
112
0.655886
3305efd0f781555a46fa05ce6aff4aa6def7ac6b
2,241
require 'rails_helper' describe Api::V1::MeasureTypesController do render_views before { login_as_api_user } describe "GET to #index" do let!(:national_measure_type) { create :measure_type, :national } let!(:non_national_measure_type) { create :measure_type, :non_national } let(:response_pattern) { [ { id: String, validity_start_date: String, description: String }.ignore_extra_keys! ] } it 'returns national measure types' do get :index, format: :json expect(response.body).to match_json_expression response_pattern expect(parsed_body.map { |f| f["id"] }).to include national_measure_type.pk end it 'does not return non-national measure type' do get :index, format: :json expect(parsed_body.map { |f| f["id"] }).not_to include non_national_measure_type.pk end end describe "GET to #show" do let!(:national_measure_type) { create :measure_type, :national } let!(:non_national_measure_type) { create :measure_type, :non_national } let(:response_pattern) { { id: String, validity_start_date: String, description: String }.ignore_extra_keys! } it 'returns national measure types' do get :show, id: national_measure_type.pk, format: :json expect(response.body).to match_json_expression response_pattern end it 'does not return non-national measure types' do get :show, id: non_national_measure_type.pk, format: :json expect(response.status).to eq 404 end end describe "PUT to #update" do it 'updates national measure type' do national_measure_type = create :measure_type, :national put :update, id: national_measure_type.pk, measure_type: { description: 'new description' }, format: :json expect(parsed_body["description"]).to eq('new description') end it 'does not update non-national measure type' do non_national_measure_type = create :measure_type, :non_national put :update, id: non_national_measure_type.pk, measure_type: {}, format: :json expect(response.status).to eq 404 end end def parsed_body JSON.parse(response.body) end end
28.367089
112
0.677376
f79ac3b1a9735f07a393b8202ed6e4785d05cc54
128
FactoryBot.define do factory :task do title { "Brush teeth" } icon { "toothbrush" } color { "#00face" } end end
16
27
0.601563
0144ae0ce3f4dfd28ecc773b65834ab3144ded8a
8,841
require 'support/shared/integration/integration_helper' require 'chef/mixin/shell_out' describe "chef-client" do include IntegrationSupport include Chef::Mixin::ShellOut let(:chef_dir) { File.join(File.dirname(__FILE__), "..", "..", "..", "bin") } # Invoke `chef-client` as `ruby PATH/TO/chef-client`. This ensures the # following constraints are satisfied: # * Windows: windows can only run batch scripts as bare executables. Rubygems # creates batch wrappers for installed gems, but we don't have batch wrappers # in the source tree. # * Other `chef-client` in PATH: A common case is running the tests on a # machine that has omnibus chef installed. In that case we need to ensure # we're running `chef-client` from the source tree and not the external one. # cf. CHEF-4914 let(:chef_client) { "ruby '#{chef_dir}/chef-client'" } when_the_repository "has a cookbook with a no-op recipe" do before { file 'cookbooks/x/recipes/default.rb', '' } it "should complete with success" do file 'config/client.rb', <<EOM local_mode true cookbook_path "#{path_to('cookbooks')}" EOM result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", :cwd => chef_dir) result.error! end context 'and no config file' do it 'should complete with success when cwd is just above cookbooks and paths are not specified' do result = shell_out("#{chef_client} -z -o 'x::default' --disable-config", :cwd => path_to('')) result.error! end it 'should complete with success when cwd is below cookbooks and paths are not specified' do result = shell_out("#{chef_client} -z -o 'x::default' --disable-config", :cwd => path_to('cookbooks/x')) result.error! end it 'should fail when cwd is below high above and paths are not specified' do result = shell_out("#{chef_client} -z -o 'x::default' --disable-config", :cwd => File.expand_path('..', path_to(''))) result.exitstatus.should == 1 end end context 'and a config file under .chef/knife.rb' do before { file '.chef/knife.rb', 'xxx.xxx' } it 'should load .chef/knife.rb when -z is specified' do result = shell_out("#{chef_client} -z -o 'x::default'", :cwd => path_to('')) # FATAL: Configuration error NoMethodError: undefined method `xxx' for nil:NilClass result.stdout.should include("xxx") end end it "should complete with success" do file 'config/client.rb', <<EOM local_mode true cookbook_path "#{path_to('cookbooks')}" EOM result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", :cwd => chef_dir) result.error! end context 'and a private key' do before do file 'mykey.pem', <<EOM -----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEApubutqtYYQ5UiA9QhWP7UvSmsfHsAoPKEVVPdVW/e8Svwpyf 0Xef6OFWVmBE+W442ZjLOe2y6p2nSnaq4y7dg99NFz6X+16mcKiCbj0RCiGqCvCk NftHhTgO9/RFvCbmKZ1RKNob1YzLrFpxBHaSh9po+DGWhApcd+I+op+ZzvDgXhNn 0nauZu3rZmApI/r7EEAOjFedAXs7VPNXhhtZAiLSAVIrwU3ZajtSzgXOxbNzgj5O AAAMmThK+71qPdffAdO4J198H6/MY04qgtFo7vumzCq0UCaGZfmeI1UNE4+xQWwP HJ3pDAP61C6Ebx2snI2kAd9QMx9Y78nIedRHPwIDAQABAoIBAHssRtPM1GacWsom 8zfeN6ZbI4KDlbetZz0vhnqDk9NVrpijWlcOP5dwZXVNitnB/HaqCqFvyPDY9JNB zI/pEFW4QH59FVDP42mVEt0keCTP/1wfiDDGh1vLqVBYl/ZphscDcNgDTzNkuxMx k+LFVxKnn3w7rGc59lALSkpeGvbbIDjp3LUMlUeCF8CIFyYZh9ZvXe4OCxYdyjxb i8tnMLKvJ4Psbh5jMapsu3rHQkfPdqzztQUz8vs0NYwP5vWge46FUyk+WNm/IhbJ G3YM22nwUS8Eu2bmTtADSJolATbCSkOwQ1D+Fybz/4obfYeGaCdOqB05ttubhenV ShsAb7ECgYEA20ecRVxw2S7qA7sqJ4NuYOg9TpfGooptYNA1IP971eB6SaGAelEL awYkGNuu2URmm5ElZpwJFFTDLGA7t2zB2xI1FeySPPIVPvJGSiZoFQOVlIg9WQzK 7jTtFQ/tOMrF+bigEUJh5bP1/7HzqSpuOsPjEUb2aoCTp+tpiRGL7TUCgYEAwtns g3ysrSEcTzpSv7fQRJRk1lkBhatgNd0oc+ikzf74DaVLhBg1jvSThDhiDCdB59mr Jh41cnR1XqE8jmdQbCDRiFrI1Pq6TPaDZFcovDVE1gue9x86v3FOH2ukPG4d2/Xy HevXjThtpMMsWFi0JYXuzXuV5HOvLZiP8sN3lSMCgYANpdxdGM7RRbE9ADY0dWK2 V14ReTLcxP7fyrWz0xLzEeCqmomzkz3BsIUoouu0DCTSw+rvAwExqcDoDylIVlWO fAifz7SeZHbcDxo+3TsXK7zwnLYsx7YNs2+aIv6hzUUbMNmNmXMcZ+IEwx+mRMTN lYmZdrA5mr0V83oDFPt/jQKBgC74RVE03pMlZiObFZNtheDiPKSG9Bz6wMh7NWMr c37MtZLkg52mEFMTlfPLe6ceV37CM8WOhqe+dwSGrYhOU06dYqUR7VOZ1Qr0aZvo fsNPu/Y0+u7rMkgv0fs1AXQnvz7kvKaF0YITVirfeXMafuKEtJoH7owRbur42cpV YCAtAoGAP1rHOc+w0RUcBK3sY7aErrih0OPh9U5bvJsrw1C0FIZhCEoDVA+fNIQL syHLXYFNy0OxMtH/bBAXBGNHd9gf5uOnqh0pYcbe/uRAxumC7Rl0cL509eURiA2T +vFmf54y9YdnLXaqv+FhJT6B6V7WX7IpU9BMqJY1cJYXHuHG2KA= -----END RSA PRIVATE KEY----- EOM end it "should complete with success even with a client key" do file 'config/client.rb', <<EOM local_mode true client_key #{path_to('mykey.pem').inspect} cookbook_path #{path_to('cookbooks').inspect} EOM result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default'", :cwd => chef_dir) result.error! end it "should run recipes specified directly on the command line" do file 'config/client.rb', <<EOM local_mode true client_key #{path_to('mykey.pem').inspect} cookbook_path #{path_to('cookbooks').inspect} EOM file 'arbitrary.rb', <<EOM file #{path_to('tempfile.txt').inspect} do content '1' end EOM file 'arbitrary2.rb', <<EOM file #{path_to('tempfile2.txt').inspect} do content '2' end EOM result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" #{path_to('arbitrary.rb')} #{path_to('arbitrary2.rb')}", :cwd => chef_dir) result.error! IO.read(path_to('tempfile.txt')).should == '1' IO.read(path_to('tempfile2.txt')).should == '2' end it "should run recipes specified as relative paths directly on the command line" do file 'config/client.rb', <<EOM local_mode true client_key #{path_to('mykey.pem').inspect} cookbook_path #{path_to('cookbooks').inspect} EOM file 'arbitrary.rb', <<EOM file #{path_to('tempfile.txt').inspect} do content '1' end EOM result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" arbitrary.rb", :cwd => path_to('')) result.error! IO.read(path_to('tempfile.txt')).should == '1' end it "should run recipes specified directly on the command line AFTER recipes in the run list" do file 'config/client.rb', <<EOM local_mode true client_key #{path_to('mykey.pem').inspect} cookbook_path #{path_to('cookbooks').inspect} EOM file 'cookbooks/x/recipes/constant_definition.rb', <<EOM class ::Blah THECONSTANT = '1' end EOM file 'arbitrary.rb', <<EOM file #{path_to('tempfile.txt').inspect} do content ::Blah::THECONSTANT end EOM result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o x::constant_definition arbitrary.rb", :cwd => path_to('')) result.error! IO.read(path_to('tempfile.txt')).should == '1' end end it "should complete with success when passed the -z flag" do file 'config/client.rb', <<EOM chef_server_url 'http://omg.com/blah' cookbook_path "#{path_to('cookbooks')}" EOM result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' -z", :cwd => chef_dir) result.error! end it "should complete with success when passed the --local-mode flag" do file 'config/client.rb', <<EOM chef_server_url 'http://omg.com/blah' cookbook_path "#{path_to('cookbooks')}" EOM result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --local-mode", :cwd => chef_dir) result.error! end it "should not print SSL warnings when running in local-mode" do file 'config/client.rb', <<EOM chef_server_url 'http://omg.com/blah' cookbook_path "#{path_to('cookbooks')}" EOM result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' --local-mode", :cwd => chef_dir) result.stdout.should_not include("SSL validation of HTTPS requests is disabled.") result.error! end it "should complete with success when passed -z and --chef-zero-port" do file 'config/client.rb', <<EOM chef_server_url 'http://omg.com/blah' cookbook_path "#{path_to('cookbooks')}" EOM result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -o 'x::default' -z", :cwd => chef_dir) result.error! end it "should complete with success when setting the run list with -r" do file 'config/client.rb', <<EOM chef_server_url 'http://omg.com/blah' cookbook_path "#{path_to('cookbooks')}" EOM result = shell_out("#{chef_client} -c \"#{path_to('config/client.rb')}\" -r 'x::default' -z", :cwd => chef_dir) result.stdout.should_not include("Overridden Run List") result.stdout.should include("Run List is [recipe[x::default]]") #puts result.stdout result.error! end end end
36.382716
155
0.706481
792d9c3c713b7914228f9b49c80971fee0310015
3,212
RSpec.describe Webview::App do let(:root_path) { Webview::ROOT_PATH } let(:s_kill) { Signal.list['KILL'] } let(:s_quit) { Signal.list[Webview::App::SIGNALS_MAPPING['QUIT'] || 'QUIT'] } describe '#open/close' do it 'should open app window by webview' do r = Open3.popen3('sleep 1') expect(Open3).to receive(:popen3).with( subject.send(:executable) + " -url \"http://localhost:1234/asdf\"" ).and_return(r) expect(subject.open('http://localhost:1234/asdf')).to eql(true) sleep 0.5 ap = subject.app_process expect(ap.alive?).to eql(true) expect { subject.close sleep 0.1 }.to change { ap.alive? }.to(false) expect(subject.app_process).to eql(nil) end it 'should open app window with options' do subject = described_class.new( width: 100, height: 100, title: "x'xx", resizable: true, debug: true ) r = Open3.popen3('sleep 1') expect(Open3).to receive(:popen3).with( subject.send(:executable) + " -url \"http://localhost:4321/aaa\"" + " -title \"x'xx\" -width \"100\" -height \"100\" -resizable -debug" ).and_return(r) expect(subject.open('http://localhost:4321/aaa')).to eql(true) sleep 0.5 ap = subject.app_process expect(ap.alive?).to eql(true) expect { subject.close }.to change { ap.alive? }.to(false) expect(subject.app_process).to eql(nil) end it 'should not raise error if not found process' do subject.open('http://xxx.com') subject.signal('KILL') subject.close end end it '#join should wait process' do subject.open('http://xxx.com') expect(Process).to receive(:wait).with(subject.app_process.pid) subject.join subject.kill end it '#kill should kill with KILL' do subject.open('http://xxx.com') expect(Process).to receive(:kill).with(s_kill, subject.app_process.pid).and_call_original subject.kill end it '#kill should raise error if process was killed' do subject.open('http://xxx.com') subject.signal('KILL') expect(Process).to receive(:kill).with(s_kill, subject.app_process.pid).and_call_original subject.kill end it '#signal should not raise error if process not found' do subject.open('http://xxx.com') expect(Process).to receive(:kill) \ .with(s_quit, subject.app_process.pid).and_call_original.twice expect(Process).to receive(:kill) \ .with(s_kill, subject.app_process.pid).and_call_original.twice subject.signal("QUIT") subject.signal("QUIT") subject.signal("KILL") subject.signal("KILL") end it '#executable should return path of webview binary' do expect(subject).to receive(:executable).and_call_original expect(subject.send(:executable)).to eql(File.join(Webview::ROOT_PATH, 'ext/webview_app')) end it 'executable should able to run' do _out, help, _ = Open3.capture3("#{subject.send(:executable)} -h") keys = help.lines.select { |l| l =~ /\s*-\w+\s/ }.map(&:strip).map { |s| s.split.first } expect(help).to match(/^Usage of /) expect(keys.sort).to eql(%w{-debug -height -resizable -title -url -width}) end end
33.810526
94
0.643213
336750360cbfa9f20b1f758e2c3f1ed552b014ea
1,763
require_relative "boot" require "rails" # Pick the frameworks you want: require "active_model/railtie" # require "active_job/railtie" # require "active_record/railtie" # require "active_storage/engine" require "action_controller/railtie" # require "action_mailer/railtie" # require "action_mailbox/engine" # require "action_text/engine" require "action_view/railtie" # require "action_cable/engine" require "sprockets/railtie" require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Demo class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 7.0 # Configuration for the application, engines, and railties goes here. # # These settings can be overridden in specific environments using the files # in config/environments, which are processed later. # # config.time_zone = "Central Time (US & Canada)" # config.eager_load_paths << Rails.root.join("extras") # Don't generate system test files. config.generators.system_tests = nil # ViewComponent config.view_component.show_previews = true config.view_component.preview_controller = "PreviewController" # Lookbook if Rails.env.development? config.lookbook.listen_paths << Rails.root.join('../app/components') else config.lookbook.auto_refresh = false end # Engine overrides overrides = "#{Rails.root}/app/overrides" Rails.autoloaders.main.ignore(overrides) config.to_prepare do Dir.glob("#{overrides}/**/*_override.rb").each do |override| load override end end end end
29.881356
79
0.731707
e84d55f54ab687164720731166f9d16edc48b831
1,260
module Schools class CoursePolicy < ApplicationPolicy def index? # Can be shown to all school admins. user&.school_admin.present? && user.school == current_school end def authors? record.school == current_school && !record.archived? && index? end def show? record.school == current_school && index? end alias new? index? alias details? show? alias images? show? alias actions? show? alias attach_images? show? alias delete_coach_enrollment? authors? alias update_coach_enrollments? authors? alias students? authors? alias applicants? authors? alias inactive_students? authors? alias mark_teams_active? authors? alias exports? authors? alias certificates? authors? alias create_certificate? authors? alias bulk_import_students? authors? def curriculum? return false if user.blank? # All school admins can manage course curriculum. return true if authors? # All course authors can manage course curriculum. user.course_authors.where(course: record).present? end alias evaluation_criteria? curriculum? class Scope < Scope def resolve current_school.courses end end end end
24.705882
68
0.683333
edad049d71671cba81f71ef231d1914790d4432f
611
filename = ARGV.first txt = open(filename) poly = txt.read.chomp def react(chain) new_string = "" chain.each_char do |current| new_string+=current new_string = new_string[0...-2] if new_string[-2]&.swapcase == current end new_string end current_lowest = poly.size ('a'..'z').each do |char_to_strip| local = poly.dup.delete(char_to_strip).delete(char_to_strip.upcase) loop do old_size = local.size local = react(local) new_size = local.size if old_size == new_size break; end end if local.size < current_lowest current_lowest = local.size end end puts current_lowest
17.970588
72
0.707038
3987bebb124b504821cd3c24eb9a74598ce01090
7,962
# frozen_string_literal: true require 'spec_helper' describe Projects::PagesDomainsController do let(:user) { create(:user) } let(:project) { create(:project) } let!(:pages_domain) { create(:pages_domain, project: project) } let(:request_params) do { namespace_id: project.namespace, project_id: project } end let(:pages_domain_params) do attributes_for(:pages_domain, domain: 'my.otherdomain.com').slice(:key, :certificate, :domain).tap do |params| params[:user_provided_key] = params.delete(:key) params[:user_provided_certificate] = params.delete(:certificate) end end before do allow(Gitlab.config.pages).to receive(:enabled).and_return(true) sign_in(user) project.add_maintainer(user) end describe 'GET show' do def make_request get(:show, params: request_params.merge(id: pages_domain.domain)) end it "redirects to the 'edit' page" do make_request expect(response).to redirect_to(edit_project_pages_domain_path(project, pages_domain.domain)) end context 'when user is developer' do before do project.add_developer(user) end it 'renders 404 page' do make_request expect(response).to have_gitlab_http_status(404) end end end describe 'GET new' do it "displays the 'new' page" do get(:new, params: request_params) expect(response).to have_gitlab_http_status(200) expect(response).to render_template('new') end end describe 'POST create' do it "creates a new pages domain" do expect do post(:create, params: request_params.merge(pages_domain: pages_domain_params)) end.to change { PagesDomain.count }.by(1) created_domain = PagesDomain.reorder(:id).last expect(created_domain).to be_present expect(response).to redirect_to(edit_project_pages_domain_path(project, created_domain)) end end describe 'GET edit' do it "displays the 'edit' page" do get(:edit, params: request_params.merge(id: pages_domain.domain)) expect(response).to have_gitlab_http_status(200) expect(response).to render_template('edit') end end describe 'PATCH update' do before do controller.instance_variable_set(:@domain, pages_domain) end let(:params) do request_params.merge(id: pages_domain.domain, pages_domain: pages_domain_params) end context 'with valid params' do let(:pages_domain_params) do attributes_for(:pages_domain, :with_trusted_chain).slice(:key, :certificate).tap do |params| params[:user_provided_key] = params.delete(:key) params[:user_provided_certificate] = params.delete(:certificate) end end it 'updates the domain' do expect do patch(:update, params: params) end.to change { pages_domain.reload.certificate }.to(pages_domain_params[:user_provided_certificate]) end it 'redirects to the project page' do patch(:update, params: params) expect(flash[:notice]).to eq 'Domain was updated' expect(response).to redirect_to(project_pages_path(project)) end end context 'with key parameter' do before do pages_domain.update!(key: nil, certificate: nil, certificate_source: 'gitlab_provided') end it 'marks certificate as provided by user' do expect do patch(:update, params: params) end.to change { pages_domain.reload.certificate_source }.from('gitlab_provided').to('user_provided') end end context 'the domain is invalid' do let(:pages_domain_params) { { user_provided_certificate: 'blabla' } } it 'renders the edit action' do patch(:update, params: params) expect(response).to render_template('edit') end end context 'when parameters include the domain' do it 'does not update domain' do expect do patch(:update, params: params.deep_merge(pages_domain: { domain: 'abc' })) end.not_to change { pages_domain.reload.domain } end end end describe 'POST verify' do let(:params) { request_params.merge(id: pages_domain.domain) } def stub_service service = double(:service) expect(VerifyPagesDomainService).to receive(:new) { service } service end it 'handles verification success' do expect(stub_service).to receive(:execute).and_return(status: :success) post :verify, params: params expect(response).to redirect_to edit_project_pages_domain_path(project, pages_domain) expect(flash[:notice]).to eq('Successfully verified domain ownership') end it 'handles verification failure' do expect(stub_service).to receive(:execute).and_return(status: :failed) post :verify, params: params expect(response).to redirect_to edit_project_pages_domain_path(project, pages_domain) expect(flash[:alert]).to eq('Failed to verify domain ownership') end it 'returns a 404 response for an unknown domain' do post :verify, params: request_params.merge(id: 'unknown-domain') expect(response).to have_gitlab_http_status(404) end end describe 'DELETE destroy' do it "deletes the pages domain" do expect do delete(:destroy, params: request_params.merge(id: pages_domain.domain)) end.to change { PagesDomain.count }.by(-1) expect(response).to redirect_to(project_pages_path(project)) end end describe 'DELETE #clean_certificate' do subject do delete(:clean_certificate, params: request_params.merge(id: pages_domain.domain)) end it 'redirects to edit page' do subject expect(response).to redirect_to(edit_project_pages_domain_path(project, pages_domain)) end it 'removes certificate' do expect do subject end.to change { pages_domain.reload.certificate }.to(nil) .and change { pages_domain.reload.key }.to(nil) end it 'sets certificate source to user_provided' do pages_domain.update!(certificate_source: :gitlab_provided) expect do subject end.to change { pages_domain.reload.certificate_source }.from("gitlab_provided").to("user_provided") end context 'when pages_https_only is set' do before do project.update!(pages_https_only: true) stub_pages_setting(external_https: '127.0.0.1') end it 'does not remove certificate' do subject pages_domain.reload expect(pages_domain.certificate).to be_present expect(pages_domain.key).to be_present end it 'redirects to edit page with a flash message' do subject expect(flash[:alert]).to include('Certificate') expect(flash[:alert]).to include('Key') expect(response).to redirect_to(edit_project_pages_domain_path(project, pages_domain)) end end end context 'pages disabled' do before do allow(Gitlab.config.pages).to receive(:enabled).and_return(false) end describe 'GET show' do it 'returns 404 status' do get(:show, params: request_params.merge(id: pages_domain.domain)) expect(response).to have_gitlab_http_status(404) end end describe 'GET new' do it 'returns 404 status' do get :new, params: request_params expect(response).to have_gitlab_http_status(404) end end describe 'POST create' do it "returns 404 status" do post(:create, params: request_params.merge(pages_domain: pages_domain_params)) expect(response).to have_gitlab_http_status(404) end end describe 'DELETE destroy' do it "deletes the pages domain" do delete(:destroy, params: request_params.merge(id: pages_domain.domain)) expect(response).to have_gitlab_http_status(404) end end end end
28.33452
114
0.67797
aca8ef45255b9d4a659849239b76fff0897a89ae
1,077
# http://www.collmex.de/cgi-bin/cgi.exe?1005,1,help,daten_importieren_abw class Collmex::Api::Cmxepf < Collmex::Api::Line SPECIFICATION = [ { name: :satzart, type: :string, const: "CMXEPF" }, { name: :kundennummer, type: :integer }, { name: :firma_nr, type: :integer }, { name: :dokument_typ, type: :integer }, { name: :ausgabemedium, type: :integer }, { name: :anrede, type: :string }, { name: :titel, type: :string }, { name: :vorname, type: :string }, { name: :name, type: :string }, { name: :firma, type: :string }, { name: :abteilung, type: :string }, { name: :strasse, type: :string }, { name: :plz, type: :string }, { name: :ort, type: :string }, { name: :land, type: :string }, { name: :telefon, type: :string }, { name: :telefon2, type: :string }, { name: :telefax, type: :string }, { name: :skype_vo_ip, type: :string }, { name: :e_mail, type: :string }, { name: :bemerkung, type: :string }, { name: :url, type: :string }, { name: :keine_mailings, type: :string }, { name: :adressgruppe, type: :integer }, ] end
33.65625
73
0.597029
edcf673eeae7ad5452719729d88593f901a95241
667
node[:deploy].each do |app_name, deploy| #Add proxypass entry for blog ruby_block "add proxypass blog entry" do Chef::Log.info("modifying #{node[:apache][:dir]}/sites-available/#{app_name}.conf") block do rc = Chef::Util::FileEdit.new("#{node[:apache][:dir]}/sites-available/#{app_name}.conf") proxy_line = " ProxyPass /blog http://#{node['config']['blog']['ip']}\n ProxyPassReverse /blog http://#{node['config']['blog']['ip']}" rc.insert_line_after_match(/^.*\DocumentRoot\b.*$/, proxy_line) rc.write_file end only_if do ::File.exists?("#{node[:apache][:dir]}/sites-available/#{app_name}.conf") end end end
39.235294
142
0.64018
1c9cc8c3b4626ace09d830039f70cd95434291c7
31,297
require "json" require "timers" require_relative "../src/rulesrb/rules" module Engine class MessageNotHandledError < StandardError def initialize(message) super("Could not handle message: #{JSON.generate(message)}") end end class MessageObservedError < StandardError def initialize(message) super("Message has already been observed: #{JSON.generate(message)}") end end class Closure attr_reader :host, :handle, :_timers, :_cancelled_timers, :_messages, :_facts, :_retract, :_deleted attr_accessor :s def initialize(host, ruleset, state, message, handle) @s = Content.new(state) @handle = handle @host = host @_ruleset = ruleset @_start_time = Time.now @_completed = false @_deleted = false if message.kind_of? Hash @m = message else @m = [] for one_message in message do if (one_message.key? "m") && (one_message.size == 1) one_message = one_message["m"] end @m << Content.new(one_message) end end if !s.sid s.sid = "0" end end def post(ruleset_name, message = nil) if message if message.kind_of? Content message = message._d end if !(message.key? :sid) && !(message.key? "sid") message[:sid] = @s.sid end @host.assert_event ruleset_name, message else message = ruleset_name if message.kind_of? Content message = message._d end if !(message.key? :sid) && !(message.key? "sid") message[:sid] = @s.sid end @_ruleset.assert_event message end end def assert(ruleset_name, fact = nil) if fact if fact.kind_of? Content fact = fact._d end if !(fact.key? :sid) && !(fact.key? "sid") fact[:sid] = @s.sid end @host.assert_fact ruleset_name, fact else fact = ruleset_name if fact.kind_of? Content fact = fact._d end if !(fact.key? :sid) && !(fact.key? "sid") fact[:sid] = @s.sid end @_ruleset.assert_fact fact end end def retract(ruleset_name, fact = nil) if fact if fact.kind_of? Content fact = fact._d end if !(fact.key? :sid) && !(fact.key? "sid") fact[:sid] = @s.sid end @host.retract_fact ruleset_name, fact else fact = ruleset_name if fact.kind_of? Content fact = fact._d end if !(fact.key? :sid) && !(fact.key? "sid") fact[:sid] = @s.sid end @_ruleset.retract_fact fact end end def start_timer(timer_name, duration, manual_reset = false) if manual_reset manual_reset = 1 else manual_reset = 0 end @_ruleset.start_timer @s.sid, timer_name, duration, manual_reset end def cancel_timer(timer_name) @_ruleset.cancel_timer @s.sid, timer_name end def renew_action_lease() if Time.now - @_start_time < 10000 @_start_time = Time.now @_ruleset.renew_action_lease @s.sid end end def delete() @_deleted = true end def has_completed() if Time.now - @_start_time > 10000 @_completed = true end value = @_completed @_completed = true value end private def handle_property(name, value=nil) name = name.to_s if name.end_with? '?' @m.key? name[0..-2] elsif @m.kind_of? Hash current = @m[name] if current.kind_of? Hash Content.new current else current end else @m end end alias method_missing handle_property end class Content attr_reader :_d def initialize(data) @_d = data end def to_s @_d.to_s end private def handle_property(name, value=nil) name = name.to_s if name.end_with? '=' if value == nil @_d.delete(name[0..-2]) else @_d[name[0..-2]] = value end nil elsif name.end_with? '?' @_d.key? name[0..-2] else current = @_d[name] if current.kind_of? Hash Content.new current else current end end end alias method_missing handle_property end class Promise attr_accessor :root def initialize(func) @func = func @next = nil @sync = true @root = self @timers = Timers::Group.new if func.arity > 1 @sync = false end end def continue_with(next_func) if next_func.kind_of? Promise @next = next_func elsif next_func.kind_of? Proc @next = Promise.new next_func else raise ArgumentError, "Unexpected Promise Type #{next_func}" end @next.root = @root @next end def run(c, complete) if @sync begin @func.call c rescue Exception => e c.s.exception = "#{e.to_s}, #{e.backtrace}" end if @next @next.run c, complete else complete.call nil end else begin time_left = @func.call c, -> e { if e c.s.exception = e.to_s end if @next @next.run c, complete else complete.call nil end } if time_left && (time_left.kind_of? Integer) max_time = Time.now + time_left my_timer = @timers.every(5) { if Time.now > max_time my_timer.cancel c.s.exception = "timeout expired" complete.call nil else c.renew_action_lease end } Thread.new do loop { @timers.wait } end end rescue Exception => e puts "unexpected error #{e}" puts e.backtrace c.s.exception = e.to_s complete.call nil end end end end class To < Promise def initialize(from_state, to_state, assert_state) super -> c { c.s.running = true if from_state != to_state begin if from_state if c.m && (c.m.kind_of? Array) c.retract c.m[0].chart_context else c.retract c.chart_context end end if assert_state c.assert(:label => to_state, :chart => 1) else c.post(:label => to_state, :chart => 1) end rescue MessageNotHandledError => e end end } end end class Ruleset attr_reader :definition def initialize(name, host, ruleset_definition) @actions = {} @name = name @host = host for rule_name, rule in ruleset_definition do rule_name = rule_name.to_s action = nil if rule.key? "run" action = rule["run"] rule.delete "run" elsif rule.key? :run action = rule[:run] rule.delete :run end if !action raise ArgumentError, "Action for #{rule_name} is null" elsif action.kind_of? String @actions[rule_name] = Promise.new host.get_action action elsif action.kind_of? Promise @actions[rule_name] = action.root elsif action.kind_of? Proc @actions[rule_name] = Promise.new action end end @handle = Rules.create_ruleset name, JSON.generate(ruleset_definition) @definition = ruleset_definition end def assert_event(message) handle_result Rules.assert_event(@handle, JSON.generate(message)), message end def assert_events(messages) handle_result Rules.assert_events(@handle, JSON.generate(messages)), messages end def assert_fact(fact) handle_result Rules.assert_fact(@handle, JSON.generate(fact)), fact end def assert_facts(facts) handle_result Rules.assert_facts(@handle, JSON.generate(facts)), facts end def retract_fact(fact) handle_result Rules.retract_fact(@handle, JSON.generate(fact)), fact end def retract_facts(facts) handle_result Rules.retract_facts(@handle, JSON.generate(facts)), facts end def start_timer(sid, timer, timer_duration, manual_reset) Rules.start_timer @handle, sid.to_s, timer_duration, manual_reset, timer end def cancel_timer(sid, timer_name) Rules.cancel_timer @handle, sid.to_s, timer_name.to_s end def update_state(state) state["$s"] = 1 Rules.update_state @handle, JSON.generate(state) end def get_state(sid) JSON.parse Rules.get_state(@handle, sid.to_s) end def delete_state(sid) Rules.delete_state(@handle, sid.to_s) end def renew_action_lease(sid) Rules.renew_action_lease @handle, sid.to_s end def Ruleset.create_rulesets(host, ruleset_definitions) branches = {} for name, definition in ruleset_definitions do name = name.to_s if name.end_with? "$state" name = name[0..-7] branches[name] = Statechart.new name, host, definition elsif name.end_with? "$flow" name = name[0..-6] branches[name] = Flowchart.new name, host, definition else branches[name] = Ruleset.new name, host, definition end end branches end def dispatch_timers() Rules.assert_timers @handle end def to_json JSON.generate @definition end def do_actions(state_handle, complete) begin result = Rules.start_action_for_state(@handle, state_handle) if !result complete.call(nil, nil) else flush_actions JSON.parse(result[0]), {:message => JSON.parse(result[1])}, state_handle, complete end rescue Exception => e complete.call(e, nil) end end def dispatch_ruleset() result = Rules.start_action(@handle) if result flush_actions JSON.parse(result[0]), {:message => JSON.parse(result[1])}, result[2], -> e, s { } end end private def handle_result(result, message) if result[0] == 1 raise MessageNotHandledError, message elsif result[0] == 2 raise MessageObservedError, message end result[1] end def flush_actions(state, result_container, state_offset, complete) while result_container.key? :message do action_name = nil for action_name, message in result_container[:message] do break end result_container.delete :message c = Closure.new @host, self, state, message, state_offset @actions[action_name].run c, -> e { if c.has_completed return end if e Rules.abandon_action @handle, c.handle complete.call e, nil else begin Rules.update_state @handle, JSON.generate(c.s._d) new_result = Rules.complete_and_start_action @handle, c.handle if new_result result_container[:message] = JSON.parse new_result else complete.call nil, state end rescue Exception => e puts "unknown exception #{e}" puts e.backtrace Rules.abandon_action @handle, c.handle complete.call e, nil end if c._deleted begin delete_state c.s.sid rescue Exception => e end end end } result_container[:async] = true end end end class Statechart < Ruleset def initialize(name, host, chart_definition) @name = name @host = host ruleset_definition = {} transform nil, nil, nil, chart_definition, ruleset_definition super name, host, ruleset_definition @definition = chart_definition @definition[:$type] = "stateChart" end def transform(parent_name, parent_triggers, parent_start_state, chart_definition, rules) start_state = {} reflexive_states = {} for state_name, state in chart_definition do next if state_name == "$type" qualified_name = state_name.to_s qualified_name = "#{parent_name}.#{state_name}" if parent_name start_state[qualified_name] = true for trigger_name, trigger in state do if ((trigger.key? :to) && (trigger[:to] == state_name)) || ((trigger.key? "to") && (trigger["to"] == state_name)) || (trigger.key? :count) || (trigger.key? "count") || (trigger.key? :cap) || (trigger.key? "cap") reflexive_states[qualified_name] = true end end end for state_name, state in chart_definition do next if state_name == "$type" qualified_name = state_name.to_s qualified_name = "#{parent_name}.#{state_name}" if parent_name triggers = {} if parent_triggers for parent_trigger_name, trigger in parent_triggers do parent_trigger_name = parent_trigger_name.to_s triggers["#{qualified_name}.#{parent_trigger_name}"] = trigger end end for trigger_name, trigger in state do trigger_name = trigger_name.to_s if trigger_name != "$chart" if parent_name && (trigger.key? "to") to_name = trigger["to"].to_s trigger["to"] = "#{parent_name}.#{to_name}" elsif parent_name && (trigger.key? :to) to_name = trigger[:to].to_s trigger[:to] = "#{parent_name}.#{to_name}" end triggers["#{qualified_name}.#{trigger_name}"] = trigger end end if state.key? "$chart" transform qualified_name, triggers, start_state, state["$chart"], rules elsif state.key? :$chart transform qualified_name, triggers, start_state, state[:$chart], rules else for trigger_name, trigger in triggers do trigger_name = trigger_name.to_s rule = {} state_test = {:chart_context => {:$and => [{:label => qualified_name}, {:chart => 1}]}} if trigger.key? :pri rule[:pri] = trigger[:pri] elsif trigger.key? "pri" rule[:pri] = trigger["pri"] end if trigger.key? :count rule[:count] = trigger[:count] elsif trigger.key? "count" rule[:count] = trigger["count"] end if trigger.key? :cap rule[:cap] = trigger[:cap] elsif trigger.key? "cap" rule[:cap] = trigger["cap"] end if (trigger.key? :all) || (trigger.key? "all") all_trigger = nil if trigger.key? :all all_trigger = trigger[:all] else all_trigger = trigger["all"] end rule[:all] = all_trigger.dup rule[:all] << state_test elsif (trigger.key? :any) || (trigger.key? "any") any_trigger = nil if trigger.key? :any any_trigger = trigger[:any] else any_trigger = trigger["any"] end rule[:all] = [state_test, {"m$any" => any_trigger}] else rule[:all] = [state_test] end if (trigger.key? "run") || (trigger.key? :run) trigger_run = nil if trigger.key? :run trigger_run = trigger[:run] else trigger_run = trigger["run"] end if trigger_run.kind_of? String rule[:run] = Promise.new @host.get_action(trigger_run) elsif trigger_run.kind_of? Promise rule[:run] = trigger_run elsif trigger_run.kind_of? Proc rule[:run] = Promise.new trigger_run end end if (trigger.key? "to") || (trigger.key? :to) trigger_to = nil if trigger.key? :to trigger_to = trigger[:to] else trigger_to = trigger["to"] end trigger_to = trigger_to.to_s from_state = nil if reflexive_states.key? qualified_name from_state = qualified_name end assert_state = false if reflexive_states.key? trigger_to assert_state = true end if rule.key? :run rule[:run].continue_with To.new(from_state, trigger_to, assert_state) else rule[:run] = To.new from_state, trigger_to, assert_state end start_state.delete trigger_to if start_state.key? trigger_to if parent_start_state && (parent_start_state.key? trigger_to) parent_start_state.delete trigger_to end else raise ArgumentError, "Trigger #{trigger_name} destination not defined" end rules[trigger_name] = rule end end end started = false for state_name in start_state.keys do raise ArgumentError, "Chart #{@name} has more than one start state" if started state_name = state_name.to_s started = true if parent_name rules[parent_name + "$start"] = {:all => [{:chart_context => {:$and => [{:label => parent_name}, {:chart => 1}]}}], :run => To.new(nil, state_name, false)}; else rules[:$start] = {:all => [{:chart_context => {:$and => [{:$nex => {:running => 1}}, {:$s => 1}]}}], :run => To.new(nil, state_name, false)}; end end raise ArgumentError, "Chart #{@name} has no start state" if not started end end class Flowchart < Ruleset def initialize(name, host, chart_definition) @name = name @host = host ruleset_definition = {} transform chart_definition, ruleset_definition super name, host, ruleset_definition @definition = chart_definition @definition["$type"] = "flowChart" end def transform(chart_definition, rules) visited = {} reflexive_stages = {} for stage_name, stage in chart_definition do if (stage.key? :to) || (stage.key? "to") stage_to = (stage.key? :to) ? stage[:to]: stage["to"] if (stage_to.kind_of? String) || (stage_to.kind_of? Symbol) if stage_to == stage_name reflexive_stages[stage_name] = true end else for transition_name, transition in stage_to do if (transition_name == stage_name) || (transition.key? :count) || (transition.key? "count") || (transition.key? :cap) || (transition.key? "cap") reflexive_stages[stage_name] = true end end end end end for stage_name, stage in chart_definition do next if stage_name == "$type" from_stage = nil if reflexive_stages.key? stage_name from_stage = stage_name end stage_name = stage_name.to_s stage_test = {:chart_context => {:$and => [{:label => stage_name}, {:chart => 1}]}} if (stage.key? :to) || (stage.key? "to") stage_to = (stage.key? :to) ? stage[:to]: stage["to"] if (stage_to.kind_of? String) || (stage_to.kind_of? Symbol) next_stage = nil rule = {:all => [stage_test]} if chart_definition.key? stage_to next_stage = chart_definition[stage_to] elsif chart_definition.key? stage_to.to_s next_stage = chart_definition[stage_to.to_s] else raise ArgumentError, "Stage #{stage_to.to_s} not found" end assert_stage = false if reflexive_stages.key? stage_to assert_stage = true end stage_to = stage_to.to_s if !(next_stage.key? :run) && !(next_stage.key? "run") rule[:run] = To.new from_stage, stage_to, assert_stage else next_stage_run = (next_stage.key? :run) ? next_stage[:run]: next_stage["run"] if next_stage_run.kind_of? String rule[:run] = To.new(from_stage, stage_to, assert_stage).continue_with Promise(@host.get_action(next_stage_run)) elsif (next_stage_run.kind_of? Promise) || (next_stage_run.kind_of? Proc) rule[:run] = To.new(from_stage, stage_to, assert_stage).continue_with next_stage_run end end rules["#{stage_name}.#{stage_to}"] = rule visited[stage_to] = true else for transition_name, transition in stage_to do rule = {} next_stage = nil if transition.key? :pri rule[:pri] = transition[:pri] elsif transition.key? "pri" rule[:pri] = transition["pri"] end if transition.key? :count rule[:count] = transition[:count] elsif transition.key? "count" rule[:count] = transition["count"] end if transition.key? :cap rule[:cap] = transition[:cap] elsif transition.key? "cap" rule[:cap] = transition["cap"] end if (transition.key? :all) || (transition.key? "all") all_transition = nil if transition.key? :all all_transition = transition[:all] else all_transition = transition["all"] end rule[:all] = all_transition.dup rule[:all] << stage_test elsif (transition.key? :any) || (transition.key? "any") any_transition = nil if transition.key? :any any_transition = transition[:any] else any_transition = transition["any"] end rule[:all] = [stage_test, {"m$any" => any_transition}] else rule[:all] = [stage_test] end if chart_definition.key? transition_name next_stage = chart_definition[transition_name] else raise ArgumentError, "Stage #{transition_name.to_s} not found" end assert_stage = false if reflexive_stages.key? transition_name assert_stage = true end transition_name = transition_name.to_s if !(next_stage.key? :run) && !(next_stage.key? "run") rule[:run] = To.new from_stage, transition_name, assert_stage else next_stage_run = (next_stage.key? :run) ? next_stage[:run]: next_stage["run"] if next_stage_run.kind_of? String rule[:run] = To.new(from_stage, transition_name, assert_stage).continue_with Promise(@host.get_action(next_stage_run)) elsif (next_stage_run.kind_of? Promise) || (next_stage_run.kind_of? Proc) rule[:run] = To.new(from_stage, transition_name, assert_stage).continue_with next_stage_run end end rules["#{stage_name}.#{transition_name}"] = rule visited[transition_name] = true end end end end started = false for stage_name, stage in chart_definition do stage_name = stage_name.to_s if !(visited.key? stage_name) if started raise ArgumentError, "Chart #{@name} has more than one start state" end started = true rule = {:all => [{:chart_context => {:$and => [{:$nex => {:running => 1}}, {:$s => 1}]}}]} if !(stage.key? :run) && !(stage.key? "run") rule[:run] = To.new nil, stage_name, false else stage_run = stage.key? :run ? stage[:run]: stage["run"] if stage_run.kind_of? String rule[:run] = To.new(nil, stage_name, false).continue_with Promise(@host.get_action(stage_run)) elsif (stage_run.kind_of? Promise) || (stage_run.kind_of? Proc) rule[:run] = To.new(nil, stage_name, false).continue_with stage_run end end rules["$start.#{stage_name}"] = rule end end end end class Host def initialize(ruleset_definitions = nil) @ruleset_directory = {} @ruleset_list = [] @assert_event_func = Proc.new do |rules, arg| rules.assert_event arg end @assert_events_func = Proc.new do |rules, arg| rules.assert_events arg end @assert_fact_func = Proc.new do |rules, arg| rules.assert_fact arg end @assert_facts_func = Proc.new do |rules, arg| rules.assert_facts arg end @retract_fact_func = Proc.new do |rules, arg| rules.retract_fact arg end @retract_facts_func = Proc.new do |rules, arg| rules.retract_facts arg end @update_state_func = Proc.new do |rules, arg| rules.update_state arg end register_rulesets nil, ruleset_definitions if ruleset_definitions start_dispatch_ruleset_thread start_dispatch_timers_thread end def get_action(action_name) raise ArgumentError, "Action with name #{action_name} not found" end def load_ruleset(ruleset_name) raise ArgumentError, "Ruleset with name #{ruleset_name} not found" end def save_ruleset(ruleset_name, ruleset_definition) end def get_ruleset(ruleset_name) ruleset_name = ruleset_name.to_s if !(@ruleset_directory.key? ruleset_name) ruleset_definition = load_ruleset ruleset_name register_rulesets nil, ruleset_definition end @ruleset_directory[ruleset_name] end def set_rulesets(ruleset_definitions) register_rulesets ruleset_definitions for ruleset_name, ruleset_definition in ruleset_definitions do save_ruleset ruleset_name, ruleset_definition end end def post(ruleset_name, event, complete = nil) if event.kind_of? Array return post_batch ruleset_name, event end rules = get_ruleset(ruleset_name) handle_function rules, @assert_event_func, event, complete end def post_batch(ruleset_name, events, complete = nil) rules = get_ruleset(ruleset_name) handle_function rules, @assert_events_func, events, complete end def assert(ruleset_name, fact, complete = nil) if fact.kind_of? Array return assert_facts ruleset_name, fact end rules = get_ruleset(ruleset_name) handle_function rules, @assert_fact_func, fact, complete end def assert_facts(ruleset_name, facts, complete = nil) rules = get_ruleset(ruleset_name) handle_function rules, @assert_facts_func, facts, complete end def retract(ruleset_name, fact, complete = nil) if fact.kind_of? Array return retract_facts ruleset_name, fact end rules = get_ruleset(ruleset_name) handle_function rules, @retract_fact_func, fact, complete end def retract_facts(ruleset_name, facts, complete = nil) rules = get_ruleset(ruleset_name) handle_function rules, @retract_facts_func, facts, complete end def update_state(ruleset_name, state, complete = nil) rules = get_ruleset(ruleset_name) handle_function rules, @update_state_func, state, complete end def get_state(ruleset_name, sid) get_ruleset(ruleset_name).get_state sid end def delete_state(ruleset_name, sid) get_ruleset(ruleset_name).delete_state sid end def renew_action_lease(ruleset_name, sid) get_ruleset(ruleset_name).renew_action_lease sid end def register_rulesets(ruleset_definitions) rulesets = Ruleset.create_rulesets(self, ruleset_definitions) for ruleset_name, ruleset in rulesets do if @ruleset_directory.key? ruleset_name raise ArgumentError, "Ruleset with name #{ruleset_name} already registered" end @ruleset_directory[ruleset_name] = ruleset @ruleset_list << ruleset end rulesets.keys end private def handle_function(rules, func, args, complete) error = nil result = nil if not complete rules.do_actions func.call(rules, args), -> e, s { error = e result = s } if error raise error end result else begin rules.do_actions func.call(rules, args), complete rescue Exception => e complete.call e, nil end end end def start_dispatch_timers_thread timer = Timers::Group.new thread_lambda = -> c { if @ruleset_list.empty? timer.after 0.5, &thread_lambda else ruleset = @ruleset_list[Thread.current[:index]] begin ruleset.dispatch_timers rescue Exception => e puts e.backtrace puts "Error #{e}" end timeout = 0 if (Thread.current[:index] == (@ruleset_list.length-1)) timeout = 0.2 end Thread.current[:index] = (Thread.current[:index] + 1) % @ruleset_list.length timer.after timeout, &thread_lambda end } timer.after 0.1, &thread_lambda Thread.new do Thread.current[:index] = 0 loop { timer.wait } end end def start_dispatch_ruleset_thread timer = Timers::Group.new thread_lambda = -> c { if @ruleset_list.empty? timer.after 0.5, &thread_lambda else ruleset = @ruleset_list[Thread.current[:index]] begin ruleset.dispatch_ruleset rescue Exception => e puts e.backtrace puts "Error #{e}" end timeout = 0 if (Thread.current[:index] == (@ruleset_list.length-1)) timeout = 0.2 end Thread.current[:index] = (Thread.current[:index] + 1) % @ruleset_list.length timer.after timeout, &thread_lambda end } timer.after 0.1, &thread_lambda Thread.new do Thread.current[:index] = 0 loop { timer.wait } end end end end
28.297468
166
0.558169
62bc70edfee77d9e7c6586c6dc11f9877a7b4f78
995
require 'spec_helper' describe Delayed::Worker do describe "backend=" do before do @clazz = Class.new Delayed::Worker.backend = @clazz end it "should set the Delayed::Job constant to the backend" do Delayed::Job.should == @clazz end it "should set backend with a symbol" do Delayed::Worker.backend = :active_record Delayed::Worker.backend.should == Delayed::Backend::ActiveRecord::Job end end describe "guess_backend" do after do Delayed::Worker.backend = :active_record end it "should set to active_record if nil" do Delayed::Worker.backend = nil lambda { Delayed::Worker.guess_backend }.should change { Delayed::Worker.backend }.to(Delayed::Backend::ActiveRecord::Job) end it "should not override the existing backend" do Delayed::Worker.backend = Class.new lambda { Delayed::Worker.guess_backend }.should_not change { Delayed::Worker.backend } end end end
26.184211
92
0.669347
87f48e87e5ead6aca53e4cdd80fea2353d5da436
1,034
# frozen_string_literal: true class ProGrammar # @api private # @since v0.13.0 module ControlDHandler # Deal with the ^D key being pressed. Different behaviour in different # cases: # 1. In an expression behave like `!` command. # 2. At top-level session behave like `exit` command. # 3. In a nested session behave like `cd ..`. def self.default(pro_grammar_instance) if !pro_grammar_instance.eval_string.empty? # Clear input buffer. pro_grammar_instance.eval_string = '' elsif pro_grammar_instance.binding_stack.one? pro_grammar_instance.binding_stack.clear throw(:breakout) else # Otherwise, saves current binding stack as old stack and pops last # binding out of binding stack (the old stack still has that binding). cd_state = ProGrammar::CommandState.default.state_for('cd') cd_state.old_stack = pro_grammar_instance.binding_stack.dup pro_grammar_instance.binding_stack.pop end end end end
35.655172
78
0.690522
1cf581e5aa391a2819e3ebcf3a6c4dec9cc27e99
2,005
Shindo.tests('Fog::Compute[:google] | image requests', ['google']) do @google = Fog::Compute[:google] @insert_image_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'name' => String, 'targetLink' => String, 'status' => String, 'user' => String, 'progress' => Integer, 'insertTime' => String, 'startTime' => String, 'operationType' => String } @get_image_format = { 'kind' => String, 'id' => String, 'creationTimestamp' => String, 'selfLink' => String, 'name' => String, 'description' => String, 'sourceType' => String, 'preferredKernel' => String, 'rawDisk' => { 'containerType' => String, 'source' => String } } @delete_image_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'name' => String, 'targetLink' => String, 'status' => String, 'user' => String, 'progress' => Integer, 'insertTime' => String, 'startTime' => String, 'operationType' => String } @list_images_format = { 'kind' => String, 'id' => String, 'selfLink' => String, 'items' => [@get_image_format] } tests('success') do image_name = 'test-image' source = 'https://www.google.com/images/srpr/logo4w.png' tests("#insert_image").formats(@insert_image_format) do pending if Fog.mocking? @google.insert_image(image_name, source).body end tests("#get_image").formats(@get_image_format) do pending if Fog.mocking? @google.insert_image(image_name, source) @google.get_image(image_name).body end tests("#list_images").formats(@list_images_format) do @google.list_images.body end tests("#delete_image").formats(@delete_image_format) do pending if Fog.mocking? @google.insert_image(image_name, source) @google.delete_image(image_name).body end end end
23.869048
69
0.574564
b983d8b3ff3a97a39718c47708dc6517d406b701
304
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'glossy' require 'minitest/autorun' class LessThan5 < Glossy::Base class << self def check(id) #return true if row is broken return id >= 5 end def fix(id) print "Sorry boss, no can do. " end end end
16
58
0.634868
1a7b609ae253e65a215663187e35355c612e7418
296
# Allergy Information module HL7 module Segment class AL1 < Base field :event_type_code field :allergen_type_code field :allergen_code field :allergy_severity_code field :allergy_reaction_code field :identification_date, type: DateTime end end end
21.142857
48
0.709459
b93272964b76de4c64214961022cd9e14a829824
3,014
require "light_service_object/version" require "dry/initializer" require "dry/monads/result" # frozen_string_literal: true if defined?(Ensurance) # Define a dispatcher for `:model` option rails_dispatcher = ->(ensure: nil, **options) do # NOTE: This is because 'ensure' is a reserved word in Ruby klass = binding.local_variable_get(:ensure) return options unless klass begin klass = klass.constantize if klass.is_a?(String) rescue NameError => e msg = "LightServiceObject: #{self.class} cannot ensure(#{klass}) as the model can't be found" Rails.logger.error msg puts msg if !Rails.env.production? raise e end klass = klass.klass if klass.is_a?(ActiveRecord::Relation) coercer = options[:optional] ? ->(value) { klass.ensure(value) } : ->(value) { klass.ensure!(value) } options.merge(type: coercer) end # Register a dispatcher Dry::Initializer::Dispatchers << rails_dispatcher end module LightServiceObject class ServiceError < StandardError; end class Base extend Dry::Initializer include Dry::Monads::Result::Mixin ## — CLASS METHODS class << self def result_class @result_class end def param(key, **options) raise Error.new("Do not use param in a service object") end def option(*args, **opts, &block) if opts.delete(:mutable) name = opts[:as] || args.first self.send("attr_writer", name) end super(*args, **opts, &block) end def required(key, **options) options[:private] = true option(key, **options) end def optional(key, **options) options[:optional] = true options[:private] = true option(key, **options) end def expected_result_class(klass) @result_class = klass @result_class = klass.constantize if klass.is_a?(String) end def call(**options) obj = self.new(**options) obj.call rescue Exception => error Dry::Monads.Failure(error.message) end end def self.failed(error) end ## — INSTANCE METHODS def result_class self.class.result_class end def call result = self.perform if self.result_class if !result.is_a?(self.result_class) a_name = "#{self.result_class}" a_name = %w[a e i o u y].include?(a_name.first.downcase) ? "an #{a_name}" : "a #{a_name}" fail!("#{self.name} is not returning #{a_name}") end end Dry::Monads.Success(result) rescue Exception => error Dry::Monads.Failure(error.message) end def fail!(error) error = ServiceError.new(error.to_s) if !error.is_a?(ServiceError) reason = self.error_reason(error) self.class.failed(error) raise error end def error_reason(error) # Give subclasses a chance to see errors first "[#{self.class}] #{error}" end end end
25.116667
99
0.617452
f814a039c9eb1880d7a06d6327587da734897dfd
289
require 'spec_helper' describe "Real World integration" do it "Lookup should work" do lookup = MooMoo::Lookup.new VCR.use_cassette("integration/lookup") do lookup.api_lookup(:domain => "opensrs.net") lookup.attributes["status"].should == "taken" end end end
20.642857
51
0.681661
e9a804fb21ce05457e2f80c640b4725effc6553b
811
require "spec_helper" describe OpenXml::Docx::Properties::TextboxTightWrap do include ValuePropertyTestMacros it_should_use tag: :textboxTightWrap, name: "textbox_tight_wrap", value: :none with_value(:allLines) do it_should_work it_should_output "<w:textboxTightWrap w:val=\"allLines\"/>" end with_value(:firstAndLastLine) do it_should_work it_should_output "<w:textboxTightWrap w:val=\"firstAndLastLine\"/>" end with_value(:firstLineOnly) do it_should_work it_should_output "<w:textboxTightWrap w:val=\"firstLineOnly\"/>" end with_value(:lastLineOnly) do it_should_work it_should_output "<w:textboxTightWrap w:val=\"lastLineOnly\"/>" end with_value(:none) do it_should_work it_should_output "<w:textboxTightWrap w:val=\"none\"/>" end end
23.852941
80
0.736128
38c47a7ed9a700a43d991f527b10e06975d863cc
1,242
require './lib/tlspretense/version' Gem::Specification.new do |s| s.name = "tlspretense" s.version = TLSPretense::VERSION s.authors = ["William (B.J.) Snow Orvis"] s.email = "[email protected]" s.date = Time.now.utc.strftime("%Y-%m-%d") s.homepage = "https://github.com/iSECPartners/tlspretense" s.licenses = ["MIT"] s.summary = "SSL/TLS client testing framework" s.description = <<-QUOTE TLSPretense provides a set of tools to test SSL/TLS certificate validation. It includes a library for generating certificates and a test framework for running tests against a client by intercepting client network traffic." QUOTE s.executables = ["tlspretense"] s.files = `git ls-files`.split("\n") s.test_files = `git ls-files spec`.split("\n") s.require_paths = ["lib"] s.extra_rdoc_files = [ "LICENSE.txt", "README.rdoc", ] + `git ls-files doc`.split("\n") s.add_runtime_dependency("eventmachine", [">= 1.0.0"]) s.add_runtime_dependency("ruby-termios", [">= 0.9.6"]) s.add_development_dependency("rake", ["~> 12.3"]) s.add_development_dependency("rspec", ["~> 3.7"]) s.add_development_dependency("rdoc", [">= 6.3.1"]) s.add_development_dependency("simplecov", ["~> 0.7"]) end
35.485714
79
0.677134
ed7649ab0a874c6269cfcae5eed89032f9a5da20
76
require 'final-api/helpers/error_handling' require 'final-api/helpers/cors'
25.333333
42
0.815789
e9e736502844ba0e6dce1693aa6bfa7bba3ebac0
10,153
# -*- coding: binary -*- require 'msf/core' module Msf ### # # The module base class is responsible for providing the common interface # that is used to interact with modules at the most basic levels, such as # by inspecting a given module's attributes (name, dsecription, version, # authors, etc) and by managing the module's data store. # ### class Module autoload :Arch, 'msf/core/module/arch' autoload :Author, 'msf/core/module/author' autoload :AuxiliaryAction, 'msf/core/module/auxiliary_action' autoload :Compatibility, 'msf/core/module/compatibility' autoload :DataStore, 'msf/core/module/data_store' autoload :Deprecated, 'msf/core/module/deprecated' autoload :Failure, 'msf/core/module/failure' autoload :FullName, 'msf/core/module/full_name' autoload :HasActions, 'msf/core/module/has_actions' autoload :ModuleInfo, 'msf/core/module/module_info' autoload :ModuleStore, 'msf/core/module/module_store' autoload :Network, 'msf/core/module/network' autoload :Options, 'msf/core/module/options' autoload :Platform, 'msf/core/module/platform' autoload :PlatformList, 'msf/core/module/platform_list' autoload :Privileged, 'msf/core/module/privileged' autoload :Ranking, 'msf/core/module/ranking' autoload :Reference, 'msf/core/module/reference' autoload :Search, 'msf/core/module/search' autoload :SiteReference, 'msf/core/module/reference' autoload :Target, 'msf/core/module/target' autoload :Type, 'msf/core/module/type' autoload :UI, 'msf/core/module/ui' autoload :UUID, 'msf/core/module/uuid' include Msf::Module::Arch include Msf::Module::Author include Msf::Module::Compatibility include Msf::Module::DataStore include Msf::Module::FullName include Msf::Module::ModuleInfo include Msf::Module::ModuleStore include Msf::Module::Network include Msf::Module::Options include Msf::Module::Privileged include Msf::Module::Ranking include Msf::Module::Search include Msf::Module::Type include Msf::Module::UI include Msf::Module::UUID # The key where a comma-separated list of Ruby module names will live in the # datastore, consumed by #replicant to allow clean override of MSF module methods. REPLICANT_EXTENSION_DS_KEY = 'ReplicantExtensions' # Make include public so we can runtime extend public_class_method :include class << self include Framework::Offspring # # This attribute holds the non-duplicated copy of the module # implementation. This attribute is used for reloading purposes so that # it can be re-duplicated. # attr_accessor :orig_cls # # The path from which the module was loaded. # attr_accessor :file_path end # # Returns the class reference to the framework # def framework self.class.framework end # # This method allows modules to tell the framework if they are usable # on the system that they are being loaded on in a generic fashion. # By default, all modules are indicated as being usable. An example of # where this is useful is if the module depends on something external to # ruby, such as a binary. # def self.is_usable true end # # Creates an instance of an abstract module using the supplied information # hash. # def initialize(info = {}) @module_info_copy = info.dup self.module_info = info generate_uuid set_defaults # Initialize module compatibility hashes init_compat # Fixup module fields as needed info_fixups # Transform some of the fields to arrays as necessary self.author = Msf::Author.transform(module_info['Author']) self.arch = Rex::Transformer.transform(module_info['Arch'], Array, [ String ], 'Arch') self.platform = PlatformList.transform(module_info['Platform']) self.references = Rex::Transformer.transform(module_info['References'], Array, [ SiteReference, Reference ], 'Ref') # Create and initialize the option container for this module self.options = Msf::OptionContainer.new self.options.add_options(info['Options'], self.class) self.options.add_advanced_options(info['AdvancedOptions'], self.class) self.options.add_evasion_options(info['EvasionOptions'], self.class) # Create and initialize the data store for this module self.datastore = ModuleDataStore.new(self) # Import default options into the datastore import_defaults self.privileged = module_info['Privileged'] || false self.license = module_info['License'] || MSF_LICENSE # Allow all modules to track their current workspace register_advanced_options( [ OptString.new('WORKSPACE', [ false, "Specify the workspace for this module" ]), OptBool.new('VERBOSE', [ false, 'Enable detailed status messages', false ]) ], Msf::Module) end # # Creates a fresh copy of an instantiated module # def replicant obj = self.class.new self.instance_variables.each { |k| v = instance_variable_get(k) v = v.dup rescue v obj.instance_variable_set(k, v) } obj.datastore = self.datastore.copy obj.user_input = self.user_input obj.user_output = self.user_output obj.module_store = self.module_store.clone obj.perform_extensions obj end # Extends self with the constant list in the datastore # @return [void] def perform_extensions if datastore[REPLICANT_EXTENSION_DS_KEY].present? if datastore[REPLICANT_EXTENSION_DS_KEY].respond_to?(:each) datastore[REPLICANT_EXTENSION_DS_KEY].each do |const| self.extend(const) end else fail "Invalid settings in datastore at key #{REPLICANT_EXTENSION_DS_KEY}" end end end # @param[Constant] One or more Ruby constants # @return [void] def register_extensions(*rb_modules) datastore[REPLICANT_EXTENSION_DS_KEY] = [] unless datastore[REPLICANT_EXTENSION_DS_KEY].present? rb_modules.each do |rb_mod| datastore[REPLICANT_EXTENSION_DS_KEY] << rb_mod unless datastore[REPLICANT_EXTENSION_DS_KEY].include? rb_mod end end # # Returns the unduplicated class associated with this module. # def orig_cls self.class.orig_cls end # # The path to the file in which the module can be loaded from. # def file_path self.class.file_path end # # Checks to see if the target is vulnerable, returning unsupported if it's # not supported. # # This method is designed to be overriden by exploit modules. # def check Msf::Exploit::CheckCode::Unsupported end # # Returns the current workspace # def workspace self.datastore['WORKSPACE'] || (framework.db and framework.db.active and framework.db.workspace and framework.db.workspace.name) end # # Returns the username that instantiated this module, this tries a handful of methods # to determine what actual user ran this module. # def owner # Generic method to configure a module owner username = self.datastore['MODULE_OWNER'].to_s.strip # Specific method used by the commercial products if username.empty? username = self.datastore['PROUSER'].to_s.strip end # Fallback when neither prior method is available, common for msfconsole if username.empty? username = (ENV['LOGNAME'] || ENV['USERNAME'] || ENV['USER'] || "unknown").to_s.strip end username end # # Scans the parent module reference to populate additional information. This # is used to inherit common settings (owner, workspace, parent uuid, etc). # def register_parent(ref) self.datastore['WORKSPACE'] = (ref.datastore['WORKSPACE'] ? ref.datastore['WORKSPACE'].dup : nil) self.datastore['PROUSER'] = (ref.datastore['PROUSER'] ? ref.datastore['PROUSER'].dup : nil) self.datastore['MODULE_OWNER'] = ref.owner.dup self.datastore['ParentUUID'] = ref.uuid.dup end # # Return a comma separated list of supported platforms, if any. # def platform_to_s platform.all? ? "All" : platform.names.join(", ") end # # Checks to see if this module is compatible with the supplied platform # def platform?(what) (platform & what).empty? == false end # # Returns true if this module is being debugged. The debug flag is set # by setting datastore['DEBUG'] to 1|true|yes # def debugging? (datastore['DEBUG'] || '') =~ /^(1|t|y)/i end # # Support fail_with for all module types, allow specific classes to override # def fail_with(reason, msg=nil) raise RuntimeError, "#{reason.to_s}: #{msg}" end ## # # Just some handy quick checks # ## # # Returns false since this is the real module # def self.cached? false end # # The array of zero or more platforms. # attr_reader :platform # # The reference count for the module. # attr_reader :references # # The license under which this module is provided. # attr_reader :license # # The job identifier that this module is running as, if any. # attr_accessor :job_id # # The last exception to occur using this module # attr_accessor :error protected # # Sets the modules unsupplied info fields to their default values. # def set_defaults self.module_info = { 'Name' => 'No module name', 'Description' => 'No module description', 'Version' => '0', 'Author' => nil, 'Arch' => nil, # No architectures by default. 'Platform' => [], # No platforms by default. 'Ref' => nil, 'Privileged' => false, 'License' => MSF_LICENSE, }.update(self.module_info) self.module_store = {} end # # Checks to see if a derived instance of a given module implements a method # beyond the one that is provided by a base class. This is a pretty lame # way of doing it, but I couldn't find a better one, so meh. # def derived_implementor?(parent, method_name) (self.method(method_name).to_s.match(/#{parent}[^:]/)) ? false : true end attr_writer :platform, :references # :nodoc: attr_writer :privileged # :nodoc: attr_writer :license # :nodoc: end end
28.76204
119
0.694081
381c5e14d33f544f5b835d038caf1a3bcce09329
524
require 'wait_for_solr' task 'sunspot:solr:start_with_waiting' => :environment do port = Sunspot::Rails.configuration.port next puts 'Solr already running' if WaitForSolr.running_on?(port) puts 'Starting Solr ...' # is namespaced within app when invoked from the engine repo task = Rake::Task.task_defined?('app:sunspot:solr:start') ? 'app:sunspot:solr:start' : 'sunspot:solr:start' Rake.application.invoke_task(task) print 'Waiting for Solr ' WaitForSolr.on(port, 30) { print '.' } puts ' done' end
27.578947
109
0.723282
919786cbccd78bdbb5945dc5f5a98d44c253826d
1,643
require_relative '../../spec_helper' require_relative 'shared/arithmetic_coerce' describe "Integer#*" do ruby_version_is "2.4"..."2.5" do it_behaves_like :integer_arithmetic_coerce_rescue, :* end ruby_version_is "2.5" do it_behaves_like :integer_arithmetic_coerce_not_rescue, :* end context "fixnum" do it "returns self multiplied by the given Integer" do (4923 * 2).should == 9846 (1342177 * 800).should == 1073741600 (65536 * 65536).should == 4294967296 (256 * bignum_value).should == 2361183241434822606848 (6712 * 0.25).should == 1678.0 end it "raises a TypeError when given a non-Integer" do -> { (obj = mock('10')).should_receive(:to_int).any_number_of_times.and_return(10) 13 * obj }.should raise_error(TypeError) -> { 13 * "10" }.should raise_error(TypeError) -> { 13 * :symbol }.should raise_error(TypeError) end end context "bignum" do before :each do @bignum = bignum_value(772) end it "returns self multiplied by the given Integer" do (@bignum * (1/bignum_value(0xffff).to_f)).should be_close(1.0, TOLERANCE) (@bignum * (1/bignum_value(0xffff).to_f)).should be_close(1.0, TOLERANCE) (@bignum * 10).should == 92233720368547765800 (@bignum * (@bignum - 40)).should == 85070591730234629737795195287525433200 end it "raises a TypeError when given a non-Integer" do -> { @bignum * mock('10') }.should raise_error(TypeError) -> { @bignum * "10" }.should raise_error(TypeError) -> { @bignum * :symbol }.should raise_error(TypeError) end end end
31.596154
85
0.651856
2633187690e9f05d774fb4dd115ef4f523cb9345
53,560
# # Author:: Adam Jacob (<[email protected]>) # Author:: Christopher Walters (<[email protected]>) # Author:: John Keiser (<[email protected]) # Copyright:: Copyright 2008-2016, Chef, Inc. # License:: Apache License, Version 2.0 # # 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 "chef/exceptions" require "chef/dsl/data_query" require "chef/dsl/registry_helper" require "chef/dsl/reboot_pending" require "chef/dsl/resources" require "chef/mixin/convert_to_class_name" require "chef/guard_interpreter/resource_guard_interpreter" require "chef/resource/conditional" require "chef/resource/conditional_action_not_nothing" require "chef/resource/action_class" require "chef/resource_collection" require "chef/node_map" require "chef/node" require "chef/platform" require "chef/resource/resource_notification" require "chef/provider_resolver" require "chef/resource_resolver" require "chef/provider" require "set" require "chef/mixin/deprecation" require "chef/mixin/properties" require "chef/mixin/provides" require "chef/dsl/universal" class Chef class Resource # # Generic User DSL (not resource-specific) # include Chef::DSL::DataQuery include Chef::DSL::RegistryHelper include Chef::DSL::RebootPending extend Chef::Mixin::Provides include Chef::DSL::Universal # Bring in `property` and `property_type` include Chef::Mixin::Properties # # The name of this particular resource. # # This special resource attribute is set automatically from the declaration # of the resource, e.g. # # execute 'Vitruvius' do # command 'ls' # end # # Will set the name to "Vitruvius". # # This is also used in to_s to show the resource name, e.g. `execute[Vitruvius]`. # # This is also used for resource notifications and subscribes in the same manner. # # This will coerce any object into a string via #to_s. Arrays are a special case # so that `package ["foo", "bar"]` becomes package[foo, bar] instead of the more # awkward `package[["foo", "bar"]]` that #to_s would produce. # # @param name [Object] The name to set, typically a String or Array # @return [String] The name of this Resource. # property :name, String, coerce: proc { |v| v.is_a?(Array) ? v.join(", ") : v.to_s }, desired_state: false # # The node the current Chef run is using. # # Corresponds to `run_context.node`. # # @return [Chef::Node] The node the current Chef run is using. # def node run_context && run_context.node end # # Find existing resources by searching the list of existing resources. Possible # forms are: # # find(:file => "foobar") # find(:file => [ "foobar", "baz" ]) # find("file[foobar]", "file[baz]") # find("file[foobar,baz]") # # Calls `run_context.resource_collection.find(*args)` # # @return the matching resource, or an Array of matching resources. # # @raise ArgumentError if you feed it bad lookup information # @raise RuntimeError if it can't find the resources you are looking for. # def resources(*args) run_context.resource_collection.find(*args) end # # Resource User Interface (for users) # # # Create a new Resource. # # @param name The name of this resource (corresponds to the #name attribute, # used for notifications to this resource). # @param run_context The context of the Chef run. Corresponds to #run_context. # def initialize(name, run_context = nil) name(name) unless name.nil? @run_context = run_context @noop = nil @before = nil @params = Hash.new @provider = nil @allowed_actions = self.class.allowed_actions.to_a @action = self.class.default_action @updated = false @updated_by_last_action = false @supports = {} @ignore_failure = false @retries = 0 @retry_delay = 2 @not_if = [] @only_if = [] @source_line = nil # We would like to raise an error when the user gives us a guard # interpreter and a ruby_block to the guard. In order to achieve this # we need to understand when the user overrides the default guard # interpreter. Therefore we store the default separately in a different # attribute. @guard_interpreter = nil @default_guard_interpreter = :default @elapsed_time = 0 @sensitive = false end # # The action or actions that will be taken when this resource is run. # # @param arg [Array[Symbol], Symbol] A list of actions (e.g. `:create`) # @return [Array[Symbol]] the list of actions. # def action(arg = nil) if arg arg = Array(arg).map(&:to_sym) arg.each do |action| validate( { action: action }, { action: { kind_of: Symbol, equal_to: allowed_actions } } ) end @action = arg else @action end end # Alias for normal assigment syntax. alias_method :action=, :action # # Sets up a notification that will run a particular action on another resource # if and when *this* resource is updated by an action. # # If the action does not update this resource, the notification never triggers. # # Only one resource may be specified per notification. # # `delayed` notifications will only *ever* happen once per resource, so if # multiple resources all notify a single resource to perform the same action, # the action will only happen once. However, if they ask for different # actions, each action will happen once, in the order they were updated. # # `immediate` notifications will cause the action to be triggered once per # notification, regardless of how many other resources have triggered the # notification as well. # # @param action The action to run on the other resource. # @param resource_spec [String, Hash, Chef::Resource] The resource to run. # @param timing [String, Symbol] When to notify. Has these values: # - `delayed`: Will run the action on the other resource after all other # actions have been run. This is the default. # - `immediate`, `immediately`: Will run the action on the other resource # immediately (before any other action is run). # - `before`: Will run the action on the other resource # immediately *before* the action is actually run. # # @example Resource by string # file '/foo.txt' do # content 'hi' # notifies :create, 'file[/bar.txt]' # end # file '/bar.txt' do # action :nothing # content 'hi' # end # @example Resource by hash # file '/foo.txt' do # content 'hi' # notifies :create, file: '/bar.txt' # end # file '/bar.txt' do # action :nothing # content 'hi' # end # @example Direct Resource # bar = file '/bar.txt' do # action :nothing # content 'hi' # end # file '/foo.txt' do # content 'hi' # notifies :create, bar # end # def notifies(action, resource_spec, timing = :delayed) # when using old-style resources(:template => "/foo.txt") style, you # could end up with multiple resources. validate_resource_spec!(resource_spec) resources = [ resource_spec ].flatten resources.each do |resource| case timing.to_s when "delayed" notifies_delayed(action, resource) when "immediate", "immediately" notifies_immediately(action, resource) when "before" notifies_before(action, resource) else raise ArgumentError, "invalid timing: #{timing} for notifies(#{action}, #{resources.inspect}, #{timing}) resource #{self} "\ "Valid timings are: :delayed, :immediate, :immediately, :before" end end true end # # Subscribes to updates from other resources, causing a particular action to # run on *this* resource when the other resource is updated. # # If multiple resources are specified, this resource action will be run if # *any* of them change. # # This notification will only trigger *once*, no matter how many other # resources are updated (or how many actions are run by a particular resource). # # @param action The action to run on the other resource. # @param resources [String, Resource, Array[String, Resource]] The resources to subscribe to. # @param timing [String, Symbol] When to notify. Has these values: # - `delayed`: An update will cause the action to run after all other # actions have been run. This is the default. # - `immediate`, `immediately`: The action will run immediately following # the other resource being updated. # - `before`: The action will run immediately before the # other resource is updated. # # @example Resources by string # file '/foo.txt' do # content 'hi' # action :nothing # subscribes :create, 'file[/bar.txt]' # end # file '/bar.txt' do # content 'hi' # end # @example Direct resource # bar = file '/bar.txt' do # content 'hi' # end # file '/foo.txt' do # content 'hi' # action :nothing # subscribes :create, '/bar.txt' # end # @example Multiple resources by string # file '/foo.txt' do # content 'hi' # action :nothing # subscribes :create, [ 'file[/bar.txt]', 'file[/baz.txt]' ] # end # file '/bar.txt' do # content 'hi' # end # file '/baz.txt' do # content 'hi' # end # @example Multiple resources # bar = file '/bar.txt' do # content 'hi' # end # baz = file '/bar.txt' do # content 'hi' # end # file '/foo.txt' do # content 'hi' # action :nothing # subscribes :create, [ bar, baz ] # end # def subscribes(action, resources, timing = :delayed) resources = [resources].flatten resources.each do |resource| if resource.is_a?(String) resource = Chef::Resource.new(resource, run_context) end if resource.run_context.nil? resource.run_context = run_context end resource.notifies(action, self, timing) end true end # # A command or block that indicates whether to actually run this resource. # The command or block is run just before the action actually executes, and # the action will be skipped if the block returns false. # # If a block is specified, it must return `true` in order for the Resource # to be executed. # # If a command is specified, the resource's #guard_interpreter will run the # command and interpret the results according to `opts`. For example, the # default `execute` resource will be treated as `false` if the command # returns a non-zero exit code, and `true` if it returns 0. Thus, in the # default case: # # - `only_if "your command"` will perform the action only if `your command` # returns 0. # - `only_if "your command", valid_exit_codes: [ 1, 2, 3 ]` will perform the # action only if `your command` returns 1, 2, or 3. # # @param command [String] A string to execute. # @param opts [Hash] Options control the execution of the command # @param block [Proc] A ruby block to run. Ignored if a command is given. # def only_if(command = nil, opts = {}, &block) if command || block_given? @only_if << Conditional.only_if(self, command, opts, &block) end @only_if end # # A command or block that indicates whether to actually run this resource. # The command or block is run just before the action actually executes, and # the action will be skipped if the block returns true. # # If a block is specified, it must return `false` in order for the Resource # to be executed. # # If a command is specified, the resource's #guard_interpreter will run the # command and interpret the results according to `opts`. For example, the # default `execute` resource will be treated as `false` if the command # returns a non-zero exit code, and `true` if it returns 0. Thus, in the # default case: # # - `not_if "your command"` will perform the action only if `your command` # returns a non-zero code. # - `only_if "your command", valid_exit_codes: [ 1, 2, 3 ]` will perform the # action only if `your command` returns something other than 1, 2, or 3. # # @param command [String] A string to execute. # @param opts [Hash] Options control the execution of the command # @param block [Proc] A ruby block to run. Ignored if a command is given. # def not_if(command = nil, opts = {}, &block) if command || block_given? @not_if << Conditional.not_if(self, command, opts, &block) end @not_if end # # The number of times to retry this resource if it fails by throwing an # exception while running an action. Default: 0 # # When the retries have run out, the Resource will throw the last # exception. # # @param arg [Integer] The number of retries. # @return [Integer] The number of retries. # def retries(arg = nil) set_or_return(:retries, arg, kind_of: Integer) end attr_writer :retries # # The number of seconds to wait between retries. Default: 2. # # @param arg [Integer] The number of seconds to wait between retries. # @return [Integer] The number of seconds to wait between retries. # def retry_delay(arg = nil) set_or_return(:retry_delay, arg, kind_of: Integer) end attr_writer :retry_delay # # Whether to treat this resource's data as sensitive. If set, no resource # data will be displayed in log output. # # @param arg [Boolean] Whether this resource is sensitive or not. # @return [Boolean] Whether this resource is sensitive or not. # def sensitive(arg = nil) set_or_return(:sensitive, arg, :kind_of => [ TrueClass, FalseClass ]) end attr_writer :sensitive # ??? TODO unreferenced. Delete? attr_reader :not_if_args # ??? TODO unreferenced. Delete? attr_reader :only_if_args # # The time it took (in seconds) to run the most recently-run action. Not # cumulative across actions. This is set to 0 as soon as a new action starts # running, and set to the elapsed time at the end of the action. # # @return [Integer] The time (in seconds) it took to process the most recent # action. Not cumulative. # attr_reader :elapsed_time # # The guard interpreter that will be used to process `only_if` and `not_if` # statements. If left unset, the #default_guard_interpreter will be used. # # Must be a resource class like `Chef::Resource::Execute`, or # a corresponding to the name of a resource. The resource must descend from # `Chef::Resource::Execute`. # # TODO this needs to be coerced on input so that retrieval is consistent. # # @param arg [Class, Symbol, String] The Guard interpreter resource class/ # symbol/name. # @return [Class, Symbol, String] The Guard interpreter resource. # def guard_interpreter(arg = nil) if arg.nil? @guard_interpreter || @default_guard_interpreter else set_or_return(:guard_interpreter, arg, :kind_of => Symbol) end end # # Get the value of the state attributes in this resource as a hash. # # Does not include properties that are not set (unless they are identity # properties). # # @return [Hash{Symbol => Object}] A Hash of attribute => value for the # Resource class's `state_attrs`. # def state_for_resource_reporter state = {} state_properties = self.class.state_properties state_properties.each do |property| if property.identity? || property.is_set?(self) state[property.name] = send(property.name) end end state end # # Since there are collisions with LWRP parameters named 'state' this # method is not used by the resource_reporter and is most likely unused. # It certainly cannot be relied upon and cannot be fixed. # # @deprecated # alias_method :state, :state_for_resource_reporter # # The value of the identity of this resource. # # - If there are no identity properties on the resource, `name` is returned. # - If there is exactly one identity property on the resource, it is returned. # - If there are more than one, they are returned in a hash. # # @return [Object,Hash<Symbol,Object>] The identity of this resource. # def identity result = {} identity_properties = self.class.identity_properties identity_properties.each do |property| result[property.name] = send(property.name) end return result.values.first if identity_properties.size == 1 result end # # Whether to ignore failures. If set to `true`, and this resource when an # action is run, the resource will be marked as failed but no exception will # be thrown (and no error will be output). Defaults to `false`. # # TODO ignore_failure and retries seem to be mutually exclusive; I doubt # that was intended. # # @param arg [Boolean] Whether to ignore failures. # @return Whether this resource will ignore failures. # def ignore_failure(arg = nil) set_or_return(:ignore_failure, arg, kind_of: [ TrueClass, FalseClass ]) end attr_writer :ignore_failure # # Equivalent to #ignore_failure. # alias :epic_fail :ignore_failure # # Make this resource into an exact (shallow) copy of the other resource. # # @param resource [Chef::Resource] The resource to copy from. # def load_from(resource) resource.instance_variables.each do |iv| unless iv == :@source_line || iv == :@action || iv == :@not_if || iv == :@only_if self.instance_variable_set(iv, resource.instance_variable_get(iv)) end end end # # Runs the given action on this resource, immediately. # # @param action The action to run (e.g. `:create`) # @param notification_type The notification type that triggered this (if any) # @param notifying_resource The resource that triggered this notification (if any) # # @raise Any error that occurs during the actual action. # def run_action(action, notification_type = nil, notifying_resource = nil) # reset state in case of multiple actions on the same resource. @elapsed_time = 0 start_time = Time.now events.resource_action_start(self, action, notification_type, notifying_resource) # Try to resolve lazy/forward references in notifications again to handle # the case where the resource was defined lazily (ie. in a ruby_block) resolve_notification_references validate_action(action) if Chef::Config[:verbose_logging] || Chef::Log.level == :debug # This can be noisy Chef::Log.info("Processing #{self} action #{action} (#{defined_at})") end # ensure that we don't leave @updated_by_last_action set to true # on accident updated_by_last_action(false) # Don't modify @retries directly and keep it intact, so that the # recipe_snippet from ResourceFailureInspector can print the value # that was set in the resource block initially. remaining_retries = retries begin return if should_skip?(action) provider_for_action(action).run_action rescue Exception => e if ignore_failure Chef::Log.error("#{custom_exception_message(e)}; ignore_failure is set, continuing") events.resource_failed(self, action, e) elsif remaining_retries > 0 events.resource_failed_retriable(self, action, remaining_retries, e) remaining_retries -= 1 Chef::Log.info("Retrying execution of #{self}, #{remaining_retries} attempt(s) left") sleep retry_delay retry else events.resource_failed(self, action, e) raise customize_exception(e) end end ensure @elapsed_time = Time.now - start_time # Reporting endpoint doesn't accept a negative resource duration so set it to 0. # A negative value can occur when a resource changes the system time backwards @elapsed_time = 0 if @elapsed_time < 0 events.resource_completed(self) end # # If we are currently initializing the resource, this will be true. # # Do NOT use this. It may be removed. It is for internal purposes only. # @api private attr_reader :resource_initializing def resource_initializing=(value) if value @resource_initializing = true else remove_instance_variable(:@resource_initializing) end end # # Generic Ruby and Data Structure Stuff (for user) # def to_s "#{resource_name}[#{name}]" end def to_text return "suppressed sensitive resource output" if sensitive ivars = instance_variables.map { |ivar| ivar.to_sym } - HIDDEN_IVARS text = "# Declared in #{@source_line}\n\n" text << "#{resource_name}(\"#{name}\") do\n" ivars.each do |ivar| if (value = instance_variable_get(ivar)) && !(value.respond_to?(:empty?) && value.empty?) value_string = value.respond_to?(:to_text) ? value.to_text : value.inspect text << " #{ivar.to_s.sub(/^@/, '')} #{value_string}\n" end end [@not_if, @only_if].flatten.each do |conditional| text << " #{conditional.to_text}\n" end text << "end\n" end def inspect ivars = instance_variables.map { |ivar| ivar.to_sym } - FORBIDDEN_IVARS ivars.inject("<#{self}") do |str, ivar| str << " #{ivar}: #{instance_variable_get(ivar).inspect}" end << ">" end # as_json does most of the to_json heavy lifted. It exists here in case activesupport # is loaded. activesupport will call as_json and skip over to_json. This ensure # json is encoded as expected def as_json(*a) safe_ivars = instance_variables.map { |ivar| ivar.to_sym } - FORBIDDEN_IVARS instance_vars = Hash.new safe_ivars.each do |iv| instance_vars[iv.to_s.sub(/^@/, "")] = instance_variable_get(iv) end { "json_class" => self.class.name, "instance_vars" => instance_vars, } end # Serialize this object as a hash def to_json(*a) results = as_json Chef::JSONCompat.to_json(results, *a) end def to_hash # Grab all current state, then any other ivars (backcompat) result = {} self.class.state_properties.each do |p| result[p.name] = p.get(self) end safe_ivars = instance_variables.map { |ivar| ivar.to_sym } - FORBIDDEN_IVARS safe_ivars.each do |iv| key = iv.to_s.sub(/^@/, "").to_sym next if result.has_key?(key) result[key] = instance_variable_get(iv) end result end def self.json_create(o) resource = self.new(o["instance_vars"]["@name"]) o["instance_vars"].each do |k, v| resource.instance_variable_set("@#{k}".to_sym, v) end resource end # # Resource Definition Interface (for resource developers) # include Chef::Mixin::Deprecation # # The provider class for this resource. # # If `action :x do ... end` has been declared on this resource or its # superclasses, this will return the `action_class`. # # If this is not set, `provider_for_action` will dynamically determine the # provider. # # @param arg [String, Symbol, Class] Sets the provider class for this resource. # If passed a String or Symbol, e.g. `:file` or `"file"`, looks up the # provider based on the name. # # @return The provider class for this resource. # # @see Chef::Resource.action_class # def provider(arg = nil) klass = if arg.kind_of?(String) || arg.kind_of?(Symbol) lookup_provider_constant(arg) else arg end set_or_return(:provider, klass, kind_of: [ Class ]) || self.class.action_class end def provider=(arg) provider(arg) end # # Set or return the list of "state properties" implemented by the Resource # subclass. # # Equivalent to calling #state_properties and getting `state_properties.keys`. # # @deprecated Use state_properties.keys instead. Note that when you declare # properties with `property`: properties are added to state_properties by # default, and can be turned off with `desired_state: false` # # ```ruby # property :x # part of desired state # property :y, desired_state: false # not part of desired state # ``` # # @param names [Array<Symbol>] A list of property names to set as desired # state. # # @return [Array<Symbol>] All property names with desired state. # def self.state_attrs(*names) state_properties(*names).map { |property| property.name } end # # Set the identity of this resource to a particular property. # # This drives #identity, which returns data that uniquely refers to a given # resource on the given node (in such a way that it can be correlated # across Chef runs). # # This method is unnecessary when declaring properties with `property`; # properties can be added to identity during declaration with # `identity: true`. # # ```ruby # property :x, identity: true # part of identity # property :y # not part of identity # ``` # # @param name [Symbol] A list of property names to set as the identity. # # @return [Symbol] The identity property if there is only one; or `nil` if # there are more than one. # # @raise [ArgumentError] If no arguments are passed and the resource has # more than one identity property. # def self.identity_property(name = nil) result = identity_properties(*Array(name)) if result.size > 1 raise Chef::Exceptions::MultipleIdentityError, "identity_property cannot be called on an object with more than one identity property (#{result.map { |r| r.name }.join(", ")})." end result.first end # # Set a property as the "identity attribute" for this resource. # # Identical to calling #identity_property.first.key. # # @param name [Symbol] The name of the property to set. # # @return [Symbol] # # @deprecated `identity_property` should be used instead. # # @raise [ArgumentError] If no arguments are passed and the resource has # more than one identity property. # def self.identity_attr(name = nil) property = identity_property(name) return nil if !property property.name end # # The guard interpreter that will be used to process `only_if` and `not_if` # statements by default. If left unset, or set to `:default`, the guard # interpreter used will be Chef::GuardInterpreter::DefaultGuardInterpreter. # # Must be a resource class like `Chef::Resource::Execute`, or # a corresponding to the name of a resource. The resource must descend from # `Chef::Resource::Execute`. # # TODO this needs to be coerced on input so that retrieval is consistent. # # @return [Class, Symbol, String] the default Guard interpreter resource. # attr_reader :default_guard_interpreter # # The list of actions this Resource is allowed to have. Setting `action` # will fail unless it is in this list. Default: [ :nothing ] # # @return [Array<Symbol>] The list of actions this Resource is allowed to # have. # attr_accessor :allowed_actions def allowed_actions(value = NOT_PASSED) if value != NOT_PASSED self.allowed_actions = value end @allowed_actions end # # Whether or not this resource was updated during an action. If multiple # actions are set on the resource, this will be `true` if *any* action # caused an update to happen. # # @return [Boolean] Whether the resource was updated during an action. # attr_reader :updated # # Whether or not this resource was updated during an action. If multiple # actions are set on the resource, this will be `true` if *any* action # caused an update to happen. # # @return [Boolean] Whether the resource was updated during an action. # def updated? updated end # # Whether or not this resource was updated during the most recent action. # This is set to `false` at the beginning of each action. # # @param true_or_false [Boolean] Whether the resource was updated during the # current / most recent action. # @return [Boolean] Whether the resource was updated during the most recent action. # def updated_by_last_action(true_or_false) @updated ||= true_or_false @updated_by_last_action = true_or_false end # # Whether or not this resource was updated during the most recent action. # This is set to `false` at the beginning of each action. # # @return [Boolean] Whether the resource was updated during the most recent action. # def updated_by_last_action? @updated_by_last_action end # # Set whether this class was updated during an action. # # @deprecated Multiple actions are supported by resources. Please call {}#updated_by_last_action} instead. # def updated=(true_or_false) Chef::Log.warn("Chef::Resource#updated=(true|false) is deprecated. Please call #updated_by_last_action(true|false) instead.") Chef::Log.warn("Called from:") caller[0..3].each { |line| Chef::Log.warn(line) } updated_by_last_action(true_or_false) @updated = true_or_false end # # The display name of this resource type, for printing purposes. # # Will be used to print out the resource in messages, e.g. resource_name[name] # # @return [Symbol] The name of this resource type (e.g. `:execute`). # def resource_name @resource_name || self.class.resource_name end # # Sets a list of capabilities of the real resource. For example, `:remount` # (for filesystems) and `:restart` (for services). # # TODO Calling resource.supports({}) will not set this to empty; it will do # a get instead. That's wrong. # # @param args Hash{Symbol=>Boolean} If non-empty, sets the capabilities of # this resource. Default: {} # @return Hash{Symbol=>Boolean} An array of things this resource supports. # def supports(args = {}) if args.any? @supports = args else @supports end end def supports=(args) supports(args) end # # A hook called after a resource is created. Meant to be overriden by # subclasses. # def after_created nil end # # The DSL name of this resource (e.g. `package` or `yum_package`) # # @return [String] The DSL name of this resource. # # @deprecated Use resource_name instead. # def self.dsl_name Chef.log_deprecation "Resource.dsl_name is deprecated and will be removed in Chef 13. Use resource_name instead." if name name = self.name.split("::")[-1] convert_to_snake_case(name) end end # # The display name of this resource type, for printing purposes. # # This also automatically calls "provides" to provide DSL with the given # name. # # resource_name defaults to your class name. # # Call `resource_name nil` to remove the resource name (and any # corresponding DSL). # # @param value [Symbol] The desired name of this resource type (e.g. # `execute`), or `nil` if this class is abstract and has no resource_name. # # @return [Symbol] The name of this resource type (e.g. `:execute`). # def self.resource_name(name = NOT_PASSED) # Setter if name != NOT_PASSED remove_canonical_dsl # Set the resource_name and call provides if name name = name.to_sym # If our class is not already providing this name, provide it. if !Chef::ResourceResolver.includes_handler?(name, self) provides name, canonical: true end @resource_name = name else @resource_name = nil end end @resource_name end def self.resource_name=(name) resource_name(name) end # # Use the class name as the resource name. # # Munges the last part of the class name from camel case to snake case, # and sets the resource_name to that: # # A::B::BlahDBlah -> blah_d_blah # def self.use_automatic_resource_name automatic_name = convert_to_snake_case(self.name.split("::")[-1]) resource_name automatic_name end # # The module where Chef should look for providers for this resource. # The provider for `MyResource` will be looked up using # `provider_base::MyResource`. Defaults to `Chef::Provider`. # # @param arg [Module] The module containing providers for this resource # @return [Module] The module containing providers for this resource # # @example # class MyResource < Chef::Resource # provider_base Chef::Provider::Deploy # # ...other stuff # end # # @deprecated Use `provides` on the provider, or `provider` on the resource, instead. # def self.provider_base(arg = nil) if arg Chef.log_deprecation("Resource.provider_base is deprecated and will be removed in Chef 13. Use provides on the provider, or provider on the resource, instead.") end @provider_base ||= arg || Chef::Provider end # # The list of allowed actions for the resource. # # @param actions [Array<Symbol>] The list of actions to add to allowed_actions. # # @return [Array<Symbol>] The list of actions, as symbols. # def self.allowed_actions(*actions) @allowed_actions ||= if superclass.respond_to?(:allowed_actions) superclass.allowed_actions.dup else [ :nothing ] end @allowed_actions |= actions.flatten end def self.allowed_actions=(value) @allowed_actions = value.uniq end # # The action that will be run if no other action is specified. # # Setting default_action will automatially add the action to # allowed_actions, if it isn't already there. # # Defaults to [:nothing]. # # @param action_name [Symbol,Array<Symbol>] The default action (or series # of actions) to use. # # @return [Array<Symbol>] The default actions for the resource. # def self.default_action(action_name = NOT_PASSED) unless action_name.equal?(NOT_PASSED) @default_action = Array(action_name).map(&:to_sym) self.allowed_actions |= @default_action end if @default_action @default_action elsif superclass.respond_to?(:default_action) superclass.default_action else [:nothing] end end def self.default_action=(action_name) default_action action_name end # # Define an action on this resource. # # The action is defined as a *recipe* block that will be compiled and then # converged when the action is taken (when Resource is converged). The recipe # has access to the resource's attributes and methods, as well as the Chef # recipe DSL. # # Resources in the action recipe may notify and subscribe to other resources # within the action recipe, but cannot notify or subscribe to resources # in the main Chef run. # # Resource actions are *inheritable*: if resource A defines `action :create` # and B is a subclass of A, B gets all of A's actions. Additionally, # resource B can define `action :create` and call `super()` to invoke A's # action code. # # The first action defined (besides `:nothing`) will become the default # action for the resource. # # @param name [Symbol] The action name to define. # @param recipe_block The recipe to run when the action is taken. This block # takes no parameters, and will be evaluated in a new context containing: # # - The resource's public and protected methods (including attributes) # - The Chef Recipe DSL (file, etc.) # - super() referring to the parent version of the action (if any) # # @return The Action class implementing the action # def self.action(action, &recipe_block) action = action.to_sym declare_action_class action_class.action(action, &recipe_block) self.allowed_actions += [ action ] default_action action if Array(default_action) == [:nothing] end # # Define a method to load up this resource's properties with the current # actual values. # # @param load_block The block to load. Will be run in the context of a newly # created resource with its identity values filled in. # def self.load_current_value(&load_block) define_method(:load_current_value!, &load_block) end # # Call this in `load_current_value` to indicate that the value does not # exist and that `current_resource` should therefore be `nil`. # # @raise Chef::Exceptions::CurrentValueDoesNotExist # def current_value_does_not_exist! raise Chef::Exceptions::CurrentValueDoesNotExist end # # Get the current actual value of this resource. # # This does not cache--a new value will be returned each time. # # @return A new copy of the resource, with values filled in from the actual # current value. # def current_value provider = provider_for_action(Array(action).first) if provider.whyrun_mode? && !provider.whyrun_supported? raise "Cannot retrieve #{self.class.current_resource} in why-run mode: #{provider} does not support why-run" end provider.load_current_resource provider.current_resource end # # The action class is an automatic `Provider` created to handle # actions declared by `action :x do ... end`. # # This class will be returned by `resource.provider` if `resource.provider` # is not set. `provider_for_action` will also use this instead of calling # out to `Chef::ProviderResolver`. # # If the user has not declared actions on this class or its superclasses # using `action :x do ... end`, then there is no need for this class and # `action_class` will be `nil`. # # If a block is passed, the action_class is always created and the block is # run inside it. # # @api private # def self.action_class(&block) return @action_class if @action_class && !block # If the superclass needed one, then we need one as well. if block || (superclass.respond_to?(:action_class) && superclass.action_class) @action_class = declare_action_class(&block) end @action_class end # # Ensure the action class actually gets created. This is called # when the user does `action :x do ... end`. # # If a block is passed, it is run inside the action_class. # # @api private def self.declare_action_class(&block) @action_class ||= begin if superclass.respond_to?(:action_class) base_provider = superclass.action_class end base_provider ||= Chef::Provider resource_class = self Class.new(base_provider) do include ActionClass self.resource_class = resource_class end end @action_class.class_eval(&block) if block @action_class end # # Internal Resource Interface (for Chef) # FORBIDDEN_IVARS = [:@run_context, :@not_if, :@only_if, :@enclosing_provider] HIDDEN_IVARS = [:@allowed_actions, :@resource_name, :@source_line, :@run_context, :@name, :@not_if, :@only_if, :@elapsed_time, :@enclosing_provider] include Chef::Mixin::ConvertToClassName extend Chef::Mixin::ConvertToClassName # XXX: this is required for definition params inside of the scope of a # subresource to work correctly. attr_accessor :params # @return [Chef::RunContext] The run context for this Resource. This is # where the context for the current Chef run is stored, including the node # and the resource collection. attr_accessor :run_context # @return [String] The cookbook this resource was declared in. attr_accessor :cookbook_name # @return [String] The recipe this resource was declared in. attr_accessor :recipe_name # @return [Chef::Provider] The provider this resource was declared in (if # it was declared in an LWRP). When you call methods that do not exist # on this Resource, Chef will try to call the method on the provider # as well before giving up. attr_accessor :enclosing_provider # @return [String] The source line where this resource was declared. # Expected to come from caller() or a stack trace, it usually follows one # of these formats: # /some/path/to/file.rb:80:in `wombat_tears' # C:/some/path/to/file.rb:80 in 1`wombat_tears' attr_accessor :source_line # @return [String] The actual name that was used to create this resource. # Sometimes, when you say something like `package 'blah'`, the system will # create a different resource (i.e. `YumPackage`). When this happens, the # user will expect to see the thing they wrote, not the type that was # returned. May be `nil`, in which case callers should read #resource_name. # See #declared_key. attr_accessor :declared_type # # Iterates over all immediate and delayed notifications, calling # resolve_resource_reference on each in turn, causing them to # resolve lazy/forward references. def resolve_notification_references run_context.before_notifications(self).each { |n| n.resolve_resource_reference(run_context.resource_collection) } run_context.immediate_notifications(self).each { |n| n.resolve_resource_reference(run_context.resource_collection) } run_context.delayed_notifications(self).each {|n| n.resolve_resource_reference(run_context.resource_collection) } end # Helper for #notifies def notifies_before(action, resource_spec) run_context.notifies_before(Notification.new(resource_spec, action, self)) end # Helper for #notifies def notifies_immediately(action, resource_spec) run_context.notifies_immediately(Notification.new(resource_spec, action, self)) end # Helper for #notifies def notifies_delayed(action, resource_spec) run_context.notifies_delayed(Notification.new(resource_spec, action, self)) end class << self # back-compat # NOTE: that we do not support unregistering classes as descendants like # we used to for LWRP unloading because that was horrible and removed in # Chef-12. # @deprecated # @api private alias :resource_classes :descendants # @deprecated # @api private alias :find_subclass_by_name :find_descendants_by_name end # @deprecated # @api private # We memoize a sorted version of descendants so that resource lookups don't # have to sort all the things, all the time. # This was causing performance issues in test runs, and probably in real # life as well. @@sorted_descendants = nil def self.sorted_descendants @@sorted_descendants ||= descendants.sort_by { |x| x.to_s } end def self.inherited(child) super @@sorted_descendants = nil # set resource_name automatically if it's not set if child.name && !child.resource_name if child.name =~ /^Chef::Resource::(\w+)$/ child.resource_name(convert_to_snake_case($1)) end end end # If an unknown method is invoked, determine whether the enclosing Provider's # lexical scope can fulfill the request. E.g. This happens when the Resource's # block invokes new_resource. def method_missing(method_symbol, *args, &block) if enclosing_provider && enclosing_provider.respond_to?(method_symbol) enclosing_provider.send(method_symbol, *args, &block) else raise NoMethodError, "undefined method `#{method_symbol}' for #{self.class}" end end # # Mark this resource as providing particular DSL. # # Resources have an automatic DSL based on their resource_name, equivalent to # `provides :resource_name` (providing the resource on all OS's). If you # declare a `provides` with the given resource_name, it *replaces* that # provides (so that you can provide your resource DSL only on certain OS's). # def self.provides(name, **options, &block) name = name.to_sym # `provides :resource_name, os: 'linux'`) needs to remove the old # canonical DSL before adding the new one. if @resource_name && name == @resource_name remove_canonical_dsl end result = Chef.resource_handler_map.set(name, self, options, &block) Chef::DSL::Resources.add_resource_dsl(name) result end def self.provides?(node, resource_name) Chef::ResourceResolver.new(node, resource_name).provided_by?(self) end # Helper for #notifies def validate_resource_spec!(resource_spec) run_context.resource_collection.validate_lookup_spec!(resource_spec) end # We usually want to store and reference resources by their declared type and not the actual type that # was looked up by the Resolver (IE, "package" becomes YumPackage class). If we have not been provided # the declared key we want to fall back on the old to_s key. def declared_key return to_s if declared_type.nil? "#{declared_type}[#{@name}]" end def before_notifications run_context.before_notifications(self) end def immediate_notifications run_context.immediate_notifications(self) end def delayed_notifications run_context.delayed_notifications(self) end def source_line_file if source_line source_line.match(/(.*):(\d+):?.*$/).to_a[1] else nil end end def source_line_number if source_line source_line.match(/(.*):(\d+):?.*$/).to_a[2] else nil end end def defined_at # The following regexp should match these two sourceline formats: # /some/path/to/file.rb:80:in `wombat_tears' # C:/some/path/to/file.rb:80 in 1`wombat_tears' # extracting the path to the source file and the line number. if cookbook_name && recipe_name && source_line "#{cookbook_name}::#{recipe_name} line #{source_line_number}" elsif source_line "#{source_line_file} line #{source_line_number}" else "dynamically defined" end end # # The cookbook in which this Resource was defined (if any). # # @return Chef::CookbookVersion The cookbook in which this Resource was defined. # def cookbook_version if cookbook_name run_context.cookbook_collection[cookbook_name] end end def events run_context.events end def validate_action(action) raise ArgumentError, "nil is not a valid action for resource #{self}" if action.nil? end def provider_for_action(action) provider_class = Chef::ProviderResolver.new(node, self, action).resolve provider = provider_class.new(self, run_context) provider.action = action provider end # ??? TODO Seems unused. Delete? def noop(tf = nil) if !tf.nil? raise ArgumentError, "noop must be true or false!" unless tf == true || tf == false @noop = tf end @noop end # TODO Seems unused. Delete? def is(*args) if args.size == 1 args.first else return *args end end # # Preface an exception message with generic Resource information. # # @param e [StandardError] An exception with `e.message` # @return [String] An exception message customized with class name. # def custom_exception_message(e) "#{self} (#{defined_at}) had an error: #{e.class.name}: #{e.message}" end def customize_exception(e) new_exception = e.exception(custom_exception_message(e)) new_exception.set_backtrace(e.backtrace) new_exception end # Evaluates not_if and only_if conditionals. Returns a falsey value if any # of the conditionals indicate that this resource should be skipped, i.e., # if an only_if evaluates to false or a not_if evaluates to true. # # If this resource should be skipped, returns the first conditional that # "fails" its check. Subsequent conditionals are not evaluated, so in # general it's not a good idea to rely on side effects from not_if or # only_if commands/blocks being evaluated. # # Also skips conditional checking when the action is :nothing def should_skip?(action) conditional_action = ConditionalActionNotNothing.new(action) conditionals = [ conditional_action ] + only_if + not_if conditionals.find do |conditional| if conditional.continue? false else events.resource_skipped(self, action, conditional) Chef::Log.debug("Skipping #{self} due to #{conditional.description}") true end end end # Returns a resource based on a short_name and node # # ==== Parameters # short_name<Symbol>:: short_name of the resource (ie :directory) # node<Chef::Node>:: Node object to look up platform and version in # # === Returns # <Chef::Resource>:: returns the proper Chef::Resource class def self.resource_for_node(short_name, node) klass = Chef::ResourceResolver.resolve(short_name, node: node) raise Chef::Exceptions::NoSuchResourceType.new(short_name, node) if klass.nil? klass end # # Returns the class with the given resource_name. # # ==== Parameters # short_name<Symbol>:: short_name of the resource (ie :directory) # # === Returns # <Chef::Resource>:: returns the proper Chef::Resource class # def self.resource_matching_short_name(short_name) Chef::ResourceResolver.resolve(short_name, canonical: true) end # @api private def self.register_deprecated_lwrp_class(resource_class, class_name) if Chef::Resource.const_defined?(class_name, false) Chef::Log.warn "#{class_name} already exists! Deprecation class overwrites #{resource_class}" Chef::Resource.send(:remove_const, class_name) end if !Chef::Config[:treat_deprecation_warnings_as_errors] Chef::Resource.const_set(class_name, resource_class) deprecated_constants[class_name.to_sym] = resource_class end end def self.deprecated_constants @deprecated_constants ||= {} end # @api private def lookup_provider_constant(name, action = :nothing) begin self.class.provider_base.const_get(convert_to_class_name(name.to_s)) rescue NameError => e if e.to_s =~ /#{Regexp.escape(self.class.provider_base.to_s)}/ raise ArgumentError, "No provider found to match '#{name}'" else raise e end end end private def self.remove_canonical_dsl if @resource_name remaining = Chef.resource_handler_map.delete_canonical(@resource_name, self) if !remaining Chef::DSL::Resources.remove_resource_dsl(@resource_name) end end end end end # Requiring things at the bottom breaks cycles require "chef/chef_class"
33.963221
184
0.649888
7a3377a48611cc9ef7fd377d737be60fcc10eb6c
524
# frozen_string_literal: true module TestProf module TagProf # :nodoc: # Object holding all the stats for tags class Result attr_reader :tag, :data def initialize(tag) @tag = tag @data = Hash.new { |h, k| h[k] = { value: k, count: 0, time: 0.0 } } end def track(tag, time:) data[tag][:count] += 1 data[tag][:time] += time end def to_json { tag: tag, data: data.values }.to_json end end end end
18.714286
76
0.515267