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
4af2ad479ede50a2f835037026bfe15b7e93e4d4
1,564
require "digest" require "method_source" module SafeMonkeypatch extend self class UpstreamChanged < StandardError end class ConfigurationError < StandardError end class InvalidMethod < StandardError end end class Module def safe_monkeypatch(meth, options={}) options = options.dup info = options.delete(:error) if meth.is_a? UnboundMethod method = meth meth = method.name else begin method = instance_method(meth) rescue NameError => e raise SafeMonkeypatch::InvalidMethod, "#{inspect} has no method #{meth} anymore" end end source = method.source if options.empty? raise SafeMonkeypatch::ConfigurationError, "Provide at least one cypher name like: md5: '...'" end found_match = false error_parts = ["#{inspect}##{meth} expected to have"] options.each do |cypher_name, expected| cypher = Digest.const_get(cypher_name.upcase) actual = cypher.hexdigest(source) found_match = if expected.is_a? Array expected.any? { |e| e == actual } else actual == expected end unless found_match error_parts << "#{cypher_name} expected: #{expected.inspect}, but has: #{actual.inspect}" end end error_parts << info.to_s if info if block_given? && found_match yield elsif block_given? nil # pass elsif not found_match raise SafeMonkeypatch::UpstreamChanged, error_parts.join(" ") end end end
23
100
0.632353
ac15857abbe15678c5f68dd2ef6c53ab6a1696d4
1,206
module Feedjira module Parser class AtomYoutubeEntry include SAXMachine include FeedEntryUtilities element :title element :link, as: :url, value: :href, with: { rel: 'alternate' } element :name, as: :author element :"media:description", as: :content element :summary element :published element :id, as: :entry_id element :updated element :"yt:videoId", as: :youtube_video_id element :"media:title", as: :media_title element :"media:content", as: :media_url, value: :url element :"media:content", as: :media_type, value: :type element :"media:content", as: :media_width, value: :width element :"media:content", as: :media_height, value: :height element :"media:thumbnail", as: :media_thumbnail_url, value: :url element :"media:thumbnail", as: :media_thumbnail_width, value: :width element :"media:thumbnail", as: :media_thumbnail_height, value: :height element :"media:starRating", as: :media_star_count, value: :count element :"media:starRating", as: :media_star_average, value: :average element :"media:statistics", as: :media_views, value: :views end end end
40.2
77
0.665008
fffca2fafb81aa7fa33c33eaf343a763ea9e826b
118
module Wf class ApplicationController < ActionController::API # protect_from_forgery with: :exception end end
19.666667
53
0.779661
61023eaba8d468d921818506281016978a03c31a
1,019
describe :argf_readlines, :shared => true do before :each do ARGV.clear @file1 = ARGFSpecs.fixture_file('file1.txt') @file2 = ARGFSpecs.fixture_file('file2.txt') @stdin = ARGFSpecs.fixture_file('stdin.txt') @contents_file1 = File.read(@file1) @contents_file2 = File.read(@file2) @contents_stdin = File.read(@stdin) end after :each do # Close any open file (catch exception if already closed) ARGF.close rescue nil ARGFSpecs.fixture_file_delete(@file1,@file2,@stdin) end it "reads all lines of all files" do ARGFSpecs.file_args('file1.txt', 'file2.txt', '-') STDIN.reopen(@stdin) all_lines = (@contents_file1 + @contents_file2 + @contents_stdin).split($/).collect { |l| l+$/ } ary = ARGF.send(@method) ary.should == all_lines end it "returns nil when end of stream reached" do ARGFSpecs.file_args('file1.txt', 'file2.txt', '-') STDIN.reopen(@stdin) ARGF.read # read all files at once ARGF.send(@method).should == nil end end
30.878788
100
0.669284
39283f6855559fc5a4af12c75823a4fde0c67a67
278
class CreateComments < ActiveRecord::Migration[5.2] def change create_table :comments do |t| t.text :content t.integer :user_id, foreign_key: true t.integer :post_id, foreign_key: true t.references :comment_id t.timestamps end end end
21.384615
51
0.672662
b9cdf0e17873a72293a0803ce28b4f3282ebab36
7,301
require_relative "../prepositions" module Acl9 module ModelExtensions module ForSubject include Prepositions DEFAULT = Class.new do def default? true end end.new.freeze ## # Role check. # # There is a global option, +Acl9.config[:protect_global_roles]+, which governs # this method behavior. # # If protect_global_roles is +false+, an object role is automatically counted # as global role. E.g. # # Acl9.config[:protect_global_roles] = false # user.has_role!(:manager, @foo) # user.has_role?(:manager, @foo) # => true # user.has_role?(:manager) # => true # # In this case manager is anyone who "manages" at least one object. # # However, if protect_global_roles option set to +true+, you'll need to # explicitly grant global role with same name. # # Acl9.config[:protect_global_roles] = true # user.has_role!(:manager, @foo) # user.has_role?(:manager) # => false # user.has_role!(:manager) # user.has_role?(:manager) # => true # # protect_global_roles option is +false+ by default as for now, but this # may change in future! # # @return [Boolean] Whether +self+ has a role +role_name+ on +object+. # @param [Symbol,String] role_name Role name # @param [Object] object Object to query a role on # # @see Acl9::ModelExtensions::Object#accepts_role? def has_role?(role_name, object = default) check! object role_name = normalize role_name object = _by_preposition object !! if object == default && !::Acl9.config[:protect_global_roles] _role_objects.find_by_name(role_name.to_s) || _role_objects.member?(get_role(role_name, object)) else role = get_role(role_name, object) role && _role_objects.exists?(role.id) end end ## # Add specified role on +object+ to +self+. # # @param [Symbol,String] role_name Role name # @param [Object] object Object to add a role for # @see Acl9::ModelExtensions::Object#accepts_role! def has_role!(role_name, object = default) check! object role_name = normalize role_name object = _by_preposition object role = get_role(role_name, object) if role.nil? role_attrs = case object when Class then { :authorizable_type => object.to_s } when default then {} else { :authorizable => object } end.merge({ :name => role_name.to_s }) role = _auth_role_class.create(role_attrs) end _role_objects << role if role && !_role_objects.exists?(role.id) end ## # Free +self+ from a specified role on +object+. # # @param [Symbol,String] role_name Role name # @param [Object] object Object to remove a role on # @see Acl9::ModelExtensions::Object#accepts_no_role! def has_no_role!(role_name, object = default) check! object role_name = normalize role_name object = _by_preposition object delete_role(get_role(role_name, object)) end ## # Are there any roles for +self+ on +object+? # # @param [Object] object Object to query roles # @return [Boolean] Returns true if +self+ has any roles on +object+. # @see Acl9::ModelExtensions::Object#accepts_roles_by? def has_roles_for?(object) check! object !!_role_objects.detect(&role_selecting_lambda(object)) end alias :has_role_for? :has_roles_for? ## # Which roles does +self+ have on +object+? # # @return [Array<Role>] Role instances, associated both with +self+ and +object+ # @param [Object] object Object to query roles # @see Acl9::ModelExtensions::Object#accepted_roles_by # @example # user = User.find(...) # product = Product.find(...) # # user.roles_for(product).map(&:name).sort #=> role names in alphabetical order def roles_for(object) check! object _role_objects.select(&role_selecting_lambda(object)) end ## # Unassign any roles on +object+ from +self+. # # @param [Object,default] object Object to unassign roles for. Empty args means unassign global roles. def has_no_roles_for!(object = default) check! object roles_for(object).each { |role| delete_role(role) } end ## # Unassign all roles from +self+. def has_no_roles! # for some reason simple # # roles.each { |role| delete_role(role) } # # doesn't work. seems like a bug in ActiveRecord _role_objects.map(&:id).each do |role_id| delete_role _auth_role_class.find(role_id) end end private def role_selecting_lambda(object) case object when Class lambda { |role| role.authorizable_type == object.to_s } when default lambda { |role| role.authorizable.nil? } else lambda do |role| auth_id = role.authorizable_id.kind_of?(String) ? object.id.to_s : object.id role.authorizable_type == object.class.base_class.to_s && role.authorizable_id == auth_id end end end def get_role(role_name, object = default) check! object role_name = normalize role_name cond = case object when Class [ 'name = ? and authorizable_type = ? and authorizable_id IS NULL', role_name, object.to_s ] when default [ 'name = ? and authorizable_type IS NULL and authorizable_id IS NULL', role_name ] else [ 'name = ? and authorizable_type = ? and authorizable_id = ?', role_name, object.class.base_class.to_s, object.id ] end if _auth_role_class.respond_to?(:where) _auth_role_class.where(cond).first else _auth_role_class.find(:first, :conditions => cond) end end def delete_role(role) if role if ret = _role_objects.delete(role) if role.send(_auth_subject_class_name.demodulize.tableize).empty? ret &&= role.destroy unless role.respond_to?(:system?) && role.system? end end ret end end def normalize role_name Acl9.config[:normalize_role_names] ? role_name.to_s.underscore.singularize : role_name.to_s end private def check! object raise NilObjectError if object.nil? end def _by_preposition object object.is_a?(Hash) ? super : object end def _auth_role_class self.class._auth_role_class_name.constantize end def _auth_role_assoc self.class._auth_role_assoc_name end def _role_objects send(_auth_role_assoc) end def default DEFAULT end end end end
31.334764
109
0.58581
01ec04f2976316e435e5468bf145358c34105125
424
require 'spec_helper' require 'result' describe Result do let(:value) {3} describe '.Success' do let(:result) {described_class.Success(value)} it 'is a success' do expect(result).to be_a(described_class::Success) end end describe '.Failure' do let(:result) {described_class.Failure(value)} it 'is a failure' do expect(result).to be_a(described_class::Failure) end end end
17.666667
54
0.67217
6a3bd609f4e814c92e2280afad5ee87c364fea72
641
rule "FC026", "Conditional execution block attribute contains only string" do tags %w{correctness} recipe do |ast| find_resources(ast).map { |r| resource_attributes(r) }.map do |resource| [resource["not_if"], resource["only_if"]] end.flatten.compact.select do |condition| condition.respond_to?(:xpath) && !condition.xpath("descendant::string_literal").empty? && !condition.xpath("(stmts_add|bodystmt/stmts_add)/string_literal").empty? && # stmts_add can go away with Ruby 2.4 condition.xpath('descendant::stmts_add[count(ancestor:: string_literal) = 0]').size == 1 end end end
42.733333
121
0.680187
62a18c28a6a5ac006579c71733b901746ad4c761
866
module BERTRPC class Service attr_accessor :host, :port, :timeout # For streaming, object must respond to write method attr_accessor :stream def initialize(host, port, timeout = nil) @host = host @port = port @timeout = timeout end def call(options = nil) verify_options(options) Request.new(self, :call, options) end def cast(options = nil) verify_options(options) Request.new(self, :cast, options) end # private def verify_options(options) if options if cache = options[:cache] unless cache[0] == :validation && cache[1].is_a?(String) raise InvalidOption.new("Valid :cache args are [:validation, String]") end else raise InvalidOption.new("Valid options are :cache") end end end end end
22.789474
82
0.605081
62517e6c1d183a2c918e2d6859a72aaa896b26f6
5,020
#-- copyright # OpenProject is an open source project management software. # Copyright (C) 2012-2021 the OpenProject GmbH # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 3. # # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows: # Copyright (C) 2006-2013 Jean-Philippe Lang # Copyright (C) 2010-2013 the ChiliProject Team # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # See docs/COPYRIGHT.rdoc for more details. #++ require 'support/pages/page' require 'support/pages/work_packages/concerns/work_package_by_button_creator' module Pages module IfcModels class Index < ::Pages::Page attr_accessor :project def initialize(project) self.project = project end def path bcf_project_ifc_models_path(project) end def model_listed(listed, model_name) within '.generic-table' do expect(page).to (listed ? have_text(model_name) : have_no_text(model_name)) end end def add_model_allowed(allowed) if allowed click_toolbar_button 'IFC model' expect_correct_page_loaded '.button[type="submit"]' expect(page).to have_current_path new_bcf_project_ifc_model_path(project) visit! else expect(page).to have_no_selector('.button.-alt-highlight', text: 'IFC model') end end def bcf_buttons(allowed) expect(page).to have_conditional_selector(allowed, '.toolbar-item', text: 'Import') expect(page).to have_conditional_selector(allowed, '.toolbar-item', text: 'Export') end def edit_model_allowed(model_name, allowed) row = find_model_table_row model_name within row do expect(page).to (allowed ? have_selector('.icon-edit') : have_no_selector('.icon-edit')) end end def delete_model_allowed(model_name, allowed) row = find_model_table_row model_name within row do expect(page).to (allowed ? have_selector('.icon-edit') : have_no_selector('.icon-edit')) end end def edit_model(model_name, new_name) click_table_icon model_name, '.icon-edit' change_model_name model_name, new_name click_on 'Save' model_listed true, new_name expect(current_path).to eq bcf_project_ifc_models_path(project) end def delete_model(model_name) click_table_icon model_name, '.icon-delete' page.driver.browser.switch_to.alert.accept model_listed false, model_name expect(current_path).to eq bcf_project_ifc_models_path(project) end def show_model(model) click_model_link model.title expect_correct_page_loaded '.ifc-model-viewer--container' expect_model_active(model) end def expect_model_active(model, active = true) expect(page).to have_field(model.id.to_s, checked: active, wait: 30) end def show_defaults(models = []) click_toolbar_button 'Show defaults' expect_correct_page_loaded '.ifc-model-viewer--container' models.each do |model| expect_model_active(model, model.is_default) end end private def find_model_table_row(model_name) within '.generic-table' do page.find('td', text: model_name).find(:xpath, '..') end end def click_model_link(model_name) within '.generic-table' do page.find('td a', text: model_name).click end end def click_toolbar_button(name) within '.toolbar' do page.find('.button', text: name).click end end def click_table_icon(model_name, icon_class) row = find_model_table_row model_name within row do page.find(icon_class).click end end def expect_correct_page_loaded(checked_selector) expect(page).to have_selector(checked_selector) end def change_model_name(model_name, new_name) expect(page).to have_selector('input[type="file"]') expect(page).to have_field('bim_ifc_models_ifc_model[title]', with: model_name) fill_in 'bim_ifc_models_ifc_model[title]', with: new_name end end end end
30.797546
98
0.677888
1cbe9865335bfbd4054a9b095fc4583ae4be2afd
1,842
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::TrafficManager::Mgmt::V2018_04_01 module Models # # Subnet first address, scope, and/or last address. # class EndpointPropertiesSubnetsItem include MsRestAzure # @return [String] First address in the subnet. attr_accessor :first # @return [String] Last address in the subnet. attr_accessor :last # @return [Integer] Block size (number of leading bits in the subnet # mask). attr_accessor :scope # # Mapper for EndpointPropertiesSubnetsItem class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'EndpointProperties_subnetsItem', type: { name: 'Composite', class_name: 'EndpointPropertiesSubnetsItem', model_properties: { first: { client_side_validation: true, required: false, serialized_name: 'first', type: { name: 'String' } }, last: { client_side_validation: true, required: false, serialized_name: 'last', type: { name: 'String' } }, scope: { client_side_validation: true, required: false, serialized_name: 'scope', type: { name: 'Number' } } } } } end end end end
26.695652
74
0.513029
1cf00665698155d9ccaab3303109ed97eebe34f4
1,429
module MathCaptcha class Captcha class << self # Only the #to_secret is shared with the client. # It can be reused here to create the Captcha again def from_secret(secret) yml = cipher.decrypt64 secret.to_s rescue {:x => 0, :y => 0, :operator => :+}.to_yaml args = YAML.load(yml) new(args[:x], args[:y], args[:operator]) end def cipher EzCrypto::Key.with_password MathCaptcha.config.key, MathCaptcha.config.salt end end attr_reader :x, :y, :operator def initialize(x=nil, y=nil, operator=nil) @x = x || MathCaptcha.config.numbers.sort_by{rand}.first @y = y || MathCaptcha.config.numbers.sort_by{rand}.first @operator = operator || MathCaptcha.config.operators.sort_by{rand}.first end def check(answer) return true if answer == 429 answer == solution end def task "#{@x} #{@operator.to_s} #{@y}" end def task_with_questionmark "#{@x} #{@operator.to_s} #{@y} = ?" end alias_method :to_s, :task def solution @x.send @operator, @y end def to_secret cipher.encrypt64(to_yaml) end def to_yaml YAML::dump({ :x => x, :y => y, :operator => operator }) end private def cipher @cipher ||= self.class.cipher end def reset_cipher @cipher = nil end end end
21.651515
93
0.578027
bbff4f5ec3f581066fc2aa7e7773aaf1b28cfd93
821
=begin #Tatum API ## Authentication <!-- ReDoc-Inject: <security-definitions> --> OpenAPI spec version: 3.9.0 Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 3.0.31 =end require 'spec_helper' require 'json' require 'date' # Unit tests for Tatum::OneOfhrm20DeployBody # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'OneOfhrm20DeployBody' do before do # run before each test @instance = Tatum::OneOfhrm20DeployBody.new end after do # run after each test end describe 'test an instance of OneOfhrm20DeployBody' do it 'should create an instance of OneOfhrm20DeployBody' do expect(@instance).to be_instance_of(Tatum::OneOfhrm20DeployBody) end end end
23.457143
85
0.749086
e9c2b1c2f28dc324eb61ab75eb94bd62e45c6fb9
151
class AddAlertSentToPipelineRun < ActiveRecord::Migration[5.1] def change add_column :pipeline_runs, :alert_sent, :integer, default: 0 end end
25.166667
64
0.768212
4ad03958dbcd205bd99784844422326185c0a80b
12,023
module RunLoop # A class for interacting with .app bundles. class App # @!attribute [r] path # @return [String] The path to the app bundle .app attr_reader :path # Creates a new App instance. # # @note The `app_bundle_path` is expanded during initialization. # # @param [String] app_bundle_path A path to a .app # @return [RunLoop::App] A instance of App with a path. def initialize(app_bundle_path) @path = File.expand_path(app_bundle_path) if !App.valid?(app_bundle_path) if App.cached_app_on_simulator?(app_bundle_path) raise RuntimeError, %Q{ App is "cached" on the simulator. #{app_bundle_path} This can happen if there was an incomplete install or uninstall. Try manually deleting the application data container and relaunching the simulator. $ rm -r #{File.dirname(app_bundle_path)} $ run-loop simctl manage-processes } else raise ArgumentError, %Q{App does not exist at path or is not an app bundle. #{app_bundle_path} Bundle must: 1. be a directory that exists, 2. have a .app extension, 3. contain an Info.plist, 4. and the app binary (CFBundleExecutable) must exist } end end end # @!visibility private def to_s cf_bundle_version = bundle_version cf_bundle_short_version = short_bundle_version if cf_bundle_version && cf_bundle_short_version version = "#{cf_bundle_version.to_s} / #{cf_bundle_short_version}" elsif cf_bundle_version version = cf_bundle_version.to_s elsif cf_bundle_short_version version = cf_bundle_short_version else version = "" end "#<APP #{bundle_identifier} #{version} #{path}>" end # @!visibility private def inspect to_s end # Is this a valid app? def valid? App.valid?(path) end # @!visibility private def self.valid?(app_bundle_path) return false if app_bundle_path.nil? return false if !File.directory?(app_bundle_path) return false if !File.extname(app_bundle_path) == ".app" return false if !self.info_plist_exist?(app_bundle_path) return false if !self.executable_file_exist?(app_bundle_path) true end # @!visibility private # # Starting in Xcode 10 betas, this can happen if there was an incomplete # install or uninstall. def self.cached_app_on_simulator?(app_bundle_path) return false if Dir[File.join(app_bundle_path, "**/*")].length != 2 return false if !app_bundle_path[RunLoop::Regex::CORE_SIMULATOR_UDID_REGEX] [File.join(app_bundle_path, "Info.plist"), File.join(app_bundle_path, "Icon.png")].all? do |file| File.exist?(file) end end # Returns the Info.plist path. # @raise [RuntimeError] If there is no Info.plist. def info_plist_path @info_plist_path ||= File.join(path, 'Info.plist') end # Inspects the app's Info.plist for the bundle identifier. # @return [String] The value of CFBundleIdentifier. # @raise [RuntimeError] If the plist cannot be read or the # CFBundleIdentifier is empty or does not exist. def bundle_identifier identifier = plist_buddy.plist_read("CFBundleIdentifier", info_plist_path) unless identifier raise "Expected key 'CFBundleIdentifier' in '#{info_plist_path}'" end identifier end # Inspects the app's Info.plist for the executable name. # @return [String] The value of CFBundleExecutable. # @raise [RuntimeError] If the plist cannot be read or the # CFBundleExecutable is empty or does not exist. def executable_name name = plist_buddy.plist_read("CFBundleExecutable", info_plist_path) unless name raise "Expected key 'CFBundleExecutable' in '#{info_plist_path}'" end name end # Returns the arches for the binary. def arches @arches ||= lipo.info end # True if the app has been built for the simulator def simulator? arches.include?("i386") || arches.include?("x86_64") end # True if the app has been built for physical devices def physical_device? arches.any? do |arch| arch[/arm/, 0] end end # Inspects the app's file for the server version def calabash_server_version version = nil executables.each do |executable| version = strings(executable).server_version break if version end version end # @!visibility private # Return the fingerprint of the linked server def calabash_server_id name = plist_buddy.plist_read("CFBundleExecutable", info_plist_path) app_executable = File.join(self.path, name) strings(app_executable).server_id end # @!visibility private def codesign_info RunLoop::Codesign.info(path) end # @!visibility private def developer_signed? RunLoop::Codesign.developer?(path) end # @!visibility private def distribution_signed? RunLoop::Codesign.distribution?(path) end # Returns the CFBundleShortVersionString of the app as Version instance. # # Apple docs: # # CFBundleShortVersionString specifies the release version number of the # bundle, which identifies a released iteration of the app. The release # version number is a string comprised of three period-separated integers. # # The first integer represents major revisions to the app, such as revisions # that implement new features or major changes. The second integer denotes # revisions that implement less prominent features. The third integer # represents maintenance releases. # # The value for this key differs from the value for CFBundleVersion, which # identifies an iteration (released or unreleased) of the app. This key can # be localized by including it in your InfoPlist.strings files. # # @return [RunLoop::Version, nil] Returns a Version instance if the # CFBundleShortVersion string is well formed and nil if not. def marketing_version string = plist_buddy.plist_read("CFBundleShortVersionString", info_plist_path) begin version = RunLoop::Version.new(string) rescue if string && string != "" RunLoop.log_debug("CFBundleShortVersionString: '#{string}' is not a well formed version string") else RunLoop.log_debug("CFBundleShortVersionString is not defined in Info.plist") end version = nil end version end # See #marketing_version alias_method :short_bundle_version, :marketing_version # Returns the CFBundleVersion of the app as Version instance. # # Apple docs: # # CFBundleVersion specifies the build version number of the bundle, which # identifies an iteration (released or unreleased) of the bundle. The build # version number should be a string comprised of three non-negative, # period-separated integers with the first integer being greater than zero. # The string should only contain numeric (0-9) and period (.) characters. # Leading zeros are truncated from each integer and will be ignored (that # is, 1.02.3 is equivalent to 1.2.3). # # @return [RunLoop::Version, nil] Returns a Version instance if the # CFBundleVersion string is well formed and nil if not. def build_version string = plist_buddy.plist_read("CFBundleVersion", info_plist_path) begin version = RunLoop::Version.new(string) rescue if string && string != "" RunLoop.log_debug("CFBundleVersion: '#{string}' is not a well formed version string") else RunLoop.log_debug("CFBundleVersion is not defined in Info.plist") end version = nil end version end # See #build_version alias_method :bundle_version, :build_version # @!visibility private # Collects the paths to executables in the bundle. def executables executables = [] Dir.glob("#{path}/**/*") do |file| next if skip_executable_check?(file) if otool.executable?(file) executables << file end end executables end # Returns the sha1 of the application. def sha1 RunLoop::Directory.directory_digest(path) end private # @!visibility private def self.info_plist_exist?(app_bundle_path) info_plist = File.join(app_bundle_path, "Info.plist") File.exist?(info_plist) end # @!visibility private def self.executable_file_exist?(app_bundle_path) return false if !self.info_plist_exist?(app_bundle_path) info_plist = File.join(app_bundle_path, "Info.plist") pbuddy = RunLoop::PlistBuddy.new name = pbuddy.plist_read("CFBundleExecutable", info_plist) if name File.exist?(File.join(app_bundle_path, name)) else false end end # @!visibility private def lipo @lipo ||= RunLoop::Lipo.new(path) end # @!visibility private def plist_buddy @plist_buddy ||= RunLoop::PlistBuddy.new end # @!visibility private def otool @otool ||= RunLoop::Otool.new(xcode) end # @!visibility private def xcode @xcode ||= RunLoop::Xcode.new end # @!visibility private # A strings factory def strings(file) RunLoop::Strings.new(file) end # @!visibility private def skip_executable_check?(file) File.directory?(file) || image?(file) || text?(file) || plist?(file) || lproj_asset?(file) || code_signing_asset?(file) || core_data_asset?(file) || font?(file) || build_artifact?(file) end # @!visibility private def text?(file) extension = File.extname(file) filename = File.basename(file) extension == ".txt" || extension == ".md" || extension == ".html" || extension == ".xml" || extension == ".json" || extension == ".yaml" || extension == ".yml" || extension == ".rtf" || ["NOTICE", "LICENSE", "README", "ABOUT"].any? do |elm| filename[/#{elm}/] end end # @!visibility private def image?(file) extension = File.extname(file) extension == ".jpeg" || extension == ".jpg" || extension == ".gif" || extension == ".png" || extension == ".tiff" || extension == ".svg" || extension == ".pdf" || extension == ".car" || file[/iTunesArtwork/, 0] end # @!visibility private def plist?(file) File.extname(file) == ".plist" end # @!visibility private def lproj_asset?(file) extension = File.extname(file) dir_extension = File.extname(File.dirname(file)) dir_extension == ".lproj" || dir_extension == ".storyboard" || dir_extension == ".storyboardc" || extension == ".strings" || extension == ".xib" || extension == ".nib" end # @!visibility private def code_signing_asset?(file) name = File.basename(file) extension = File.extname(file) dirname = File.basename(File.dirname(file)) name == "PkgInfo" || name == "embedded" || extension == ".mobileprovision" || extension == ".xcent" || dirname == "_CodeSignature" end # @!visibility private def core_data_asset?(file) extension = File.extname(file) dir_extension = File.extname(File.dirname(file)) dir_extension == ".momd" || extension == ".mom" || extension == ".db" || extension == ".omo" end # @!visibility private def font?(file) extension = File.extname(file) extension == ".ttf" || extension == ".otf" end # @!visibility private def build_artifact?(file) File.extname(file) == ".xcconfig" end end end
28.694511
106
0.63994
1d0b0e089a3c05a662de1cb41c829f2ff83c4f15
1,166
require "test_helper" class MaintainingRepoSubscriptionsTest < ActionDispatch::IntegrationTest fixtures :repos def triage_the_sandbox login_via_github visit "/" click_link "issue_triage_sandbox" first(:button, "Triage Issues").click assert page.has_content?("You'll receive daily triage e-mails for this repository.") end test "subscribing to a repo" do assert_difference 'ActionMailer::Base.deliveries.size', +1 do triage_the_sandbox assert page.has_content?("issue_triage_sandbox") end assert_equal IssueAssignment.last.delivered, true end test "send an issue! button" do triage_the_sandbox assert_difference 'ActionMailer::Base.deliveries.size', +1 do click_link "Send me a new issue!" assert page.has_content?("You will receive an email with your new issue shortly") end assert_equal IssueAssignment.last.delivered, true end test "listing subscribers" do triage_the_sandbox assert page.has_content?("mockstar") end # test "list only favorite languages" do # login_via_github # visit "/" # assert !page.has_content?("javascript") # end end
25.911111
88
0.723842
e2d9fd62378da33f9c00af8daa62cd89ed2b3c53
735
require 'test_helper' class HomeControllerTest < ActionController::TestCase include Devise::TestHelpers test "anonymous index" do get :index assert_redirected_to user_session_path end test "AdminUser index" do sign_in users(:admin_user) get :index assert_response :success assert_select "a[href=#{cities_path}]" assert_select "a[href=#{admin_users_path}]" assert_select "a[href=#{franquia_users_path}]" end test "FranquiaUser index" do sign_in users(:franquia_1) get :index assert_response :success assert_select "a[href=#{cities_path}]", false assert_select "a[href=#{admin_users_path}]", false assert_select "a[href=#{franquia_users_path}]", false end end
25.344828
57
0.718367
d562beb5b0a0902b00c9acd1664690a550df9303
122
module Fix module Protocol # # The message classes container module # module Messages end end end
12.2
42
0.639344
6201bbdadacd99e47287640b3f08419ede68c690
30,372
# Copyright 2018 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. # # EDITING INSTRUCTIONS # This file was generated from the file # https://github.com/googleapis/googleapis/blob/master/google/cloud/dataproc/v1/clusters.proto, # and updates to that file get reflected here through a refresh process. # For the short term, the refresh process will only be runnable by Google # engineers. require "json" require "pathname" require "google/gax" require "google/gax/operation" require "google/longrunning/operations_client" require "google/cloud/dataproc/v1/clusters_pb" require "google/cloud/dataproc/v1/credentials" module Google module Cloud module Dataproc module V1 # The ClusterControllerService provides methods to manage clusters # of Google Compute Engine instances. # # @!attribute [r] cluster_controller_stub # @return [Google::Cloud::Dataproc::V1::ClusterController::Stub] class ClusterControllerClient # @private attr_reader :cluster_controller_stub # The default address of the service. SERVICE_ADDRESS = "dataproc.googleapis.com".freeze # The default port of the service. DEFAULT_SERVICE_PORT = 443 # The default set of gRPC interceptors. GRPC_INTERCEPTORS = [] DEFAULT_TIMEOUT = 30 PAGE_DESCRIPTORS = { "list_clusters" => Google::Gax::PageDescriptor.new( "page_token", "next_page_token", "clusters") }.freeze private_constant :PAGE_DESCRIPTORS # The scopes needed to make gRPC calls to all of the methods defined in # this service. ALL_SCOPES = [ "https://www.googleapis.com/auth/cloud-platform" ].freeze # @private class OperationsClient < Google::Longrunning::OperationsClient self::SERVICE_ADDRESS = ClusterControllerClient::SERVICE_ADDRESS self::GRPC_INTERCEPTORS = ClusterControllerClient::GRPC_INTERCEPTORS end # @param credentials [Google::Auth::Credentials, String, Hash, GRPC::Core::Channel, GRPC::Core::ChannelCredentials, Proc] # Provides the means for authenticating requests made by the client. This parameter can # be many types. # A `Google::Auth::Credentials` uses a the properties of its represented keyfile for # authenticating requests made by this client. # A `String` will be treated as the path to the keyfile to be used for the construction of # credentials for this client. # A `Hash` will be treated as the contents of a keyfile to be used for the construction of # credentials for this client. # A `GRPC::Core::Channel` will be used to make calls through. # A `GRPC::Core::ChannelCredentials` for the setting up the RPC client. The channel credentials # should already be composed with a `GRPC::Core::CallCredentials` object. # A `Proc` will be used as an updater_proc for the Grpc channel. The proc transforms the # metadata for requests, generally, to give OAuth credentials. # @param scopes [Array<String>] # The OAuth scopes for this service. This parameter is ignored if # an updater_proc is supplied. # @param client_config [Hash] # A Hash for call options for each method. See # Google::Gax#construct_settings for the structure of # this data. Falls back to the default config if not specified # or the specified config is missing data points. # @param timeout [Numeric] # The default timeout, in seconds, for calls made through this client. # @param metadata [Hash] # Default metadata to be sent with each request. This can be overridden on a per call basis. # @param exception_transformer [Proc] # An optional proc that intercepts any exceptions raised during an API call to inject # custom error handling. def initialize \ credentials: nil, scopes: ALL_SCOPES, client_config: {}, timeout: DEFAULT_TIMEOUT, metadata: nil, exception_transformer: nil, lib_name: nil, lib_version: "" # These require statements are intentionally placed here to initialize # the gRPC module only when it's required. # See https://github.com/googleapis/toolkit/issues/446 require "google/gax/grpc" require "google/cloud/dataproc/v1/clusters_services_pb" credentials ||= Google::Cloud::Dataproc::V1::Credentials.default @operations_client = OperationsClient.new( credentials: credentials, scopes: scopes, client_config: client_config, timeout: timeout, lib_name: lib_name, lib_version: lib_version, ) if credentials.is_a?(String) || credentials.is_a?(Hash) updater_proc = Google::Cloud::Dataproc::V1::Credentials.new(credentials).updater_proc end if credentials.is_a?(GRPC::Core::Channel) channel = credentials end if credentials.is_a?(GRPC::Core::ChannelCredentials) chan_creds = credentials end if credentials.is_a?(Proc) updater_proc = credentials end if credentials.is_a?(Google::Auth::Credentials) updater_proc = credentials.updater_proc end package_version = Gem.loaded_specs['google-cloud-dataproc'].version.version google_api_client = "gl-ruby/#{RUBY_VERSION}" google_api_client << " #{lib_name}/#{lib_version}" if lib_name google_api_client << " gapic/#{package_version} gax/#{Google::Gax::VERSION}" google_api_client << " grpc/#{GRPC::VERSION}" google_api_client.freeze headers = { :"x-goog-api-client" => google_api_client } headers.merge!(metadata) unless metadata.nil? client_config_file = Pathname.new(__dir__).join( "cluster_controller_client_config.json" ) defaults = client_config_file.open do |f| Google::Gax.construct_settings( "google.cloud.dataproc.v1.ClusterController", JSON.parse(f.read), client_config, Google::Gax::Grpc::STATUS_CODE_NAMES, timeout, page_descriptors: PAGE_DESCRIPTORS, errors: Google::Gax::Grpc::API_ERRORS, metadata: headers ) end # Allow overriding the service path/port in subclasses. service_path = self.class::SERVICE_ADDRESS port = self.class::DEFAULT_SERVICE_PORT interceptors = self.class::GRPC_INTERCEPTORS @cluster_controller_stub = Google::Gax::Grpc.create_stub( service_path, port, chan_creds: chan_creds, channel: channel, updater_proc: updater_proc, scopes: scopes, interceptors: interceptors, &Google::Cloud::Dataproc::V1::ClusterController::Stub.method(:new) ) @create_cluster = Google::Gax.create_api_call( @cluster_controller_stub.method(:create_cluster), defaults["create_cluster"], exception_transformer: exception_transformer ) @update_cluster = Google::Gax.create_api_call( @cluster_controller_stub.method(:update_cluster), defaults["update_cluster"], exception_transformer: exception_transformer ) @delete_cluster = Google::Gax.create_api_call( @cluster_controller_stub.method(:delete_cluster), defaults["delete_cluster"], exception_transformer: exception_transformer ) @get_cluster = Google::Gax.create_api_call( @cluster_controller_stub.method(:get_cluster), defaults["get_cluster"], exception_transformer: exception_transformer ) @list_clusters = Google::Gax.create_api_call( @cluster_controller_stub.method(:list_clusters), defaults["list_clusters"], exception_transformer: exception_transformer ) @diagnose_cluster = Google::Gax.create_api_call( @cluster_controller_stub.method(:diagnose_cluster), defaults["diagnose_cluster"], exception_transformer: exception_transformer ) end # Service calls # Creates a cluster in a project. # # @param project_id [String] # Required. The ID of the Google Cloud Platform project that the cluster # belongs to. # @param region [String] # Required. The Cloud Dataproc region in which to handle the request. # @param cluster [Google::Cloud::Dataproc::V1::Cluster | Hash] # Required. The cluster to create. # A hash of the same form as `Google::Cloud::Dataproc::V1::Cluster` # can also be provided. # @param options [Google::Gax::CallOptions] # Overrides the default settings for this call, e.g, timeout, # retries, etc. # @return [Google::Gax::Operation] # @raise [Google::Gax::GaxError] if the RPC is aborted. # @example # require "google/cloud/dataproc" # # cluster_controller_client = Google::Cloud::Dataproc::ClusterController.new(version: :v1) # # # TODO: Initialize +project_id+: # project_id = '' # # # TODO: Initialize +region+: # region = '' # # # TODO: Initialize +cluster+: # cluster = {} # # # Register a callback during the method call. # operation = cluster_controller_client.create_cluster(project_id, region, cluster) do |op| # raise op.results.message if op.error? # op_results = op.results # # Process the results. # # metadata = op.metadata # # Process the metadata. # end # # # Or use the return value to register a callback. # operation.on_done do |op| # raise op.results.message if op.error? # op_results = op.results # # Process the results. # # metadata = op.metadata # # Process the metadata. # end # # # Manually reload the operation. # operation.reload! # # # Or block until the operation completes, triggering callbacks on # # completion. # operation.wait_until_done! def create_cluster \ project_id, region, cluster, options: nil req = { project_id: project_id, region: region, cluster: cluster }.delete_if { |_, v| v.nil? } req = Google::Gax::to_proto(req, Google::Cloud::Dataproc::V1::CreateClusterRequest) operation = Google::Gax::Operation.new( @create_cluster.call(req, options), @operations_client, Google::Cloud::Dataproc::V1::Cluster, Google::Cloud::Dataproc::V1::ClusterOperationMetadata, call_options: options ) operation.on_done { |operation| yield(operation) } if block_given? operation end # Updates a cluster in a project. # # @param project_id [String] # Required. The ID of the Google Cloud Platform project the # cluster belongs to. # @param region [String] # Required. The Cloud Dataproc region in which to handle the request. # @param cluster_name [String] # Required. The cluster name. # @param cluster [Google::Cloud::Dataproc::V1::Cluster | Hash] # Required. The changes to the cluster. # A hash of the same form as `Google::Cloud::Dataproc::V1::Cluster` # can also be provided. # @param update_mask [Google::Protobuf::FieldMask | Hash] # Required. Specifies the path, relative to +Cluster+, of # the field to update. For example, to change the number of workers # in a cluster to 5, the +update_mask+ parameter would be # specified as +config.worker_config.num_instances+, # and the +PATCH+ request body would specify the new value, as follows: # # { # "config":{ # "workerConfig":{ # "numInstances":"5" # } # } # } # Similarly, to change the number of preemptible workers in a cluster to 5, # the +update_mask+ parameter would be # +config.secondary_worker_config.num_instances+, and the +PATCH+ request # body would be set as follows: # # { # "config":{ # "secondaryWorkerConfig":{ # "numInstances":"5" # } # } # } # <strong>Note:</strong> Currently, only the following fields can be updated: # # <table> # <tbody> # <tr> # <td><strong>Mask</strong></td> # <td><strong>Purpose</strong></td> # </tr> # <tr> # <td><strong><em>labels</em></strong></td> # <td>Update labels</td> # </tr> # <tr> # <td><strong><em>config.worker_config.num_instances</em></strong></td> # <td>Resize primary worker group</td> # </tr> # <tr> # <td><strong><em>config.secondary_worker_config.num_instances</em></strong></td> # <td>Resize secondary worker group</td> # </tr> # </tbody> # </table> # A hash of the same form as `Google::Protobuf::FieldMask` # can also be provided. # @param options [Google::Gax::CallOptions] # Overrides the default settings for this call, e.g, timeout, # retries, etc. # @return [Google::Gax::Operation] # @raise [Google::Gax::GaxError] if the RPC is aborted. # @example # require "google/cloud/dataproc" # # cluster_controller_client = Google::Cloud::Dataproc::ClusterController.new(version: :v1) # # # TODO: Initialize +project_id+: # project_id = '' # # # TODO: Initialize +region+: # region = '' # # # TODO: Initialize +cluster_name+: # cluster_name = '' # # # TODO: Initialize +cluster+: # cluster = {} # # # TODO: Initialize +update_mask+: # update_mask = {} # # # Register a callback during the method call. # operation = cluster_controller_client.update_cluster(project_id, region, cluster_name, cluster, update_mask) do |op| # raise op.results.message if op.error? # op_results = op.results # # Process the results. # # metadata = op.metadata # # Process the metadata. # end # # # Or use the return value to register a callback. # operation.on_done do |op| # raise op.results.message if op.error? # op_results = op.results # # Process the results. # # metadata = op.metadata # # Process the metadata. # end # # # Manually reload the operation. # operation.reload! # # # Or block until the operation completes, triggering callbacks on # # completion. # operation.wait_until_done! def update_cluster \ project_id, region, cluster_name, cluster, update_mask, options: nil req = { project_id: project_id, region: region, cluster_name: cluster_name, cluster: cluster, update_mask: update_mask }.delete_if { |_, v| v.nil? } req = Google::Gax::to_proto(req, Google::Cloud::Dataproc::V1::UpdateClusterRequest) operation = Google::Gax::Operation.new( @update_cluster.call(req, options), @operations_client, Google::Cloud::Dataproc::V1::Cluster, Google::Cloud::Dataproc::V1::ClusterOperationMetadata, call_options: options ) operation.on_done { |operation| yield(operation) } if block_given? operation end # Deletes a cluster in a project. # # @param project_id [String] # Required. The ID of the Google Cloud Platform project that the cluster # belongs to. # @param region [String] # Required. The Cloud Dataproc region in which to handle the request. # @param cluster_name [String] # Required. The cluster name. # @param options [Google::Gax::CallOptions] # Overrides the default settings for this call, e.g, timeout, # retries, etc. # @return [Google::Gax::Operation] # @raise [Google::Gax::GaxError] if the RPC is aborted. # @example # require "google/cloud/dataproc" # # cluster_controller_client = Google::Cloud::Dataproc::ClusterController.new(version: :v1) # # # TODO: Initialize +project_id+: # project_id = '' # # # TODO: Initialize +region+: # region = '' # # # TODO: Initialize +cluster_name+: # cluster_name = '' # # # Register a callback during the method call. # operation = cluster_controller_client.delete_cluster(project_id, region, cluster_name) do |op| # raise op.results.message if op.error? # op_results = op.results # # Process the results. # # metadata = op.metadata # # Process the metadata. # end # # # Or use the return value to register a callback. # operation.on_done do |op| # raise op.results.message if op.error? # op_results = op.results # # Process the results. # # metadata = op.metadata # # Process the metadata. # end # # # Manually reload the operation. # operation.reload! # # # Or block until the operation completes, triggering callbacks on # # completion. # operation.wait_until_done! def delete_cluster \ project_id, region, cluster_name, options: nil req = { project_id: project_id, region: region, cluster_name: cluster_name }.delete_if { |_, v| v.nil? } req = Google::Gax::to_proto(req, Google::Cloud::Dataproc::V1::DeleteClusterRequest) operation = Google::Gax::Operation.new( @delete_cluster.call(req, options), @operations_client, Google::Protobuf::Empty, Google::Cloud::Dataproc::V1::ClusterOperationMetadata, call_options: options ) operation.on_done { |operation| yield(operation) } if block_given? operation end # Gets the resource representation for a cluster in a project. # # @param project_id [String] # Required. The ID of the Google Cloud Platform project that the cluster # belongs to. # @param region [String] # Required. The Cloud Dataproc region in which to handle the request. # @param cluster_name [String] # Required. The cluster name. # @param options [Google::Gax::CallOptions] # Overrides the default settings for this call, e.g, timeout, # retries, etc. # @yield [result, operation] Access the result along with the RPC operation # @yieldparam result [Google::Cloud::Dataproc::V1::Cluster] # @yieldparam operation [GRPC::ActiveCall::Operation] # @return [Google::Cloud::Dataproc::V1::Cluster] # @raise [Google::Gax::GaxError] if the RPC is aborted. # @example # require "google/cloud/dataproc" # # cluster_controller_client = Google::Cloud::Dataproc::ClusterController.new(version: :v1) # # # TODO: Initialize +project_id+: # project_id = '' # # # TODO: Initialize +region+: # region = '' # # # TODO: Initialize +cluster_name+: # cluster_name = '' # response = cluster_controller_client.get_cluster(project_id, region, cluster_name) def get_cluster \ project_id, region, cluster_name, options: nil, &block req = { project_id: project_id, region: region, cluster_name: cluster_name }.delete_if { |_, v| v.nil? } req = Google::Gax::to_proto(req, Google::Cloud::Dataproc::V1::GetClusterRequest) @get_cluster.call(req, options, &block) end # Lists all regions/\\{region}/clusters in a project. # # @param project_id [String] # Required. The ID of the Google Cloud Platform project that the cluster # belongs to. # @param region [String] # Required. The Cloud Dataproc region in which to handle the request. # @param filter [String] # Optional. A filter constraining the clusters to list. Filters are # case-sensitive and have the following syntax: # # field = value [AND [field = value]] ... # # where **field** is one of +status.state+, +clusterName+, or +labels.[KEY]+, # and +[KEY]+ is a label key. **value** can be +*+ to match all values. # +status.state+ can be one of the following: +ACTIVE+, +INACTIVE+, # +CREATING+, +RUNNING+, +ERROR+, +DELETING+, or +UPDATING+. +ACTIVE+ # contains the +CREATING+, +UPDATING+, and +RUNNING+ states. +INACTIVE+ # contains the +DELETING+ and +ERROR+ states. # +clusterName+ is the name of the cluster provided at creation time. # Only the logical +AND+ operator is supported; space-separated items are # treated as having an implicit +AND+ operator. # # Example filter: # # status.state = ACTIVE AND clusterName = mycluster # AND labels.env = staging AND labels.starred = * # @param page_size [Integer] # The maximum number of resources contained in the underlying API # response. If page streaming is performed per-resource, this # parameter does not affect the return value. If page streaming is # performed per-page, this determines the maximum number of # resources in a page. # @param options [Google::Gax::CallOptions] # Overrides the default settings for this call, e.g, timeout, # retries, etc. # @yield [result, operation] Access the result along with the RPC operation # @yieldparam result [Google::Gax::PagedEnumerable<Google::Cloud::Dataproc::V1::Cluster>] # @yieldparam operation [GRPC::ActiveCall::Operation] # @return [Google::Gax::PagedEnumerable<Google::Cloud::Dataproc::V1::Cluster>] # An enumerable of Google::Cloud::Dataproc::V1::Cluster instances. # See Google::Gax::PagedEnumerable documentation for other # operations such as per-page iteration or access to the response # object. # @raise [Google::Gax::GaxError] if the RPC is aborted. # @example # require "google/cloud/dataproc" # # cluster_controller_client = Google::Cloud::Dataproc::ClusterController.new(version: :v1) # # # TODO: Initialize +project_id+: # project_id = '' # # # TODO: Initialize +region+: # region = '' # # # Iterate over all results. # cluster_controller_client.list_clusters(project_id, region).each do |element| # # Process element. # end # # # Or iterate over results one page at a time. # cluster_controller_client.list_clusters(project_id, region).each_page do |page| # # Process each page at a time. # page.each do |element| # # Process element. # end # end def list_clusters \ project_id, region, filter: nil, page_size: nil, options: nil, &block req = { project_id: project_id, region: region, filter: filter, page_size: page_size }.delete_if { |_, v| v.nil? } req = Google::Gax::to_proto(req, Google::Cloud::Dataproc::V1::ListClustersRequest) @list_clusters.call(req, options, &block) end # Gets cluster diagnostic information. # After the operation completes, the Operation.response field # contains +DiagnoseClusterOutputLocation+. # # @param project_id [String] # Required. The ID of the Google Cloud Platform project that the cluster # belongs to. # @param region [String] # Required. The Cloud Dataproc region in which to handle the request. # @param cluster_name [String] # Required. The cluster name. # @param options [Google::Gax::CallOptions] # Overrides the default settings for this call, e.g, timeout, # retries, etc. # @return [Google::Gax::Operation] # @raise [Google::Gax::GaxError] if the RPC is aborted. # @example # require "google/cloud/dataproc" # # cluster_controller_client = Google::Cloud::Dataproc::ClusterController.new(version: :v1) # # # TODO: Initialize +project_id+: # project_id = '' # # # TODO: Initialize +region+: # region = '' # # # TODO: Initialize +cluster_name+: # cluster_name = '' # # # Register a callback during the method call. # operation = cluster_controller_client.diagnose_cluster(project_id, region, cluster_name) do |op| # raise op.results.message if op.error? # op_results = op.results # # Process the results. # # metadata = op.metadata # # Process the metadata. # end # # # Or use the return value to register a callback. # operation.on_done do |op| # raise op.results.message if op.error? # op_results = op.results # # Process the results. # # metadata = op.metadata # # Process the metadata. # end # # # Manually reload the operation. # operation.reload! # # # Or block until the operation completes, triggering callbacks on # # completion. # operation.wait_until_done! def diagnose_cluster \ project_id, region, cluster_name, options: nil req = { project_id: project_id, region: region, cluster_name: cluster_name }.delete_if { |_, v| v.nil? } req = Google::Gax::to_proto(req, Google::Cloud::Dataproc::V1::DiagnoseClusterRequest) operation = Google::Gax::Operation.new( @diagnose_cluster.call(req, options), @operations_client, Google::Protobuf::Empty, Google::Cloud::Dataproc::V1::DiagnoseClusterResults, call_options: options ) operation.on_done { |operation| yield(operation) } if block_given? operation end end end end end end
41.210312
131
0.548795
086fcb23b16c8ec63fe22b8d1f28cb0585a80220
2,159
# frozen_string_literal: true module MachineLearningWorkbench::Compressor # Incremental Dictionary Train-less VQ, creating new centroids rather than training # Optimized for online training. # TODO: as the deadline grows nigh, the hacks grow foul. Refactor all VQs together. class IncrDictVQ < VectorQuantization attr_reader :equal_simil undef :ntrains # centroids are not trained def initialize **opts puts "Ignoring learning rate: `lrate: #{opts[:lrate]}`" if opts[:lrate] puts "Ignoring similarity: `simil_type: #{opts[:simil_type]}`" unless opts[:simil_type] == :dot puts "Ignoring ncentrs: `ncentrs: #{opts[:ncentrs]}`" if opts[:ncentrs] # TODO: try different epsilons to reduce the number of states # for example, in qbert we care what is lit and what is not, not the colors @equal_simil = opts.delete(:equal_simil) || 0.0 super **opts.merge({ncentrs: 1, lrate: nil, simil_type: :dot}) @ntrains = nil # will disable the counting end # Overloading lrate check from original VQ def check_lrate lrate; nil; end # Train on one vector: # - train only if the image is not already in dictionary # - create new centroid from the image # @return [Integer] index of new centroid def train_one vec, eps: equal_simil # NOTE: novelty needs to be re-computed for each image, as after each # training the novelty signal changes! # NOTE the reconstruction error here depends once more on the _color_ # this is wrong and should be taken out of the equation # NOTE: this is fixed if I use the differences sparse coding method residual_img = reconstr_error(vec) rec_err = residual_img.mean return -1 if rec_err < eps puts "Creating centr #{ncentrs} (rec_err: #{rec_err})" # norm_vec = vec / NLinalg.norm(vec) # @centrs = centrs.concatenate norm_vec # @centrs = centrs.concatenate vec @centrs = centrs.concatenate residual_img # HACK: make it more general by using `code_size` @utility = @utility.concatenate [0] * (encoding_type == :sparse_coding_v1 ? 2 : 1) ncentrs end end end
40.735849
101
0.693377
7ac233be2e66a5c8c3c06cde14bce39da6ab16f2
4,376
# Copyright 2011-2018, The Trustees of Indiana University and Northwestern # University. 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. # --- END LICENSE_HEADER BLOCK --- require 'rdf' module Avalon module RDFVocab class Common < RDF::StrictVocabulary("http://avalonmediasystem.org/rdf/vocab/common#") property :resolution, "rdfs:isDefinedBy" => %(avr-common:).freeze, type: "rdfs:Class".freeze end class Transcoding < RDF::StrictVocabulary("http://avalonmediasystem.org/rdf/vocab/transcoding#") property :workflowId, "rdfs:isDefinedBy" => %(avr-transcoding:).freeze, type: "rdfs:Class".freeze property :workflowName, "rdfs:isDefinedBy" => %(avr-transcoding:).freeze, type: "rdfs:Class".freeze property :percentComplete, "rdfs:isDefinedBy" => %(avr-transcoding:).freeze, type: "rdfs:Class".freeze property :percentSucceeded, "rdfs:isDefinedBy" => %(avr-transcoding:).freeze, type: "rdfs:Class".freeze property :percentFailed, "rdfs:isDefinedBy" => %(avr-transcoding:).freeze, type: "rdfs:Class".freeze property :statusCode, "rdfs:isDefinedBy" => %(avr-transcoding:).freeze, type: "rdfs:Class".freeze property :operation, "rdfs:isDefinedBy" => %(avr-transcoding:).freeze, type: "rdfs:Class".freeze property :error, "rdfs:isDefinedBy" => %(avr-transcoding:).freeze, type: "rdfs:Class".freeze property :failures, "rdfs:isDefinedBy" => %(avr-transcoding:).freeze, type: "rdfs:Class".freeze property :encoderClassname, "rdfs:isDefinedBy" => %(avr-transcoding:).freeze, type: "rdfs:Class".freeze end class MasterFile < RDF::StrictVocabulary("http://avalonmediasystem.org/rdf/vocab/master_file#") property :posterOffset, "rdfs:isDefinedBy" => %(avr-master_file:).freeze, type: "rdfs:Class".freeze property :thumbnailOffset, "rdfs:isDefinedBy" => %(avr-master_file:).freeze, type: "rdfs:Class".freeze end class Derivative < RDF::StrictVocabulary("http://avalonmediasystem.org/rdf/vocab/derivative#") property :hlsURL, "rdfs:isDefinedBy" => %(avr-derivative:).freeze, type: "rdfs:Class".freeze property :hlsTrackID, "rdfs:isDefinedBy" => %(avr-derivative:).freeze, type: "rdfs:Class".freeze property :isManaged, "rdfs:isDefinedBy" => %(avr-derivative:).freeze, type: "rdfs:Class".freeze end class Encoding < RDF::StrictVocabulary("http://avalonmediasystem.org/rdf/vocab/encoding#") property :audioCodec, "rdfs:isDefinedBy" => %(avr-encoding:).freeze, type: "rdfs:Class".freeze property :audioBitrate, "rdfs:isDefinedBy" => %(avr-encoding:).freeze, type: "rdfs:Class".freeze end class MediaObject < RDF::StrictVocabulary("http://avalonmediasystem.org/rdf/vocab/media_object#") property :avalon_resource_type, "rdfs:isDefinedBy" => %(avr-media_object:).freeze, type: "rdfs:Class".freeze property :avalon_publisher, "rdfs:isDefinedBy" => %(avr-media_object:).freeze, type: "rdfs:Class".freeze property :avalon_uploader, "rdfs:isDefinedBy" => %(avr-media_object:).freeze, type: "rdfs:Class".freeze end class Collection < RDF::StrictVocabulary("http://avalonmediasystem.org/rdf/vocab/collection#") property :dropbox_directory_name, "rdfs:isDefinedBy" => %(avr-collection:).freeze, type: "rdfs:Class".freeze property :default_read_users, "rdfs:isDefinedBy" => %(avr-collection:).freeze, type: "rdfs:Class".freeze property :default_read_groups, "rdfs:isDefinedBy" => %(avr-collection:).freeze, type: "rdfs:Class".freeze property :default_visibility, "rdfs:isDefinedBy" => %(avr-collection:).freeze, type: "rdfs:Class".freeze property :default_hidden, "rdfs:isDefinedBy" => %(avr-collection:).freeze, type: "rdfs:Class".freeze end end end
66.30303
116
0.693556
f7346af505d4c7648af3a4331ddda1b2fd771ee4
7,587
# frozen_string_literal: true # # Provides the ability to perform +FileUtils+ actions, while restricting # any destructive actions outside of the specified +sandbox_path+. # # == Usage # # To enable protection: # # require 'sandbox_file_utils' # # SandboxFileUtils.activate! # SandboxFileUtils.sandbox_path = 'my_sandbox' # # or # # SandboxFileUtils.activate! 'my_sandbox' # # FileUtils.touch 'my_sandbox/file' # => OK # FileUtils.touch 'file' # => Error # # To disable protection: # # SandboxFileUtils.deactivate! # FileUtils.touch 'my_sandbox/file' # => OK # FileUtils.touch 'file' # => OK # # # When re-activating, the currently set +sandbox_path+ will still be in effect. # SandboxFileUtils.activate! # FileUtils.touch 'my_sandbox/file' # => OK # FileUtils.touch 'file' # => Error # # When disabling protection, you may also pass +:noop+ which will restore # +::FileUtils+ to +FileUtils::NoWrite+. # # SandboxFileUtils.deactivate!(:noop) # FileUtils.touch 'file' # => OK # File.exist? 'file' # => false # # The +sandbox_path+ may be changed at any time. # # require 'sandbox_file_utils' # # SandboxFileUtils.activate! 'my_sandbox' # FileUtils.touch 'my_sandbox/file' # => OK # FileUtils.touch 'other_path/file' # => Error # # SandboxFileUtils.sandbox_path = 'other_path' # FileUtils.touch 'other_path/file' # => OK # FileUtils.touch 'my_sandbox/file' # => Error # # This module may also be used directly, with no activation required. # # require 'sandbox_file_utils' # # SandboxFileUtils.sandbox_path = 'my_sandbox' # SandboxFileUtils.touch 'my_sandbox/file' # => OK # SandboxFileUtils.touch 'other_path/file' # => Error # # == Module Functions # # The following are accessible and operate without restriction: # # pwd (alias: getwd) # cd (alias: chdir) # uptodate? # compare_file (alias: identical? cmp) # compare_stream # # The following are accessible, but will not allow operations on files or # directories outside of the +sandbox_path+. # # No links may be created within the +sandbox_path+ to outside files or # directories. Files may be copied from outside into the +sandbox_path+. # # Operations not permitted will raise an +Error+. # # mkdir # mkdir_p (alias: makedirs mkpath) # rmdir # ln (alias: link) # ln_s (alias: symlink) # ln_sf # cp (alias: copy) # cp_r # mv (alias: move) # rm (alias: remove) # rm_f (alias: safe_unlink) # rm_r # rm_rf (alias: rmtree) # install # chmod # chmod_R # chown # chown_R # touch # # The following low-level methods, normally available through +FileUtils+, # will remain private and not be available: # # copy_entry # copy_file # copy_stream # remove_entry_secure # remove_entry # remove_file # remove_dir # require "fileutils" module SandboxFileUtils class Error < StandardError; end class << self include FileUtils RealFileUtils = FileUtils # Sets the root path where restricted operations will be allowed. # # This is evaluated at the time of each method call, # so it may be changed at any time. # # This may be a relative or absolute path. If relative, it will be # based on the current working directory. # # The +sandbox_path+ itself may be created or removed by this module. # Missing parent directories in this path may be created using +mkdir_p+, # but you would not be able to remove them. # # FileUtils.sandbox_path = 'my/sandbox' # FileUtils.mkdir 'my' # => will raise an Error # FileUtils.mkdir_p 'my/sandbox' # => creates both directories # FileUtils.rmdir 'my/sandbox' # => removes 'sandbox' # FileUtils.rmdir 'my' # => will raise an Error # # This would work in 1.9.x, but the :parents option is currently broken. # # FileUtils.rmdir 'my/sandbox', parents: true # # An +Error+ will be raised if any module functions are called without this set. attr_accessor :sandbox_path # Returns whether or not SandboxFileUtils protection for +::FileUtils+ is active. def activated? ::FileUtils == self end # Enables this module so that all calls to +::FileUtils+ will be protected. # # If +path+ is given, it will be used to set +sandbox_path+ - regardless of # whether or not this call returns +true+ or +false+. # # Returns +true+ if activation occurs. # Returns +false+ if +activated?+ already +true+. def activate!(path = nil) path = path.to_s self.sandbox_path = path unless path.empty? return false if activated? Object.send(:remove_const, :FileUtils) Object.const_set(:FileUtils, self) true end # Disables this module by restoring +::FileUtils+ to the real +FileUtils+ module. # # When deactivated, +sandbox_path+ will remain set to it's current value. # Therefore, if +activate!+ is called again, +sandbox_path+ will still be set. # # By default, +deactivate!+ will restore +::FileUtils+ to the fully functional # +FileUtils+ module. If +type+ is set to +:noop+, it will restore +::FileUtils+ # to +FileUtils::NoWrite+, so that any method calls to +::FileUtils+ will be +noop+. # # Returns +true+ if deactivation occurs. # Returns +false+ if +activated?+ is already +false+. def deactivate!(type = :real) return false unless activated? Object.send(:remove_const, :FileUtils) if type == :noop Object.const_set(:FileUtils, RealFileUtils::NoWrite) else Object.const_set(:FileUtils, RealFileUtils) end true end %w[ pwd getwd cd chdir uptodate? compare_file identical? cmp compare_stream ].each do |name| public :"#{name}" end %w[ mkdir mkdir_p makedirs mkpath rmdir rm remove rm_f safe_unlink rm_r rm_rf rmtree touch ].each do |name| class_eval(<<-EOS, __FILE__, __LINE__ + 1) def #{name}(list, options = {}) protect!(list) super end EOS end %w[cp copy cp_r install].each do |name| class_eval(<<-EOS, __FILE__, __LINE__ + 1) def #{name}(src, dest, options = {}) protect!(dest) super end EOS end %w[ln link ln_s symlink ln_sf mv move].each do |name| class_eval(<<-EOS, __FILE__, __LINE__ + 1) def #{name}(src, dest, options = {}) protect!(src) super end EOS end %w[chmod chmod_R].each do |name| class_eval(<<-EOS, __FILE__, __LINE__ + 1) def #{name}(mode, list, options = {}) protect!(list) super end EOS end %w[chown chown_R].each do |name| class_eval(<<-EOS, __FILE__, __LINE__ + 1) def #{name}(user, group, list, options = {}) protect!(list) super end EOS end private def protect!(list) list = Array(list).flatten.map { |p| File.expand_path(p) } path = current_sandbox_path + "/" unless list.all? { |p| p.start_with?(path) || p == path.chomp("/") } raise Error, <<-EOS.gsub(%r{^ +}, ""), caller(1) path(s) outside of the current sandbox path were detected. sandbox_path: #{path} path(s) for the current operation: #{list.join($INPUT_RECORD_SEPARATOR)} EOS end end def current_sandbox_path path = sandbox_path.to_s.chomp("/") raise Error, "sandbox_path must be set" if path.empty? File.expand_path(path) end end end
28.958015
88
0.639779
33316f949ed81f3058d7287b4f99f5badfbca831
1,194
# m_3_3_03.rb require_relative 'mesh' include GeometricForm U_RANGE = (-PI..PI) V_RANGE = (-PI..PI) MAX_V = 200 MAX_U = 200 attr_reader :renderer, :points def settings size 300, 300 , P3D end def setup sketch_title 'Geometric Forms' ArcBall.init(self) @renderer = AppRender.new(self) @points = generate_points(MAX_U, MAX_V) no_stroke fill rand(255),rand(255), rand(255) end def draw background 200 setup_lights (MAX_V - 1).times do |iv| begin_shape(TRIANGLE_STRIP) (MAX_U).times do |iu| points[iv][iu].to_vertex(renderer) points[iv + 1][iu].to_vertex(renderer) end end_shape end end def setup_lights lights light_specular(230, 230, 230) directional_light(200, 200, 200, 0.5, 0.5, -1) specular(color(200)) shininess(5.0) end # Edit this method to choose different shape def generate_points(u_count, v_count) points = [] v_count.times do |iv| row = [] u_count.times do |iu| u = map1d(iu, (0..u_count), U_RANGE) v = map1d(iv, (0..v_count), V_RANGE) # default scale: 50, param: Array.new(12, 1) and mesh_distortion: 0 row << superformula(u: u, v: v) end points << row end points end
19.57377
73
0.663317
e219cd87c5efbe1cd93cf900e69f9d682425bf87
135
require 'rails_helper' RSpec.describe Spree::SeedCredit, type: :model do pending "add some examples to (or delete) #{__FILE__}" end
22.5
56
0.748148
eda06876cd33135670209ffce55d43712607c5bd
3,129
#!/usr/bin/env ruby # frozen_string_literal: true require 'minitest/autorun' require_relative '../../constants' require_relative '../../../lib/wavefront-cli/stdlib/string' require_relative '../../../lib/wavefront-cli/commands/base' # Test extensions to string class # class StringTest < MiniTest::Test def test_cmd_fold cmn = '[-DnV] [-c file] [-P profile] [-E endpoint] [-t token]' str = "command subcommand #{cmn} [-a alpha] [-b beta] [-c gamma] <id>" assert_equal(str.cmd_fold, 'command subcommand [-DnV] [-c file] [-P profile] ' \ "[-E endpoint]\n [-t token] [-a alpha] " \ '[-b beta] [-c gamma] <id>') assert_equal(str.cmd_fold(240), str) assert_equal(str.cmd_fold(50), "command subcommand [-DnV] [-c file]\n [-P " \ "profile] [-E endpoint] [-t token]\n [-a " \ 'alpha] [-b beta] [-c gamma] <id>') end def test_opt_fold assert_equal('short string'.opt_fold, ' short string') str = '-o, --option PARAMETER a rather pointless option with a ' \ 'needlessly wordy description string' pad = "\n" + ' ' * 12 assert_equal(" -o, --option PARAMETER a#{pad}rather pointless" \ "#{pad}option with a#{pad}needlessly wordy#{pad}" \ "description#{pad}string", str.opt_fold(30, 10)) end def test_fold_options str = '-l, --longoption a long option with a quite long ' \ 'description which needs folding' assert_equal(str.opt_fold, ' -l, --longoption a long option with a quite ' \ "long description which\n needs folding") assert_equal(str.opt_fold(50), " -l, --longoption a long option with a\n " \ " quite long description which needs\n " \ ' folding') assert_equal(str.opt_fold(100), " #{str}") end def test_to_seconds assert_equal(14, '14s'.to_seconds) assert_equal(300, '5m'.to_seconds) assert_equal(10_800, '3h'.to_seconds) assert_equal(1_209_600, '2w'.to_seconds) assert_raises(ArgumentError) { 'm'.to_seconds } assert_raises(ArgumentError) { '3m5s'.to_seconds } end def test_unit_factor assert_equal(60, '1'.unit_factor(:m)) assert_equal(1, '1'.unit_factor('m')) assert_equal(1, '1'.unit_factor(:t)) end def test_to_snake assert_equal('snake_case', 'snakeCase'.to_snake) assert_equal('lots_and_lots_of_words', 'lotsAndLotsOfWords'.to_snake) assert_equal('unchanged', 'unchanged'.to_snake) assert_equal('Unchanged', 'Unchanged'.to_snake) end def test_value_fold input = 'A reasonably long string which might for instance be a ' \ 'descripton of an alert. Perhaps an embedded runbook.' expected = 'A reasonably long string which might for instance be a descripton of an alert. Perhaps an embedded runbook.' assert_equal(expected, input.value_fold(38)) end end
36.811765
75
0.592522
4a841b53fe1b85ab6c0e7b91fc9f9ccf9e07a4ca
1,698
require_relative '../lib/banking_processor/io/preety_output' require_relative '../lib/banking_processor/config' require_relative '../lib/banking_processor/datastore/ddb_handler' preety = BankingProcessor::IO::PreetyOutput.new config = BankingProcessor::Config.new ddb = BankingProcessor::Datastore::DynamoDBHandler.new(config).client account = config.default_account table = config.transaction_table(account) scan_options = { table_name: table } preety.heading("Scanning DynamoDB table") resp = ddb.scan(scan_options) transactions = resp.items puts "Number of transactions: #{transactions.size}" # determine number of duplicates found_transaction = {} duplicated_transactions = [] transactions.each do |transaction| balance = transaction['balance'] year_month = transaction['year-month'] integer_balance = balance.to_i key = "#{year_month}/#{integer_balance}" if found_transaction[key] duplicated_transactions.push(transaction) else found_transaction[key] = true end end puts "Number of duplicate transactions: #{duplicated_transactions.size}" preety.heading("Deleting duplicates from transaction table") duplicated_transactions.each do |transaction| year_month = transaction['year-month'] balance = transaction['balance'].to_f delete_options = { table_name: table, key: { "year-month" => year_month, "balance" => balance } } begin ddb.delete_item(delete_options); print '.' rescue => e STDERR.puts "[ERROR] Unable to delete transaction #{year_month}/#{balance}. #{e.class}: #{e.message}" end sleep(2); # stay under free call limit end puts ''
26.123077
106
0.71437
bffbe1e7c85d53b4ce531d711d5e4d45d73bbac7
3,078
require_relative "../models/story" require_relative "../utils/sample_story" class StoryRepository def self.add(entry, feed) Story.create(feed: feed, title: entry.title, permalink: entry.url, body: extract_content(entry), is_read: false, is_starred: false, published: entry.published || Time.now, entry_id: entry.id) end def self.fetch(id) Story.find(id) end def self.fetch_by_ids(ids) Story.where(id: ids) end def self.fetch_unread_by_timestamp(timestamp) timestamp = Time.at(timestamp.to_i) Story.where("created_at < ? AND is_read = ?", timestamp, false) end def self.fetch_unread_for_feed_by_timestamp(feed_id, timestamp) timestamp = Time.at(timestamp.to_i) Story.where(feed_id: feed_id).where("created_at < ? AND is_read = ?", timestamp, false) end def self.save(story) story.save end def self.unread Story.where(is_read: false).order("published desc").includes(:feed) end def self.unread_since_id(since_id) unread.where('id > ?', since_id) end def self.feed(feed_id) Story.where('feed_id = ?', feed_id).order("published desc").includes(:feed) end def self.read(page = 1) Story.where(is_read: true).includes(:feed) .order("published desc").page(page).per_page(20) end def self.starred(page = 1) Story.where(is_starred: true).includes(:feed) .order("published desc").page(page).per_page(20) end def self.all_starred Story.where(is_starred: true) end def self.unstarred_read_stories_older_than(num_days) Story.where(is_read: true, is_starred: false) .where('published <= ?', num_days.days.ago) end def self.read_count Story.where(is_read: true).count end def self.extract_content(entry) sanitized_content = "" if entry.content sanitized_content = sanitize(entry.content) elsif entry.summary sanitized_content = sanitize(entry.summary) end expand_absolute_urls(sanitized_content, entry.url) end def self.sanitize(content) Loofah.fragment(content.gsub(/<wbr\s*>/i, "")) .scrub!(:prune) .to_s .gsub("\u2028", '') .gsub("\u2029", '') end def self.expand_absolute_urls(content, base_url) doc = Nokogiri::HTML.fragment(content) abs_re = URI::DEFAULT_PARSER.regexp[:ABS_URI] [["a", "href"], ["img", "src"], ["video", "src"]].each do |tag, attr| doc.css("#{tag}[#{attr}]").each do |node| url = node.get_attribute(attr) unless url =~ abs_re node.set_attribute(attr, URI.join(base_url, url).to_s) end end end doc.to_html end def self.samples [ SampleStory.new("Darin' Fireballs", "Why you should trade your firstborn for a Retina iPad"), SampleStory.new("TechKrunch", "SugarGlidr raises $1.2M Series A for Social Network for Photo Filters"), SampleStory.new("Lambda Da Ultimate", "Flimsy types are the new hotness") ] end end
26.084746
109
0.643925
38bd76738c31ca35a8ee6179116e570efdd52c59
644
class ChangeEnvDeployGroupToScope < ActiveRecord::Migration def change remove_index :environment_variables, name: "environment_variables_unique_deploy_group_id" add_column :environment_variables, :scope_type, :string rename_column :environment_variables, :deploy_group_id, :scope_id EnvironmentVariable.update_all scope_type: "DeployGroup" add_index :environment_variables, [:parent_id, :parent_type, :name, :scope_type, :scope_id], unique: true, name: "environment_variables_unique_scope", length: { name: 191, parent_type: 191, scope_type: 191 } add_column :environment_variable_groups, :comment, :text end end
46
211
0.793478
1a5714fcc59173726e01155402a6f908343dddfe
3,023
require 'spec_helper' describe Bosh::OpenStackCloud::Cloud do before(:each) { allow(Bosh::OpenStackCloud::TagManager).to receive(:tag_server) } let(:server) { double('server', id: 'i-foobar', metadata: double('metadata')) } context 'without registry_key set' do before(:each) do @cloud = mock_cloud do |fog| allow(fog.compute.servers).to receive(:get).with('i-foobar').and_return(server) end allow(server.metadata).to receive(:get) end it 'should only tag with metadata' do metadata = { job: 'job', index: 'index' } expect(Bosh::OpenStackCloud::TagManager).to receive(:tag_server).with(server, job: 'job', index: 'index') @cloud.set_vm_metadata('i-foobar', metadata) end it "logs 'compiling/x'" do @cloud.set_vm_metadata('i-foobar', {}) expect(Bosh::Clouds::Config.logger).to have_received(:debug).with("VM with id 'i-foobar' has no 'registry_key' tag") end end context 'with registry_key set' do before(:each) do @cloud = mock_cloud do |fog| allow(fog.compute.servers).to receive(:get).with('i-foobar').and_return(server) allow(fog.compute).to receive(:update_server) end allow(server.metadata).to receive(:get).with(:registry_key).and_return(double('metadatum')) end context 'for normal job' do context "when bosh provides NO 'name' property" do let(:metadata) { { 'job' => 'job', 'index' => 'index' } } it "sets the vm name 'job/index'" do @cloud.set_vm_metadata('i-foobar', metadata) expect(@cloud.compute).to have_received(:update_server).with('i-foobar', 'name' => 'job/index') end it 'logs job name & index' do @cloud.set_vm_metadata('i-foobar', metadata) expect(Bosh::Clouds::Config.logger).to have_received(:debug).with("Rename VM with id 'i-foobar' to 'job/index'") end end context "when bosh provides a 'name' property" do let(:metadata) { { 'name' => 'job/id' } } it "sets the vm name 'job/id'" do @cloud.set_vm_metadata('i-foobar', metadata) expect(@cloud.compute).to have_received(:update_server).with('i-foobar', 'name' => 'job/id') end it 'logs instance name' do @cloud.set_vm_metadata('i-foobar', metadata) expect(Bosh::Clouds::Config.logger).to have_received(:debug).with("Rename VM with id 'i-foobar' to 'job/id'") end end end context 'for compilation vms' do let(:metadata) { { 'compiling' => 'x' } } it "sets the vm name 'compiling/x'" do @cloud.set_vm_metadata('i-foobar', metadata) expect(@cloud.compute).to have_received(:update_server).with('i-foobar', 'name' => 'compiling/x') end it "logs 'compiling/x'" do @cloud.set_vm_metadata('i-foobar', metadata) expect(Bosh::Clouds::Config.logger).to have_received(:debug).with("Rename VM with id 'i-foobar' to 'compiling/x'") end end end end
35.988095
122
0.62653
3951e65dc4fd4858f2634b8d511f8f7f0bab0866
54,486
Rails.application.routes.draw do # No Devise modules are enabled # Custom, magic-link based authentication flow used. See, for example - # CandidateInterface::SignInController devise_for :candidates, skip: :all devise_scope :candidate do get '/candidate/sign-out', to: 'devise/sessions#destroy', as: :candidate_interface_sign_out end if HostingEnvironment.sandbox_mode? root to: 'content#sandbox' else root to: redirect('/candidate/account') end namespace :candidate_interface, path: '/candidate' do if HostingEnvironment.production? get '/' => redirect(GOVUK_APPLY_START_PAGE_URL) else get '/' => redirect('/') end get '/accessibility', to: 'content#accessibility' get '/cookies', to: 'content#cookies_page', as: :cookies get '/make-a-complaint', to: 'content#complaints', as: :complaints get '/privacy-policy', to: 'content#privacy_policy', as: :privacy_policy get '/providers', to: 'content#providers', as: :providers get '/terms-of-use', to: 'content#terms_candidate', as: :terms resources :cookie_preferences, only: 'create', path: 'cookie-preferences' get '/account', to: 'start_page#create_account_or_sign_in', as: :create_account_or_sign_in post '/account', to: 'start_page#create_account_or_sign_in_handler' get '/applications-closed' => 'start_page#applications_closed', as: :applications_closed get '/sign-up', to: 'sign_up#new', as: :sign_up post '/sign-up', to: 'sign_up#create' get '/sign-up/check-email', to: 'sign_in#check_your_email', as: :check_email_sign_up get '/sign-up/external-sign-up-forbidden', to: 'sign_up#external_sign_up_forbidden', as: :external_sign_up_forbidden get '/sign-in', to: 'sign_in#new', as: :sign_in post '/sign-in', to: 'sign_in#create' post '/sign-in/expired', to: 'sign_in#create_from_expired_token', as: :create_expired_sign_in get '/sign-in/check-email', to: 'sign_in#check_your_email', as: :check_email_sign_in get '/sign-in/expired', to: 'sign_in#expired', as: :expired_sign_in get '/confirm_authentication', to: redirect('/candidate/sign-in/confirm') get '/sign-in/confirm', to: 'sign_in#confirm_authentication', as: :authenticate post '/sign-in/confirm', to: 'sign_in#authenticate' get '/authenticate', to: 'sign_in#expired' get '/apply', to: 'apply_from_find#show', as: :apply_from_find post '/apply', to: 'apply_from_find#ucas_or_apply' get '/apply/ucas', to: 'apply_from_find#ucas_interstitial', as: :apply_with_ucas_interstitial get '/interstitial', to: 'after_sign_in#interstitial', as: :interstitial scope '/find-feedback' do get '/' => 'find_feedback#new', as: :find_feedback post '/' => 'find_feedback#create' get '/thank-you' => 'find_feedback#thank_you', as: :find_feedback_thank_you end scope '/application' do get '/prefill', to: 'prefill_application_form#new' post '/prefill', to: 'prefill_application_form#create' get '/before-you-start', to: 'unsubmitted_application_form#before_you_start' get '/' => 'unsubmitted_application_form#show', as: :application_form get '/review' => 'unsubmitted_application_form#review', as: :application_review get '/submit' => 'unsubmitted_application_form#submit_show', as: :application_submit_show post '/submit' => 'unsubmitted_application_form#submit', as: :application_submit get '/submit-success' => 'submitted_application_form#submit_success', as: :application_submit_success get '/complete' => 'submitted_application_form#complete', as: :application_complete get '/review/submitted' => 'submitted_application_form#review_submitted', as: :application_review_submitted get '/review/submitted/:id' => 'application_form#review_previous_application', as: :review_previous_application get '/start-apply-again' => 'submitted_application_form#start_apply_again', as: :start_apply_again post '/apply-again' => 'submitted_application_form#apply_again', as: :apply_again get '/start-carry-over' => 'carry_over#start', as: :start_carry_over post '/carry-over' => 'carry_over#create', as: :carry_over scope '/personal-details' do get '/', to: redirect('/candidate/application/personal-information') get '/edit', to: redirect('/candidate/application/personal-information/edit') get '/nationalities', to: redirect('/candidate/application/personal-information/nationality'), as: :personal_details_nationalities get '/nationalities/edit', to: redirect('/candidate/application/personal-information/nationality/edit'), as: :personal_details_edit_nationalities get '/languages', to: redirect('/candidate/application/personal-information/languages'), as: :personal_details_languages get '/languages/edit', to: redirect('/candidate/application/personal-information/languages/edit'), as: :personal_details_edit_languages get '/right-to-work-or-study', to: redirect('/candidate/application/personal-information/right-to-work-or-study'), as: :personal_details_right_to_work_or_study get '/right-to-work-or-study/edit', to: redirect('/candidate/application/personal-information/right-to-work-or-study/edit'), as: :personal_details_edit_right_to_work_or_study get 'review', to: redirect('/candidate/application/personal-information/review') end scope '/personal-information' do get '/' => 'personal_details/name_and_dob#new', as: :name_and_dob patch '/' => 'personal_details/name_and_dob#create' get '/edit' => 'personal_details/name_and_dob#edit', as: :edit_name_and_dob patch '/edit' => 'personal_details/name_and_dob#update' get '/nationality' => 'personal_details/nationalities#new', as: :nationalities patch '/nationality' => 'personal_details/nationalities#create' get '/nationality/edit' => 'personal_details/nationalities#edit', as: :edit_nationalities patch '/nationality/edit' => 'personal_details/nationalities#update' get '/languages' => 'personal_details/languages#new', as: :languages patch '/languages' => 'personal_details/languages#create' get '/languages/edit' => 'personal_details/languages#edit', as: :edit_languages patch '/languages/edit' => 'personal_details/languages#update' get '/right-to-work-or-study' => 'personal_details/right_to_work_or_study#new', as: :right_to_work_or_study patch '/right-to-work-or-study' => 'personal_details/right_to_work_or_study#create' get '/right-to-work-or-study/edit' => 'personal_details/right_to_work_or_study#edit', as: :edit_right_to_work_or_study patch '/right-to-work-or-study/edit' => 'personal_details/right_to_work_or_study#update' get '/review' => 'personal_details/review#show', as: :personal_details_show patch '/review' => 'personal_details/review#complete', as: :personal_details_complete end scope '/personal-statement' do # TODO: Remove redirects from Jan 15 2021 get '/becoming-a-teacher', to: redirect('/candidate/application/personal-statement') get '/becoming-a-teacher/review', to: redirect('/candidate/application/personal-statement/review') get '/subject-knowledge', to: redirect('/candidate/application/subject-knowledge') get '/subject-knowledge/review', to: redirect('/candidate/application/subject-knowledge/review') get '/interview-preferences', to: redirect('/candidate/application/interview-needs') get '/interview-preferences/review', to: redirect('/candidate/application/interview-needs/review') get '/' => 'personal_statement#edit', as: :edit_becoming_a_teacher patch '/' => 'personal_statement#update' get '/review' => 'personal_statement#show', as: :becoming_a_teacher_show patch '/complete' => 'personal_statement#complete', as: :becoming_a_teacher_complete end scope '/subject-knowledge' do get '/' => 'subject_knowledge#edit', as: :edit_subject_knowledge patch '/' => 'subject_knowledge#update' get '/review' => 'subject_knowledge#show', as: :subject_knowledge_show patch '/complete' => 'subject_knowledge#complete', as: :subject_knowledge_complete end scope '/interview-needs' do get '/' => 'interview_needs#edit', as: :edit_interview_preferences patch '/' => 'interview_needs#update' get '/review' => 'interview_needs#show', as: :interview_preferences_show patch '/complete' => 'interview_needs#complete', as: :interview_preferences_complete end scope '/training-with-a-disability' do get '/', to: redirect('/candidate/application/additional-support') get '/review', to: redirect('/candidate/application/additional-support/review') end scope '/additional-support' do get '/' => 'training_with_a_disability#edit', as: :edit_training_with_a_disability patch '/' => 'training_with_a_disability#update' get '/review' => 'training_with_a_disability#show', as: :training_with_a_disability_show patch '/complete' => 'training_with_a_disability#complete', as: :training_with_a_disability_complete end scope '/contact-details' do get '/', to: redirect('/candidate/application/contact-information') get '/address_type', to: redirect('/candidate/application/contact-information/address-type') get '/address', to: redirect('/candidate/application/contact-information/address') get '/review', to: redirect('/candidate/application/contact-information/review') end scope '/contact-information' do get '/' => 'contact_details/phone_number#edit', as: :contact_information_edit_phone_number patch '/' => 'contact_details/phone_number#update' get '/address-type' => 'contact_details/address_type#edit', as: :contact_information_edit_address_type patch '/address-type' => 'contact_details/address_type#update' get '/address' => 'contact_details/address#edit', as: :contact_information_edit_address patch '/address' => 'contact_details/address#update' get '/review' => 'contact_details/review#show', as: :contact_information_review patch '/complete' => 'contact_details/review#complete', as: :contact_information_complete end scope '/gcse' do get '/maths/grade' => 'gcse/maths/grade#edit', as: :edit_gcse_maths_grade patch '/maths/grade' => 'gcse/maths/grade#update' get '/science/grade' => 'gcse/science/grade#edit', as: :edit_gcse_science_grade patch '/english/grade' => 'gcse/english/grade#update' get '/english/grade' => 'gcse/english/grade#edit', as: :edit_gcse_english_grade patch '/science/grade' => 'gcse/science/grade#update' end scope '/gcse/:subject', constraints: { subject: /(maths|english|science)/ } do get '/' => 'gcse/type#edit', as: :gcse_details_edit_type post '/' => 'gcse/type#update' get '/country' => 'gcse/institution_country#edit', as: :gcse_details_edit_institution_country patch '/country' => 'gcse/institution_country#update' get '/naric' => 'gcse/naric#edit', as: :gcse_details_edit_naric patch '/naric' => 'gcse/naric#update' get '/year' => 'gcse/year#edit', as: :gcse_details_edit_year patch '/year' => 'gcse/year#update' get '/review' => 'gcse/review#show', as: :gcse_review patch '/complete' => 'gcse/review#complete', as: :gcse_complete end scope '/work-history' do get '/length' => 'work_history/length#show', as: :work_history_length post '/length' => 'work_history/length#submit' get '/missing' => 'work_history/explanation#show', as: :work_history_explanation post '/missing' => 'work_history/explanation#submit' get '/explain-break/new' => 'work_history/break#new', as: :new_work_history_break post '/explain-break/new' => 'work_history/break#create' get '/explain-break/edit/:id' => 'work_history/break#edit', as: :edit_work_history_break patch '/explain-break/edit/:id' => 'work_history/break#update' get '/explain-break/delete/:id' => 'work_history/break#confirm_destroy', as: :destroy_work_history_break delete '/explain-break/delete/:id' => 'work_history/break#destroy' get '/new' => 'work_history/edit#new', as: :new_work_history post '/new' => 'work_history/edit#create' get '/edit/:id' => 'work_history/edit#edit', as: :work_history_edit post '/edit/:id' => 'work_history/edit#update' get '/review' => 'work_history/review#show', as: :work_history_show patch '/review' => 'work_history/review#complete', as: :work_history_complete get '/delete/:id' => 'work_history/destroy#confirm_destroy', as: :work_history_destroy delete '/delete/:id' => 'work_history/destroy#destroy' end scope '/restructured-work-history' do get '/' => 'restructured_work_history/start#choice', as: :restructured_work_history post '/' => 'restructured_work_history/start#submit_choice' get '/new' => 'restructured_work_history/job#new', as: :new_restructured_work_history post '/new' => 'restructured_work_history/job#create' get '/edit/:id' => 'restructured_work_history/job#edit', as: :edit_restructured_work_history patch '/edit/:id' => 'restructured_work_history/job#update' get '/delete/:id' => 'restructured_work_history/job#confirm_destroy', as: :destroy_restructured_work_history delete '/delete/:id' => 'restructured_work_history/job#destroy' get '/explain-break/new' => 'restructured_work_history/break#new', as: :new_restructured_work_history_break post '/explain-break/new' => 'restructured_work_history/break#create' get '/explain-break/edit/:id' => 'restructured_work_history/break#edit', as: :edit_restructured_work_history_break patch '/explain-break/edit/:id' => 'restructured_work_history/break#update' get '/explain-break/delete/:id' => 'restructured_work_history/break#confirm_destroy', as: :destroy_restructured_work_history_break delete '/explain-break/delete/:id' => 'restructured_work_history/break#destroy' get '/review' => 'restructured_work_history/review#show', as: :restructured_work_history_review patch '/review' => 'restructured_work_history/review#complete', as: :restructured_work_history_complete end scope '/school-experience' do get '/', to: redirect('/candidate/application/unpaid-experience') get '/new', to: redirect('/candidate/application/unpaid-experience/new') get '/edit/:id', to: redirect { |params, _| "/candidate/application/unpaid-experience/edit/#{params[:id]}" } get '/review', to: redirect('/candidate/application/unpaid-experience/review') get '/delete/:id', to: redirect { |params, _| "/candidate/application/unpaid-experience/delete/#{params[:id]}" } end scope '/unpaid-experience' do get '/' => 'volunteering/start#show', as: :volunteering_experience post '/' => 'volunteering/start#submit' get '/new' => 'volunteering/role#new', as: :new_volunteering_role post '/new' => 'volunteering/role#create' get '/edit/:id' => 'volunteering/role#edit', as: :edit_volunteering_role patch '/edit/:id' => 'volunteering/role#update' get '/review' => 'volunteering/review#show', as: :review_volunteering patch '/review' => 'volunteering/review#complete', as: :complete_volunteering get '/delete/:id' => 'volunteering/destroy#confirm_destroy', as: :confirm_destroy_volunteering_role delete '/delete/:id' => 'volunteering/destroy#destroy' end scope '/degrees' do get '/' => 'degrees/type#new', as: :new_degree post '/' => 'degrees/type#create' get '/:id/type/edit' => 'degrees/type#edit', as: :edit_degree_type patch '/:id/type/edit' => 'degrees/type#update' get '/:id/subject' => 'degrees/subject#new', as: :degree_subject post '/:id/subject' => 'degrees/subject#create' get '/:id/subject/edit' => 'degrees/subject#edit', as: :edit_degree_subject patch '/:id/subject/edit' => 'degrees/subject#update' get '/:id/institution' => 'degrees/institution#new', as: :degree_institution post '/:id/institution' => 'degrees/institution#create' get '/:id/institution/edit' => 'degrees/institution#edit', as: :edit_degree_institution patch '/:id/institution/edit' => 'degrees/institution#update' get '/:id/completion_status', to: redirect { |params, _| "/candidate/application/degrees/#{params[:id]}/completion-status" } get '/:id/completion_status/edit', to: redirect { |params, _| "/candidate/application/degrees/#{params[:id]}/completion-status/edit" } get '/:id/completion-status' => 'degrees/completion_status#new', as: :degree_completion_status post '/:id/completion-status' => 'degrees/completion_status#create' get '/:id/completion-status/edit' => 'degrees/completion_status#edit', as: :edit_degree_completion_status patch '/:id/completion-status/edit' => 'degrees/completion_status#update' get '/:id/naric' => 'degrees/naric#new', as: :degree_naric post '/:id/naric' => 'degrees/naric#create' get '/:id/naric/edit' => 'degrees/naric#edit', as: :edit_degree_naric patch '/:id/naric/edit' => 'degrees/naric#update' get '/:id/grade' => 'degrees/grade#new', as: :degree_grade post '/:id/grade' => 'degrees/grade#create' get '/:id/grade/edit' => 'degrees/grade#edit', as: :edit_degree_grade patch '/:id/grade/edit' => 'degrees/grade#update' get '/:id/year' => 'degrees/year#new', as: :degree_year post '/:id/year' => 'degrees/year#create' get '/:id/year/edit' => 'degrees/year#edit', as: :edit_degree_year patch '/:id/year/edit' => 'degrees/year#update' get '/review' => 'degrees/review#show', as: :degrees_review patch '/review' => 'degrees/review#complete', as: :degrees_complete get '/delete/:id' => 'degrees/destroy#confirm_destroy', as: :confirm_degree_destroy delete '/delete/:id' => 'degrees/destroy#destroy' end scope '/courses' do get '/' => 'application_choices#index', as: :course_choices_index get '/choose' => 'course_choices/have_you_chosen#ask', as: :course_choices_choose post '/choose' => 'course_choices/have_you_chosen#decide' get '/find-a-course' => 'course_choices/have_you_chosen#go_to_find', as: :go_to_find get '/find_a_course', to: redirect('/candidate/application/courses/find-a-course') get '/provider' => 'course_choices/provider_selection#new', as: :course_choices_provider post '/provider' => 'course_choices/provider_selection#create' get '/provider/:provider_id/courses' => 'course_choices/course_selection#new', as: :course_choices_course post '/provider/:provider_id/courses' => 'course_choices/course_selection#create' get '/provider/:provider_id/courses/:course_id' => 'course_choices/study_mode_selection#new', as: :course_choices_study_mode post '/provider/:provider_id/courses/:course_id' => 'course_choices/study_mode_selection#create' get '/provider/:provider_id/courses/:course_id/full' => 'course_choices/course_selection#full', as: :course_choices_full get '/provider/:provider_id/courses/:course_id/:study_mode' => 'course_choices/site_selection#new', as: :course_choices_site post '/provider/:provider_id/courses/:course_id/:study_mode' => 'course_choices/site_selection#create' get '/another' => 'course_choices/add_another_course#ask', as: :course_choices_add_another_course post '/another' => 'course_choices/add_another_course#decide', as: :course_choices_add_another_course_selection get '/apply-on-ucas/provider/:provider_id' => 'course_choices/ucas#no_courses', as: :course_choices_ucas_no_courses get '/apply-on-ucas/provider/:provider_id/course/:course_id' => 'course_choices/ucas#with_course', as: :course_choices_ucas_with_course get '/confirm-selection/:course_id' => 'find_course_selections#confirm_selection', as: :course_confirm_selection get '/confirm_selection/:course_id', to: redirect('/candidate/application/courses/confirm-selection/%{course_id}') post '/complete-selection/:course_id' => 'find_course_selections#complete_selection', as: :course_complete_selection get '/complete_selection/:course_id', to: redirect('/candidate/application/courses/complete-selection/%{course_id}') get '/review' => 'application_choices#review', as: :course_choices_review patch '/review' => 'application_choices#complete', as: :course_choices_complete get '/delete/:id' => 'application_choices#confirm_destroy', as: :confirm_destroy_course_choice delete '/delete/:id' => 'application_choices#destroy' end scope '/choice/:id' do get '/offer' => 'decisions#offer', as: :offer post '/offer/respond' => 'decisions#respond_to_offer', as: :respond_to_offer get '/offer/decline' => 'decisions#decline_offer', as: :decline_offer post '/offer/decline' => 'decisions#confirm_decline' get '/offer/accept' => 'decisions#accept_offer', as: :accept_offer post '/offer/accept' => 'decisions#confirm_accept' get '/withdraw' => 'decisions#withdraw', as: :withdraw post '/withdraw' => 'decisions#confirm_withdraw' get '/withdraw/feedback' => 'decisions#withdrawal_feedback', as: :withdrawal_feedback post '/withdraw/confirm-feedback' => 'decisions#confirm_withdrawal_feedback', as: :confirm_withdrawal_feedback end scope '/other-qualifications' do get '/' => 'other_qualifications/type#new', as: :other_qualification_type post '/' => 'other_qualifications/type#create' get '/type/edit/:id' => 'other_qualifications/type#edit', as: :edit_other_qualification_type patch '/type/edit/:id' => 'other_qualifications/type#update' get '/details' => 'other_qualifications/details#new', as: :other_qualification_details patch '/details' => 'other_qualifications/details#create' get '/details/edit/:id' => 'other_qualifications/details#edit', as: :edit_other_qualification_details patch '/details/edit/:id' => 'other_qualifications/details#update' get '/review' => 'other_qualifications/review#show', as: :review_other_qualifications patch '/review' => 'other_qualifications/review#complete', as: :complete_other_qualifications get '/delete/:id' => 'other_qualifications/destroy#confirm_destroy', as: :confirm_destroy_other_qualification delete '/delete/:id' => 'other_qualifications/destroy#destroy' end scope '/english-as-a-foreign-language' do get '/' => 'english_foreign_language/start#new', as: :english_foreign_language_start post '/' => 'english_foreign_language/start#create' get '/edit' => 'english_foreign_language/start#edit', as: :english_foreign_language_edit_start patch '/edit' => 'english_foreign_language/start#update' get '/type' => 'english_foreign_language/type#new', as: :english_foreign_language_type post '/type' => 'english_foreign_language/type#create' get '/ielts' => 'english_foreign_language/ielts#new', as: :ielts post '/ielts' => 'english_foreign_language/ielts#create' get '/ielts/edit' => 'english_foreign_language/ielts#edit', as: :edit_ielts patch '/ielts/edit' => 'english_foreign_language/ielts#update' get '/toefl' => 'english_foreign_language/toefl#new', as: :toefl post '/toefl' => 'english_foreign_language/toefl#create' get '/toefl/edit' => 'english_foreign_language/toefl#edit', as: :edit_toefl patch '/toefl/edit' => 'english_foreign_language/toefl#update' get '/other' => 'english_foreign_language/other_efl_qualification#new', as: :other_efl_qualification post '/other' => 'english_foreign_language/other_efl_qualification#create' get '/other/edit' => 'english_foreign_language/other_efl_qualification#edit', as: :edit_other_efl_qualification patch '/other/edit' => 'english_foreign_language/other_efl_qualification#update' get '/review' => 'english_foreign_language/review#show', as: :english_foreign_language_review patch '/review' => 'english_foreign_language/review#complete', as: :english_foreign_language_complete end scope '/references' do get '/start' => 'references/start#show', as: :references_start get '/type' => 'references/type#new', as: :references_type post '/type' => 'references/type#create' get '/type/edit/:id' => 'references/type#edit', as: :references_edit_type patch '/type/edit/:id' => 'references/type#update' get '/name/:id' => 'references/name#new', as: :references_name patch '/name/:id' => 'references/name#create' get '/name/edit/:id' => 'references/name#edit', as: :references_edit_name patch '/name/edit/:id' => 'references/name#update' get '/email/:id' => 'references/email_address#new', as: :references_email_address patch '/email/:id' => 'references/email_address#create' get '/email/edit/:id' => 'references/email_address#edit', as: :references_edit_email_address patch '/email/edit/:id' => 'references/email_address#update' get '/relationship/:id' => 'references/relationship#new', as: :references_relationship patch '/relationship/:id' => 'references/relationship#create' get '/relationship/edit/:id' => 'references/relationship#edit', as: :references_edit_relationship patch '/relationship/edit/:id' => 'references/relationship#update' get '/review-unsubmitted/:id' => 'references/review#unsubmitted', as: :references_review_unsubmitted post '/review-unsubmitted/:id' => 'references/review#submit', as: :references_submit get '/review' => 'references/review#show', as: :references_review get '/review/delete-referee/:id' => 'references/review#confirm_destroy_referee', as: :confirm_destroy_referee get '/review/delete-reference/:id' => 'references/review#confirm_destroy_reference', as: :confirm_destroy_reference get '/review/delete-reference-request/:id' => 'references/review#confirm_destroy_reference_request', as: :confirm_destroy_reference_request delete '/review/delete/:id' => 'references/review#destroy', as: :destroy_reference get 'review/cancel/:id' => 'references/review#confirm_cancel', as: :confirm_cancel_reference patch 'review/cancel/:id' => 'references/review#cancel', as: :cancel_reference get '/request/:id' => 'references/request#new', as: :references_new_request post '/request/:id' => 'references/request#create', as: :references_create_request get '/retry-request/:id' => 'references/retry_request#new', as: :references_retry_request post '/retry-request/:id' => 'references/retry_request#create' get '/reminder/:id' => 'references/reminder#new', as: :references_new_reminder post '/reminder/:id' => 'references/reminder#create' get '/candidate-name/:id' => 'references/candidate_name#new', as: :references_new_candidate_name post '/candidate-name/:id' => 'references/candidate_name#create', as: :references_create_candidate_name end scope '/equality-and-diversity' do get '/' => 'equality_and_diversity#start', as: :start_equality_and_diversity post '/' => 'equality_and_diversity#choice' get '/sex' => 'equality_and_diversity#edit_sex', as: :edit_equality_and_diversity_sex patch '/sex' => 'equality_and_diversity#update_sex' get '/disability-status' => 'equality_and_diversity#edit_disability_status', as: :edit_equality_and_diversity_disability_status patch '/disability-status' => 'equality_and_diversity#update_disability_status' get '/disabilities' => 'equality_and_diversity#edit_disabilities', as: :edit_equality_and_diversity_disabilities patch '/disabilities' => 'equality_and_diversity#update_disabilities' get '/ethnic-group' => 'equality_and_diversity#edit_ethnic_group', as: :edit_equality_and_diversity_ethnic_group patch '/ethnic-group' => 'equality_and_diversity#update_ethnic_group' get '/ethnic-background' => 'equality_and_diversity#edit_ethnic_background', as: :edit_equality_and_diversity_ethnic_background patch '/ethnic-background' => 'equality_and_diversity#update_ethnic_background' get '/review' => 'equality_and_diversity#review', as: :review_equality_and_diversity end scope '/safeguarding' do get '/' => 'safeguarding#edit', as: :edit_safeguarding post '/' => 'safeguarding#update' get '/review' => 'safeguarding#show', as: :review_safeguarding post '/complete' => 'safeguarding#complete', as: :complete_safeguarding end scope '/feedback-form' do get '/' => 'feedback_form#new', as: :feedback_form post '/' => 'feedback_form#create' get '/thank-you' => 'feedback_form#thank_you', as: :feedback_form_thank_you end scope '/application-feedback' do get '/' => 'application_feedback#new', as: :application_feedback post '/' => 'application_feedback#create' get '/thank-you' => 'application_feedback#thank_you', as: :application_feedback_thank_you end end get '*path', to: 'errors#not_found' end namespace :referee_interface, path: '/reference' do get '/' => 'reference#relationship', as: :reference_relationship patch '/confirm-relationship' => 'reference#confirm_relationship', as: :confirm_relationship get '/safeguarding' => 'reference#safeguarding', as: :safeguarding patch '/confirm-safeguarding' => 'reference#confirm_safeguarding', as: :confirm_safeguarding get '/feedback' => 'reference#feedback', as: :reference_feedback get '/confirmation' => 'reference#confirmation', as: :confirmation patch '/confirmation' => 'reference#submit_feedback', as: :submit_feedback get '/review' => 'reference#review', as: :reference_review patch '/submit' => 'reference#submit_reference', as: :submit_reference patch '/questionnaire' => 'reference#submit_questionnaire', as: :submit_questionnaire get '/finish' => 'reference#finish', as: :finish get '/refuse-feedback' => 'reference#refuse_feedback', as: :refuse_feedback patch '/refuse-feedback' => 'reference#confirm_feedback_refusal' get '/thank-you' => 'reference#thank_you', as: :thank_you end namespace :vendor_api, path: 'api/v1' do get '/applications' => 'applications#index' get '/applications/:application_id' => 'applications#show' scope path: '/applications/:application_id' do post '/offer' => 'decisions#make_offer' post '/confirm-conditions-met' => 'decisions#confirm_conditions_met' post '/conditions-not-met' => 'decisions#conditions_not_met' post '/reject' => 'decisions#reject' post '/confirm-enrolment' => 'decisions#confirm_enrolment' end post '/test-data/regenerate' => 'test_data#regenerate' post '/test-data/generate' => 'test_data#generate' post '/test-data/clear' => 'test_data#clear!' get '/reference-data/gcse-subjects' => 'reference_data#gcse_subjects' get '/reference-data/gcse-grades' => 'reference_data#gcse_grades' get '/reference-data/a-and-as-level-subjects' => 'reference_data#a_and_as_level_subjects' get '/reference-data/a-and-as-level-grades' => 'reference_data#a_and_as_level_grades' post '/experimental/test-data/generate' => 'test_data#experimental_endpoint_moved' post '/experimental/test-data/clear' => 'test_data#experimental_endpoint_moved' get '/ping', to: 'ping#ping' end namespace :provider_interface, path: '/provider' do get '/' => 'start_page#show' get '/accessibility', to: 'content#accessibility' get '/privacy-policy', to: 'content#privacy_policy', as: :privacy_policy get '/cookies', to: 'content#cookies_page', as: :cookies get '/make-a-complaint', to: 'content#complaints', as: :complaints get '/service-guidance', to: 'content#service_guidance_provider', as: :service_guidance get '/covid-19-guidance', to: redirect('/') resources :cookie_preferences, only: 'create', path: 'cookie-preferences' get '/getting-ready-for-next-cycle', to: redirect('/provider/guidance-for-the-new-cycle') get '/guidance-for-the-new-cycle', to: 'content#guidance_for_the_new_cycle', as: :guidance_for_the_new_cycle get '/data-sharing-agreements/new', to: 'provider_agreements#new_data_sharing_agreement', as: :new_data_sharing_agreement post '/data-sharing-agreements', to: 'provider_agreements#create_data_sharing_agreement', as: :create_data_sharing_agreement get '/activity' => 'activity_log#index', as: :activity_log get '/applications' => 'application_choices#index' get '/applications/hesa-export/new' => 'hesa_export#new', as: :new_hesa_export get '/applications/hesa-export' => 'hesa_export#export', as: :hesa_export get 'applications/data-export/new' => 'application_data_export#new', as: :new_application_data_export get 'applications/data-export' => 'application_data_export#export', as: :application_data_export scope path: '/applications/:application_choice_id' do get '/' => 'application_choices#show', as: :application_choice get '/offer' => 'application_choices#offer', as: :application_choice_offer get '/timeline' => 'application_choices#timeline', as: :application_choice_timeline get '/emails' => 'application_choices#emails', as: :application_choice_emails get '/feedback' => 'application_choices#feedback', as: :application_choice_feedback get '/respond' => 'decisions#respond', as: :application_choice_respond post '/respond' => 'decisions#submit_response', as: :application_choice_submit_response get '/offer/new' => 'decisions#new_offer', as: :application_choice_new_offer post '/offer/confirm' => 'decisions#confirm_offer', as: :application_choice_confirm_offer post '/offer' => 'decisions#create_offer', as: :application_choice_create_offer get '/conditions' => 'conditions#edit', as: :application_choice_edit_conditions patch '/conditions/confirm' => 'conditions#confirm_update', as: :application_choice_confirm_update_conditions patch '/conditions' => 'conditions#update', as: :application_choice_update_conditions get '/offer/change/*step' => 'offer_changes#edit_offer', as: :application_choice_edit_offer patch '/offer/change' => 'offer_changes#update_offer', as: :application_choice_update_offer get '/offer/new_withdraw' => redirect('/offer/withdraw') post '/offer/confirm_withdraw' => redirect('/offer/confirm-withdraw') get '/offer/withdraw' => 'decisions#new_withdraw_offer', as: :application_choice_new_withdraw_offer post '/offer/confirm-withdraw' => 'decisions#confirm_withdraw_offer', as: :application_choice_confirm_withdraw_offer post '/offer/withdraw' => 'decisions#withdraw_offer', as: :application_choice_withdraw_offer get '/offer/defer' => 'decisions#new_defer_offer', as: :application_choice_new_defer_offer post '/offer/defer' => 'decisions#defer_offer', as: :application_choice_defer_offer get '/rbd-feedback' => 'feedback#new', as: :application_choice_new_rbd_feedback post '/feedback/check' => 'feedback#check', as: :application_choice_check_feedback post '/rbd-feedback' => 'feedback#create', as: :application_choice_rbd_feedback get '/rejection-reasons' => 'reasons_for_rejection#edit_initial_questions', as: :reasons_for_rejection_initial_questions post '/rejection-reasons' => 'reasons_for_rejection#update_initial_questions', as: :reasons_for_rejection_update_initial_questions get '/rejection-reasons/other-reasons-for-rejection' => 'reasons_for_rejection#edit_other_reasons', as: :reasons_for_rejection_other_reasons post '/rejection-reasons/other-reasons-for-rejection' => 'reasons_for_rejection#update_other_reasons', as: :reasons_for_rejection_update_other_reasons get '/rejection-reasons/check' => 'reasons_for_rejection#check', as: :reasons_for_rejection_check post '/rejection-reasons/commit' => 'reasons_for_rejection#commit', as: :reasons_for_rejection_commit resources :notes, only: %i[index show new create], as: :application_choice_notes resources :interviews, only: %i[new edit index], as: :application_choice_interviews do collection do post '/new/check', to: 'interviews#check' post '/confirm', to: 'interviews#commit' end member do get :cancel post '/cancel/review/', to: 'interviews#review_cancel' post '/cancel/confirm/', to: 'interviews#confirm_cancel' post '/check', to: 'interviews#check' put '/update', to: 'interviews#update' end end end resource :interview_schedule, path: 'interview-schedule', only: :show do get :past, on: :collection end post '/candidates/:candidate_id/impersonate' => 'candidates#impersonate', as: :impersonate_candidate get '/sign-in' => 'sessions#new' get '/sign-out' => 'sessions#destroy' post '/request-sign-in-by-email' => 'sessions#sign_in_by_email', as: :sign_in_by_email get '/sign-in/check-email', to: 'sessions#check_your_email', as: :check_your_email get '/sign-in-by-email' => 'sessions#authenticate_with_token', as: :authenticate_with_token get '/account' => 'account#show' scope path: '/account' do get '/profile' => 'profile#show' scope path: '/users' do get '/' => 'provider_users#index', as: :provider_users get '/new' => 'provider_users_invitations#edit_details', as: :edit_invitation_basic_details post '/new' => 'provider_users_invitations#update_details', as: :update_invitation_basic_details get '/new/providers' => 'provider_users_invitations#edit_providers', as: :edit_invitation_providers post '/new/providers' => 'provider_users_invitations#update_providers', as: :update_invitation_providers get '/new/providers/:provider_id/permissions' => 'provider_users_invitations#edit_permissions', as: :edit_invitation_provider_permissions post '/new/providers/:provider_id/permissions' => 'provider_users_invitations#update_permissions', as: :update_invitation_provider_permissions get '/new/check' => 'provider_users_invitations#check', as: :check_invitation post '/new/commit' => 'provider_users_invitations#commit', as: :commit_invitation scope '/:provider_user_id', as: :provider_user do get '/' => 'provider_users#show' get '/edit-providers' => 'provider_users#edit_providers', as: :edit_providers patch '/edit-providers' => 'provider_users#update_providers' get '/remove' => 'provider_users#confirm_remove', as: :remove_provider_user delete '/remove' => 'provider_users#remove' get '/providers/:provider_id/permissions' => 'provider_users#edit_permissions', as: :edit_permissions patch '/providers/:provider_id/permissions' => 'provider_users#update_permissions' end end resources :organisations, only: %i[index show], path: 'organisational-permissions' resource :notifications, only: %i[show update], path: 'notification-settings' end scope path: '/provider-relationship-permissions' do get '/organisations-to-setup' => 'provider_relationship_permissions_setup#organisations', as: :provider_relationship_permissions_organisations get '/:id/setup' => 'provider_relationship_permissions_setup#setup_permissions', as: :setup_provider_relationship_permissions post '/:id/create' => 'provider_relationship_permissions_setup#save_permissions', as: :save_provider_relationship_permissions get '/check' => 'provider_relationship_permissions_setup#check', as: :check_provider_relationship_permissions post '/commit' => 'provider_relationship_permissions_setup#commit', as: :commit_provider_relationship_permissions get '/success' => 'provider_relationship_permissions_setup#success', as: :provider_relationship_permissions_success get '/:id/edit' => 'provider_relationship_permissions#edit', as: :edit_provider_relationship_permissions patch '/:id' => 'provider_relationship_permissions#update', as: :update_provider_relationship_permissions end scope path: '/applications/:application_choice_id/offer/reconfirm' do get '/' => 'reconfirm_deferred_offers#start', as: :reconfirm_deferred_offer get '/conditions' => 'reconfirm_deferred_offers#conditions', as: :reconfirm_deferred_offer_conditions patch '/conditions' => 'reconfirm_deferred_offers#update_conditions' get '/check' => 'reconfirm_deferred_offers#check', as: :reconfirm_deferred_offer_check post '/' => 'reconfirm_deferred_offers#commit' end get '*path', to: 'errors#not_found' end get '/auth/dfe/callback' => 'dfe_sign_in#callback' post '/auth/developer/callback' => 'dfe_sign_in#bypass_callback' get '/auth/dfe/sign-out' => 'dfe_sign_in#redirect_after_dsi_signout' namespace :integrations, path: '/integrations' do post '/notify/callback' => 'notify#callback' get '/feature-flags' => 'feature_flags#index' get '/performance-dashboard' => redirect('support/performance/service') end namespace :data_api, path: '/data-api' do get '/docs/tad-data-exports' => 'tad_docs#docs' get '/tad-data-exports/latest' => 'tad_data_exports#latest' end namespace :support_interface, path: '/support' do get '/' => redirect('/support/applications') get '/applications' => 'application_forms#index' scope path: '/applications/:application_form_id' do get '/' => 'application_forms#show', as: :application_form get '/add-course/search' => 'application_forms/courses#new_search', as: :application_form_search_course_new post '/add-course/search' => 'application_forms/courses#search', as: :application_form_search_course get '/add-course/:course_code' => 'application_forms/courses#new', as: :application_form_new_course post '/add-course/:course_code' => 'application_forms/courses#create', as: :application_form_create_course get '/audit' => 'application_forms#audit', as: :application_form_audit get '/comments/new' => 'application_forms/comments#new', as: :application_form_new_comment post '/comments' => 'application_forms/comments#create', as: :application_form_comments get '/applicant-details' => 'application_forms/applicant_details#edit', as: :application_form_edit_applicant_details post '/applicant-details' => 'application_forms/applicant_details#update', as: :application_form_update_applicant_details get '/gcses/:gcse_id' => 'application_forms/gcses#edit', as: :application_form_edit_gcse post '/gcses/:gcse_id' => 'application_forms/gcses#update', as: :application_form_update_gcse get '/degrees/:degree_id' => 'application_forms/degrees#edit', as: :application_form_edit_degree post '/degrees/:degree_id' => 'application_forms/degrees#update', as: :application_form_update_degree get '/references/:reference_id/details' => 'application_forms/references#edit_reference_details', as: :application_form_edit_reference_details post '/references/:reference_id/details' => 'application_forms/references#update_reference_details', as: :application_form_update_reference_details get '/references/:reference_id/feedback' => 'application_forms/references#edit_reference_feedback', as: :application_form_edit_reference_feedback post '/references/:reference_id/feedback' => 'application_forms/references#update_reference_feedback', as: :application_form_update_reference_feedback get '/applicant-address-type' => 'application_forms/address_type#edit', as: :application_form_edit_address_type post '/applicant-address-type' => 'application_forms/address_type#update', as: :application_form_update_address_type get '/applicant-address-details' => 'application_forms/address_details#edit', as: :application_form_edit_address_details post '/applicant-address-details' => 'application_forms/address_details#update', as: :application_form_update_address_details get '/nationalities' => 'application_forms/nationalities#edit', as: :application_form_edit_nationalities patch '/nationalities' => 'application_forms/nationalities#update' get '/right-to-work-or-study' => 'application_forms/right_to_work_or_study#edit', as: :application_form_edit_right_to_work_or_study patch '/right-to-work-or-study' => 'application_forms/right_to_work_or_study#update' end get '/ucas-matches' => 'ucas_matches#index' scope path: '/ucas-matches/:id' do get '/' => 'ucas_matches#show', as: :ucas_match get '/audit' => 'ucas_matches#audit', as: :ucas_match_audit post '/record-ucas-withdrawal-requested' => 'ucas_matches#record_ucas_withdrawal_requested', as: :record_ucas_withdrawal_requested end get '/application_choices/:application_choice_id' => redirect('/application-choices/%{application_choice_id}') get '/application-choices/:application_choice_id' => 'application_choices#show', as: :application_choice get '/candidates' => 'candidates#index' scope path: '/candidates/:candidate_id' do get '/' => 'candidates#show', as: :candidate post '/hide' => 'candidates#hide_in_reporting', as: :hide_candidate post '/show' => 'candidates#show_in_reporting', as: :show_candidate post '/impersonate' => 'candidates#impersonate', as: :impersonate_candidate end scope path: '/references/:reference_id' do get '/cancel' => 'references#cancel', as: :cancel_reference post '/cancel' => 'references#confirm_cancel' get '/reinstate' => 'references#reinstate', as: :reinstate_reference post '/reinstate' => 'references#confirm_reinstate' get '/impersonate-and-give' => 'references#impersonate_and_give', as: :impersonate_referee_and_give_reference get 'impersonate-and-decline' => 'references#impersonate_and_decline', as: :impersonate_referee_and_decline_reference end get '/tokens' => 'api_tokens#index', as: :api_tokens post '/tokens' => 'api_tokens#create' get '/providers' => 'providers#index', as: :providers scope path: '/providers/:provider_id' do get '/' => 'providers#show', as: :provider get '/courses' => 'providers#courses', as: :provider_courses get '/ratified-courses' => 'providers#ratified_courses', as: :provider_ratified_courses get '/vacancies' => 'providers#vacancies', as: :provider_vacancies get '/sites' => 'providers#sites', as: :provider_sites get '/users' => 'providers#users', as: :provider_user_list get '/applications' => 'providers#applications', as: :provider_applications get '/history' => 'providers#history', as: :provider_history get '/relationships' => 'providers#relationships', as: :provider_relationships post '/relationships' => 'providers#update_relationships', as: :update_provider_relationships post '' => 'providers#open_all_courses' post '/enable_course_syncing' => redirect('/enable-course-syncing') post '/enable-course-syncing' => 'providers#enable_course_syncing', as: :enable_provider_course_syncing end scope path: '/courses/:course_id' do get '/' => 'course#show', as: :course get '/applications' => 'course#applications', as: :course_applications get '/vacancies' => 'course#vacancies', as: :course_vacancies post '' => 'course#update' end scope '/performance' do get '/' => 'performance#index', as: :performance get '/course-statistics', to: 'performance#courses_dashboard', as: :courses_dashboard get '/feature-metrics' => 'performance#feature_metrics_dashboard', as: :feature_metrics_dashboard get '/reasons-for-rejection' => 'performance#reasons_for_rejection_dashboard', as: :reasons_for_rejection_dashboard get '/reasons-for-rejection/application-choices' => 'performance#reasons_for_rejection_application_choices', as: :reasons_for_rejection_application_choices get '/service' => 'performance#service_performance_dashboard', as: :service_performance_dashboard get '/ucas-matches' => 'performance#ucas_matches_dashboard', as: :ucas_matches_dashboard get '/course-options', to: 'performance#course_options', as: :course_options get '/unavailable-choices' => 'performance#unavailable_choices', as: :unavailable_choices get '/validation-errors' => 'validation_errors#index', as: :validation_errors get '/validation-errors/search' => 'validation_errors#search', as: :validation_error_search get '/validation-errors/summary' => 'validation_errors#summary', as: :validation_error_summary get '/data-export/documentation/:export_type_id' => 'data_exports#data_set_documentation', as: :data_set_documentation resources :data_exports, path: '/data-exports' do member do get :download end end end get '/email-log', to: 'email_log#index', as: :email_log get '/vendor-api-requests', to: 'vendor_api_requests#index', as: :vendor_api_requests scope '/settings' do get '/' => redirect('/support/settings/feature-flags'), as: :settings get '/feature-flags' => 'settings#feature_flags', as: :feature_flags post '/feature-flags/:feature_name/activate' => 'settings#activate_feature_flag', as: :activate_feature_flag post '/feature-flags/:feature_name/deactivate' => 'settings#deactivate_feature_flag', as: :deactivate_feature_flag get '/cycles', to: 'settings#cycles', as: :cycles unless HostingEnvironment.production? post '/cycles', to: 'settings#switch_cycle_schedule', as: :switch_cycle_schedule end get '/tasks' => 'tasks#index', as: :tasks post '/tasks/create-fake-provider' => 'tasks#create_fake_provider' post '/tasks/:task' => 'tasks#run', as: :run_task get '/tasks/confirm-delete-test-applications' => 'tasks#confirm_delete_test_applications', as: :confirm_delete_test_applications get '/tasks/confirm-cancel-applications-at-end-of-cycle' => 'tasks#confirm_cancel_applications_at_end_of_cycle', as: :confirm_cancel_applications_at_end_of_cycle end scope '/docs' do get '/', to: 'docs#index', as: :docs get '/provider-flow', to: 'docs#provider_flow', as: :docs_provider_flow get '/candidate-flow', to: 'docs#candidate_flow', as: :docs_candidate_flow get '/when-emails-are-sent', to: 'docs#when_emails_are_sent', as: :docs_when_emails_are_sent get '/mailers' => 'docs#mailer_previews', as: :docs_mailer_previews end scope '/users' do get '/' => 'users#index', as: :users get '/delete/:id' => 'support_users#confirm_destroy', as: :confirm_destroy_support_user delete '/delete/:id' => 'support_users#destroy', as: :destroy_support_user get '/restore/:id' => 'support_users#confirm_restore', as: :confirm_restore_support_user delete '/restore/:id' => 'support_users#restore', as: :restore_support_user resources :support_users, only: %i[index new create show], path: :support get '/provider/end-impersonation' => 'provider_users#end_impersonation', as: :end_impersonation resources :provider_users, only: %i[show index new create edit update], path: :provider do get '/audits' => 'provider_users#audits' patch '/toggle-notifications' => 'provider_users#toggle_notifications', as: :toggle_notifications post '/impersonate' => 'provider_users#impersonate', as: :impersonate end end get '/sign-in' => 'sessions#new', as: :sign_in get '/sign-out' => 'sessions#destroy', as: :sign_out get '/confirm-environment' => 'sessions#confirm_environment', as: :confirm_environment post '/confirm-environment' => 'sessions#confirmed_environment' post '/request-sign-in-by-email' => 'sessions#sign_in_by_email', as: :sign_in_by_email get '/sign-in/check-email', to: 'sessions#check_your_email', as: :check_your_email get '/sign-in-by-email' => 'sessions#authenticate_with_token', as: :authenticate_with_token # https://github.com/mperham/sidekiq/wiki/Monitoring#rails-http-basic-auth-from-routes require 'sidekiq/web' require 'support_user_constraint' mount Sidekiq::Web => '/sidekiq', constraints: SupportUserConstraint.new get '/sidekiq', to: redirect('/support/sign-in'), status: 302 mount Blazer::Engine => '/blazer', constraints: SupportUserConstraint.new get '/blazer', to: redirect('/support/sign-in'), status: 302 get '*path', to: 'errors#not_found' end namespace :api_docs, path: '/api-docs' do get '/' => 'pages#home', as: :home get '/usage-scenarios' => 'pages#usage', as: :usage get '/reference' => 'reference#reference', as: :reference get '/release-notes' => 'pages#release_notes', as: :release_notes get '/alpha-release-notes' => 'pages#alpha_release_notes' get '/lifecycle' => 'pages#lifecycle' get '/when-emails-are-sent' => 'pages#when_emails_are_sent' get '/help' => 'pages#help', as: :help get '/spec.yml' => 'openapi#spec', as: :spec end get '/check', to: 'healthcheck#show' get '/check/version', to: 'healthcheck#version' scope via: :all do match '/404', to: 'errors#not_found' match '/406', to: 'errors#not_acceptable' match '/422', to: 'errors#unprocessable_entity' match '/500', to: 'errors#internal_server_error' end end
55.484725
182
0.701832
2631f6671a0721f5433e29a8a58a1f54a3e09dac
136
class AddBlogsCommentCountToUser < ActiveRecord::Migration def change add_column :users, :blogs_comment_count, :integer end end
22.666667
58
0.794118
087133bf7f1772c0049b42af22a327ac4092d10b
1,784
require 'stash/indexer/index_config' require 'rsolr' module Stash module Indexer module Solr # Configuration for a Solr index. class SolrIndexConfig < IndexConfig adapter 'Solr' SUSPICIOUS_OPTS = { proxy_url: :proxy, proxy_uri: :proxy }.freeze private_constant :SUSPICIOUS_OPTS attr_reader :proxy_uri attr_reader :opts # Constructs a new `SolrIndexConfig` with the specified properties. # # @param url [URI, String] The URL of the Solr core, e.g. # `http://solr.example.org:8983/solr/stash` # @param proxy [URI, String] The URL of any proxy server required # to access the Solr server # @param opts [Hash] Additional options to be passed when creating # the [RSolr](https://github.com/rsolr/rsolr) client. def initialize(url:, proxy: nil, **opts) super(url: url) check_opts(opts) @proxy_uri = Util.to_uri(proxy) all_opts = opts.clone all_opts[:url] = uri.to_s all_opts[:proxy] = @proxy_uri.to_s if @proxy_uri @opts = all_opts end # Creates a new `SolrIndexer` with this configuration. def create_indexer(metadata_mapper) SolrIndexer.new(config: self, metadata_mapper: metadata_mapper) end def description opts_desc = @opts.map { |k, v| "#{k}: #{v}" }.join(', ') "#{self.class} (#{opts_desc})" end private def check_opts(opts) SUSPICIOUS_OPTS.each do |k, v| Indexer.log.warn("#{SolrIndexConfig} initialized with #{k.inspect} => #{opts[k].inspect}. Did you mean #{v.inspect}?") if opts.include?(k) end end end end end end
29.733333
150
0.59417
2865c5833420b7852470bc3fe82c32618d462745
8,737
# frozen_string_literal: true require "isolation/abstract_unit" require "env_helpers" module ApplicationTests class RakeTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation, EnvHelpers def setup build_app end def teardown teardown_app end def test_gems_tasks_are_loaded_first_than_application_ones app_file "lib/tasks/app.rake", <<-RUBY $task_loaded = Rake::Task.task_defined?("db:create:all") RUBY require "#{app_path}/config/environment" ::Rails.application.load_tasks assert $task_loaded end test "task backtrace is silenced" do add_to_config <<-RUBY rake_tasks do task :boom do raise "boom" end end RUBY backtrace = rails("boom", allow_failure: true).lines.grep(/:\d+:in /) app_lines, framework_lines = backtrace.partition { |line| line.start_with?(app_path) } assert_not_empty app_lines assert_empty framework_lines end test "task is protected when previous migration was production" do with_rails_env "production" do rails "generate", "model", "product", "name:string" rails "db:create", "db:migrate" output = rails("db:test:prepare", allow_failure: true) assert_match(/ActiveRecord::ProtectedEnvironmentError/, output) end end def test_not_protected_when_previous_migration_was_not_production with_rails_env "test" do rails "generate", "model", "product", "name:string" rails "db:create", "db:migrate" output = rails("db:test:prepare", "test") assert_no_match(/ActiveRecord::ProtectedEnvironmentError/, output) end end def test_environment_is_required_in_rake_tasks app_file "config/environment.rb", <<-RUBY SuperMiddleware = Struct.new(:app) Rails.application.configure do config.middleware.use SuperMiddleware end Rails.application.initialize! RUBY assert_match("SuperMiddleware", rails("middleware")) end def test_initializers_are_executed_in_rake_tasks add_to_config <<-RUBY initializer "do_something" do puts "Doing something..." end rake_tasks do task do_nothing: :environment do end end RUBY output = rails("do_nothing") assert_match "Doing something...", output end def test_does_not_explode_when_accessing_a_model add_to_config <<-RUBY rake_tasks do task do_nothing: :environment do Hello.new.world end end RUBY app_file "app/models/hello.rb", <<-RUBY class Hello def world puts 'Hello world' end end RUBY output = rails("do_nothing") assert_match "Hello world", output end def test_should_not_eager_load_model_for_rake_when_rake_eager_load_is_false add_to_config <<-RUBY rake_tasks do task do_nothing: :environment do puts 'There is nothing' end end RUBY add_to_env_config "production", <<-RUBY config.eager_load = true RUBY app_file "app/models/hello.rb", <<-RUBY raise 'should not be pre-required for rake even eager_load=true' RUBY output = rails("do_nothing", "RAILS_ENV=production") assert_match "There is nothing", output end def test_should_eager_load_model_for_rake_when_rake_eager_load_is_true add_to_config <<-RUBY rake_tasks do task do_something: :environment do puts "Answer: " + Hello::TEST.to_s end end RUBY add_to_env_config "production", <<-RUBY config.rake_eager_load = true RUBY app_file "app/models/hello.rb", <<-RUBY class Hello TEST = 42 end RUBY output = Dir.chdir(app_path) { `bin/rails do_something RAILS_ENV=production` } assert_equal "Answer: 42\n", output end def test_code_statistics_sanity assert_match "Code LOC: 32 Test LOC: 3 Code to Test Ratio: 1:0.1", rails("stats") end def test_logger_is_flushed_when_exiting_production_rake_tasks add_to_config <<-RUBY rake_tasks do task log_something: :environment do Rails.logger.error("Sample log message") end end RUBY rails "log_something", "RAILS_ENV=production" assert_match "Sample log message", File.read("#{app_path}/log/production.log") end def test_loading_specific_fixtures rails "generate", "model", "user", "username:string", "password:string" rails "generate", "model", "product", "name:string" rails "db:migrate" require "#{rails_root}/config/environment" # loading a specific fixture rails "db:fixtures:load", "FIXTURES=products" assert_equal 2, Product.count assert_equal 0, User.count end def test_loading_only_yml_fixtures rails "db:migrate" app_file "test/fixtures/products.csv", "" require "#{rails_root}/config/environment" rails "db:fixtures:load" end def test_scaffold_tests_pass_by_default rails "generate", "scaffold", "user", "username:string", "password:string" with_rails_env("test") do rails("db:migrate") end output = rails("test") assert_match(/7 runs, 9 assertions, 0 failures, 0 errors/, output) assert_no_match(/Errors running/, output) end def test_api_scaffold_tests_pass_by_default add_to_config <<-RUBY config.api_only = true RUBY app_file "app/controllers/application_controller.rb", <<-RUBY class ApplicationController < ActionController::API end RUBY rails "generate", "scaffold", "user", "username:string", "password:string" with_rails_env("test") { rails("db:migrate") } output = rails("test") assert_match(/5 runs, 7 assertions, 0 failures, 0 errors/, output) assert_no_match(/Errors running/, output) end def test_scaffold_with_references_columns_tests_pass_by_default rails "generate", "model", "Product" rails "generate", "model", "Cart" rails "generate", "scaffold", "LineItems", "product:references", "cart:belongs_to" with_rails_env("test") do rails("db:migrate") end output = rails("test") assert_match(/7 runs, 9 assertions, 0 failures, 0 errors/, output) assert_no_match(/Errors running/, output) end def test_db_test_prepare_when_using_sql_format add_to_config "config.active_record.schema_format = :sql" rails "generate", "scaffold", "user", "username:string" rails "db:migrate" output = rails("db:test:prepare", "--trace") assert_match(/Execute db:test:load_structure/, output) end def test_rake_dump_structure_should_respect_db_structure_env_variable # ensure we have a schema_migrations table to dump rails "db:migrate", "db:structure:dump", "SCHEMA=db/my_structure.sql" assert File.exist?(File.join(app_path, "db", "my_structure.sql")) end def test_rake_dump_structure_should_be_called_twice_when_migrate_redo add_to_config "config.active_record.schema_format = :sql" rails "g", "model", "post", "title:string" output = rails("db:migrate:redo", "--trace") # expect only Invoke db:structure:dump (first_time) assert_no_match(/^\*\* Invoke db:structure:dump\s+$/, output) end def test_rake_dump_schema_cache rails "generate", "model", "post", "title:string" rails "generate", "model", "product", "name:string" rails "db:migrate", "db:schema:cache:dump" assert File.exist?(File.join(app_path, "db", "schema_cache.yml")) end def test_rake_clear_schema_cache rails "db:schema:cache:dump", "db:schema:cache:clear" assert_not File.exist?(File.join(app_path, "db", "schema_cache.yml")) end def test_copy_templates rails "app:templates:copy" %w(controller mailer scaffold).each do |dir| assert File.exist?(File.join(app_path, "lib", "templates", "erb", dir)) end %w(controller helper scaffold_controller assets).each do |dir| assert File.exist?(File.join(app_path, "lib", "templates", "rails", dir)) end end def test_template_load_initializers app_file "config/initializers/dummy.rb", "puts 'Hello, World!'" app_file "template.rb", "" output = rails("app:template", "LOCATION=template.rb") assert_match(/Hello, World!/, output) end end end
29.417508
92
0.649765
61d323b1e9ade3435d2d6645ea83f551c58bd0f1
125
class AddSignInCountToUsers < ActiveRecord::Migration def change add_column :users, :sign_in_count, :integer end end
20.833333
53
0.776
d54e11f817855965c2ac75a86e2cbbeab2c34fc9
6,866
require 'file/visitor' require 'spec_utils' describe File::Visitor do include SpecUtils before(:each) do setup_test_dir @visitor = File::Visitor.new end after(:all) do clear_test_dir end it 'can be created with new()' do visitor = File::Visitor.new expect(visitor).to be_a File::Visitor end describe 'file/directory traversal' do it 'raises error on non-dir argument' do expect { @visitor.visit(nil) }.to raise_error(ArgumentError) expect { @visitor.visit(1) }.to raise_error(ArgumentError) expect { @visitor.visit_dir(nil) }.to raise_error(ArgumentError) expect { @visitor.visit_dir(1) }.to raise_error(ArgumentError) end it 'can visit given directory' do create_file(['dir1'], 'file1', 'a') create_file(['dir1'], 'file2', 'b') create_file(['dir1'], 'file3', 'c') files = [] @visitor.visit(test_dir) do |path| files.push File.basename(path) end expect(files.size).to eq 3 expect(files[0]).to eq "file1" expect(files[1]).to eq "file2" expect(files[2]).to eq "file3" end it 'can visit sibling directories' do create_file(['dir1'], 'file10', 'a') create_file(['dir2'], 'file11', 'b') create_file(['dir3'], 'file12', 'c') files = [] @visitor.visit(test_dir) do |path| files.push File.basename(path) end expect(files.size).to eq 3 expect(files[0]).to eq "file10" expect(files[1]).to eq "file11" expect(files[2]).to eq "file12" end it 'can visit deep directories' do create_file(['sub'], 'file20', 'a') create_file(['sub', 'subsub'], 'file21', 'b') create_file(['sub', 'subsub', 'subsubsub'], 'file22', 'c') files = [] @visitor.visit(test_dir) do |path| files.push File.basename(path) end expect(files.size).to eq 3 expect(files[0]).to eq "file20" expect(files[1]).to eq "file21" expect(files[2]).to eq "file22" end it 'return empty array when no target files' do files = [] @visitor.visit(test_dir) do |path| files.push File.basename(path) end expect(files).to be_empty end it 'can do dir-only traversal' do create_file(['dir1'], 'file', 'a') create_file(['dir2-1'], 'file', 'a') create_file(['dir2-1', 'dir2-2'], 'file', 'a') dirs = [] @visitor.visit_dir(test_dir) do |path| expect(File.directory?(path)).to be_truthy dirs.push File.basename(path) end expect(dirs.size).to eq 3 expect(dirs[0]).to eq "dir1" expect(dirs[1]).to eq "dir2-1" expect(dirs[2]).to eq "dir2-2" end end it 'it can get files list' do create_file(['dir1'], 'file1', 'a') create_file(['dir2'], 'file2', 'b') create_file(['dir2'], 'file3', 'c') files = @visitor.file_list(test_dir) expect(files.size).to eq 3 expect(File.exist?(files[0])).to be_truthy expect(File.exist?(files[1])).to be_truthy expect(File.exist?(files[2])).to be_truthy expect(File.basename(files[0])).to eq "file1" expect(File.basename(files[1])).to eq "file2" expect(File.basename(files[2])).to eq "file3" end it 'can get dir list' do create_file(['dir1'], 'file1', 'a') create_file(['dir2'], 'file2', 'b') create_file(['dir2'], 'file3', 'c') dirs = @visitor.dir_list(test_dir) expect(dirs.size).to eq 2 expect(File.directory?(dirs[0])).to be_truthy expect(File.directory?(dirs[1])).to be_truthy expect(File.basename(dirs[0])).to eq "dir1" expect(File.basename(dirs[1])).to eq "dir2" end context "filters registration" do before(:each) do end it 'built-in filter' do @visitor.add_filter(:name, '2013-01-01.log') expect(@visitor.filters.size).to eq 1 expect(@visitor.filters[0]).to be_a File::Visitor::Filter::Name end it 'custom filter' do class ValidCustomFilter def match? true end end @visitor.add_filter(ValidCustomFilter.new) expect(@visitor.filters.size).to eq 1 expect(@visitor.filters[0]).to be_a ValidCustomFilter end it "add custom filter fails on invalid class" do class BrokenCustomFilter # match? not implemented end expect { @visitor.add_filter(BrokenCustomFilter.new) }.to raise_error(ArgumentError, /must implement match\?\(\)/) end it 'block filter' do @visitor.add_filter do |path| path =~ /\./ end expect(@visitor.filters.size).to eq 1 expect(@visitor.filters[0]).to be_a File::Visitor::Filter::Proc end end describe "target?" do it "all the paths are target, when no filters" do expect(@visitor.target?("/tmp")).to be_truthy end it "filter AND combination" do @visitor.add_filter(:ext, :txt) @visitor.add_filter { |path| path =~ /feb/ } expect(@visitor.target?("/tmp/2013-jan.txt")).to be_falsy expect(@visitor.target?("/tmp/2013-feb.txt")).to be_truthy expect(@visitor.target?("/tmp/2013-mar.txt")).to be_falsy end end describe "direction" do it "has a default direction" do expect(@visitor.direction).to eq :asc end it "changes direction" do @visitor.set_direction(:desc) expect(@visitor.direction).to eq :desc @visitor.set_direction(:asc) expect(@visitor.direction).to eq :asc @visitor.set_direction(:desc) expect(@visitor.direction).to eq :desc end it "raises error on invalid direction" do expect { @visitor.set_direction(nil) } .to raise_error(ArgumentError, /is nil/) expect { @visitor.set_direction("hoge") } .to raise_error(ArgumentError, /invalid/) expect { @visitor.set_direction(:hoge) } .to raise_error(ArgumentError, /invalid/) end describe "affects list order" do before(:each) do create_file(['dirA'], 'fileA1', '') create_file(['dirA'], 'fileA2', '') create_file(['dirB'], 'fileB1', '') create_file(['dirB'], 'fileB2', '') end it "ascending" do @visitor.set_direction(:asc) files = @visitor.file_list(test_dir) expect(File.basename(files[0])).to eq "fileA1" expect(File.basename(files[1])).to eq "fileA2" expect(File.basename(files[2])).to eq "fileB1" expect(File.basename(files[3])).to eq "fileB2" end it "descending" do @visitor.set_direction(:desc) files = @visitor.file_list(test_dir) expect(File.basename(files[0])).to eq "fileB2" expect(File.basename(files[1])).to eq "fileB1" expect(File.basename(files[2])).to eq "fileA2" expect(File.basename(files[3])).to eq "fileA1" end end end end
27.13834
70
0.607049
f7fc2bc05c5d0cbce42ba24a9ca9d18239a75c23
740
$vertx.create_http_server().request_handler() { |request| # Let's say we have to call a blocking API (e.g. JDBC) to execute a query for each # request. We can't do this directly or it will block the event loop # But you can do this using executeBlocking: $vertx.execute_blocking(lambda { |promise| # Do the blocking operation in here # Imagine this was a call to a blocking API to get the result begin Java::JavaLang::Thread.sleep(500) rescue end result = "armadillos!" promise.complete(result) }) { |res_err,res| if (res_err == nil) request.response().put_header("content-type", "text/plain").end(res) else res_err.print_stack_trace() end } }.listen(8080)
21.142857
84
0.663514
616447cbac7aa67d5cde9f13372205ab3ba642ee
414
class User < ApplicationRecord before_save { self.email = email.downcase } validates :name, presence: true, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } has_secure_password validates :password, presence: true, length: { minimum: 6 } end
46
135
0.695652
d5fcc1ed9e6b29b625f13178c4df95395e26d6c7
61,253
# Copyright 2017 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "google/cloud/spanner/errors" require "google/cloud/spanner/project" require "google/cloud/spanner/data" require "google/cloud/spanner/pool" require "google/cloud/spanner/session" require "google/cloud/spanner/transaction" require "google/cloud/spanner/snapshot" require "google/cloud/spanner/range" require "google/cloud/spanner/column_value" require "google/cloud/spanner/convert" module Google module Cloud module Spanner ## # # Client # # A client is used to read and/or modify data in a Cloud Spanner database. # # See {Google::Cloud::Spanner::Project#client}. # # @example # require "google/cloud" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # db.transaction do |tx| # results = tx.execute_query "SELECT * FROM users" # # results.rows.each do |row| # puts "User #{row[:id]} is #{row[:name]}" # end # end # class Client ## # @private Creates a new Spanner Client instance. def initialize project, instance_id, database_id, session_labels: nil, pool_opts: {} @project = project @instance_id = instance_id @database_id = database_id @session_labels = session_labels @pool = Pool.new self, pool_opts end # The unique identifier for the project. # @return [String] def project_id @project.service.project end # The unique identifier for the instance. # @return [String] def instance_id @instance_id end # The unique identifier for the database. # @return [String] def database_id @database_id end # The Spanner project connected to. # @return [Project] def project @project end # The Spanner instance connected to. # @return [Instance] def instance @project.instance instance_id end # The Spanner database connected to. # @return [Database] def database @project.database instance_id, database_id end ## # Executes a SQL query. # # @param [String] sql The SQL query string. See [Query # syntax](https://cloud.google.com/spanner/docs/query-syntax). # # The SQL query string can contain parameter placeholders. A parameter # placeholder consists of "@" followed by the parameter name. # Parameter names consist of any combination of letters, numbers, and # underscores. # @param [Hash] params SQL parameters for the query string. The # parameter placeholders, minus the "@", are the the hash keys, and # the literal values are the hash values. If the query string contains # something like "WHERE id > @msg_id", then the params must contain # something like `:msg_id => 1`. # # Ruby types are mapped to Spanner types as follows: # # | Spanner | Ruby | Notes | # |-------------|----------------|---| # | `BOOL` | `true`/`false` | | # | `INT64` | `Integer` | | # | `FLOAT64` | `Float` | | # | `STRING` | `String` | | # | `DATE` | `Date` | | # | `TIMESTAMP` | `Time`, `DateTime` | | # | `BYTES` | `File`, `IO`, `StringIO`, or similar | | # | `ARRAY` | `Array` | Nested arrays are not supported. | # | `STRUCT` | `Hash`, {Data} | | # # See [Data # types](https://cloud.google.com/spanner/docs/data-definition-language#data_types). # # See [Data Types - Constructing a # STRUCT](https://cloud.google.com/spanner/docs/data-types#constructing-a-struct). # @param [Hash] types Types of the SQL parameters in `params`. It is not # always possible for Cloud Spanner to infer the right SQL type from a # value in `params`. In these cases, the `types` hash must be used to # specify the SQL type for these values. # # The keys of the hash should be query string parameter placeholders, # minus the "@". The values of the hash should be Cloud Spanner type # codes from the following list: # # * `:BOOL` # * `:BYTES` # * `:DATE` # * `:FLOAT64` # * `:INT64` # * `:STRING` # * `:TIMESTAMP` # * `Array` - Lists are specified by providing the type code in an # array. For example, an array of integers are specified as # `[:INT64]`. # * {Fields} - Types for STRUCT values (`Hash`/{Data} objects) are # specified using a {Fields} object. # # Types are optional. # @param [Hash] single_use Perform the read with a single-use snapshot # (read-only transaction). (See # [TransactionOptions](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#transactionoptions).) # The snapshot can be created by providing exactly one of the # following options in the hash: # # * **Strong** # * `:strong` (true, false) Read at a timestamp where all previously # committed transactions are visible. # * **Exact** # * `:timestamp`/`:read_timestamp` (Time, DateTime) Executes all # reads at the given timestamp. Unlike other modes, reads at a # specific timestamp are repeatable; the same read at the same # timestamp always returns the same data. If the timestamp is in # the future, the read will block until the specified timestamp, # modulo the read's deadline. # # Useful for large scale consistent reads such as mapreduces, or # for coordinating many reads against a consistent snapshot of the # data. # * `:staleness`/`:exact_staleness` (Numeric) Executes all reads at # a timestamp that is exactly the number of seconds provided old. # The timestamp is chosen soon after the read is started. # # Guarantees that all writes that have committed more than the # specified number of seconds ago are visible. Because Cloud # Spanner chooses the exact timestamp, this mode works even if the # client's local clock is substantially skewed from Cloud Spanner # commit timestamps. # # Useful for reading at nearby replicas without the distributed # timestamp negotiation overhead of single-use # `bounded_staleness`. # * **Bounded** # * `:bounded_timestamp`/`:min_read_timestamp` (Time, DateTime) # Executes all reads at a timestamp greater than the value # provided. # # This is useful for requesting fresher data than some previous # read, or data that is fresh enough to observe the effects of # some previously committed transaction whose timestamp is known. # * `:bounded_staleness`/`:max_staleness` (Numeric) Read data at a # timestamp greater than or equal to the number of seconds # provided. Guarantees that all writes that have committed more # than the specified number of seconds ago are visible. Because # Cloud Spanner chooses the exact timestamp, this mode works even # if the client's local clock is substantially skewed from Cloud # Spanner commit timestamps. # # Useful for reading the freshest data available at a nearby # replica, while bounding the possible staleness if the local # replica has fallen behind. # # @return [Google::Cloud::Spanner::Results] The results of the query # execution. # # @example # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # results = db.execute_query "SELECT * FROM users" # # results.rows.each do |row| # puts "User #{row[:id]} is #{row[:name]}" # end # # @example Query using query parameters: # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # results = db.execute_query( # "SELECT * FROM users WHERE active = @active", # params: { active: true } # ) # # results.rows.each do |row| # puts "User #{row[:id]} is #{row[:name]}" # end # # @example Query with a SQL STRUCT query parameter as a Hash: # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # user_hash = { id: 1, name: "Charlie", active: false } # # results = db.execute_query( # "SELECT * FROM users WHERE " \ # "ID = @user_struct.id " \ # "AND name = @user_struct.name " \ # "AND active = @user_struct.active", # params: { user_struct: user_hash } # ) # # results.rows.each do |row| # puts "User #{row[:id]} is #{row[:name]}" # end # # @example Specify the SQL STRUCT type using Fields object: # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # user_type = db.fields id: :INT64, name: :STRING, active: :BOOL # user_hash = { id: 1, name: nil, active: false } # # results = db.execute_query( # "SELECT * FROM users WHERE " \ # "ID = @user_struct.id " \ # "AND name = @user_struct.name " \ # "AND active = @user_struct.active", # params: { user_struct: user_hash }, # types: { user_struct: user_type } # ) # # results.rows.each do |row| # puts "User #{row[:id]} is #{row[:name]}" # end # # @example Or, query with a SQL STRUCT as a typed Data object: # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # user_type = db.fields id: :INT64, name: :STRING, active: :BOOL # user_data = user_type.struct id: 1, name: nil, active: false # # results = db.execute_query( # "SELECT * FROM users WHERE " \ # "ID = @user_struct.id " \ # "AND name = @user_struct.name " \ # "AND active = @user_struct.active", # params: { user_struct: user_data } # ) # # results.rows.each do |row| # puts "User #{row[:id]} is #{row[:name]}" # end # def execute_query sql, params: nil, types: nil, single_use: nil validate_single_use_args! single_use ensure_service! params, types = Convert.to_input_params_and_types params, types single_use_tx = single_use_transaction single_use results = nil @pool.with_session do |session| results = session.execute_query \ sql, params: params, types: types, transaction: single_use_tx end results end alias execute execute_query alias query execute_query alias execute_sql execute_query ## # Executes a Partitioned DML SQL statement. # # Partitioned DML is an alternate implementation with looser semantics # to enable large-scale changes without running into transaction size # limits or (accidentally) locking the entire table in one large # transaction. At a high level, it partitions the keyspace and executes # the statement on each partition in separate internal transactions. # # Partitioned DML does not guarantee database-wide atomicity of the # statement - it guarantees row-based atomicity, which includes updates # to any indices. Additionally, it does not guarantee that it will # execute exactly one time against each row - it guarantees "at least # once" semantics. # # Where DML statements must be executed using Transaction (see # {Transaction#execute_update}), Paritioned DML statements are executed # outside of a read/write transaction. # # Not all DML statements can be executed in the Partitioned DML mode and # the backend will return an error for the statements which are not # supported. # # DML statements must be fully-partitionable. Specifically, the # statement must be expressible as the union of many statements which # each access only a single row of the table. # {Google::Cloud::InvalidArgumentError} is raised if the statement does # not qualify. # # The method will block until the update is complete. Running a DML # statement with this method does not offer exactly once semantics, and # therefore the DML statement should be idempotent. The DML statement # must be fully-partitionable. Specifically, the statement must be # expressible as the union of many statements which each access only a # single row of the table. This is a Partitioned DML transaction in # which a single Partitioned DML statement is executed. Partitioned DML # partitions the and runs the DML statement over each partition in # parallel using separate, internal transactions that commit # independently. Partitioned DML transactions do not need to be # committed. # # Partitioned DML updates are used to execute a single DML statement # with a different execution strategy that provides different, and often # better, scalability properties for large, table-wide operations than # DML in a {Transaction#execute_update} transaction. Smaller scoped # statements, such as an OLTP workload, should prefer using # {Transaction#execute_update}. # # That said, Partitioned DML is not a drop-in replacement for standard # DML used in {Transaction#execute_update}. # # * The DML statement must be fully-partitionable. Specifically, the # statement must be expressible as the union of many statements which # each access only a single row of the table. # * The statement is not applied atomically to all rows of the table. # Rather, the statement is applied atomically to partitions of the # table, in independent internal transactions. Secondary index rows # are updated atomically with the base table rows. # * Partitioned DML does not guarantee exactly-once execution semantics # against a partition. The statement will be applied at least once to # each partition. It is strongly recommended that the DML statement # should be idempotent to avoid unexpected results. For instance, it # is potentially dangerous to run a statement such as `UPDATE table # SET column = column + 1` as it could be run multiple times against # some rows. # * The partitions are committed automatically - there is no support for # Commit or Rollback. If the call returns an error, or if the client # issuing the DML statement dies, it is possible that some rows had # the statement executed on them successfully. It is also possible # that statement was never executed against other rows. # * If any error is encountered during the execution of the partitioned # DML operation (for instance, a UNIQUE INDEX violation, division by # zero, or a value that cannot be stored due to schema constraints), # then the operation is stopped at that point and an error is # returned. It is possible that at this point, some partitions have # been committed (or even committed multiple times), and other # partitions have not been run at all. # # Given the above, Partitioned DML is good fit for large, database-wide, # operations that are idempotent, such as deleting old rows from a very # large table. # # @param [String] sql The Partitioned DML statement string. See [Query # syntax](https://cloud.google.com/spanner/docs/query-syntax). # # The Partitioned DML statement string can contain parameter # placeholders. A parameter placeholder consists of "@" followed by # the parameter name. Parameter names consist of any combination of # letters, numbers, and underscores. # @param [Hash] params Parameters for the Partitioned DML statement # string. The parameter placeholders, minus the "@", are the the hash # keys, and the literal values are the hash values. If the query # string contains something like "WHERE id > @msg_id", then the params # must contain something like `:msg_id => 1`. # # Ruby types are mapped to Spanner types as follows: # # | Spanner | Ruby | Notes | # |-------------|----------------|---| # | `BOOL` | `true`/`false` | | # | `INT64` | `Integer` | | # | `FLOAT64` | `Float` | | # | `STRING` | `String` | | # | `DATE` | `Date` | | # | `TIMESTAMP` | `Time`, `DateTime` | | # | `BYTES` | `File`, `IO`, `StringIO`, or similar | | # | `ARRAY` | `Array` | Nested arrays are not supported. | # | `STRUCT` | `Hash`, {Data} | | # # See [Data # types](https://cloud.google.com/spanner/docs/data-definition-language#data_types). # # See [Data Types - Constructing a # STRUCT](https://cloud.google.com/spanner/docs/data-types#constructing-a-struct). # @param [Hash] types Types of the SQL parameters in `params`. It is not # always possible for Cloud Spanner to infer the right SQL type from a # value in `params`. In these cases, the `types` hash can be used to # specify the exact SQL type for some or all of the SQL query # parameters. # # The keys of the hash should be query string parameter placeholders, # minus the "@". The values of the hash should be Cloud Spanner type # codes from the following list: # # * `:BOOL` # * `:BYTES` # * `:DATE` # * `:FLOAT64` # * `:INT64` # * `:STRING` # * `:TIMESTAMP` # * `Array` - Lists are specified by providing the type code in an # array. For example, an array of integers are specified as # `[:INT64]`. # * {Fields} - Nested Structs are specified by providing a Fields # object. # @return [Integer] The lower bound number of rows that were modified. # # @example # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # db = spanner.client "my-instance", "my-database" # # row_count = db.execute_partition_update \ # "UPDATE users SET friends = NULL WHERE active = false" # # @example Query using query parameters: # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # db = spanner.client "my-instance", "my-database" # # row_count = db.execute_partition_update \ # "UPDATE users SET friends = NULL WHERE active = @active", # params: { active: false } # def execute_partition_update sql, params: nil, types: nil ensure_service! params, types = Convert.to_input_params_and_types params, types results = nil @pool.with_session do |session| results = session.execute_query \ sql, params: params, types: types, transaction: pdml_transaction(session) end # Stream all PartialResultSet to get ResultSetStats results.rows.to_a # Raise an error if there is not a row count returned if results.row_count.nil? raise Google::Cloud::InvalidArgumentError, "Partitioned DML statement is invalid." end results.row_count end alias execute_pdml execute_partition_update ## # Read rows from a database table, as a simple alternative to # {#execute_query}. # # @param [String] table The name of the table in the database to be # read. # @param [Array<String, Symbol>] columns The columns of table to be # returned for each row matching this request. # @param [Object, Array<Object>] keys A single, or list of keys or key # ranges to match returned data to. Values should have exactly as many # elements as there are columns in the primary key. # @param [String] index The name of an index to use instead of the # table's primary key when interpreting `id` and sorting result rows. # Optional. # @param [Integer] limit If greater than zero, no more than this number # of rows will be returned. The default is no limit. # @param [Hash] single_use Perform the read with a single-use snapshot # (read-only transaction). (See # [TransactionOptions](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#transactionoptions).) # The snapshot can be created by providing exactly one of the # following options in the hash: # # * **Strong** # * `:strong` (true, false) Read at a timestamp where all previously # committed transactions are visible. # * **Exact** # * `:timestamp`/`:read_timestamp` (Time, DateTime) Executes all # reads at the given timestamp. Unlike other modes, reads at a # specific timestamp are repeatable; the same read at the same # timestamp always returns the same data. If the timestamp is in # the future, the read will block until the specified timestamp, # modulo the read's deadline. # # Useful for large scale consistent reads such as mapreduces, or # for coordinating many reads against a consistent snapshot of the # data. # * `:staleness`/`:exact_staleness` (Numeric) Executes all reads at # a timestamp that is exactly the number of seconds provided old. # The timestamp is chosen soon after the read is started. # # Guarantees that all writes that have committed more than the # specified number of seconds ago are visible. Because Cloud # Spanner chooses the exact timestamp, this mode works even if the # client's local clock is substantially skewed from Cloud Spanner # commit timestamps. # # Useful for reading at nearby replicas without the distributed # timestamp negotiation overhead of single-use # `bounded_staleness`. # * **Bounded** # * `:bounded_timestamp`/`:min_read_timestamp` (Time, DateTime) # Executes all reads at a timestamp greater than the value # provided. # # This is useful for requesting fresher data than some previous # read, or data that is fresh enough to observe the effects of # some previously committed transaction whose timestamp is known. # * `:bounded_staleness`/`:max_staleness` (Numeric) Read data at a # timestamp greater than or equal to the number of seconds # provided. Guarantees that all writes that have committed more # than the specified number of seconds ago are visible. Because # Cloud Spanner chooses the exact timestamp, this mode works even # if the client's local clock is substantially skewed from Cloud # Spanner commit timestamps. # # Useful for reading the freshest data available at a nearby # replica, while bounding the possible staleness if the local # replica has fallen behind. # # @return [Google::Cloud::Spanner::Results] The results of the read. # # @example # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # results = db.read "users", [:id, :name] # # results.rows.each do |row| # puts "User #{row[:id]} is #{row[:name]}" # end # # @example Use the `keys` option to pass keys and/or key ranges to read. # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # results = db.read "users", [:id, :name], keys: 1..5 # # results.rows.each do |row| # puts "User #{row[:id]} is #{row[:name]}" # end # def read table, columns, keys: nil, index: nil, limit: nil, single_use: nil validate_single_use_args! single_use ensure_service! columns = Array(columns).map(&:to_s) keys = Convert.to_key_set keys single_use_tx = single_use_transaction single_use results = nil @pool.with_session do |session| results = session.read \ table, columns, keys: keys, index: index, limit: limit, transaction: single_use_tx end results end ## # Inserts or updates rows in a table. If any of the rows already exist, # then its column values are overwritten with the ones provided. Any # column values not explicitly written are preserved. # # Changes are made immediately upon calling this method using a # single-use transaction. To make multiple changes in the same # single-use transaction use {#commit}. To make changes in a transaction # that supports reads and automatic retry protection use {#transaction}. # # **Note:** This method does not feature replay protection present in # {Transaction#upsert} (See {#transaction}). This method makes a single # RPC, whereas {Transaction#upsert} requires two RPCs (one of which may # be performed in advance), and so this method may be appropriate for # latency sensitive and/or high throughput blind upserts. # # @param [String] table The name of the table in the database to be # modified. # @param [Array<Hash>] rows One or more hash objects with the hash keys # matching the table's columns, and the hash values matching the # table's values. # # Ruby types are mapped to Spanner types as follows: # # | Spanner | Ruby | Notes | # |-------------|----------------|---| # | `BOOL` | `true`/`false` | | # | `INT64` | `Integer` | | # | `FLOAT64` | `Float` | | # | `STRING` | `String` | | # | `DATE` | `Date` | | # | `TIMESTAMP` | `Time`, `DateTime` | | # | `BYTES` | `File`, `IO`, `StringIO`, or similar | | # | `ARRAY` | `Array` | Nested arrays are not supported. | # # See [Data # types](https://cloud.google.com/spanner/docs/data-definition-language#data_types). # # @return [Time] The timestamp at which the operation committed. # # @example # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # db.upsert "users", [{ id: 1, name: "Charlie", active: false }, # { id: 2, name: "Harvey", active: true }] # def upsert table, *rows @pool.with_session do |session| session.upsert table, rows end end alias save upsert ## # Inserts new rows in a table. If any of the rows already exist, the # write or request fails with {Google::Cloud::AlreadyExistsError}. # # Changes are made immediately upon calling this method using a # single-use transaction. To make multiple changes in the same # single-use transaction use {#commit}. To make changes in a transaction # that supports reads and automatic retry protection use {#transaction}. # # **Note:** This method does not feature replay protection present in # {Transaction#insert} (See {#transaction}). This method makes a single # RPC, whereas {Transaction#insert} requires two RPCs (one of which may # be performed in advance), and so this method may be appropriate for # latency sensitive and/or high throughput blind inserts. # # @param [String] table The name of the table in the database to be # modified. # @param [Array<Hash>] rows One or more hash objects with the hash keys # matching the table's columns, and the hash values matching the # table's values. # # Ruby types are mapped to Spanner types as follows: # # | Spanner | Ruby | Notes | # |-------------|----------------|---| # | `BOOL` | `true`/`false` | | # | `INT64` | `Integer` | | # | `FLOAT64` | `Float` | | # | `STRING` | `String` | | # | `DATE` | `Date` | | # | `TIMESTAMP` | `Time`, `DateTime` | | # | `BYTES` | `File`, `IO`, `StringIO`, or similar | | # | `ARRAY` | `Array` | Nested arrays are not supported. | # # See [Data # types](https://cloud.google.com/spanner/docs/data-definition-language#data_types). # # @return [Time] The timestamp at which the operation committed. # # @example # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # db.insert "users", [{ id: 1, name: "Charlie", active: false }, # { id: 2, name: "Harvey", active: true }] # def insert table, *rows @pool.with_session do |session| session.insert table, rows end end ## # Updates existing rows in a table. If any of the rows does not already # exist, the request fails with {Google::Cloud::NotFoundError}. # # Changes are made immediately upon calling this method using a # single-use transaction. To make multiple changes in the same # single-use transaction use {#commit}. To make changes in a transaction # that supports reads and automatic retry protection use {#transaction}. # # **Note:** This method does not feature replay protection present in # {Transaction#update} (See {#transaction}). This method makes a single # RPC, whereas {Transaction#update} requires two RPCs (one of which may # be performed in advance), and so this method may be appropriate for # latency sensitive and/or high throughput blind updates. # # @param [String] table The name of the table in the database to be # modified. # @param [Array<Hash>] rows One or more hash objects with the hash keys # matching the table's columns, and the hash values matching the # table's values. # # Ruby types are mapped to Spanner types as follows: # # | Spanner | Ruby | Notes | # |-------------|----------------|---| # | `BOOL` | `true`/`false` | | # | `INT64` | `Integer` | | # | `FLOAT64` | `Float` | | # | `STRING` | `String` | | # | `DATE` | `Date` | | # | `TIMESTAMP` | `Time`, `DateTime` | | # | `BYTES` | `File`, `IO`, `StringIO`, or similar | | # | `ARRAY` | `Array` | Nested arrays are not supported. | # # See [Data # types](https://cloud.google.com/spanner/docs/data-definition-language#data_types). # # @return [Time] The timestamp at which the operation committed. # # @example # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # db.update "users", [{ id: 1, name: "Charlie", active: false }, # { id: 2, name: "Harvey", active: true }] # def update table, *rows @pool.with_session do |session| session.update table, rows end end ## # Inserts or replaces rows in a table. If any of the rows already exist, # it is deleted, and the column values provided are inserted instead. # Unlike #upsert, this means any values not explicitly written become # `NULL`. # # Changes are made immediately upon calling this method using a # single-use transaction. To make multiple changes in the same # single-use transaction use {#commit}. To make changes in a transaction # that supports reads and automatic retry protection use {#transaction}. # # **Note:** This method does not feature replay protection present in # {Transaction#replace} (See {#transaction}). This method makes a single # RPC, whereas {Transaction#replace} requires two RPCs (one of which may # be performed in advance), and so this method may be appropriate for # latency sensitive and/or high throughput blind replaces. # # @param [String] table The name of the table in the database to be # modified. # @param [Array<Hash>] rows One or more hash objects with the hash keys # matching the table's columns, and the hash values matching the # table's values. # # Ruby types are mapped to Spanner types as follows: # # | Spanner | Ruby | Notes | # |-------------|----------------|---| # | `BOOL` | `true`/`false` | | # | `INT64` | `Integer` | | # | `FLOAT64` | `Float` | | # | `STRING` | `String` | | # | `DATE` | `Date` | | # | `TIMESTAMP` | `Time`, `DateTime` | | # | `BYTES` | `File`, `IO`, `StringIO`, or similar | | # | `ARRAY` | `Array` | Nested arrays are not supported. | # # See [Data # types](https://cloud.google.com/spanner/docs/data-definition-language#data_types). # # @return [Time] The timestamp at which the operation committed. # # @example # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # db.replace "users", [{ id: 1, name: "Charlie", active: false }, # { id: 2, name: "Harvey", active: true }] # def replace table, *rows @pool.with_session do |session| session.replace table, rows end end ## # Deletes rows from a table. Succeeds whether or not the specified rows # were present. # # Changes are made immediately upon calling this method using a # single-use transaction. To make multiple changes in the same # single-use transaction use {#commit}. To make changes in a transaction # that supports reads and automatic retry protection use {#transaction}. # # **Note:** This method does not feature replay protection present in # {Transaction#delete} (See {#transaction}). This method makes a single # RPC, whereas {Transaction#delete} requires two RPCs (one of which may # be performed in advance), and so this method may be appropriate for # latency sensitive and/or high throughput blind deletions. # # @param [String] table The name of the table in the database to be # modified. # @param [Object, Array<Object>] keys A single, or list of keys or key # ranges to match returned data to. Values should have exactly as many # elements as there are columns in the primary key. # # @return [Time] The timestamp at which the operation committed. # # @example # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # db.delete "users", [1, 2, 3] # def delete table, keys = [] @pool.with_session do |session| session.delete table, keys end end ## # Creates and commits a transaction for writes that execute atomically # at a single logical point in time across columns, rows, and tables in # a database. # # All changes are accumulated in memory until the block completes. # Unlike {#transaction}, which can also perform reads, this operation # accepts only mutations and makes a single API request. # # **Note:** This method does not feature replay protection present in # {#transaction}. This method makes a single RPC, whereas {#transaction} # requires two RPCs (one of which may be performed in advance), and so # this method may be appropriate for latency sensitive and/or high # throughput blind changes. # # @yield [commit] The block for mutating the data. # @yieldparam [Google::Cloud::Spanner::Commit] commit The Commit object. # # @return [Time] The timestamp at which the operation committed. # # @example # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # db.commit do |c| # c.update "users", [{ id: 1, name: "Charlie", active: false }] # c.insert "users", [{ id: 2, name: "Harvey", active: true }] # end # def commit &block raise ArgumentError, "Must provide a block" unless block_given? @pool.with_session do |session| session.commit(&block) end end # rubocop:disable Metrics/AbcSize # rubocop:disable Metrics/MethodLength ## # Creates a transaction for reads and writes that execute atomically at # a single logical point in time across columns, rows, and tables in a # database. # # The transaction will always commit unless an error is raised. If the # error raised is {Rollback} the transaction method will return without # passing on the error. All other errors will be passed on. # # All changes are accumulated in memory until the block completes. # Transactions will be automatically retried when possible, until # `deadline` is reached. This operation makes separate API requests to # begin and commit the transaction. # # @param [Numeric] deadline The total amount of time in seconds the # transaction has to succeed. The default is `120`. # # @yield [transaction] The block for reading and writing data. # @yieldparam [Google::Cloud::Spanner::Transaction] transaction The # Transaction object. # # @return [Time] The timestamp at which the transaction committed. # # @example # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # db = spanner.client "my-instance", "my-database" # # db.transaction do |tx| # results = tx.execute_query "SELECT * FROM users" # # results.rows.each do |row| # puts "User #{row[:id]} is #{row[:name]}" # end # # tx.update "users", [{ id: 1, name: "Charlie", active: false }] # tx.insert "users", [{ id: 2, name: "Harvey", active: true }] # end # # @example Manually rollback the transaction using {Rollback}: # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # db = spanner.client "my-instance", "my-database" # # db.transaction do |tx| # tx.update "users", [{ id: 1, name: "Charlie", active: false }] # tx.insert "users", [{ id: 2, name: "Harvey", active: true }] # # if something_wrong? # # Rollback the transaction without passing on the error # # outside of the transaction method. # raise Google::Cloud::Spanner::Rollback # end # end # def transaction deadline: 120 ensure_service! unless Thread.current[:transaction_id].nil? raise "Nested transactions are not allowed" end deadline = validate_deadline deadline backoff = 1.0 start_time = current_time @pool.with_transaction do |tx| begin Thread.current[:transaction_id] = tx.transaction_id yield tx commit_resp = @project.service.commit \ tx.session.path, tx.mutations, transaction_id: tx.transaction_id return Convert.timestamp_to_time commit_resp.commit_timestamp rescue GRPC::Aborted, Google::Cloud::AbortedError => err # Re-raise if deadline has passed if current_time - start_time > deadline if err.is_a? GRPC::BadStatus err = Google::Cloud::Error.from_error err end raise err end # Sleep the amount from RetryDelay, or incremental backoff sleep(delay_from_aborted(err) || backoff *= 1.3) # Create new transaction on the session and retry the block tx = tx.session.create_transaction retry rescue StandardError => err # Rollback transaction when handling unexpected error tx.session.rollback tx.transaction_id # Return nil if raised with rollback. return nil if err.is_a? Rollback # Re-raise error. raise err ensure Thread.current[:transaction_id] = nil end end end # rubocop:enable Metrics/AbcSize # rubocop:enable Metrics/MethodLength ## # Creates a snapshot read-only transaction for reads that execute # atomically at a single logical point in time across columns, rows, and # tables in a database. For transactions that only read, snapshot # read-only transactions provide simpler semantics and are almost always # faster than read-write transactions. # # @param [true, false] strong Read at a timestamp where all previously # committed transactions are visible. # @param [Time, DateTime] timestamp Executes all reads at the given # timestamp. Unlike other modes, reads at a specific timestamp are # repeatable; the same read at the same timestamp always returns the # same data. If the timestamp is in the future, the read will block # until the specified timestamp, modulo the read's deadline. # # Useful for large scale consistent reads such as mapreduces, or for # coordinating many reads against a consistent snapshot of the data. # (See # [TransactionOptions](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#transactionoptions).) # @param [Time, DateTime] read_timestamp Same as `timestamp`. # @param [Numeric] staleness Executes all reads at a timestamp that is # `staleness` seconds old. For example, the number 10.1 is translated # to 10 seconds and 100 milliseconds. # # Guarantees that all writes that have committed more than the # specified number of seconds ago are visible. Because Cloud Spanner # chooses the exact timestamp, this mode works even if the client's # local clock is substantially skewed from Cloud Spanner commit # timestamps. # # Useful for reading at nearby replicas without the distributed # timestamp negotiation overhead of single-use `staleness`. (See # [TransactionOptions](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#transactionoptions).) # @param [Numeric] exact_staleness Same as `staleness`. # # @yield [snapshot] The block for reading and writing data. # @yieldparam [Google::Cloud::Spanner::Snapshot] snapshot The Snapshot # object. # # @example # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # db = spanner.client "my-instance", "my-database" # # db.snapshot do |snp| # results = snp.execute_query "SELECT * FROM users" # # results.rows.each do |row| # puts "User #{row[:id]} is #{row[:name]}" # end # end # def snapshot strong: nil, timestamp: nil, read_timestamp: nil, staleness: nil, exact_staleness: nil validate_snapshot_args! strong: strong, timestamp: timestamp, read_timestamp: read_timestamp, staleness: staleness, exact_staleness: exact_staleness ensure_service! unless Thread.current[:transaction_id].nil? raise "Nested snapshots are not allowed" end @pool.with_session do |session| begin snp_grpc = @project.service.create_snapshot \ session.path, strong: strong, timestamp: (timestamp || read_timestamp), staleness: (staleness || exact_staleness) Thread.current[:transaction_id] = snp_grpc.id snp = Snapshot.from_grpc snp_grpc, session yield snp if block_given? ensure Thread.current[:transaction_id] = nil end end nil end ## # Creates a configuration object ({Fields}) that may be provided to # queries or used to create STRUCT objects. (The STRUCT will be # represented by the {Data} class.) See {Client#execute} and/or # {Fields#struct}. # # For more information, see [Data Types - Constructing a # STRUCT](https://cloud.google.com/spanner/docs/data-types#constructing-a-struct). # # @param [Array, Hash] types Accepts an array or hash types. # # Arrays can contain just the type value, or a sub-array of the # field's name and type value. Hash keys must contain the field name # as a `Symbol` or `String`, or the field position as an `Integer`. # Hash values must contain the type value. If a Hash is used the # fields will be created using the same order as the Hash keys. # # Supported type values incude: # # * `:BOOL` # * `:BYTES` # * `:DATE` # * `:FLOAT64` # * `:INT64` # * `:STRING` # * `:TIMESTAMP` # * `Array` - Lists are specified by providing the type code in an # array. For example, an array of integers are specified as # `[:INT64]`. # * {Fields} - Nested Structs are specified by providing a Fields # object. # # @return [Fields] The fields of the given types. # # @example Create a STRUCT value with named fields using Fields object: # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # named_type = db.fields( # { id: :INT64, name: :STRING, active: :BOOL } # ) # named_data = named_type.struct( # { id: 42, name: nil, active: false } # ) # # @example Create a STRUCT value with anonymous field names: # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # anon_type = db.fields [:INT64, :STRING, :BOOL] # anon_data = anon_type.struct [42, nil, false] # # @example Create a STRUCT value with duplicate field names: # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # dup_type = db.fields [[:x, :INT64], [:x, :STRING], [:x, :BOOL]] # dup_data = dup_type.struct [42, nil, false] # def fields types Fields.new types end ## # @private # Executes a query to retrieve the field names and types for a table. # # @param [String] table The name of the table in the database to # retrieve fields for. # # @return [Fields] The fields of the given table. # # @example # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # users_types = db.fields_for "users" # db.insert "users", [{ id: 1, name: "Charlie", active: false }, # { id: 2, name: "Harvey", active: true }], # types: users_types # def fields_for table execute_query("SELECT * FROM #{table} WHERE 1 = 0").fields end ## # Creates a Spanner Range. This can be used in place of a Ruby Range # when needing to exclude the beginning value. # # @param [Object] beginning The object that defines the beginning of the # range. # @param [Object] ending The object that defines the end of the range. # @param [Boolean] exclude_begin Determines if the range excludes its # beginning value. Default is `false`. # @param [Boolean] exclude_end Determines if the range excludes its # ending value. Default is `false`. # # @return [Google::Cloud::Spanner::Range] The new Range instance. # # @example # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # key_range = db.range 1, 100 # results = db.read "users", [:id, :name], keys: key_range # # results.rows.each do |row| # puts "User #{row[:id]} is #{row[:name]}" # end # def range beginning, ending, exclude_begin: false, exclude_end: false Range.new beginning, ending, exclude_begin: exclude_begin, exclude_end: exclude_end end ## # Creates a column value object representing setting a field's value to # the timestamp of the commit. (See {ColumnValue.commit_timestamp}) # # This placeholder value can only be used for timestamp columns that # have set the option "(allow_commit_timestamp=true)" in the schema. # # @return [ColumnValue] The commit timestamp column value object. # # @example # require "google/cloud/spanner" # # spanner = Google::Cloud::Spanner.new # # db = spanner.client "my-instance", "my-database" # # # create column value object # commit_timestamp = db.commit_timestamp # # db.commit do |c| # c.insert "users", [ # { id: 5, name: "Murphy", updated_at: commit_timestamp } # ] # end # def commit_timestamp ColumnValue.commit_timestamp end ## # Closes the client connection and releases resources. # def close @pool.close end ## # @private # Creates a new session object every time. def create_new_session ensure_service! grpc = @project.service.create_session \ Admin::Database::V1::DatabaseAdminClient.database_path( project_id, instance_id, database_id ), labels: @session_labels Session.from_grpc grpc, @project.service end ## # @private # Creates a batch of new session objects of size `total`. # Makes multiple RPCs if necessary. Returns empty array if total is 0. def batch_create_new_sessions total sessions = [] remaining = total while remaining > 0 sessions += batch_create_sessions remaining remaining = total - sessions.count end sessions end ## # @private # The response may have fewer sessions than requested in the RPC. # def batch_create_sessions session_count ensure_service! resp = @project.service.batch_create_sessions \ Admin::Database::V1::DatabaseAdminClient.database_path( project_id, instance_id, database_id ), session_count, labels: @session_labels resp.session.map { |grpc| Session.from_grpc grpc, @project.service } end # @private def to_s "(project_id: #{project_id}, instance_id: #{instance_id}, " \ "database_id: #{database_id})" end # @private def inspect "#<#{self.class.name} #{self}>" end protected ## # @private Raise an error unless an active connection to the service is # available. def ensure_service! raise "Must have active connection to service" unless @project.service end ## # Check for valid snapshot arguments def validate_single_use_args! opts return true if opts.nil? || opts.empty? valid_keys = %i[strong timestamp read_timestamp staleness exact_staleness bounded_timestamp min_read_timestamp bounded_staleness max_staleness] if opts.keys.count == 1 && valid_keys.include?(opts.keys.first) return true end raise ArgumentError, "Must provide only one of the following single_use values: " \ "#{valid_keys}" end ## # Create a single-use TransactionSelector def single_use_transaction opts return nil if opts.nil? || opts.empty? exact_timestamp = Convert.time_to_timestamp \ opts[:timestamp] || opts[:read_timestamp] exact_staleness = Convert.number_to_duration \ opts[:staleness] || opts[:exact_staleness] bounded_timestamp = Convert.time_to_timestamp \ opts[:bounded_timestamp] || opts[:min_read_timestamp] bounded_staleness = Convert.number_to_duration \ opts[:bounded_staleness] || opts[:max_staleness] Google::Spanner::V1::TransactionSelector.new(single_use: Google::Spanner::V1::TransactionOptions.new(read_only: Google::Spanner::V1::TransactionOptions::ReadOnly.new({ strong: opts[:strong], read_timestamp: exact_timestamp, exact_staleness: exact_staleness, min_read_timestamp: bounded_timestamp, max_staleness: bounded_staleness, return_read_timestamp: true }.delete_if { |_, v| v.nil? }))) end def pdml_transaction session pdml_tx_grpc = @project.service.create_pdml session.path Google::Spanner::V1::TransactionSelector.new id: pdml_tx_grpc.id end ## # Check for valid snapshot arguments def validate_snapshot_args! strong: nil, timestamp: nil, read_timestamp: nil, staleness: nil, exact_staleness: nil valid_args_count = [strong, timestamp, read_timestamp, staleness, exact_staleness].compact.count return true if valid_args_count <= 1 raise ArgumentError, "Can only provide one of the following arguments: " \ "(strong, timestamp, read_timestamp, staleness, " \ "exact_staleness)" end def validate_deadline deadline return 120 unless deadline.is_a? Numeric return 120 if deadline < 0 deadline end ## # Defer to this method so we have something to mock for tests def current_time Time.now end ## # Retrieves the delay value from Google::Cloud::AbortedError or # GRPC::Aborted def delay_from_aborted err return nil if err.nil? if err.respond_to?(:metadata) && err.metadata["retryDelay"] # a correct metadata will look like this: # "{\"retryDelay\":{\"seconds\":60}}" seconds = err.metadata["retryDelay"]["seconds"].to_i nanos = err.metadata["retryDelay"]["nanos"].to_i return seconds if nanos.zero? return seconds + (nanos / 1000000000.0) end # No metadata? Try the inner error delay_from_aborted err.cause rescue StandardError # Any error indicates the backoff should be handled elsewhere nil end end end end end
42.714784
124
0.566242
1a5c0cc655008494a43b35ef2043f28822a5a667
959
class Pgdbf < Formula desc "Converter of XBase/FoxPro tables to PostgreSQL" homepage "https://github.com/kstrauser/pgdbf" url "https://downloads.sourceforge.net/project/pgdbf/pgdbf/0.6.2/pgdbf-0.6.2.tar.xz" sha256 "e46f75e9ac5f500bd12c4542b215ea09f4ebee638d41dcfd642be8e9769aa324" bottle do cellar :any_skip_relocation sha256 "caf544eee09339bb34ab68a35880bc863bb13aa7943de98ef25680cb0182f901" => :high_sierra sha256 "7d0eabf3051e9cf450d985987f89cf0d70476b37202b3b5bdc84ec48e8cb670d" => :sierra sha256 "72ad6b801d25db2008d0ab4badd2bb280f55eb6f6956925ee5620d62d8f06bbb" => :el_capitan sha256 "4042a284cac8abe88e7d1c9e6c003e00a9b8247905739829cd768a824df7993b" => :yosemite sha256 "c53298c57bb2d31d82ddce41ed65057d7781de2118857f5f795aaaefe3c00110" => :mavericks end def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end end
43.590909
93
0.777894
f808796241550b009331e0f3c69a3d37255dfe8b
4,471
# frozen_string_literal: true require 'test_helper' class ShopifyApp::ScripttagsManagerTest < ActiveSupport::TestCase include ActiveJob::TestHelper setup do @scripttags = [ { event: 'onload', src: 'https://example-app.com/fancy.js' }, { event: 'onload', src: 'https://example-app.com/foobar.js' }, { event: 'onload', src: ->(domain) { "https://example-app.com/#{domain}-123.js" } }, ] @manager = ShopifyApp::ScripttagsManager.new(@scripttags, 'example-app.com') end test "#create_scripttags makes calls to create scripttags" do ShopifyAPI::ScriptTag.stubs(all: []) expect_scripttag_creation('onload', 'https://example-app.com/fancy.js') expect_scripttag_creation('onload', 'https://example-app.com/foobar.js') expect_scripttag_creation('onload', "https://example-app.com/example-app.com-123.js") @manager.create_scripttags end test "#create_scripttags when creating a dynamic src, does not overwrite the src with its result" do ShopifyAPI::ScriptTag.stubs(all: []) stub_scripttag = stub(persisted?: true) ShopifyAPI::ScriptTag.expects(:create).returns(stub_scripttag).times(3) @manager.create_scripttags assert_respond_to @manager.required_scripttags.last[:src], :call end test "#create_scripttags when creating a scripttag fails, raises an error" do ShopifyAPI::ScriptTag.stubs(all: []) scripttag = stub(persisted?: false, errors: stub(full_messages: ["Source needs to be https"])) ShopifyAPI::ScriptTag.stubs(create: scripttag) e = assert_raise ShopifyApp::ScripttagsManager::CreationFailed do @manager.create_scripttags end assert_equal 'Source needs to be https', e.message end test "#create_scripttags when a script src raises an exception, it's propagated" do ShopifyAPI::ScriptTag.stubs(:all).returns(all_mock_scripttags[0..1]) @manager.required_scripttags.last[:src] = -> (_domain) { raise 'oops!' } e = assert_raise do @manager.create_scripttags end assert_equal 'oops!', e.message end test "#recreate_scripttags! destroys all scripttags and recreates" do @manager.expects(:destroy_scripttags) @manager.expects(:create_scripttags) @manager.recreate_scripttags! end test "#destroy_scripttags makes calls to destroy scripttags" do ShopifyAPI::ScriptTag.stubs(:all).returns(Array.wrap(all_mock_scripttags.first)) ShopifyAPI::ScriptTag.expects(:delete).with(all_mock_scripttags.first.id) @manager.destroy_scripttags end test "#destroy_scripttags makes calls to destroy scripttags with a dynamic src" do ShopifyAPI::ScriptTag.stubs(:all).returns(Array.wrap(all_mock_scripttags.last)) ShopifyAPI::ScriptTag.expects(:delete).with(all_mock_scripttags.last.id) @manager.destroy_scripttags end test "#destroy_scripttags when deleting a dynamic src, does not overwrite the src with its result" do ShopifyAPI::ScriptTag.stubs(all: Array.wrap(all_mock_scripttags.last)) ShopifyAPI::ScriptTag.expects(:delete).with(all_mock_scripttags.last.id) @manager.destroy_scripttags assert_respond_to @manager.required_scripttags.last[:src], :call end test "#destroy_scripttags does not destroy scripttags that do not have a matching address" do ShopifyAPI::ScriptTag.stubs(:all).returns([stub(src: 'http://something-or-the-other.com/badscript.js', id: 7214109)]) ShopifyAPI::ScriptTag.expects(:delete).never @manager.destroy_scripttags end test ".queue enqueues a ScripttagsManagerJob" do args = { shop_domain: 'example-app.com', shop_token: 'token', scripttags: [event: 'onload', src: 'https://example-app.com/example-app.com-123.js'], } assert_enqueued_with(job: ShopifyApp::ScripttagsManagerJob, args: [args]) do ShopifyApp::ScripttagsManager.queue(args[:shop_domain], args[:shop_token], @scripttags[-1, 1]) end end private def expect_scripttag_creation(event, src) stub_scripttag = stub(persisted?: true) ShopifyAPI::ScriptTag.expects(:create).with(event: event, src: src, format: 'json').returns(stub_scripttag) end def all_mock_scripttags [ stub(id: 1, src: "https://example-app.com/fancy.js", event: 'onload'), stub(id: 2, src: "https://example-app.com/foobar.js", event: 'onload'), stub(id: 3, src: "https://example-app.com/example-app.com-123.js", event: 'onload'), ] end end
36.349593
111
0.711698
f88dd8c66a50e9f6bee0fb2d4e6eedd7aa2b0c83
332
ENV['SINATRA_ENV'] ||="Development" require 'bigdecimal' require 'bundler/setup' Bundler.require(:default, ENV['SINATRA_ENV']) #ActiveRecord::Base.establish_connection(ENV['SINATRA_ENV'].to_sym) ActiveRecord::Base.establish_connection( :adapter => "sqlite3", :database => "db/#{ENV['SINATRA_ENV']}.sqlite" ) require_all 'app'
25.538462
67
0.740964
e2d9ba8cb76300a63df2d08d1d5b4b4b836ec8cd
887
class DockerCompletion < Formula desc "Bash, Zsh and Fish completion for Docker" homepage "https://www.docker.com/" url "https://github.com/docker/cli.git", tag: "v20.10.8", revision: "3967b7d28e15a020e4ee344283128ead633b3e0c" license "Apache-2.0" livecheck do formula "docker" end bottle do sha256 cellar: :any_skip_relocation, all: "90ed4550064c756f9cc165649143b5daf88a32af7c254ee20410cb1b26e7c064" end conflicts_with "docker", because: "docker already includes these completion scripts" def install bash_completion.install "contrib/completion/bash/docker" fish_completion.install "contrib/completion/fish/docker.fish" zsh_completion.install "contrib/completion/zsh/_docker" end test do assert_match "-F _docker", shell_output("bash -c 'source #{bash_completion}/docker && complete -p docker'") end end
28.612903
112
0.733935
f8d9b27e3dd9d3a88510765a347d7376827fb4c6
918
class EmancipationCategory < ApplicationRecord has_many :casa_case_emancipation_categories, dependent: :destroy has_many :casa_cases, through: :casa_case_emancipation_categories has_many :emancipation_options validates :name, presence: true validates :mutually_exclusive, inclusion: {in: [true, false]} def add_option(option_name) emancipation_options.where(name: option_name).first_or_create end def delete_option(option_name) emancipation_options.find_by(name: option_name)&.destroy end end # == Schema Information # # Table name: emancipation_categories # # id :bigint not null, primary key # mutually_exclusive :boolean not null # name :string not null # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_emancipation_categories_on_name (name) UNIQUE #
29.612903
67
0.705882
7a7dc6f2eca7ae54e9cbb8400693cf5e56081724
734
# frozen_string_literal: true describe ::AwsPublicIps::Checks::Cloudfront do it 'should return cloudfront ips' do stub_request(:get, 'https://cloudfront.amazonaws.com/2018-06-18/distribution') .to_return(body: ::IO.read('spec/fixtures/cloudfront.xml')) stub_dns( 'd22ycgwdruc4lt.cloudfront.net' => %w[54.0.0.1 54.0.0.2], 'd1k00qwg2uxphp.cloudfront.net' => %w[54.0.0.3] ) expect(subject.run(true)).to eq([ { id: 'E1DABYDY46RHFK', hostname: 'd22ycgwdruc4lt.cloudfront.net', ip_addresses: %w[54.0.0.1 54.0.0.2] }, { id: 'E3SFCHHIPK43DR', hostname: 'd1k00qwg2uxphp.cloudfront.net', ip_addresses: %w[54.0.0.3] } ]) end end
28.230769
82
0.613079
3883d3163598b21ea7ce2103a0ab8d3f77885b19
984
cask "unity-ios-support-for-editor" do version "2021.3.0f1,6eacc8284459" sha256 "4566c87017abe6e5c03acb86d2ce9e32cde70794e34f3d882710d77de474d65e" url "https://download.unity3d.com/download_unity/#{version.csv.second}/MacEditorTargetInstaller/UnitySetup-iOS-Support-for-Editor-#{version.csv.first}.pkg", verified: "download.unity3d.com/download_unity/" name "Unity iOS Build Support" desc "iOS target support for Unity" homepage "https://unity.com/products" livecheck do url "https://public-cdn.cloud.unity3d.com/hub/prod/releases-darwin.json" strategy :page_match do |page| page.scan(%r{ /download_unity/(\h+)/MacEditorTargetInstaller /UnitySetup-iOS-Support-for-Editor-(\d+(?:\.\d+)+[a-z]*\d*)\.pkg }ix).map do |match| "#{match[1]},#{match[0]}" end end end depends_on cask: "unity" pkg "UnitySetup-iOS-Support-for-Editor-#{version.csv.first}.pkg" uninstall pkgutil: "com.unity3d.iOSSupport" end
33.931034
158
0.704268
bfaa4a822fdee90e6412401a8796722434f6b3db
450
class AccountActivationsController < ApplicationController skip_before_action :authorize_request, only: :edit def edit user = User.find_by(email: params[:email]) if user && !user.activated? && user.authenticated?(:activation, params[:id]) user.activate #log_in user #render inline: "<p><%= Account Activated! %></p>" render plain: "Account Activated!" # redirect_to user end end end
32.142857
82
0.648889
bb1c3b46f52759de14a61d477d5e7d9823076496
922
# frozen_string_literal: true class AddLdapAttrsToUser < ActiveRecord::Migration[5.1] def self.up add_column :users, :display_name, :string add_column :users, :address, :string add_column :users, :admin_area, :string add_column :users, :department, :string add_column :users, :title, :string add_column :users, :office, :string add_column :users, :chat_id, :string add_column :users, :website, :string add_column :users, :affiliation, :string add_column :users, :telephone, :string end def self.down remove_column :users, :display_name remove_column :users, :address remove_column :users, :admin_area remove_column :users, :department remove_column :users, :title remove_column :users, :office remove_column :users, :chat_id remove_column :users, :website remove_column :users, :affiliation remove_column :users, :telephone end end
30.733333
55
0.713666
b9c03a338ff351c6023179006425b326507a701a
223
class Idris < Cask url 'http://www.idris-lang.org/pkgs/idris-current.pkg' homepage 'http://www.idris-lang.org' version 'latest' no_checksum install 'idris-current.pkg' uninstall :pkgutil => 'org.idris-lang' end
24.777778
56
0.713004
2697fceab058cb7f5bdb762e90b0c444beeb99b2
561
require 'json' package = JSON.parse(File.read(File.join(__dir__, 'package.json'))) Pod::Spec.new do |s| s.name = 'AparajitaCapacitorSecureStorage' s.version = package['version'] s.summary = package['description'] s.license = package['license'] s.homepage = package['repository']['url'] s.author = package['author'] s.source = { :git => package['repository']['url'], :tag => s.version.to_s } s.source_files = 'ios/Plugin/**/*.{swift,h,m,c,cc,mm,cpp}' s.ios.deployment_target = '11.0' s.dependency 'Capacitor' s.swift_version = '5.1' end
31.166667
77
0.666667
338961076e60cff2aea8e6537d39c4e63463ead4
1,115
# Page Helper # mixin for methods which can be used on more than one Page module PageHelper # Common to Checkout pages def progress_bar_element(stage) browser.div(:class => 'progress_wrapper', :class => 'top').li(:class => stage, :class => 'act') end # Common to Item pages def add_checkout msg #click button self.buy #deal with a pop-up - click checkout Watir::Wait.until {browser.text.include?(msg)} browser.link(:href => 'http://store.demoqa.com/products-page/checkout/').focus browser.send_keys :enter #return shopping cart page next_page = Checkout_Cart.new(browser) next_page.loaded? next_page end def add_continue msg #click button self.buy #deal with a pop-up - click continue shopping Watir::Wait.until {browser.text.include?(msg)} browser.link(:class => 'continue_shopping').focus browser.send_keys :enter #return this item page self end end
26.547619
102
0.583857
916b5a0271d13a4ac62f66878a5e85b7959135dc
502
cask 'packages' do version '1.2.2' sha256 'bbee49a09e63339600ff5a97dedcecd8a00e4271477f02623e88ce6ebf295288' url 'http://s.sudre.free.fr/Software/files/Packages.dmg' appcast 'http://s.sudre.free.fr/Software/documentation/RemoteVersion.plist', checkpoint: '36303735f67c30f292c67cdeed1c4d9ac050547eca212f9ca3cc184f90777181' name 'Packages' homepage 'http://s.sudre.free.fr/Software/Packages/about.html' pkg 'packages/Packages.pkg' uninstall script: 'Extras/uninstall.sh' end
33.466667
88
0.778884
1d4f890d384b879caf05df661f141ab9d0052a81
489
# frozen_string_literal: true require 'spec_helper' RSpec.shared_examples_for 'Agent' do subject { described_class.new(api_key: ENV['API-KEY']) } let(:config_params) { { appid: subject.api_key } } it '#execute', :vcr do allow(subject).to receive(:execute) .with(city: 'Santiago', action: 'weather', config: config_params) .and_return(Hash) end it '#encode_query' do allow(subject).to receive(:encode_query).with(config_params).and_return(String) end end
27.166667
83
0.705521
d526e9746484a14071640037e8bee1d3ba9f364e
9,216
#encoding: utf-8 module PFM class Pokemon # Tell if PSDK test evolve on form 0 or the current form EVOLVE_ON_FORM0 = true # Return the base experience of the Pokemon # @return [Integer] def base_exp return $game_data_pokemon[@sub_id ? @sub_id : @id][@form].base_exp end # Return the exp curve type ID # @return [Integer] def exp_type return $game_data_pokemon[@sub_id ? @sub_id : @id][@form].exp_type end # Return the exp curve # @return [Array<Integer>] def exp_list return GameData::EXP_TABLE[exp_type] end # Return the required exp to increase the Pokemon's level # @return [Integer] def exp_lvl data = GameData::EXP_TABLE[exp_type] v = data[@level + 1] return data[@level] unless v return v end # Return the text of the amount of exp the pokemon needs to go to the next level # @return [String] def exp_remaining_text expa = self.exp_lvl - self.exp expa = 0 if expa < 0 return expa.to_s end # Return the text of the current pokemon experience # @return [String] def exp_text "#@exp" end # Change the Pokemon total exp # @param v [Integer] the new exp value def exp=(v) @exp = v.to_i _exp_lvl = self.exp_lvl if(_exp_lvl >= @exp) _exp_last = GameData::EXP_TABLE[exp_type][@level] delta = _exp_lvl - _exp_last current = exp - _exp_last @exp_rate = (delta == 0 ? 1 : current / delta.to_f) #> Vérifier pour la correction else @exp_rate = (@level < GameData::MAX_LEVEL ? 1 : 0) end end # Increase the level of the Pokemon # @return [Boolean] if the level has successfully been increased def level_up return false if @level >= GameData::MAX_LEVEL _exp_last = GameData::EXP_TABLE[exp_type][@level] delta = self.exp_lvl - _exp_last self.exp += (delta - (exp - _exp_last)) return true end # Generate the level up stat list for the level up window # @return [Array<Array<Integer>>] list0, list1 : old, new basis value def level_up_stat_refresh st=$game_temp.in_battle $game_temp.in_battle=false list0=[self.max_hp, self.atk_basis, self.dfe_basis, self.ats_basis, self.dfs_basis, self.spd_basis] @level += 1 if @level < GameData::MAX_LEVEL self.exp = exp_list[@level] if @exp<exp_list[@level].to_i hp_diff = list0[0] - @hp list1=[self.max_hp, self.atk_basis, self.dfe_basis, self.ats_basis, self.dfs_basis, self.spd_basis] self.hp = (self.max_hp-hp_diff) if @hp > 0 $game_temp.in_battle=st return [list0, list1] end # Show the level up window # @param list0 [Array<Integer>] old basis stat list # @param list1 [Array<Integer>] new basis stat list # @param z_level [Integer] z superiority of the Window def level_up_window_call(list0, list1, z_level) window = Window.new window.lock window.z = z_level window.set_size(140, 180) window.set_position(Graphics.width - window.width - 2, Graphics.height - window.height - 2) window.window_builder = GameData::Windows::MessageWindow window.windowskin = RPG::Cache.windowskin('Message') sprite = Sprite.new(window).set_bitmap(sbmp = icon) texts = UI::SpriteStack.new(window) start_y = sbmp.height w = sbmp.width width = 140 - window.window_builder[4] * 2 - 2 texts.add_text(w, 0, width - w, start_y, given_name, 1) format_str = '%d (+%d)' 6.times do |i| start_y += 16 texts.add_text(0, start_y, width, 16, text_get(22, 121 + i)) texts.add_text(0, start_y, width, 16, format(format_str, list1[i], list1[i] - list0[i]), 2, color: 1) end window.unlock Graphics.sort_z Graphics.update until Input.trigger?(:A) $game_system.se_play($data_system.decision_se) window.dispose sprite.dispose unless sprite.disposed? end # Change the level of the Pokemon # @param lvl [Integer] the new level of the Pokemon def level=(lvl) if(lvl>0 and lvl<=GameData::MAX_LEVEL) @exp=self.exp_list[lvl] @exp_rate = 0 @level=lvl end end # Check if the Pokemon can evolve and return the evolve id if possible # @param reason [Symbol] evolve check reason (:level_up, :trade, :stone) # @param extend_data [Hash, nil] extend_data generated by an item # @return [Integer, false] if the Pokemon can evolve, the evolve id, otherwise false def evolve_check(reason = :level_up, extend_data = nil) return false if @item_holding == 229#>Pierre Stase data = EVOLVE_ON_FORM0 ? $game_data_pokemon[@id][0] : get_data if(reason == :level_up and data.evolution_level and data.evolution_level <= @level and data.evolution_id and data.evolution_id != 0) return data.evolution_id end return false unless data.special_evolution stone = (reason == :stone) data.special_evolution.each do |e| #>Prévention des pierres next if stone and !e[:stone] #>Echanger contre next if(e[:trade_with] and e[:trade_with] != extend_data) #>Niveau minimum next if(e[:min_level] and e[:min_level] > @level) #>Niveau maximum next if(e[:max_level] and e[:max_level] < @level) #>En portant un objet next if(e[:item_hold] and e[:item_hold] != @item_holding) #>Bonheur min next if(e[:min_loyalty] and e[:min_loyalty] > @loyalty) #>Bonheur max next if(e[:max_loyalty] and e[:max_loyalty] < @loyalty) #>Les attaques if(e[:skill_1]) next unless skill_learnt?(e[:skill_1]) if(e[:skill_2]) next unless skill_learnt?(e[:skill_2]) if(e[:skill_3]) next unless skill_learnt?(e[:skill_3]) if(e[:skill_4]) next unless skill_learnt?(e[:skill_4]) end end end end #>Météo spécifique next if(e[:weather] and $env.weather != e[:weather]) #>Être sur un tag next if(e[:env] and $game_player.system_tag != e[:env]) #>Un genre spécifique next if(e[:gender] and @gender != e[:gender]) #>Application d'une pierrre next if(e[:stone] and e[:stone] != extend_data) #>Moment de la journée next if(e[:day_night] and e[:day_night] != $game_variables[::Yuki::Var::TJN_Tone]) #>Appel de fonction next if(e[:func] and !self.send(*e[:func])) #>Sur des maps next if(e[:maps] and !e[:maps].include?($game_map.map_id)) if(reason == :trade) return e[:trade] if e[:trade] else return e[:id] if e[:id] end end return false end # Change the id of the Pokemon # @param v [Integer] the new id of the Pokemon def id=(v) @character = nil if(v && $game_data_pokemon[v]) @id = v @form = 0 unless $game_data_pokemon[v][@form] @form = form_generation(-1) if @form == 0 @form = 0 unless $game_data_pokemon[v][@form] update_ability end end # Update the Pokemon Ability def update_ability if @ability_index @ability_current = @ability = get_data.abilities[@ability_index.to_i] else @ability_current = @ability end end # Check evolve condition to evolve in Hitmonlee (kicklee) # @return [Boolean] if the condition is valid def elv_kicklee self.atk > self.dfe end # Check evolve condition to evolve in Hitmonchan (tygnon) # @return [Boolean] if the condition is valid def elv_tygnon self.atk < self.dfe end # Check evolve condition to evolve in Hitmontop (Kapoera) # @return [Boolean] if the condition is valid def elv_kapoera self.atk == self.dfe end # Check evolve condition to evolve in Silcoon (Armulys) # @return [Boolean] if the condition is valid def elv_armulys ((@code & 0xFFFF) % 10) <= 4 end # Check evolve condition to evolve in Cascoon (Blindalys) # @return [Boolean] if the condition is valid def elv_blindalys !self.elv_armulys end # Check evolve condition to evolve in Mantine (Démanta) # @return [Boolean] if the condition is valid def elv_demanta $pokemon_party.has_pokemon?(223) end # Check evolve condition to evolve in Pangoro (Pandarbare) # @return [Boolean] if the condition is valid def elv_pandarbare $actors.each do |i| return true if i and i.type_dark? end return false end # Check evolve condition to evolve in Malamar (Sepiatroce) # @note uses :DOWN to validate the evolve condition # @return [Boolean] if the condition is valid def elv_sepiatroce return Input.press?(:DOWN) end # Check evolve condition to evolve in Sylveon (Nymphali) # @return [Boolean] if the condition is valid def elv_nymphali @skills_set.each do |skill| return true if skill and skill.type_fairy? end return false end end end
36
138
0.625326
39da90836ef4ebcde8b8bff60ad381c7ab5bffb1
2,482
=begin #Hydrogen Atom API #The Hydrogen Atom API OpenAPI spec version: 1.7.0 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.4.14 =end require 'spec_helper' require 'json' require 'date' # Unit tests for NucleusApi::PageModelAssetSize # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'PageModelAssetSize' do before do # run before each test @instance = NucleusApi::PageModelAssetSize.new end after do # run after each test end describe 'test an instance of PageModelAssetSize' do it 'should create an instance of PageModelAssetSize' do expect(@instance).to be_instance_of(NucleusApi::PageModelAssetSize) end end describe 'test attribute "content"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "first"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "last"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "number"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "number_of_elements"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "size"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "sort"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "total_elements"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end describe 'test attribute "total_pages"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
27.577778
102
0.717969
abdf1f1b0eabf1a773eb66d06bf6090cde6249df
207
require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../../../shared/mutex/try_lock', __FILE__) describe "Mutex#try_lock" do it_behaves_like :mutex_try_lock, :try_lock end
29.571429
68
0.73913
0124e2e10eee8330cf3819d207e8ff90a77d1538
1,950
# frozen_string_literal: true require 'spec_helper' describe Dnsimple::Client, ".vanity_name_servers" do subject { described_class.new(base_url: "https://api.dnsimple.test", access_token: "a1b2c3").vanity_name_servers } describe "#enable_vanity_name_servers" do let(:account_id) { 1010 } before do stub_request(:put, %r{/v2/#{account_id}/vanity/.+$}) .to_return(read_http_fixture("enableVanityNameServers/success.http")) end it "builds the correct request" do subject.enable_vanity_name_servers(account_id, domain_name = "example.com") expect(WebMock).to have_requested(:put, "https://api.dnsimple.test/v2/#{account_id}/vanity/#{domain_name}") .with(headers: { "Accept" => "application/json" }) end it "returns vanity name servers of the domain" do response = subject.enable_vanity_name_servers(account_id, "example.com") expect(response).to be_a(Dnsimple::Response) vanity_name_servers = response.data.map { |ns| ns["name"] } expect(vanity_name_servers).to match_array(%w(ns1.example.com ns2.example.com ns3.example.com ns4.example.com)) end end describe "#disable_vanity_name_servers" do let(:account_id) { 1010 } before do stub_request(:delete, %r{/v2/#{account_id}/vanity/.+$}) .to_return(read_http_fixture("disableVanityNameServers/success.http")) end it "builds the correct request" do subject.disable_vanity_name_servers(account_id, domain_name = "example.com") expect(WebMock).to have_requested(:delete, "https://api.dnsimple.test/v2/#{account_id}/vanity/#{domain_name}") .with(headers: { "Accept" => "application/json" }) end it "returns empty response" do response = subject.disable_vanity_name_servers(account_id, "example.com") expect(response).to be_a(Dnsimple::Response) result = response.data expect(result).to be_nil end end end
34.210526
117
0.696923
bb98937203457f35777e8e9fbb5bee6059edbfdd
3,260
# 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::KeyVault::V7_1_preview module Models # # The SAS definition create parameters. # class SasDefinitionCreateParameters include MsRestAzure # @return [String] The SAS definition token template signed with an # arbitrary key. Tokens created according to the SAS definition will # have the same properties as the template. attr_accessor :template_uri # @return [SasTokenType] The type of SAS token the SAS definition will # create. Possible values include: 'account', 'service' attr_accessor :sas_type # @return [String] The validity period of SAS tokens created according to # the SAS definition. attr_accessor :validity_period # @return [SasDefinitionAttributes] The attributes of the SAS definition. attr_accessor :sas_definition_attributes # @return [Hash{String => String}] Application specific metadata in the # form of key-value pairs. attr_accessor :tags # # Mapper for SasDefinitionCreateParameters class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'SasDefinitionCreateParameters', type: { name: 'Composite', class_name: 'SasDefinitionCreateParameters', model_properties: { template_uri: { client_side_validation: true, required: true, serialized_name: 'templateUri', type: { name: 'String' } }, sas_type: { client_side_validation: true, required: true, serialized_name: 'sasType', type: { name: 'String' } }, validity_period: { client_side_validation: true, required: true, serialized_name: 'validityPeriod', type: { name: 'String' } }, sas_definition_attributes: { client_side_validation: true, required: false, serialized_name: 'attributes', type: { name: 'Composite', class_name: 'SasDefinitionAttributes' } }, tags: { client_side_validation: true, required: false, serialized_name: 'tags', type: { name: 'Dictionary', value: { client_side_validation: true, required: false, serialized_name: 'StringElementType', type: { name: 'String' } } } } } } } end end end end
31.047619
79
0.515951
21ad92a597f3d85b059a7b75eedb9f5e3d233a44
1,765
Rails.application.routes.draw do get 'authors/new' # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rails routes". # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :authors resources :papers # You can have the root of your site routed with "root" root 'home#index' # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # 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 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
28.467742
101
0.655524
1d14f5075b83ae7ae3606fb6c2a58fae0f8e2795
724
# frozen_string_literal: true require 'tanker/c_tanker' module Tanker class Core def create_group(member_identities) cmember_identities = CTanker.new_cstring_array member_identities CTanker.tanker_create_group(@ctanker, cmember_identities, member_identities.length).get_string end def update_group_members(group_id, users_to_add: [], users_to_remove: []) cadd_identities = CTanker.new_cstring_array users_to_add cremove_identities = CTanker.new_cstring_array users_to_remove CTanker.tanker_update_group_members(@ctanker, group_id, cadd_identities, users_to_add.length, cremove_identities, users_to_remove.length).get end end end
36.2
119
0.751381
61f25e4b809fb263d63f16208b6cf981e48fb3e7
3,267
#!/usr/bin/env ruby # # This is a 'fake' MQTT server to help with testing client implementations # # It behaves in the following ways: # * Responses to CONNECT with a successful CONACK # * Responses to PUBLISH by echoing the packet back # * Responses to SUBSCRIBE with SUBACK and a PUBLISH to the topic # * Responses to PINGREQ with PINGRESP # * Responses to DISCONNECT by closing the socket # # It has the following restrictions # * Doesn't deal with timeouts # * Only handles a single connection at a time # $:.unshift File.dirname(__FILE__)+'/../lib' require 'logger' require 'socket' require 'mqtt' class MQTT::FakeServer attr_reader :address, :port attr_reader :last_publish attr_reader :thread attr_reader :pings_received attr_accessor :just_one attr_accessor :logger # Create a new fake MQTT server # # If no port is given, bind to a random port number # If no bind address is given, bind to localhost def initialize(port=nil, bind_address='127.0.0.1') @port = port @address = bind_address end # Get the logger used by the server def logger @logger ||= Logger.new(STDOUT) end # Start the thread and open the socket that will process client connections def start @socket ||= TCPServer.new(@address, @port) @address = @socket.addr[3] @port = @socket.addr[1] @thread ||= Thread.new do logger.info "Started a fake MQTT server on #{@address}:#{@port}" loop do # Wait for a client to connect client = @socket.accept @pings_received = 0 handle_client(client) break if just_one end end end # Stop the thread and close the socket def stop logger.info "Stopping fake MQTT server" @socket.close unless @socket.nil? @socket = nil @thread.kill if @thread and @thread.alive? @thread = nil end # Start the server thread and wait for it to finish (possibly never) def run start begin @thread.join rescue Interrupt stop end end protected # Given a client socket, process MQTT packets from the client def handle_client(client) loop do packet = MQTT::Packet.read(client) logger.debug packet.inspect case packet when MQTT::Packet::Connect client.write MQTT::Packet::Connack.new(:return_code => 0) when MQTT::Packet::Publish client.write packet @last_publish = packet when MQTT::Packet::Subscribe client.write MQTT::Packet::Suback.new( :id => packet.id, :return_codes => 0 ) topic = packet.topics[0][0] client.write MQTT::Packet::Publish.new( :topic => topic, :payload => "hello #{topic}", :retain => true ) when MQTT::Packet::Pingreq client.write MQTT::Packet::Pingresp.new @pings_received += 1 when MQTT::Packet::Disconnect client.close break end end rescue MQTT::ProtocolException => e logger.warn "Protocol error, closing connection: #{e}" client.close end end if __FILE__ == $0 server = MQTT::FakeServer.new(MQTT::DEFAULT_PORT) server.logger.level = Logger::DEBUG server.run end
25.130769
77
0.640649
e8b15a05e216837a342371bf085d146525bd4a7b
674
require "magic/link/engine" require "magic/link/railtie" module Magic module Link mattr_accessor :user_class @@user_class = "User" mattr_accessor :email_from @@email_from = "[email protected]" mattr_accessor :token_expiration_hours @@token_expiration_hours = 6 mattr_accessor :after_sign_in_path @@after_sign_in_path = "root_path" mattr_accessor :force_new_tokens @@force_new_tokens = false mattr_accessor :force_user_change @@force_user_change = false class << self def configure yield self end def user_class @@user_class.constantize end end end end
19.257143
52
0.689911
113a3faea5119d9fb146a9d46248dc18f70a52a9
1,104
require 'spec_helper' require 'trix/simple_form/trix_editor_input' describe Trix::SimpleForm::TrixEditorInput, type: :view do include SimpleFormSpecHelper let(:post) { mock_model('Post', body: 'My super awesome post content.') } let(:form) do simple_form_for(post, url: 'some-url') do |f| f.input(:body, as: :trix_editor) end end before { concat(form) } it 'outputs HTML containing the hidden input field' do assert_select format('input[type="hidden"][id="post_body"][value="%s"]', post.body) end it 'outputs HTML containing the trix editor tag' do assert_select 'trix-editor[input="post_body"]' end it 'outputs HTML containing the trix editor tag with a trix-content class' do assert_select 'trix-editor.trix-content' end context 'with custom toolbar' do let(:form) do simple_form_for(post, url: 'some-url') do |f| f.input(:body, as: :trix_editor, toolbar: 'my-custom-toolbar') end end it 'outputs the custom toolbar attribute' do assert_select 'trix-editor[toolbar="my-custom-toolbar"]' end end end
26.926829
87
0.689312
1dcda1d18e2a812b75d25fe6d33e10b5d267854b
813
# frozen_string_literal: true require 'term/ansicolor' module Pact module XML NEWLINE = "\n" C = ::Term::ANSIColor # Formats list of differences into string class DiffFormatter def self.color(text, color, options) options.fetch(:colour, false) ? C.color(color, text) : text end def self.make_line(diff, options) "EXPECTED : #{color diff.expected, :red, options} #{NEWLINE}" \ "ACTUAL : #{color diff.actual, :green, options} #{NEWLINE}" \ "MESSAGE : #{diff.message}" end def self.call( result, options = { colour: Pact.configuration.color_enabled } ) diff = result[:body] return '' if diff.nil? diff.map { |d| make_line d, options }.join NEWLINE end end end end
24.636364
71
0.587946
bfaf0eb2fae152ad10766aabfef5fc5903847c2a
3,158
class SentNotification < ActiveRecord::Base serialize :position, Gitlab::Diff::Position belongs_to :project belongs_to :noteable, polymorphic: true belongs_to :recipient, class_name: "User" validates :project, :recipient, presence: true validates :reply_key, presence: true, uniqueness: true validates :noteable_id, presence: true, unless: :for_commit? validates :commit_id, presence: true, if: :for_commit? validates :in_reply_to_discussion_id, format: { with: /\A\h{40}\z/, allow_nil: true } validate :note_valid after_save :keep_around_commit class << self def reply_key SecureRandom.hex(16) end def for(reply_key) find_by(reply_key: reply_key) end def record(noteable, recipient_id, reply_key = self.reply_key, attrs = {}) noteable_id = nil commit_id = nil if noteable.is_a?(Commit) commit_id = noteable.id else noteable_id = noteable.id end attrs.reverse_merge!( project: noteable.project, recipient_id: recipient_id, reply_key: reply_key, noteable_type: noteable.class.name, noteable_id: noteable_id, commit_id: commit_id, ) create(attrs) end def record_note(note, recipient_id, reply_key = self.reply_key, attrs = {}) attrs[:in_reply_to_discussion_id] = note.discussion_id record(note.noteable, recipient_id, reply_key, attrs) end end def unsubscribable? !for_commit? end def for_commit? noteable_type == "Commit" end def noteable if for_commit? project.commit(commit_id) rescue nil else super end end def position=(new_position) if new_position.is_a?(String) new_position = JSON.parse(new_position) rescue nil end if new_position.is_a?(Hash) new_position = new_position.with_indifferent_access new_position = Gitlab::Diff::Position.new(new_position) end super(new_position) end def to_param self.reply_key end def create_reply(message, dryrun: false) klass = dryrun ? Notes::BuildService : Notes::CreateService klass.new(self.project, self.recipient, reply_params.merge(note: message)).execute end private def reply_params attrs = { noteable_type: self.noteable_type, noteable_id: self.noteable_id, commit_id: self.commit_id } if self.in_reply_to_discussion_id.present? attrs[:in_reply_to_discussion_id] = self.in_reply_to_discussion_id else # Remove in GitLab 10.0, when we will not support replying to SentNotifications # that don't have `in_reply_to_discussion_id` anymore. attrs.merge!( type: self.note_type, # LegacyDiffNote line_code: self.line_code, # DiffNote position: self.position.to_json ) end attrs end def note_valid note = create_reply('Test', dryrun: true) unless note.valid? self.errors.add(:base, "Note parameters are invalid: #{note.errors.full_messages.to_sentence}") end end def keep_around_commit project.repository.keep_around(self.commit_id) end end
23.744361
101
0.682711
18a4f45b9b4c7fc8b6890359275acd5ed9e66913
5,090
# frozen_string_literal: true require 'spec_helper' RSpec.shared_examples_for 'running the molecule graph plugin' do let(:conversion_attributes) { { source: :molecule_source } } let(:graph) do gql = Scenario.default.gql graph = gql.future_graph node = graph.plugin(:molecules).molecule_graph.node(:m_left) node.dataset_set( :from_energy, Atlas::NodeAttributes::EnergyToMolecules.new(conversion_attributes) ) allow(graph.area).to receive(:use_merit_order_demands).and_return(causality_enabled) graph end let(:molecule_graph) { graph.plugin(:molecules).molecule_graph } let(:energy_node) { graph.node(:molecule_source) } let(:molecule_node) { molecule_graph.node(:m_left) } context 'when the molecule node uses demand without a conversion' do before do graph.calculate end it 'has a non-nil demand' do expect(molecule_node.demand).not_to be_nil end it 'sets demand of the molecule node' do expect(molecule_node.demand).to eq(energy_node.demand) end end context 'when the molecule node uses demand with a conversion' do let(:conversion_attributes) { super().merge(conversion: 0.5) } before do graph.calculate end it 'has a non-nil demand' do expect(molecule_node.demand).not_to be_nil end it 'sets demand of the molecule node' do expect(molecule_node.demand).to eq(energy_node.demand * 0.5) end end context 'when the molecule node uses input with a conversion' do let(:conversion_attributes) do super().merge(direction: :input, conversion: { electricity: 0.5, natural_gas: 1.0 }) end before do allow(energy_node.input(:electricity)).to receive(:conversion).and_return(1.0) allow(energy_node.input(:natural_gas)).to receive(:conversion).and_return(0.1) graph.calculate end it 'has a non-nil demand' do expect(molecule_node.demand).not_to be_nil end it 'sets demand of the molecule node' do expect(molecule_node.demand).to eq(60) # 50% of elec. 100% of natural gas. end end context 'when the molecule node uses input with a carrier attribute' do let(:conversion_attributes) do super().merge(direction: :input, conversion: { electricity: 'carrier: co2_conversion_per_mj', natural_gas: 1.0 }) end before do allow(energy_node.input(:electricity).carrier) .to receive(:co2_conversion_per_mj).and_return(0.3) allow(energy_node.input(:electricity)).to receive(:conversion).and_return(1.0) allow(energy_node.input(:natural_gas)).to receive(:conversion).and_return(0.1) graph.calculate end it 'has a non-nil demand' do expect(molecule_node.demand).not_to be_nil end it 'sets demand of the molecule node' do expect(molecule_node.demand).to eq(40) # 30% of elec. 100% of natural gas. end end context "when the molecule node uses input with a carrier attribute which doesn't exist" do let(:conversion_attributes) do super().merge(direction: :input, conversion: { electricity: 'carrier: not_a_real_attribute' }) end it 'raises an error' do expect { graph.calculate }.to raise_error( 'Invalid molecule conversion attribute for electricity carrier on molecule_source node: ' \ '"carrier: not_a_real_attribute"' ) end end context 'when the molecule node uses output with a conversion' do let(:conversion_attributes) do super().merge(direction: :output, conversion: { electricity: 0.25, natural_gas: 1.0 }) end before do allow(energy_node.output(:electricity)).to receive(:conversion).and_return(1.0) allow(energy_node.output(:natural_gas)).to receive(:conversion).and_return(0.1) graph.calculate end it 'has a non-nil demand' do expect(molecule_node.demand).not_to be_nil end it 'sets demand of the molecule node' do expect(molecule_node.demand).to eq(35) # 25% of elec. 100% of natural gas. end end end RSpec.describe Qernel::Plugins::Molecules do context 'when Causality is disabled' do include_examples 'running the molecule graph plugin' do let(:causality_enabled) { false } context 'when an energy node receives a value from the molecule graph' do before { graph.calculate } let(:energy_target) { graph.node(:molecule_target) } it 'has no demand' do expect(energy_target.demand).to be_nil end end end end context 'when Causality is enabled' do include_examples 'running the molecule graph plugin' do let(:causality_enabled) { true } context 'when an energy node receives a value from the molecule graph' do before { graph.calculate } let(:energy_target) { graph.node(:molecule_target) } it 'has a demand' do # m_left demand * 0.75 share to m_right_one * 0.75 conversion expect(energy_target.demand).to eq(100 * 0.75 * 0.75) end end end end end
29.085714
99
0.681532
212ab486c97cf517896da01ff77eb050a794db1a
1,051
class AddValidationsToEvents < ActiveRecord::Migration[5.1] def self.up change_column :events, :title, :string, null: false change_column :events, :overview, :text, null: false change_column :events, :agenda, :text, null: false change_column :events, :img, :string, null: false change_column :events, :event_date, :date, null: false change_column :events, :start_datetime, :datetime, null: false change_column :events, :end_datetime, :datetime, null: false change_column :events, :category_id, :integer, null: false end def self.down change_column :events, :title, :string, null: true change_column :events, :overview, :text, null: true change_column :events, :agenda, :text, null: true change_column :events, :img, :string, null: true change_column :events, :event_date, :date, null: true change_column :events, :start_datetime, :datetime, null: true change_column :events, :end_datetime, :datetime, null: true change_column :events, :category_id, :integer, null: true end end
43.791667
66
0.714558
39bb7d644783cb08716c3b39ae0e2dc2b6b65c79
1,514
# frozen_string_literal: true ENV['RAILS_ENV'] ||= 'test' require File.expand_path('dummy/config/environment', __dir__) abort('The Rails environment is running in production mode!') if Rails.env.production? require 'rspec/rails' require 'factory_bot' require 'spree/testing_support/factories' require 'spree/testing_support/preferences' require 'solidus_support/extension/rails_helper' Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } Dir[File.join(__dir__, 'support/**/*.rb')].each { |f| require f } RSpec.configure do |config| config.backtrace_exclusion_patterns = [%r{gems/activesupport}, %r{gems/actionpack}, %r{gems/rspec}] config.infer_spec_type_from_file_location! # Allows RSpec to persist some state between runs in order to support # the `--only-failures` and `--next-failure` CLI options. We recommend # you configure your source control system to ignore this file. config.example_status_persistence_file_path = 'spec/examples.txt' config.define_derived_metadata(file_path: %r{/spec/spree/graphql/schema/}) do |metadata| metadata[:type] = :graphql end config.shared_context_metadata_behavior = :apply_to_host_groups config.include Spree::GraphQL::Spec::Helpers, type: :graphql config.before do Spree::Core::Engine.routes.draw do post :graphql, to: 'graphql#execute' end end config.before type: :graphql do Spree::GraphQL::LazyResolver.clear_cache end config.after(:all) do Rails.application.reload_routes! end end
31.541667
101
0.749009
916f33edfd8a52986f2d061b40c4fba9b85f12ca
1,296
Rails.application.configure do config.cache_classes = false config.eager_load = false config.consider_all_requests_local = true 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 config.action_mailer.raise_delivery_errors = true config.action_mailer.delivery_method = :smtp host = 'https://protected-cove-69705.herokuapp.com' config.action_mailer.default_url_options = { host: host } ActionMailer::Base.smtp_settings = { :address => 'smtp.sendgrid.net', :port => '587', :authentication => :plain, :user_name => ENV['SENDGRID_USERNAME'], :password => ENV['SENDGRID_PASSWORD'], :domain => 'heroku.com', :enable_starttls_auto => true } config.action_mailer.perform_caching = false config.active_support.deprecation = :log config.active_record.migration_error = :page_load config.assets.debug = true config.assets.quiet = true config.file_watcher = ActiveSupport::EventedFileUpdateChecker end
32.4
65
0.709877
1df3c1400aed4a0663238c2b0120a5c8bb1ffdac
34,551
# encoding: utf-8 require 'spec_helper' describe Ably::Rest::Push::Admin do include Ably::Modules::Conversions vary_by_protocol do let(:default_options) { { key: api_key, environment: environment, protocol: protocol} } let(:client_options) { default_options } let(:client) do Ably::Rest::Client.new(client_options) end let(:basic_notification_payload) do { notification: { title: 'Test message', body: 'Test message body' } } end let(:basic_recipient) do { transport_type: 'apns', deviceToken: 'foo.bar' } end describe '#publish' do subject { client.push.admin } context 'without publish permissions' do let(:capability) { { :foo => ['subscribe'] } } before do client.auth.authorize(capability: capability) end it 'raises a permissions issue exception' do expect { subject.publish(basic_recipient, basic_notification_payload) }.to raise_error Ably::Exceptions::UnauthorizedRequest end end context 'invalid arguments (#RHS1a)' do it 'raises an exception with a nil recipient' do expect { subject.publish(nil, {}) }.to raise_error ArgumentError, /Expecting a Hash/ end it 'raises an exception with a empty recipient' do expect { subject.publish({}, {}) }.to raise_error ArgumentError, /empty/ end it 'raises an exception with a nil recipient' do expect { subject.publish(basic_recipient, nil) }.to raise_error ArgumentError, /Expecting a Hash/ end it 'raises an exception with a empty recipient' do expect { subject.publish(basic_recipient, {}) }.to raise_error ArgumentError, /empty/ end end context 'invalid recipient (#RSH1a)' do it 'raises an error after receiving a 40x realtime response' do expect { subject.publish({ invalid_recipient_details: 'foo.bar' }, basic_notification_payload) }.to raise_error Ably::Exceptions::InvalidRequest end end context 'invalid push data (#RSH1a)' do it 'raises an error after receiving a 40x realtime response' do expect { subject.publish(basic_recipient, { invalid_property_only: true }) }.to raise_error Ably::Exceptions::InvalidRequest end end context 'recipient variable case', webmock: true do let(:recipient_payload) do { camel_case: { second_level_camel_case: 'val' } } end let(:content_type) do if protocol == :msgpack 'application/x-msgpack' else 'application/json' end end let!(:publish_stub) do stub_request(:post, "#{client.endpoint}/push/publish"). with do |request| expect(deserialize_body(request.body, protocol)['recipient']['camelCase']['secondLevelCamelCase']).to eql('val') expect(deserialize_body(request.body, protocol)['recipient']).to_not have_key('camel_case') true end.to_return( :status => 201, :body => serialize_body({}, protocol), :headers => { 'Content-Type' => content_type } ) end it 'is converted to snakeCase' do subject.publish(recipient_payload, basic_notification_payload) expect(publish_stub).to have_been_requested end end it 'accepts valid push data and recipient (#RSH1a)' do subject.publish(basic_recipient, basic_notification_payload) end context 'using test environment channel recipient (#RSH1a)' do let(:channel) { random_str } let(:recipient) do { 'transportType' => 'ablyChannel', 'channel' => channel, 'ablyKey' => api_key, 'ablyUrl' => client.endpoint.to_s } end let(:notification_payload) do { notification: { title: random_str, }, data: { foo: random_str } } end it 'triggers a push notification' do subject.publish(recipient, notification_payload) sleep 5 notification_published_on_channel = client.channels.get(channel).history.items.first expect(notification_published_on_channel.name).to eql('__ably_push__') expect(JSON.parse(notification_published_on_channel.data)['data']).to eql(JSON.parse(notification_payload[:data].to_json)) end end end describe '#device_registrations (#RSH1b)' do subject { client.push.admin.device_registrations } context 'without permissions' do let(:capability) { { :foo => ['subscribe'] } } before do client.auth.authorize(capability: capability) end it 'raises a permissions not authorized exception' do expect { subject.get('does-not-exist') }.to raise_error Ably::Exceptions::UnauthorizedRequest expect { subject.list }.to raise_error Ably::Exceptions::UnauthorizedRequest expect { subject.remove('does-not-exist') }.to raise_error Ably::Exceptions::UnauthorizedRequest expect { subject.remove_where(device_id: 'does-not-exist') }.to raise_error Ably::Exceptions::UnauthorizedRequest end end describe '#list (#RSH1b2)' do let(:client_id) { random_str } let(:fixture_count) { 6 } before(:all) do # As push tests often use the global scope (devices), # we need to ensure tests cannot conflict reload_test_app end before do fixture_count.times.map do |index| Thread.new do subject.save({ id: "device-#{client_id}-#{index}", platform: 'ios', form_factor: 'phone', client_id: client_id, push: { recipient: { transport_type: 'gcm', registration_token: 'secret_token', } } }) end end.each(&:join) # Wait for all threads to complete end after do subject.remove_where client_id: client_id, full_wait: true end it 'returns a PaginatedResult object containing DeviceDetails objects' do page = subject.list expect(page).to be_a(Ably::Models::PaginatedResult) expect(page.items.first).to be_a(Ably::Models::DeviceDetails) end it 'returns an empty PaginatedResult if not params match' do page = subject.list(client_id: 'does-not-exist') expect(page).to be_a(Ably::Models::PaginatedResult) expect(page.items).to be_empty end it 'supports paging' do page = subject.list(limit: 3, client_id: client_id) expect(page).to be_a(Ably::Models::PaginatedResult) expect(page.items.count).to eql(3) page = page.next expect(page.items.count).to eql(3) page = page.next expect(page.items.count).to eql(0) expect(page).to be_last end it 'provides filtering' do page = subject.list(client_id: client_id) expect(page.items.length).to eql(fixture_count) page = subject.list(device_id: "device-#{client_id}-0") expect(page.items.length).to eql(1) page = subject.list(client_id: random_str) expect(page.items.length).to eql(0) end end describe '#get (#RSH1b1)' do let(:fixture_count) { 2 } let(:client_id) { random_str } before(:all) do # As push tests often use the global scope (devices), # we need to ensure tests cannot conflict reload_test_app end before do fixture_count.times.map do |index| Thread.new do subject.save({ id: "device-#{client_id}-#{index}", platform: 'ios', form_factor: 'phone', client_id: client_id, push: { recipient: { transport_type: 'gcm', registration_token: 'secret_token', } } }) end end.each(&:join) # Wait for all threads to complete end after do subject.remove_where client_id: client_id, full_wait: true end it 'returns a DeviceDetails object if a device ID string is provided' do device = subject.get("device-#{client_id}-0") expect(device).to be_a(Ably::Models::DeviceDetails) expect(device.platform).to eql('ios') expect(device.client_id).to eql(client_id) expect(device.push.recipient.fetch(:transport_type)).to eql('gcm') end it 'returns a DeviceDetails object if a DeviceDetails object is provided' do device = subject.get(Ably::Models::DeviceDetails.new(id: "device-#{client_id}-1")) expect(device).to be_a(Ably::Models::DeviceDetails) expect(device.platform).to eql('ios') expect(device.client_id).to eql(client_id) expect(device.push.recipient.fetch(:transport_type)).to eql('gcm') end it 'raises a ResourceMissing exception if device ID does not exist' do expect { subject.get("device-does-not-exist") }.to raise_error(Ably::Exceptions::ResourceMissing) end end describe '#save (#RSH1b3)' do let(:device_id) { random_str } let(:client_id) { random_str } let(:transport_token) { random_str } let(:device_details) do { id: device_id, platform: 'android', form_factor: 'phone', client_id: client_id, metadata: { foo: 'bar', deep: { val: true } }, push: { recipient: { transport_type: 'apns', device_token: transport_token, foo_bar: 'string', }, error_reason: { message: "this will be ignored" }, } } end before(:all) do # As push tests often use the global scope (devices), # we need to ensure tests cannot conflict reload_test_app end after do subject.remove_where client_id: client_id, full_wait: true end it 'saves the new DeviceDetails Hash object' do subject.save(device_details) device_retrieved = subject.get(device_details.fetch(:id)) expect(device_retrieved).to be_a(Ably::Models::DeviceDetails) expect(device_retrieved.id).to eql(device_id) expect(device_retrieved.platform).to eql('android') expect(device_retrieved.form_factor).to eql('phone') expect(device_retrieved.client_id).to eql(client_id) expect(device_retrieved.metadata.keys.length).to eql(2) expect(device_retrieved.metadata[:foo]).to eql('bar') expect(device_retrieved.metadata['deep']['val']).to eql(true) end it 'saves the associated DevicePushDetails' do subject.save(device_details) device_retrieved = subject.list(device_id: device_details.fetch(:id)).items.first expect(device_retrieved.push).to be_a(Ably::Models::DevicePushDetails) expect(device_retrieved.push.recipient.fetch(:transport_type)).to eql('apns') expect(device_retrieved.push.recipient['deviceToken']).to eql(transport_token) expect(device_retrieved.push.recipient['foo_bar']).to eql('string') end context 'with GCM target' do let(:device_token) { random_str } it 'saves the associated DevicePushDetails' do subject.save(device_details.merge( push: { recipient: { transport_type: 'gcm', registrationToken: device_token } } )) device_retrieved = subject.get(device_details.fetch(:id)) expect(device_retrieved.push.recipient.fetch('transportType')).to eql('gcm') expect(device_retrieved.push.recipient[:registration_token]).to eql(device_token) end end context 'with web target' do let(:target_url) { 'http://foo.com/bar' } let(:encryption_key) { random_str } it 'saves the associated DevicePushDetails' do subject.save(device_details.merge( push: { recipient: { transport_type: 'web', targetUrl: target_url, encryptionKey: encryption_key } } )) device_retrieved = subject.get(device_details.fetch(:id)) expect(device_retrieved.push.recipient[:transport_type]).to eql('web') expect(device_retrieved.push.recipient['targetUrl']).to eql(target_url) expect(device_retrieved.push.recipient['encryptionKey']).to eql(encryption_key) end end it 'does not allow some fields to be configured' do subject.save(device_details) device_retrieved = subject.get(device_details.fetch(:id)) expect(device_retrieved.push.state).to eql('ACTIVE') expect(device_retrieved.device_secret).to be_nil # Errors are exclusively configure by Ably expect(device_retrieved.push.error_reason).to be_nil end it 'allows device_secret to be configured' do device_secret = random_str subject.save(device_details.merge(device_secret: device_secret)) device_retrieved = subject.get(device_details.fetch(:id)) expect(device_retrieved.device_secret).to eql(device_secret) end it 'saves the new DeviceDetails object' do subject.save(DeviceDetails(device_details)) device_retrieved = subject.get(device_details.fetch(:id)) expect(device_retrieved.id).to eql(device_id) expect(device_retrieved.metadata[:foo]).to eql('bar') expect(device_retrieved.push.recipient[:transport_type]).to eql('apns') end it 'allows arbitrary number of subsequent saves' do 3.times do subject.save(DeviceDetails(device_details)) end device_retrieved = subject.get(device_details.fetch(:id)) expect(device_retrieved.metadata[:foo]).to eql('bar') subject.save(DeviceDetails(device_details.merge(metadata: { foo: 'changed'}))) device_retrieved = subject.get(device_details.fetch(:id)) expect(device_retrieved.metadata[:foo]).to eql('changed') end it 'fails if data is invalid' do expect { subject.save(id: random_str, foo: 'bar') }.to raise_error Ably::Exceptions::InvalidRequest end end describe '#remove_where (#RSH1b5)' do let(:device_id) { random_str } let(:client_id) { random_str } before(:all) do # As push tests often use the global scope (devices), # we need to ensure tests cannot conflict reload_test_app end before do [ Thread.new do subject.save({ id: "device-#{client_id}-0", platform: 'ios', form_factor: 'phone', client_id: client_id, push: { recipient: { transport_type: 'gcm', registrationToken: 'secret_token', } } }) end, Thread.new do subject.save({ id: "device-#{client_id}-1", platform: 'ios', form_factor: 'phone', client_id: client_id, push: { recipient: { transport_type: 'gcm', registration_token: 'secret_token', } } }) end ].each(&:join) # Wait for all threads to complete end after do subject.remove_where client_id: client_id, full_wait: true end it 'removes all matching device registrations by client_id' do subject.remove_where(client_id: client_id, full_wait: true) # undocumented full_wait to compelte synchronously expect(subject.list.items.count).to eql(0) end it 'removes device by device_id' do subject.remove_where(device_id: "device-#{client_id}-1", full_wait: true) # undocumented full_wait to compelte synchronously expect(subject.list.items.count).to eql(1) end it 'succeeds even if there is no match' do subject.remove_where(device_id: 'does-not-exist', full_wait: true) # undocumented full_wait to compelte synchronously expect(subject.list.items.count).to eql(2) end end describe '#remove (#RSH1b4)' do let(:device_id) { random_str } let(:client_id) { random_str } before(:all) do # As push tests often use the global scope (devices), # we need to ensure tests cannot conflict reload_test_app end before do [ Thread.new do subject.save({ id: "device-#{client_id}-0", platform: 'ios', form_factor: 'phone', client_id: client_id, push: { recipient: { transport_type: 'gcm', registration_token: 'secret_token', } } }) end, Thread.new do subject.save({ id: "device-#{client_id}-1", platform: 'ios', form_factor: 'phone', client_id: client_id, push: { recipient: { transport_type: 'gcm', registration_token: 'secret_token', } } }) end ].each(&:join) # Wait for all threads to complete end after do subject.remove_where client_id: client_id, full_wait: true end it 'removes the provided device id string' do subject.remove("device-#{client_id}-0") expect(subject.list.items.count).to eql(1) end it 'removes the provided DeviceDetails' do subject.remove(DeviceDetails(id: "device-#{client_id}-1")) expect(subject.list.items.count).to eql(1) end it 'succeeds if the item does not exist' do subject.remove('does-not-exist') expect(subject.list.items.count).to eql(2) end end end describe '#channel_subscriptions (#RSH1c)' do let(:client_id) { random_str } let(:device_id) { random_str } let(:device_id_2) { random_str } let(:default_device_attr) { { platform: 'ios', form_factor: 'phone', client_id: client_id, push: { recipient: { transport_type: 'gcm', registration_token: 'secret_token', } } } } let(:device_registrations) { client.push.admin.device_registrations } subject { client.push.admin.channel_subscriptions } # Set up 2 devices with the same client_id # and two device with the unique device_id and no client_id before do [ lambda { device_registrations.save(default_device_attr.merge(id: device_id, client_id: nil)) }, lambda { device_registrations.save(default_device_attr.merge(id: device_id_2, client_id: nil)) }, lambda { device_registrations.save(default_device_attr.merge(client_id: client_id, id: random_str)) }, lambda { device_registrations.save(default_device_attr.merge(client_id: client_id, id: random_str)) } ].map do |proc| Thread.new { proc.call } end.each(&:join) # Wait for all threads to complete end after do device_registrations.remove_where client_id: client_id device_registrations.remove_where device_id: device_id end describe '#list (#RSH1c1)' do let(:fixture_count) { 6 } before(:all) do # As push tests often use the global scope (devices), # we need to ensure tests cannot conflict reload_test_app end before do fixture_count.times.map do |index| Thread.new { subject.save(channel: "pushenabled:#{random_str}", client_id: client_id) } end + fixture_count.times.map do |index| Thread.new { subject.save(channel: "pushenabled:#{random_str}", device_id: device_id) } end.each(&:join) # Wait for all threads to complete end it 'returns a PaginatedResult object containing DeviceDetails objects' do page = subject.list(client_id: client_id) expect(page).to be_a(Ably::Models::PaginatedResult) expect(page.items.first).to be_a(Ably::Models::PushChannelSubscription) end it 'returns an empty PaginatedResult if params do not match' do page = subject.list(client_id: 'does-not-exist') expect(page).to be_a(Ably::Models::PaginatedResult) expect(page.items).to be_empty end it 'supports paging' do page = subject.list(limit: 3, device_id: device_id) expect(page).to be_a(Ably::Models::PaginatedResult) expect(page.items.count).to eql(3) page = page.next expect(page.items.count).to eql(3) page = page.next expect(page.items.count).to eql(0) expect(page).to be_last end it 'provides filtering' do page = subject.list(device_id: device_id) expect(page.items.length).to eql(fixture_count) page = subject.list(client_id: client_id) expect(page.items.length).to eql(fixture_count) random_channel = "pushenabled:#{random_str}" subject.save(channel: random_channel, client_id: client_id) page = subject.list(channel: random_channel) expect(page.items.length).to eql(1) page = subject.list(channel: random_channel, client_id: client_id) expect(page.items.length).to eql(1) page = subject.list(channel: random_channel, device_id: random_str) expect(page.items.length).to eql(0) page = subject.list(device_id: random_str) expect(page.items.length).to eql(0) page = subject.list(client_id: random_str) expect(page.items.length).to eql(0) page = subject.list(channel: random_str) expect(page.items.length).to eql(0) end it 'raises an exception if none of the required filters are provided' do expect { subject.list({ limit: 100 }) }.to raise_error(ArgumentError) end end describe '#list_channels (#RSH1c2)' do let(:fixture_count) { 6 } before(:all) do # As push tests often use the global scope (devices), # we need to ensure tests cannot conflict reload_test_app end before do # Create 6 channel subscriptions to the client ID for this test fixture_count.times.map do |index| Thread.new do subject.save(channel: "pushenabled:#{index}:#{random_str}", client_id: client_id) end end.each(&:join) # Wait for all threads to complete end after do subject.remove_where client_id: client_id, full_wait: true # undocumented arg to do deletes synchronously end it 'returns a PaginatedResult object containing String objects' do page = subject.list_channels expect(page).to be_a(Ably::Models::PaginatedResult) expect(page.items.first).to be_a(String) expect(page.items.length).to eql(fixture_count) end it 'supports paging' do subject.list_channels page = subject.list_channels(limit: 3) expect(page).to be_a(Ably::Models::PaginatedResult) expect(page.items.count).to eql(3) page = page.next expect(page.items.count).to eql(3) page = page.next expect(page.items.count).to eql(0) expect(page).to be_last end # This test is not necessary for client libraries, but was useful when building the Ruby # lib to ensure the realtime implementation did not suffer from timing issues it 'returns an accurate number of channels after devices are deleted' do expect(subject.list_channels.items.length).to eql(fixture_count) subject.save(channel: "pushenabled:#{random_str}", device_id: device_id) subject.save(channel: "pushenabled:#{random_str}", device_id: device_id) expect(subject.list_channels.items.length).to eql(fixture_count + 2) expect(device_registrations.list(device_id: device_id).items.count).to eql(1) device_registrations.remove_where device_id: device_id, full_wait: true # undocumented arg to do deletes synchronously expect(device_registrations.list(device_id: device_id).items.count).to eql(0) expect(subject.list_channels.items.length).to eql(fixture_count) subject.remove_where client_id: client_id, full_wait: true # undocumented arg to do deletes synchronously expect(subject.list_channels.items.length).to eql(0) end end describe '#save (#RSH1c3)' do let(:channel) { "pushenabled:#{random_str}" } let(:client_id) { random_str } let(:device_id) { random_str } before(:all) do # As push tests often use the global scope (devices), # we need to ensure tests cannot conflict reload_test_app end it 'saves the new client_id PushChannelSubscription Hash object' do subject.save(channel: channel, client_id: client_id) channel_sub = subject.list(client_id: client_id).items.first expect(channel_sub).to be_a(Ably::Models::PushChannelSubscription) expect(channel_sub.channel).to eql(channel) expect(channel_sub.client_id).to eql(client_id) expect(channel_sub.device_id).to be_nil end it 'saves the new device_id PushChannelSubscription Hash object' do subject.save(channel: channel, device_id: device_id) channel_sub = subject.list(device_id: device_id).items.first expect(channel_sub).to be_a(Ably::Models::PushChannelSubscription) expect(channel_sub.channel).to eql(channel) expect(channel_sub.device_id).to eql(device_id) expect(channel_sub.client_id).to be_nil end it 'saves the client_id PushChannelSubscription object' do subject.save(PushChannelSubscription(channel: channel, client_id: client_id)) channel_sub = subject.list(client_id: client_id).items.first expect(channel_sub).to be_a(Ably::Models::PushChannelSubscription) expect(channel_sub.channel).to eql(channel) expect(channel_sub.client_id).to eql(client_id) expect(channel_sub.device_id).to be_nil end it 'saves the device_id PushChannelSubscription object' do subject.save(PushChannelSubscription(channel: channel, device_id: device_id)) channel_sub = subject.list(device_id: device_id).items.first expect(channel_sub).to be_a(Ably::Models::PushChannelSubscription) expect(channel_sub.channel).to eql(channel) expect(channel_sub.device_id).to eql(device_id) expect(channel_sub.client_id).to be_nil end it 'allows arbitrary number of subsequent saves' do 10.times do subject.save(PushChannelSubscription(channel: channel, device_id: device_id)) end channel_subs = subject.list(device_id: device_id).items expect(channel_subs.length).to eql(1) expect(channel_subs.first).to be_a(Ably::Models::PushChannelSubscription) expect(channel_subs.first.channel).to eql(channel) expect(channel_subs.first.device_id).to eql(device_id) expect(channel_subs.first.client_id).to be_nil end it 'fails if data is invalid' do expect { subject.save(channel: '', client_id: '') }.to raise_error ArgumentError expect { subject.save({}) }.to raise_error ArgumentError expect { subject.save(channel: 'not-enabled-channel', device_id: 'foo') }.to raise_error Ably::Exceptions::UnauthorizedRequest expect { subject.save(channel: 'pushenabled:foo', device_id: 'not-registered-so-will-fail') }.to raise_error Ably::Exceptions::InvalidRequest end end describe '#remove_where (#RSH1c5)' do let(:client_id) { random_str } let(:device_id) { random_str } let(:fixed_channel) { "pushenabled:#{random_str}" } let(:fixture_count) { 6 } before(:all) do # As push tests often use the global scope (devices), # we need to ensure tests cannot conflict reload_test_app end before do fixture_count.times.map do |index| [ lambda { subject.save(channel: "pushenabled:#{random_str}", client_id: client_id) }, lambda { subject.save(channel: "pushenabled:#{random_str}", device_id: device_id) }, lambda { subject.save(channel: fixed_channel, device_id: device_id_2) } ] end.flatten.map do |proc| Thread.new { proc.call } end.each(&:join) # Wait for all threads to complete end # TODO: Reinstate once delete subscriptions by channel is possible # See https://github.com/ably/realtime/issues/1359 it 'removes matching channels' do skip 'deleting subscriptions is not yet supported realtime#1359' subject.remove_where channel: fixed_channel, full_wait: true expect(subject.list(channel: fixed_channel).items.count).to eql(0) expect(subject.list(client_id: client_id).items.count).to eql(0) expect(subject.list(device_id: device_id).items.count).to eql(0) end it 'removes matching client_ids' do subject.remove_where client_id: client_id, full_wait: true expect(subject.list(client_id: client_id).items.count).to eql(0) expect(subject.list(device_id: device_id).items.count).to eql(fixture_count) end it 'removes matching device_ids' do subject.remove_where device_id: device_id, full_wait: true expect(subject.list(device_id: device_id).items.count).to eql(0) expect(subject.list(client_id: client_id).items.count).to eql(fixture_count) end it 'device_id and client_id filters in the same request are not suppoorted' do expect { subject.remove_where(device_id: device_id, client_id: client_id) }.to raise_error(Ably::Exceptions::InvalidRequest) end it 'succeeds on no match' do subject.remove_where device_id: random_str, full_wait: true expect(subject.list(device_id: device_id).items.count).to eql(fixture_count) subject.remove_where client_id: random_str expect(subject.list(client_id: client_id).items.count).to eql(fixture_count) end end describe '#remove (#RSH1c4)' do let(:channel) { "pushenabled:#{random_str}" } let(:channel2) { "pushenabled:#{random_str}" } let(:client_id) { random_str } let(:device_id) { random_str } before(:all) do # As push tests often use the global scope (devices), # we need to ensure tests cannot conflict reload_test_app end before do [ lambda { subject.save(channel: channel, client_id: client_id) }, lambda { subject.save(channel: channel, device_id: device_id) }, lambda { subject.save(channel: channel2, client_id: client_id) } ].map do |proc| Thread.new { proc.call } end.each(&:join) # Wait for all threads to complete end it 'removes match for Hash object by channel and client_id' do subject.remove(channel: channel, client_id: client_id) expect(subject.list(client_id: client_id).items.count).to eql(1) end it 'removes match for PushChannelSubscription object by channel and client_id' do push_sub = subject.list(channel: channel, client_id: client_id).items.first expect(push_sub).to be_a(Ably::Models::PushChannelSubscription) subject.remove(push_sub) expect(subject.list(client_id: client_id).items.count).to eql(1) end it 'removes match for Hash object by channel and device_id' do subject.remove(channel: channel, device_id: device_id) expect(subject.list(device_id: device_id).items.count).to eql(0) end it 'removes match for PushChannelSubscription object by channel and client_id' do push_sub = subject.list(channel: channel, device_id: device_id).items.first expect(push_sub).to be_a(Ably::Models::PushChannelSubscription) subject.remove(push_sub) expect(subject.list(device_id: device_id).items.count).to eql(0) end it 'succeeds even if there is no match' do subject.remove(device_id: 'does-not-exist', channel: random_str) expect(subject.list(device_id: 'does-not-exist').items.count).to eql(0) end end end end end
36.874066
154
0.600127
ed239b1c57cace5336a1a4ad1ad3f10c993a2cfd
1,925
# I'm sorry for this code require "mongo_mapper" require "json" require "httparty" MongoMapper.database = "food" require_relative "model.rb" require_relative "apikey.rb" class Migros include HTTParty base_uri "https://test-web-api.migros.ch/eth-hack" def someProducts limit, offset respons = self.class.get("/products?key=#{API_KEY}&lang=de&limit=#{limit}&offset=#{offset}&sort=category&roots=lebensmittel") responsJson = JSON.parse respons.body if respons.code == 200 products = responsJson["products"] products end end scraper = Migros.new totalResult = 100 element_counter = 0 (0..50).each_with_index do |item, index| prod = scraper.someProducts totalResult, totalResult * index for product in prod do unless product[1]["image"].nil? categories = product[1]["categories"] if categories.to_s.include? "lebensmittel" facts = product[1]["nutrition_facts"] unless facts.nil? || facts["standard"].nil? || facts["standard"]["nutrients"].nil? url = "http://#{product[1]["image"]["large"]}".split(".jpg")[0] leshop_url = product[1]["links"]["leshop"]["url"] unless product[1]["links"].nil? || product[1]["links"]["leshop"].nil? || product[1]["links"]["leshop"]["url"].nil? db_product = Product.new(:productNummber => product[0], :name => product[1]["name"], :imgurl => "#{url}.jpg", :rnd => rand(), :leshopurl => leshop_url) for nut in product[1]["nutrition_facts"]["standard"]["nutrients"] db_product.nutritions.build(:name => nut["name"], :unit => nut["quantity_unit"], :quantity => nut["quantity"]) end db_product.save! element_counter = element_counter + 1 end end end end end p element_counter
29.615385
174
0.596883
e948ce425a86575afb590020619203612c600263
8,365
# frozen_string_literal: true require 'logstasher/version' require 'logstasher/active_support/log_subscriber' require 'logstasher/active_support/mailer_log_subscriber' require 'logstasher/active_record/log_subscriber' if defined?(ActiveRecord) require 'logstasher/action_view/log_subscriber' if defined?(ActionView) require 'logstasher/active_job/log_subscriber' if defined?(ActiveJob) require 'logstasher/rails_ext/action_controller/base' require 'logstasher/custom_fields' require 'logstasher/event' require 'request_store' require 'active_support/core_ext/module/attribute_accessors' require 'active_support/core_ext/string/inflections' require 'active_support/ordered_options' module LogStasher extend self STORE_KEY = :logstasher_data REQUEST_CONTEXT_KEY = :logstasher_request_context attr_accessor :logger, :logger_path, :enabled, :log_controller_parameters, :source, :backtrace, :controller_monkey_patch, :field_renaming, :backtrace_filter # Setting the default to 'unknown' to define the default behaviour @source = 'unknown' # By default log the backtrace of exceptions @backtrace = true def remove_existing_log_subscriptions ::ActiveSupport::LogSubscriber.log_subscribers.each do |subscriber| case subscriber.class.name when 'ActionView::LogSubscriber' unsubscribe(:action_view, subscriber) when 'ActionController::LogSubscriber' unsubscribe(:action_controller, subscriber) when 'ActionMailer::LogSubscriber' unsubscribe(:action_mailer, subscriber) when 'ActiveRecord::LogSubscriber' unsubscribe(:active_record, subscriber) when 'ActiveJob::LogSubscriber' # For Rails 6 unsubscribe(:active_job, subscriber) when 'ActiveJob::Logging::LogSubscriber' # For Rails 5 unsubscribe(:active_job, subscriber) end end end def unsubscribe(component, subscriber) events = subscriber.public_methods(false).reject { |method| method.to_s == 'call' } events.each do |event| ::ActiveSupport::Notifications.notifier.listeners_for("#{event}.#{component}").each do |listener| ::ActiveSupport::Notifications.unsubscribe listener if listener.instance_variable_get('@delegate') == subscriber end end end def add_default_fields_to_payload(payload, request) payload[:ip] = request.remote_ip payload[:route] = "#{request.params[:controller]}##{request.params[:action]}" payload[:request_id] = request.env['action_dispatch.request_id'] LogStasher::CustomFields.add(:ip, :route, :request_id) if log_controller_parameters payload[:parameters] = payload[:params].except(*::ActionController::LogSubscriber::INTERNAL_PARAMS) LogStasher::CustomFields.add(:parameters) end end def add_custom_fields(&block) wrapped_block = proc do |fields| LogStasher::CustomFields.add(*LogStasher.store.keys) instance_exec(fields, &block) end ::ActiveSupport.on_load(:action_controller) do ::ActionController::Metal.send(:define_method, :logstasher_add_custom_fields_to_payload, &wrapped_block) ::ActionController::Base.send(:define_method, :logstasher_add_custom_fields_to_payload, &wrapped_block) end end def add_custom_fields_to_request_context(&block) wrapped_block = proc do |fields| instance_exec(fields, &block) LogStasher::CustomFields.add(*fields.keys) end ::ActiveSupport.on_load(:action_controller) do ::ActionController::Metal.send(:define_method, :logstasher_add_custom_fields_to_request_context, &wrapped_block) ::ActionController::Base.send(:define_method, :logstasher_add_custom_fields_to_request_context, &wrapped_block) end end def add_default_fields_to_request_context(request) request_context[:request_id] = request.env['action_dispatch.request_id'] end def clear_request_context request_context.clear end def setup_before(config) self.enabled = config.enabled LogStasher::ActiveSupport::LogSubscriber.attach_to :action_controller if config.controller_enabled LogStasher::ActiveSupport::MailerLogSubscriber.attach_to :action_mailer if config.mailer_enabled LogStasher::ActiveRecord::LogSubscriber.attach_to :active_record if config.record_enabled LogStasher::ActionView::LogSubscriber.attach_to :action_view if config.view_enabled LogStasher::ActiveJob::LogSubscriber.attach_to :active_job if has_active_job? && config.job_enabled end def setup(config) # Path instrumentation class to insert our hook if (!config.controller_monkey_patch && config.controller_monkey_patch != false) || config.controller_monkey_patch == true require 'logstasher/rails_ext/action_controller/metal/instrumentation' end suppress_app_logs(config) self.logger_path = config.logger_path || "#{Rails.root}/log/logstash_#{Rails.env}.log" self.logger = config.logger || new_logger(logger_path) logger.level = config.log_level || Logger::WARN self.source = config.source unless config.source.nil? self.log_controller_parameters = !config.log_controller_parameters.nil? self.backtrace = !config.backtrace.nil? unless config.backtrace.nil? self.backtrace_filter = config.backtrace_filter set_data_for_rake set_data_for_console self.field_renaming = Hash(config.field_renaming) end def set_data_for_rake request_context['request_id'] = ::Rake.application.top_level_tasks if called_as_rake? end def set_data_for_console request_context['request_id'] = Process.pid.to_s if called_as_console? end def called_as_rake? File.basename($PROGRAM_NAME) == 'rake' end def called_as_console? defined?(Rails::Console) && true || false end def has_active_job? defined?(ActiveJob) end def suppress_app_logs(config) if configured_to_suppress_app_logs?(config) require 'logstasher/rails_ext/rack/logger' LogStasher.remove_existing_log_subscriptions end end def configured_to_suppress_app_logs?(config) # This supports both spellings: "suppress_app_log" and "supress_app_log" !!(config.suppress_app_log.nil? ? config.supress_app_log : config.suppress_app_log) end # Log an arbitrary message. # # Usually invoked by the level-based wrapper methods defined below. # # Examples # # LogStasher.info("message") # LogStasher.info("message", tags:"tag1") # LogStasher.info("message", tags:["tag1", "tag2"]) # LogStasher.info("message", timing:1234) # LogStasher.info(custom1:"yes", custom2:"no") def log(severity, message, additional_fields = {}) if logger&.send("#{severity}?") data = { 'level' => severity } if message.respond_to?(:to_hash) data.merge!(message.to_hash) else data['message'] = message end # tags get special handling tags = Array(additional_fields.delete(:tags) || 'log') data.merge!(additional_fields) logger << "#{build_logstash_event(data, tags).to_json}\n" end end def build_logstash_event(data, tags) field_renaming.each do |old_name, new_name| data[new_name] = data.delete(old_name) if data.key?(old_name) end Event.new(data.merge('source' => source, 'tags' => tags)) end def store if RequestStore.store[STORE_KEY].nil? # Get each store it's own private Hash instance. RequestStore.store[STORE_KEY] = Hash.new { |hash, key| hash[key] = {} } end RequestStore.store[STORE_KEY] end def request_context RequestStore.store[REQUEST_CONTEXT_KEY] ||= {} end def watch(event, opts = {}, &block) event_group = opts[:event_group] || event ::ActiveSupport::Notifications.subscribe(event) do |*args| # Calling the processing block with the Notification args and the store block.call(*args, store[event_group]) end end %w[fatal error warn info debug unknown].each do |severity| eval <<-EOM, nil, __FILE__, __LINE__ + 1 def #{severity}(message=nil, additional_fields={}) self.log(:#{severity}, message, additional_fields) end EOM end def enabled? enabled || false end private def new_logger(path) if path.is_a? String FileUtils.touch path # prevent autocreate messages in log end Logger.new path end end require 'logstasher/railtie' if defined?(Rails)
35.147059
125
0.73425
7a87d4cfba9e53714aa093caeb733e962d351e58
4,955
$:.unshift(File.expand_path('../../../lib', __FILE__)) require 'chef/config' require 'tempfile' require 'opscode/dark_launch' describe Opscode::DarkLaunch do before(:each) do Chef::Log.level = :fatal @valid_config_file = Tempfile.new("valid_dark_launch_config") @valid_config_file_contents = <<EOM { "feature1":[ "testorg1", "testorg2" ], "feature2":true, "feature3":false } EOM @valid_config_file.write @valid_config_file_contents @valid_config_file.close @malformed_config_file = Tempfile.new("malformed_dark_launch_config") @malformed_config_file.write <<EOM { "feature1":{ "testorg1":"true" } } EOM @malformed_config_file.close @bad_json_config_file = Tempfile.new("bad_json_dark_launch_config") @bad_json_config_file.write <<EOM this is not JSON EOM @bad_json_config_file.close # Reset the cache of features configuration Opscode::DarkLaunch.reset_features_config end after(:each) do @valid_config_file.delete @bad_json_config_file.delete @malformed_config_file.delete end describe "is_feature_enabled?" do it "should return true for an org which is in a properly-formed config file" do Chef::Config[:dark_launch_config_filename] = @valid_config_file.path Opscode::DarkLaunch.is_feature_enabled?("feature1", "testorg1").should == true end it "should cache the results of a feature config load after the first call" do Chef::Config[:dark_launch_config_filename] = @valid_config_file.path IO.should_receive(:read).exactly(1).times.with(@valid_config_file.path).and_return(@valid_config_file_contents) Opscode::DarkLaunch.is_feature_enabled?("feature1", "testorg1").should == true Opscode::DarkLaunch.is_feature_enabled?("feature1", "testorg1").should == true end it "should return false with a non-existent config file" do Chef::Config[:dark_launch_config_filename] = "/does_not_exist" Opscode::DarkLaunch.is_feature_enabled?("feature1", "testorg1").should == false end it "should return false if Chef::Config[:dark_launch_config_filename] isn't set" do Chef::Config.delete(:dark_launch_config_filename) Opscode::DarkLaunch.is_feature_enabled?("feature1", "testorg1").should == false end it "should not spam the log if called repeatedly with a non-existent config file" do Chef::Config[:dark_launch_config_filename] = "/does_not_exist" Chef::Log.should_receive(:error).at_most(:twice) 10.times do Opscode::DarkLaunch.is_feature_enabled?("feature1", "testorg1").should == false end end describe "when orgname is nil" do it "should return false for nil org and org-specific feature" do Chef::Config[:dark_launch_config_filename] = @valid_config_file.path Opscode::DarkLaunch.is_feature_enabled?("feature1", nil).should == false end it "should return true for nil org and globally enabled feature" do Chef::Config[:dark_launch_config_filename] = @valid_config_file.path Opscode::DarkLaunch.is_feature_enabled?("feature2", nil).should == true end it "should return false for nil org and globally disabled feature" do Chef::Config[:dark_launch_config_filename] = @valid_config_file.path Opscode::DarkLaunch.is_feature_enabled?("feature3", nil).should == false end end it "should return false for an org which is not in a properly-formed config file" do Chef::Config[:dark_launch_config_filename] = @valid_config_file.path Opscode::DarkLaunch.is_feature_enabled?("feature1", "testorg_notthere").should == false end it "should return false for a feature not in a properly-formed config file" do Chef::Config[:dark_launch_config_filename] = @valid_config_file.path Opscode::DarkLaunch.is_feature_enabled?("feature_notthere", "testorg1").should == false end it "should return false for a feature given an improperly-formed config file" do Chef::Config[:dark_launch_config_filename] = @malformed_config_file.path Opscode::DarkLaunch.is_feature_enabled?("feature1", "testorg1").should == false end it "should return false for a feature given an config file containing invalid JSON" do Chef::Config[:dark_launch_config_filename] = @bad_json_config_file.path Opscode::DarkLaunch.is_feature_enabled?("feature1", "testorg1").should == false end it "should return true for a feature that is switched on for all" do Chef::Config[:dark_launch_config_filename] = @valid_config_file.path Opscode::DarkLaunch.is_feature_enabled?("feature2", "anything").should == true end it "should return false for a feature that is switched off for all" do Chef::Config[:dark_launch_config_filename] = @valid_config_file.path Opscode::DarkLaunch.is_feature_enabled?("feature3", "anything").should == false end end end
38.115385
117
0.723108
085d39aef5db15d6ed60696920803d9f49947dc0
2,908
class LibtorrentRasterbar < Formula desc "C++ bittorrent library with Python bindings" homepage "https://www.libtorrent.org/" url "https://github.com/arvidn/libtorrent/releases/download/libtorrent_1_2_7/libtorrent-rasterbar-1.2.7.tar.gz" sha256 "bc00069e65c0825cbe1eee5cdd26f94fcd9a621c4e7f791810b12fab64192f00" bottle do cellar :any sha256 "ebcf3c671f25bf16e9643b647e2dff1339458d7b6b4e28fbde07e0e54abe29fd" => :catalina sha256 "68bd2a4ed0dd30a61b4bf5667eb21a01e3bc617a6bcb55a5ea5cdbea8954b50e" => :mojave sha256 "1f25a63a7e555b4f4c9f0491e363aa2ba8d5eb134dc3f65a1df6c60cc926c187" => :high_sierra sha256 "a0b0ed8190763fe9b2f5f31fe51a1d063c2a78d3a9d8827588f0b25392e7ca43" => :x86_64_linux end head do url "https://github.com/arvidn/libtorrent.git" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build end depends_on "pkg-config" => :build depends_on "boost" depends_on "boost-python3" depends_on "[email protected]" depends_on "[email protected]" conflicts_with "libtorrent-rakshasa", :because => "they both use the same libname" def install pyver = Language::Python.major_minor_version(Formula["[email protected]"].bin/"python3").to_s.delete(".") args = %W[ --disable-debug --disable-dependency-tracking --disable-silent-rules --prefix=#{prefix} --enable-encryption --enable-python-binding --with-boost=#{Formula["boost"].opt_prefix} --with-boost-python=boost_python#{pyver}-mt PYTHON=python3 PYTHON_EXTRA_LIBS=#{`#{Formula["[email protected]"].opt_bin}/python3-config --libs --embed`.chomp} PYTHON_EXTRA_LDFLAGS=#{`#{Formula["[email protected]"].opt_bin}/python3-config --ldflags`.chomp} ] if build.head? system "./bootstrap.sh", *args else system "./configure", *args end system "make", "install" rm Dir["examples/Makefile*"] libexec.install "examples" end test do if OS.mac? system ENV.cxx, "-std=c++11", "-I#{Formula["boost"].include}/boost", "-L#{lib}", "-ltorrent-rasterbar", "-L#{Formula["boost"].lib}", "-lboost_system", "-framework", "SystemConfiguration", "-framework", "CoreFoundation", libexec/"examples/make_torrent.cpp", "-o", "test" else system ENV.cxx, libexec/"examples/make_torrent.cpp", "-std=c++11", "-I#{Formula["boost"].include}/boost", "-L#{Formula["boost"].lib}", "-I#{include}", "-L#{lib}", "-lpthread", "-lboost_system", "-ltorrent-rasterbar", "-o", "test" end system "./test", test_fixtures("test.mp3"), "-o", "test.torrent" assert_predicate testpath/"test.torrent", :exist? end end
36.35
113
0.628267
4a9304f19cfe110b9b71ebe55d64b6692a8d0d6b
262
module GabeKossDotCom class SitemapHelper def self.sitemap_items(items) items.reject do |i| i[:is_hidden] || i.binary? || i.path == '/sitemap.xml' || !( i.identifier.scan(/\.json/).empty? ) end end end end
20.153846
47
0.553435
919785ceb88474ebdce2a620826a0c5ff2af4ee9
641
# Ignore Styles. # Illustration by George Brower. # # Shapes are loaded with style information that tells them how # to draw (the color, stroke weight, etc.) The disableStyle() # method of PShape turns off this information. The enableStyle() # method turns it back on. class DisableStyle < Processing::App def setup size 640, 360 smooth @bot = load_shape "bot1.svg" no_loop end def draw background 102 @bot.disable_style fill 0, 102, 153 stroke 255 shape @bot, 20, 25 @bot.enable_style shape @bot, 320, 25 end end DisableStyle.new :title => "Disable Style"
17.805556
64
0.656786
21b2d50fc3f07bfc3b5d85bddf825284f0b9a5c8
4,123
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) # Environment variables (ENV['...']) can be set in the file .env file. predicate_depositor = Hydramata::Works::Predicates::Storage.create!(identity: 'depositor') predicate_title = Hydramata::Works::Predicates::Storage.create!( identity: 'http://purl.org/dc/terms/title', namespace_context_name: 'dc:title', namespace_context_prefix: 'dc', namespace_context_url: 'http://purl.org/dc/terms/', name_for_application_usage: 'dc_title', value_parser_name: 'InterrogationParser', datastream_name: 'descMetadata', validations: '{ "presence_of_each": true }' ) predicate_attachment = Hydramata::Works::Predicates::Storage.create!( identity: 'opaque:file', name_for_application_usage: 'file', view_path_fragment: 'attachment', value_parser_name: 'AttachmentParser', value_presenter_class_name: 'AttachmentPresenter' ) predicate_abstract = Hydramata::Works::Predicates::Storage.create!( identity: 'http://purl.org/dc/terms/abstract', namespace_context_prefix: 'dc', namespace_context_name: 'dc:abstract', namespace_context_url: 'http://purl.org/dc/terms/', name_for_application_usage: 'dc_abstract', value_parser_name: 'InterrogationParser', datastream_name: 'descMetadata' ) predicate_contributor = Hydramata::Works::Predicates::Storage.create!( identity: 'http://purl.org/dc/terms/contributor', namespace_context_name: 'dc:contributor', namespace_context_prefix: 'dc', namespace_context_url: 'http://purl.org/dc/terms/', name_for_application_usage: 'dc_contributor', value_parser_name: 'Contributor', datastream_name: 'descMetadata' ) predicate_created = Hydramata::Works::Predicates::Storage.create!(identity: 'http://purl.org/dc/terms/created', name_for_application_usage: 'dc_created', value_parser_name: 'DateParser') predicate_language = Hydramata::Works::Predicates::Storage.create!(identity: 'http://purl.org/dc/terms/language', name_for_application_usage: 'dc_language', value_parser_name: 'InterrogationParser' ) predicate_publicher = Hydramata::Works::Predicates::Storage.create!(identity: 'http://purl.org/dc/terms/publisher', name_for_application_usage: 'dc_publisher', value_parser_name: 'InterrogationParser') predicate_dateSubmitted = Hydramata::Works::Predicates::Storage.create!(identity: 'http://purl.org/dc/terms/dateSubmitted', name_for_application_usage: 'dc_dateSubmitted', value_parser_name: 'DateParser') predicate_modified = Hydramata::Works::Predicates::Storage.create!(identity: 'http://purl.org/dc/terms/modified', name_for_application_usage: 'dc_modified', value_parser_name: 'DateParser') predicate_rights = Hydramata::Works::Predicates::Storage.create!(identity: 'http://purl.org/dc/terms/rights', name_for_application_usage: 'dc_rights', value_parser_name: 'InterrogationParser') ['document', 'article'].each do |identifier| work_type = Hydramata::Works::WorkTypes::Storage.create(identity: identifier, name_for_application_usage: identifier) predicate_set = Hydramata::Works::PredicateSets::Storage.create!(identity: 'required', work_type: work_type, presentation_sequence: 1, name_for_application_usage: 'required') predicate_set.predicate_presentation_sequences.create!(presentation_sequence: 1, predicate: predicate_title) optional_predicate_set = Hydramata::Works::PredicateSets::Storage.create!(identity: 'optional', work_type: work_type, presentation_sequence: 2, name_for_application_usage: 'optional') optional_predicate_set.predicate_presentation_sequences.create!(presentation_sequence: 1, predicate: predicate_abstract) optional_predicate_set.predicate_presentation_sequences.create!(presentation_sequence: 2, predicate: predicate_contributor) optional_predicate_set.predicate_presentation_sequences.create!(presentation_sequence: 3, predicate: predicate_attachment) end
62.469697
204
0.792142
1ad195922723ebb8e2555869f0182db534661b4b
290
execute "allow clicking by touch" do command "defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad Clicking 1" user WS_USER end execute "allow dragging by touch" do command "defaults write com.apple.driver.AppleBluetoothMultitouch.trackpad Dragging 1" user WS_USER end
32.222222
88
0.813793
3983cab001863790cf6a506be7fa0248f2e1b071
201
require_relative "phone_form" class ContactForm < Rectify::Form attribute :name, String attribute :number, String attribute :phones, Array[PhoneForm] validates :name, :presence => true end
20.1
37
0.746269
d5e5dd42f0dde15d51241d2449909a313be27e32
346
module TelefonicaHandle class MeteringDelegate < DelegateClass(Fog::Metering::TeleFonica) include TelefonicaHandle::HandledList include Vmdb::Logging SERVICE_NAME = "Metering" attr_reader :name def initialize(dobj, os_handle, name) super(dobj) @os_handle = os_handle @name = name end end end
20.352941
67
0.687861
e9d6e7e91e9155c108d00b90906bfdfe236ede78
991
class Gvars < Formula desc "Lightweight and simple configuration library for C++ programs." homepage "http://www.edwardrosten.com/cvd/gvars3.html" url "http://www.edwardrosten.com/cvd/gvars-3.0.tar.gz" sha256 "fc051961d4da5dce99a20f525dc1e98368f7283aed7b20e68ffb35e34ac3f5fa" license "BSD-2-Clause" head "https://github.com/edrosten/gvars.git" depends_on "pkg-config" => :build depends_on 'toon' => :recommended depends_on 'fltk' => :optional depends_on 'readline' def toonflags build.with?('toon') ? '--with-TooN' : '' end def fltkflags build.without?('fltk') ? '--disable-fltk' : '' end def install # Avoid superenv shim ENV["PKG_CONFIG"] = Formula["pkg-config"].bin/"pkg-config" system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}", toonflags, fltkflags system "make", "install" end end
30.96875
75
0.622603
d59305544701436b7d5a34d225c224d6a93cc183
3,796
# frozen_string_literal: true require 'spec_helper' require 'logstasher/active_record/log_subscriber' describe LogStasher::ActiveRecord::LogSubscriber do let(:log_output) { StringIO.new } let(:logger) do logger = Logger.new(log_output) logger.formatter = lambda { |_, _, _, msg| msg } def log_output.json JSON.parse! string end logger end before do LogStasher.logger = logger LogStasher.log_controller_parameters = true LogStasher.field_renaming = {} LogStasher::CustomFields.custom_fields = [] allow(described_class).to receive(:runtime).and_return(0) allow(described_class).to receive(:runtime=) end after do LogStasher.log_controller_parameters = false end let(:event) do ActiveSupport::Notifications::Event.new( 'identity.active_record', Time.now, Time.now, 1, { sql: 'SELECT * FROM nothing;' } ) end describe '.process_action' do let(:logger) { double } let(:json) do '{"sql":"SELECT * FROM nothing;","duration":0.0,"request_id":"1","source":"unknown","tags":["request"],"@timestamp":"1970-01-01T00:00:00.000Z","@version":"1"}' + "\n" end before do LogStasher.store.clear allow(LogStasher).to receive(:request_context).and_return({ request_id: '1' }) allow(LogStasher).to receive(:logger).and_return(logger) allow(Time).to receive(:now).and_return(Time.at(0)) end it 'calls all extractors and outputs the json' do expect(LogStasher.logger).to receive(:<<).with(json) subject.identity(event) end end describe 'logstasher output' do it 'should contain request tag' do subject.identity(event) expect(log_output.json['tags']).to eq ['request'] end it 'should contain identifier' do subject.identity(event) expect(log_output.json['sql']).to eq 'SELECT * FROM nothing;' end it 'should include duration time' do subject.identity(event) expect(log_output.json['duration']).to eq 0.00 end it 'should not contain :connection' do event.payload[:connection] = Object.new subject.identity(event) expect(event.payload[:connection]).not_to be_nil expect(log_output.json['connection']).to be_nil end end describe 'with append_custom_params block specified' do let(:request) { double(remote_ip: '10.0.0.1', env: {}) } it 'should add default custom data to the output' do allow(request).to receive_messages(params: { controller: 'home', action: 'index' }) LogStasher.add_default_fields_to_payload(event.payload.merge!(params: { foo: 'bar' }), request) subject.identity(event) expect(log_output.json['ip']).to eq '10.0.0.1' expect(log_output.json['route']).to eq 'home#index' expect(log_output.json['parameters']).to eq 'foo' => 'bar' end end describe 'with append_custom_params block specified' do before do allow(LogStasher).to receive(:add_custom_fields) do |&block| @block = block end LogStasher.add_custom_fields do |payload| payload[:user] = 'user' end LogStasher::CustomFields.custom_fields += [:user] end it 'should add the custom data to the output' do @block.call(event.payload) subject.identity(event) expect(log_output.json['user']).to eq 'user' end end describe 'db_runtime incrementing' do let(:event) do start = Time.now finish = Time.now + 1 ActiveSupport::Notifications::Event.new( 'identity.active_record', start, finish, 1, { sql: '' } ) end it 'should increment runtime by event duration' do expect(described_class).to receive(:runtime=).with(be_within(0.05).of(1000.0)) subject.identity(event) end end end
31.114754
172
0.66254
5d463b271665d6b24e2089c1ada3deabbd1b2bcc
1,341
Gem::Specification.new do |s| s.name = 'logstash-input-elasticsearch' s.version = '4.0.6' s.licenses = ['Apache License (2.0)'] s.summary = "Read from an Elasticsearch cluster, based on search query results" s.description = "This gem is a Logstash plugin required to be installed on top of the Logstash core pipeline using $LS_HOME/bin/logstash-plugin install gemname. This gem is not a stand-alone program" s.authors = ["Elastic"] s.email = '[email protected]' s.homepage = "http://www.elastic.co/guide/en/logstash/current/index.html" s.require_paths = ["lib"] # Files s.files = Dir["lib/**/*","spec/**/*","*.gemspec","*.md","CONTRIBUTORS","Gemfile","LICENSE","NOTICE.TXT", "vendor/jar-dependencies/**/*.jar", "vendor/jar-dependencies/**/*.rb", "VERSION", "docs/**/*"] # Tests s.test_files = s.files.grep(%r{^(test|spec|features)/}) # Special flag to let us know this is actually a logstash plugin s.metadata = { "logstash_plugin" => "true", "logstash_group" => "input" } # Gem dependencies s.add_runtime_dependency "logstash-core-plugin-api", ">= 1.60", "<= 2.99" s.add_runtime_dependency 'elasticsearch', ['>= 5.0.3', '< 6.0.0'] s.add_runtime_dependency 'logstash-codec-json' s.add_development_dependency 'logstash-devutils' end
43.258065
205
0.652498
339588735c30d55585a9a810823c7e9611bbe3c1
2,725
xml.instruct! xml.person do xml.identification @person.identification xml.lastname @person.last_name xml.firstnames @person.first_names xml.date_of_birth @person.date_of_birth xml.gender @person.gender xml.place_of_residence @person.municipality.to_s xml.type_of_residence @person.accommodation xml.language @person.language xml.nationality @person.nationality xml.education @person.education_to_s xml.disabilities @person.disabilities xml.contact_information do xml.email_address @person.email xml.phone_number @person.phone xml.street_address @person.address xml.postal_code @person.postcode.code xml.postal_address @person.postcode.name end xml.notes @person.notes xml.related_people do @person.relationships.each do |relationship| xml.related_person legal_guardian: relationship.legal_guardian? do xml.relationship relationship.relation.to_s xml.lastname relationship.parent.last_name xml.firstnames relationship.parent.first_names end end end xml.customer_records do @person.customers.at(current_unit).each do |customer| xml.customer_record do xml.timestamp customer.created_at xml.status customer.status xml.referring_party customer.referrer_to_s xml.personnel do customer.contacts.each do |contact| xml.contact_person contact end end xml.scheduled_events do customer.events.each do |event| xml.scheduled_event do xml.type event.event_type xml.title event.title xml.start_time event.starts_at xml.duration event.duration / 60, unit: 'minutes' end end end xml.milestones do customer.steps.each do |step| xml.milestone do xml.date step.reached_at xml.description step.milestone.to_s xml.notes step.notes end end end xml.internal_data do xml.notes do customer.notes.each do |note| xml.note do xml.timestamp note.created_at xml.title note.title xml.html do xml.cdata! note.content end end end end xml.reviews do customer.reviews.each do |review| xml.review do xml.timestamp review.created_at xml.title review.title xml.html do xml.cdata! review.content end end end end end end end end end
30.617978
72
0.61211
f78e8cb07483b03d69c479e490639ef920798120
496
cask '4k-video-downloader' do version '4.4.7.2307' sha256 '4aa585e4f89d3ffc80618518dc7950aed8bf16c07fcb3f77224b8b9fd9eec7a2' url "https://dl.4kdownload.com/app/4kvideodownloader_#{version.major_minor_patch}.dmg" appcast 'https://www.4kdownload.com/download', checkpoint: 'bc602309e88e5f0311dbad6bb4feaa37187e97aa2db120383b4e765347959bf8' name '4K Video Downloader' homepage 'https://www.4kdownload.com/products/product-videodownloader' app '4K Video Downloader.app' end
38.153846
88
0.794355
e2f04805c2ed3cf7f643c220a7d80b1302decf35
2,585
require 'pp' if defined?(RUBY_ENGINE) and RUBY_ENGINE == 'rbx' Object.const_set(:Compiler, Compile.compiler) require 'compiler/text' else $: << 'lib' require File.join(File.dirname(__FILE__), '..', 'compiler', 'mri_shim') end def record_block(data, block) record_seq data, block.dup 0.upto(block.size - 3) do |start| 2.upto(10) do |size| seq = block[start, size] record_seq data, seq if seq.size > 1 end end end def record_seq(data, seq) count = data[seq] if count data[seq] = count + 1 else data[seq] = 1 end end Terms = [:goto, :goto_if_false, :goto_if_true] def walk_stream(stream, data) seq = [] stream.each do |inst| seq << inst.first if Terms.include? inst.first if seq.size > 1 record_block data, seq end seq = [] end end record_block data, seq if seq.size > 1 end def update_data(stream, data, extra) stream.each_with_index do |inst, i| combo = [inst.first] extra.times do |x| next_inst = stream[i + x + 1] return unless next_inst combo << next_inst.first end count = data[combo] if count data[combo] = count + 1 else data[combo] = 1 end end end def describe_compiled_method(cm, data, max) extra = cm.literals.to_a.find_all { |l| l.kind_of? CompiledMethod } name = cm.name ? cm.name.inspect : 'anonymous' stream = cm.iseq.decode walk_stream stream, data =begin 2.upto(max) do |size| update_data stream, data[size], size - 1 end =end until extra.empty? sub = extra.shift describe_compiled_method(sub, data, max) extra += sub.literals.to_a.find_all { |l| l.kind_of? CompiledMethod } end end # Temporary workaround for Rubinius bug in __FILE__ paths if __FILE__.include?($0) then flags = [] file = nil while arg = ARGV.shift case arg when /-I(.+)/ then other_paths = $1[2..-1].split(":") other_paths.each { |n| $:.unshift n } when /-f(.+)/ then flags << $1 else file = arg break end end unless file interactive() exit 0 end require 'yaml' out = ARGV.shift or "analyze.yml" max = 10 puts "Gathering data on #{file}..." if File.exists?(out) data = Marshal.load File.read(out) else data = Hash.new =begin 2.upto(max) do |size| data[size] = Hash.new end =end end begin top = Compiler.compile_file(file, flags) describe_compiled_method(top, data, max) rescue SyntaxError exit 1 end File.open out, "w" do |f| f << Marshal.dump(data) end end
18.597122
73
0.621277
edf3545782ec3e83203fa8eeafa9402bbfac253e
1,223
require "abstract_unit" module ContentNegotiation # This has no layout and it works class BasicController < ActionController::Base self.view_paths = [ActionView::FixtureResolver.new( "content_negotiation/basic/hello.html.erb" => "Hello world <%= request.formats.first.to_s %>!" )] def all render plain: formats.inspect end end class TestContentNegotiation < Rack::TestCase test "A */* Accept header will return HTML" do get "/content_negotiation/basic/hello", headers: { "HTTP_ACCEPT" => "*/*" } assert_body "Hello world */*!" end test "A js or */* Accept header will return HTML" do get "/content_negotiation/basic/hello", headers: { "HTTP_ACCEPT" => "text/javascript, */*" } assert_body "Hello world text/html!" end test "A js or */* Accept header on xhr will return HTML" do get "/content_negotiation/basic/hello", headers: { "HTTP_ACCEPT" => "text/javascript, */*" }, xhr: true assert_body "Hello world text/javascript!" end test "Unregistered mimes are ignored" do get "/content_negotiation/basic/all", headers: { "HTTP_ACCEPT" => "text/plain, mime/another" } assert_body '[:text]' end end end
33.054054
109
0.663941
e8d4161af1ccf5143469de956191b3ca96fc0aca
2,661
class Sshguard < Formula desc "Protect from brute force attacks against SSH" homepage "http://www.sshguard.net/" url "https://downloads.sourceforge.net/project/sshguard/sshguard/1.6.0/sshguard-1.6.0.tar.xz" mirror "https://mirrors.kernel.org/debian/pool/main/s/sshguard/sshguard_1.6.0.orig.tar.xz" sha256 "dce32b1fc3fb0f8d15b6c56b9822c300434faaa87240e5373c095dc22bfa07e4" bottle do cellar :any sha256 "5fd4d11c40756356476a882a5ef8317ade15d163eb7b5b402e9b3e4474dbb1d7" => :yosemite sha256 "e272de3bb7284d8dfb930295d0dc310666bcf807356d9af80b31e2e6e4bd5a7e" => :mavericks sha256 "16d633776b9b44032a3c3067851217193fdd7e2984ae881d7aece14cca772b13" => :mountain_lion end depends_on "automake" => :build depends_on "autoconf" => :build # Fix blacklist flag (-b) so that it doesn't abort on first usage. # Upstream bug report: # http://sourceforge.net/tracker/?func=detail&aid=3252151&group_id=188282&atid=924685 patch do url "http://sourceforge.net/p/sshguard/bugs/_discuss/thread/3d94b7ef/c062/attachment/sshguard.c.diff" sha1 "68cd0910d310e4d23e7752dee1b077ccfe715c0b" end def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}", "--with-firewall=#{firewall}" system "make", "install" end def firewall MacOS.version >= :lion ? "pf" : "ipfw" end def log_path MacOS.version >= :lion ? "/var/log/system.log" : "/var/log/secure.log" end def caveats if MacOS.version >= :lion then <<-EOS.undent Add the following lines to /etc/pf.conf to block entries in the sshguard table (replace $ext_if with your WAN interface): table <sshguard> persist block in quick on $ext_if proto tcp from <sshguard> to any port 22 label "ssh bruteforce" Then run sudo pfctl -f /etc/pf.conf to reload the rules. EOS end end plist_options :startup => true def plist; <<-EOS.undent <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>KeepAlive</key> <true/> <key>ProgramArguments</key> <array> <string>#{opt_sbin}/sshguard</string> <string>-l</string> <string>#{log_path}</string> </array> <key>RunAtLoad</key> <true/> </dict> </plist> EOS end test do assert_match version.to_s, shell_output("#{sbin}/sshguard -v 2>&1", 1) end end
32.060241
106
0.662157
6aa762c5cabb45f1b779ce92c1627d7eb1e40fe6
5,243
require File.dirname(__FILE__) + '/spec_helper' require 'rack/mock' require 'rack/contrib/response_cache' require 'fileutils' context Rack::ResponseCache do F = ::File def request(opts={}, &block) Rack::MockRequest.new(Rack::ResponseCache.new(block||@def_app, opts[:cache]||@cache, &opts[:rc_block])).send(opts[:meth]||:get, opts[:path]||@def_path, opts[:headers]||{}) end setup do @cache = {} @def_disk_cache = F.join(F.dirname(__FILE__), 'response_cache_test_disk_cache') @def_value = ["rack-response-cache"] @def_path = '/path/to/blah' @def_app = lambda { |env| [200, {'Content-Type' => env['CT'] || 'text/html'}, @def_value]} end teardown do FileUtils.rm_rf(@def_disk_cache) end specify "should cache results to disk if cache is a string" do request(:cache=>@def_disk_cache) F.read(F.join(@def_disk_cache, 'path', 'to', 'blah.html')).should.equal @def_value.first request(:path=>'/path/3', :cache=>@def_disk_cache) F.read(F.join(@def_disk_cache, 'path', '3.html')).should.equal @def_value.first end specify "should cache results to given cache if cache is not a string" do request @cache.should.equal('/path/to/blah.html'=>@def_value) request(:path=>'/path/3') @cache.should.equal('/path/to/blah.html'=>@def_value, '/path/3.html'=>@def_value) end specify "should not CACHE RESults if request method is not GET" do request(:meth=>:post) @cache.should.equal({}) request(:meth=>:put) @cache.should.equal({}) request(:meth=>:delete) @cache.should.equal({}) end specify "should not cache results if there is a query string" do request(:path=>'/path/to/blah?id=1') @cache.should.equal({}) request(:path=>'/path/to/?id=1') @cache.should.equal({}) request(:path=>'/?id=1') @cache.should.equal({}) end specify "should cache results if there is an empty query string" do request(:path=>'/?') @cache.should.equal('/index.html'=>@def_value) end specify "should not cache results if the request is not sucessful (status 200)" do request{|env| [404, {'Content-Type' => 'text/html'}, ['']]} @cache.should.equal({}) request{|env| [500, {'Content-Type' => 'text/html'}, ['']]} @cache.should.equal({}) request{|env| [302, {'Content-Type' => 'text/html'}, ['']]} @cache.should.equal({}) end specify "should not cache results if the block returns nil or false" do request(:rc_block=>proc{false}) @cache.should.equal({}) request(:rc_block=>proc{nil}) @cache.should.equal({}) end specify "should cache results to path returned by block" do request(:rc_block=>proc{"1"}) @cache.should.equal("1"=>@def_value) request(:rc_block=>proc{"2"}) @cache.should.equal("1"=>@def_value, "2"=>@def_value) end specify "should pass the environment and response to the block" do e, r = nil, nil request(:rc_block=>proc{|env,res| e, r = env, res; nil}) e['PATH_INFO'].should.equal @def_path e['REQUEST_METHOD'].should.equal 'GET' e['QUERY_STRING'].should.equal '' r.should.equal([200, {"Content-Type"=>"text/html"}, ["rack-response-cache"]]) end specify "should unescape the path by default" do request(:path=>'/path%20with%20spaces') @cache.should.equal('/path with spaces.html'=>@def_value) request(:path=>'/path%3chref%3e') @cache.should.equal('/path with spaces.html'=>@def_value, '/path<href>.html'=>@def_value) end specify "should cache html, css, and xml responses by default" do request(:path=>'/a') @cache.should.equal('/a.html'=>@def_value) request(:path=>'/b', :headers=>{'CT'=>'text/xml'}) @cache.should.equal('/a.html'=>@def_value, '/b.xml'=>@def_value) request(:path=>'/c', :headers=>{'CT'=>'text/css'}) @cache.should.equal('/a.html'=>@def_value, '/b.xml'=>@def_value, '/c.css'=>@def_value) end specify "should cache responses by default with the extension added if not already present" do request(:path=>'/a.html') @cache.should.equal('/a.html'=>@def_value) request(:path=>'/b.xml', :headers=>{'CT'=>'text/xml'}) @cache.should.equal('/a.html'=>@def_value, '/b.xml'=>@def_value) request(:path=>'/c.css', :headers=>{'CT'=>'text/css'}) @cache.should.equal('/a.html'=>@def_value, '/b.xml'=>@def_value, '/c.css'=>@def_value) end specify "should not delete existing extensions" do request(:path=>'/d.css', :headers=>{'CT'=>'text/html'}) @cache.should.equal('/d.css.html'=>@def_value) end specify "should cache html responses with empty basename to index.html by default" do request(:path=>'/') @cache.should.equal('/index.html'=>@def_value) request(:path=>'/blah/') @cache.should.equal('/index.html'=>@def_value, '/blah/index.html'=>@def_value) request(:path=>'/blah/2/') @cache.should.equal('/index.html'=>@def_value, '/blah/index.html'=>@def_value, '/blah/2/index.html'=>@def_value) end specify "should raise an error if a cache argument is not provided" do app = Rack::Builder.new{use Rack::ResponseCache; run lambda { |env| [200, {'Content-Type' => 'text/plain'}, Rack::Request.new(env).POST]}} proc{Rack::MockRequest.new(app).get('/')}.should.raise(ArgumentError) end end
37.992754
175
0.646958
1a8365736ab610e97773441686cd2b742f377395
148
class CreateBlogs < ActiveRecord::Migration def change create_table :blogs do |t| t.string :title t.timestamps end end end
14.8
43
0.662162
3819ef07292459b2b849495aa6d2064e35e8e841
3,028
# frozen_string_literal: true require 'commonmarker' module GraphQLDocs module Helpers SLUGIFY_PRETTY_REGEXP = Regexp.new("[^[:alnum:]._~!$&'()+,;=@]+").freeze attr_accessor :templates def slugify(str) slug = str.gsub(SLUGIFY_PRETTY_REGEXP, '-') slug.gsub!(%r!^\-|\-$!i, '') slug.downcase end def include(filename, opts = {}) template = fetch_include(filename) opts = { base_url: @options[:base_url], classes: @options[:classes] }.merge(opts) template.result(OpenStruct.new(opts.merge(helper_methods)).instance_eval { binding }) end def markdownify(string) return '' if string.nil? type = @options[:pipeline_config][:context][:unsafe] ? :UNSAFE : :DEFAULT ::CommonMarker.render_html(string, type).strip end def graphql_root_types @parsed_schema[:root_types] || [] end def graphql_operation_types @parsed_schema[:operation_types] || [] end def graphql_mutation_types @parsed_schema[:mutation_types] || [] end def graphql_object_types @parsed_schema[:object_types] || [] end def graphql_interface_types @parsed_schema[:interface_types] || [] end def graphql_enum_types @parsed_schema[:enum_types] || [] end def graphql_union_types @parsed_schema[:union_types] || [] end def graphql_input_object_types @parsed_schema[:input_object_types] || [] end def graphql_scalar_types @parsed_schema[:scalar_types] || [] end def graphql_directive_types @parsed_schema[:directive_types] || [] end def split_into_metadata_and_contents(contents, parse: true) opts = {} pieces = yaml_split(contents) if pieces.size < 4 raise RuntimeError.new( "The file '#{content_filename}' appears to start with a metadata section (three or five dashes at the top) but it does not seem to be in the correct format.", ) end # Parse begin if parse meta = YAML.load(pieces[2]) || {} else meta = pieces[2] end rescue Exception => e # rubocop:disable Lint/RescueException raise "Could not parse YAML for #{name}: #{e.message}" end [meta, pieces[4]] end def has_yaml?(contents) contents =~ /\A-{3,5}\s*$/ end def yaml_split(contents) contents.split(/^(-{5}|-{3})[ \t]*\r?\n?/, 3) end private def fetch_include(filename) @templates ||= {} return @templates[filename] unless @templates[filename].nil? contents = File.read(File.join(@options[:templates][:includes], filename)) @templates[filename] = ERB.new(contents) end def helper_methods return @helper_methods if defined?(@helper_methods) @helper_methods = {} Helpers.instance_methods.each do |name| next if name == :helper_methods @helper_methods[name] = method(name) end @helper_methods end end end
24.419355
168
0.623184
bb5e19740d7714a2060c408c60c7972dd45d27bd
461
cask :v1 => 'detect-crop' do version '5.4' sha256 'cfcf3d492b13d22c15ea9566364592a6b1e193a798bd7eca7e348681318f0dbb' url 'https://github.com/donmelton/video-transcoding-scripts/archive/master.zip' name 'Video Transcoding Scripts' homepage 'https://github.com/donmelton/video-transcoding-scripts/' license :mit binary 'video-transcoding-scripts-master/detect-crop.sh' depends_on :cask => 'handbrakecli', :formula => 'mplayer' end
30.733333
81
0.744035
b92e332fdbb6feee09431926c53e9e7a7c376b54
2,134
# This command does some automation with the _drafts folder. Specifically, # when run, it: # # * Copies every file from _drafts into _posts, into my preferred folder # structure (one folder per year) # * Creates a Git commit for the change # * Pushes said Git commit to GitHub # # It gets copied directly into the Docker container, rather than being # installed as a gem, because installing local gems adds a whole extra layer # of complication that I don't want right now. require 'fileutils' require 'shell/executer.rb' class PublishDrafts < Jekyll::Command class << self def init_with_program(prog) prog.command(:publish_drafts) do |cmd| cmd.action do |_, options| options = configuration_from_options(options) publish_drafts(options["source"]) end end end def publish_drafts(source_dir) puts "*** Publishing drafts" Dir.chdir(source_dir) do drafts_dir = "_drafts" tracked_drafts = `git ls-tree --name-only HEAD #{drafts_dir}/`.split("\n") if tracked_drafts.empty? puts "*** No drafts to publish!" end now = Time.now tracked_drafts.each do |entry| puts "*** Publishing draft post #{entry}" name = File.basename(entry) new_name = File.join("_posts", now.strftime("%Y"), "#{now.strftime('%Y-%m-%d')}-#{name}") FileUtils.mkdir_p File.dirname(new_name) File.rename(entry, new_name) # Now we write the exact date and time into the top of the file. # This means that if I publish more than one post on the same day, # they have an unambiguous ordering. doc = File.read(new_name) doc = doc.gsub( /layout:\s+post\s*\n/, "layout: post\ndate: #{now}\n") File.open(new_name, 'w') { |f| f.write(doc) } puts "*** Creating Git commit for #{entry}" Shell.execute!("git rm #{entry}") Shell.execute!("git add #{new_name}") Shell.execute!("git commit -m \"Publish new post #{name}\"") end end end end end
31.850746
99
0.613402
87e7296bdb19d0b8a726e7a4e6f122fd8aa9ff33
762
require "rails/generators" module Clubhouse module Generators class InstallGenerator < Rails::Generators::Base source_root File.expand_path("../templates", __FILE__) def install_migrations Dir.chdir(Rails.root) { `rake clubhouse:install:migrations` } end def mount inject_into_file "config/routes.rb", after: "Rails.application.routes.draw do\n" do " mount Clubhouse::Engine => \"/\"\n\n" end end def inject_into_member_model inject_into_class "app/models/user.rb", User do " include Clubhouse::Memberable\n\n" end end def create_initializer copy_file "initializer.rb", "config/initializers/clubhouse.rb" end end end end
25.4
91
0.645669
e2bb2ee0244c0cd55f0e04e0d9c26473d37d2c16
246
describe Fastlane::Actions::FigletAction do describe '#run' do it 'prints a message' do expect(Fastlane::UI).to receive(:message).with("The figlet plugin is working!") Fastlane::Actions::FigletAction.run(nil) end end end
24.6
85
0.691057
39c9c74c9467b4c07e1bb5821a415a027735b0bb
27,466
require 'abstract_unit' require 'pp' module ModuleWithMissing mattr_accessor :missing_count def self.const_missing(name) self.missing_count += 1 name end end module ModuleWithConstant InheritedConstant = "Hello" end class DependenciesTest < Test::Unit::TestCase def teardown ActiveSupport::Dependencies.clear end def with_loading(*from) old_mechanism, ActiveSupport::Dependencies.mechanism = ActiveSupport::Dependencies.mechanism, :load dir = File.dirname(__FILE__) prior_load_paths = ActiveSupport::Dependencies.load_paths ActiveSupport::Dependencies.load_paths = from.collect { |f| "#{dir}/#{f}" } yield ensure ActiveSupport::Dependencies.load_paths = prior_load_paths ActiveSupport::Dependencies.mechanism = old_mechanism ActiveSupport::Dependencies.explicitly_unloadable_constants = [] end def test_tracking_loaded_files require_dependency 'dependencies/service_one' require_dependency 'dependencies/service_two' assert_equal 2, ActiveSupport::Dependencies.loaded.size end def test_tracking_identical_loaded_files require_dependency 'dependencies/service_one' require_dependency 'dependencies/service_one' assert_equal 1, ActiveSupport::Dependencies.loaded.size end def test_missing_dependency_raises_missing_source_file assert_raises(MissingSourceFile) { require_dependency("missing_service") } end def test_missing_association_raises_nothing assert_nothing_raised { require_association("missing_model") } end def test_dependency_which_raises_exception_isnt_added_to_loaded_set with_loading do filename = 'dependencies/raises_exception' $raises_exception_load_count = 0 5.times do |count| begin require_dependency filename flunk 'should have loaded dependencies/raises_exception which raises an exception' rescue Exception => e assert_equal 'Loading me failed, so do not add to loaded or history.', e.message end assert_equal count + 1, $raises_exception_load_count assert !ActiveSupport::Dependencies.loaded.include?(filename) assert !ActiveSupport::Dependencies.history.include?(filename) end end end def test_warnings_should_be_enabled_on_first_load with_loading 'dependencies' do old_warnings, ActiveSupport::Dependencies.warnings_on_first_load = ActiveSupport::Dependencies.warnings_on_first_load, true filename = "check_warnings" expanded = File.expand_path("test/dependencies/#{filename}") $check_warnings_load_count = 0 assert !ActiveSupport::Dependencies.loaded.include?(expanded) assert !ActiveSupport::Dependencies.history.include?(expanded) silence_warnings { require_dependency filename } assert_equal 1, $check_warnings_load_count assert_equal true, $checked_verbose, 'On first load warnings should be enabled.' assert ActiveSupport::Dependencies.loaded.include?(expanded) ActiveSupport::Dependencies.clear assert !ActiveSupport::Dependencies.loaded.include?(expanded) assert ActiveSupport::Dependencies.history.include?(expanded) silence_warnings { require_dependency filename } assert_equal 2, $check_warnings_load_count assert_equal nil, $checked_verbose, 'After first load warnings should be left alone.' assert ActiveSupport::Dependencies.loaded.include?(expanded) ActiveSupport::Dependencies.clear assert !ActiveSupport::Dependencies.loaded.include?(expanded) assert ActiveSupport::Dependencies.history.include?(expanded) enable_warnings { require_dependency filename } assert_equal 3, $check_warnings_load_count assert_equal true, $checked_verbose, 'After first load warnings should be left alone.' assert ActiveSupport::Dependencies.loaded.include?(expanded) end end def test_mutual_dependencies_dont_infinite_loop with_loading 'dependencies' do $mutual_dependencies_count = 0 assert_nothing_raised { require_dependency 'mutual_one' } assert_equal 2, $mutual_dependencies_count ActiveSupport::Dependencies.clear $mutual_dependencies_count = 0 assert_nothing_raised { require_dependency 'mutual_two' } assert_equal 2, $mutual_dependencies_count end end def test_as_load_path assert_equal '', DependenciesTest.as_load_path end def test_module_loading with_loading 'autoloading_fixtures' do assert_kind_of Module, A assert_kind_of Class, A::B assert_kind_of Class, A::C::D assert_kind_of Class, A::C::E::F end end def test_non_existing_const_raises_name_error with_loading 'autoloading_fixtures' do assert_raises(NameError) { DoesNotExist } assert_raises(NameError) { NoModule::DoesNotExist } assert_raises(NameError) { A::DoesNotExist } assert_raises(NameError) { A::B::DoesNotExist } end end def test_directories_manifest_as_modules_unless_const_defined with_loading 'autoloading_fixtures' do assert_kind_of Module, ModuleFolder Object.send! :remove_const, :ModuleFolder end end def test_module_with_nested_class with_loading 'autoloading_fixtures' do assert_kind_of Class, ModuleFolder::NestedClass Object.send! :remove_const, :ModuleFolder end end def test_module_with_nested_inline_class with_loading 'autoloading_fixtures' do assert_kind_of Class, ModuleFolder::InlineClass Object.send! :remove_const, :ModuleFolder end end def test_directories_may_manifest_as_nested_classes with_loading 'autoloading_fixtures' do assert_kind_of Class, ClassFolder Object.send! :remove_const, :ClassFolder end end def test_class_with_nested_class with_loading 'autoloading_fixtures' do assert_kind_of Class, ClassFolder::NestedClass Object.send! :remove_const, :ClassFolder end end def test_class_with_nested_inline_class with_loading 'autoloading_fixtures' do assert_kind_of Class, ClassFolder::InlineClass Object.send! :remove_const, :ClassFolder end end def test_class_with_nested_inline_subclass_of_parent with_loading 'autoloading_fixtures' do assert_kind_of Class, ClassFolder::ClassFolderSubclass assert_kind_of Class, ClassFolder assert_equal 'indeed', ClassFolder::ClassFolderSubclass::ConstantInClassFolder Object.send! :remove_const, :ClassFolder end end def test_nested_class_can_access_sibling with_loading 'autoloading_fixtures' do sibling = ModuleFolder::NestedClass.class_eval "NestedSibling" assert defined?(ModuleFolder::NestedSibling) assert_equal ModuleFolder::NestedSibling, sibling Object.send! :remove_const, :ModuleFolder end end def failing_test_access_thru_and_upwards_fails with_loading 'autoloading_fixtures' do assert ! defined?(ModuleFolder) assert_raises(NameError) { ModuleFolder::Object } assert_raises(NameError) { ModuleFolder::NestedClass::Object } Object.send! :remove_const, :ModuleFolder end end def test_non_existing_const_raises_name_error_with_fully_qualified_name with_loading 'autoloading_fixtures' do begin A::DoesNotExist.nil? flunk "No raise!!" rescue NameError => e assert_equal "uninitialized constant A::DoesNotExist", e.message end begin A::B::DoesNotExist.nil? flunk "No raise!!" rescue NameError => e assert_equal "uninitialized constant A::B::DoesNotExist", e.message end end end def test_smart_name_error_strings begin Object.module_eval "ImaginaryObject" flunk "No raise!!" rescue NameError => e assert e.message.include?("uninitialized constant ImaginaryObject") end end def test_loadable_constants_for_path_should_handle_empty_autoloads assert_equal [], ActiveSupport::Dependencies.loadable_constants_for_path('hello') end def test_loadable_constants_for_path_should_handle_relative_paths fake_root = 'dependencies' relative_root = File.dirname(__FILE__) + '/dependencies' ['', '/'].each do |suffix| with_loading fake_root + suffix do assert_equal ["A::B"], ActiveSupport::Dependencies.loadable_constants_for_path(relative_root + '/a/b') end end end def test_loadable_constants_for_path_should_provide_all_results fake_root = '/usr/apps/backpack' with_loading fake_root, fake_root + '/lib' do root = ActiveSupport::Dependencies.load_paths.first assert_equal ["Lib::A::B", "A::B"], ActiveSupport::Dependencies.loadable_constants_for_path(root + '/lib/a/b') end end def test_loadable_constants_for_path_should_uniq_results fake_root = '/usr/apps/backpack/lib' with_loading fake_root, fake_root + '/' do root = ActiveSupport::Dependencies.load_paths.first assert_equal ["A::B"], ActiveSupport::Dependencies.loadable_constants_for_path(root + '/a/b') end end def test_loadable_constants_with_load_path_without_trailing_slash path = File.dirname(__FILE__) + '/autoloading_fixtures/class_folder/inline_class.rb' with_loading 'autoloading_fixtures/class/' do assert_equal [], ActiveSupport::Dependencies.loadable_constants_for_path(path) end end def test_qualified_const_defined assert ActiveSupport::Dependencies.qualified_const_defined?("Object") assert ActiveSupport::Dependencies.qualified_const_defined?("::Object") assert ActiveSupport::Dependencies.qualified_const_defined?("::Object::Kernel") assert ActiveSupport::Dependencies.qualified_const_defined?("::Object::Dependencies") assert ActiveSupport::Dependencies.qualified_const_defined?("::Test::Unit::TestCase") end def test_qualified_const_defined_should_not_call_method_missing ModuleWithMissing.missing_count = 0 assert ! ActiveSupport::Dependencies.qualified_const_defined?("ModuleWithMissing::A") assert_equal 0, ModuleWithMissing.missing_count assert ! ActiveSupport::Dependencies.qualified_const_defined?("ModuleWithMissing::A::B") assert_equal 0, ModuleWithMissing.missing_count end def test_autoloaded? with_loading 'autoloading_fixtures' do assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder") assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass") assert ActiveSupport::Dependencies.autoloaded?(ModuleFolder) assert ActiveSupport::Dependencies.autoloaded?("ModuleFolder") assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass") assert ActiveSupport::Dependencies.autoloaded?(ModuleFolder::NestedClass) assert ActiveSupport::Dependencies.autoloaded?("ModuleFolder") assert ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass") assert ActiveSupport::Dependencies.autoloaded?("::ModuleFolder") assert ActiveSupport::Dependencies.autoloaded?(:ModuleFolder) # Anonymous modules aren't autoloaded. assert !ActiveSupport::Dependencies.autoloaded?(Module.new) nil_name = Module.new def nil_name.name() nil end assert !ActiveSupport::Dependencies.autoloaded?(nil_name) Object.class_eval { remove_const :ModuleFolder } end end def test_qualified_name_for assert_equal "A", ActiveSupport::Dependencies.qualified_name_for(Object, :A) assert_equal "A", ActiveSupport::Dependencies.qualified_name_for(:Object, :A) assert_equal "A", ActiveSupport::Dependencies.qualified_name_for("Object", :A) assert_equal "A", ActiveSupport::Dependencies.qualified_name_for("::Object", :A) assert_equal "A", ActiveSupport::Dependencies.qualified_name_for("::Kernel", :A) assert_equal "ActiveSupport::Dependencies::A", ActiveSupport::Dependencies.qualified_name_for(:'ActiveSupport::Dependencies', :A) assert_equal "ActiveSupport::Dependencies::A", ActiveSupport::Dependencies.qualified_name_for(ActiveSupport::Dependencies, :A) end def test_file_search with_loading 'dependencies' do root = ActiveSupport::Dependencies.load_paths.first assert_equal nil, ActiveSupport::Dependencies.search_for_file('service_three') assert_equal nil, ActiveSupport::Dependencies.search_for_file('service_three.rb') assert_equal root + '/service_one.rb', ActiveSupport::Dependencies.search_for_file('service_one') assert_equal root + '/service_one.rb', ActiveSupport::Dependencies.search_for_file('service_one.rb') end end def test_file_search_uses_first_in_load_path with_loading 'dependencies', 'autoloading_fixtures' do deps, autoload = ActiveSupport::Dependencies.load_paths assert_match %r/dependencies/, deps assert_match %r/autoloading_fixtures/, autoload assert_equal deps + '/conflict.rb', ActiveSupport::Dependencies.search_for_file('conflict') end with_loading 'autoloading_fixtures', 'dependencies' do autoload, deps = ActiveSupport::Dependencies.load_paths assert_match %r/dependencies/, deps assert_match %r/autoloading_fixtures/, autoload assert_equal autoload + '/conflict.rb', ActiveSupport::Dependencies.search_for_file('conflict') end end def test_custom_const_missing_should_work Object.module_eval <<-end_eval module ModuleWithCustomConstMissing def self.const_missing(name) const_set name, name.to_s.hash end module A end end end_eval with_loading 'autoloading_fixtures' do assert_kind_of Integer, ::ModuleWithCustomConstMissing::B assert_kind_of Module, ::ModuleWithCustomConstMissing::A assert_kind_of String, ::ModuleWithCustomConstMissing::A::B end end def test_const_missing_should_not_double_load $counting_loaded_times = 0 with_loading 'autoloading_fixtures' do require_dependency '././counting_loader' assert_equal 1, $counting_loaded_times assert_raises(ArgumentError) { ActiveSupport::Dependencies.load_missing_constant Object, :CountingLoader } assert_equal 1, $counting_loaded_times end end def test_const_missing_within_anonymous_module $counting_loaded_times = 0 m = Module.new m.module_eval "def a() CountingLoader; end" extend m kls = nil with_loading 'autoloading_fixtures' do kls = nil assert_nothing_raised { kls = a } assert_equal "CountingLoader", kls.name assert_equal 1, $counting_loaded_times assert_nothing_raised { kls = a } assert_equal 1, $counting_loaded_times end end def test_removal_from_tree_should_be_detected with_loading 'dependencies' do root = ActiveSupport::Dependencies.load_paths.first c = ServiceOne ActiveSupport::Dependencies.clear assert ! defined?(ServiceOne) begin ActiveSupport::Dependencies.load_missing_constant(c, :FakeMissing) flunk "Expected exception" rescue ArgumentError => e assert_match %r{ServiceOne has been removed from the module tree}i, e.message end end end def test_nested_load_error_isnt_rescued with_loading 'dependencies' do assert_raises(MissingSourceFile) do RequiresNonexistent1 end end end def test_load_once_paths_do_not_add_to_autoloaded_constants with_loading 'autoloading_fixtures' do ActiveSupport::Dependencies.load_once_paths = ActiveSupport::Dependencies.load_paths.dup assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder") assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass") assert ! ActiveSupport::Dependencies.autoloaded?(ModuleFolder) 1 if ModuleFolder::NestedClass # 1 if to avoid warning assert ! ActiveSupport::Dependencies.autoloaded?(ModuleFolder::NestedClass) end ensure Object.class_eval { remove_const :ModuleFolder } ActiveSupport::Dependencies.load_once_paths = [] end def test_application_should_special_case_application_controller with_loading 'autoloading_fixtures' do require_dependency 'application' assert_equal 10, ApplicationController assert ActiveSupport::Dependencies.autoloaded?(:ApplicationController) end end def test_const_missing_on_kernel_should_fallback_to_object with_loading 'autoloading_fixtures' do kls = Kernel::E assert_equal "E", kls.name assert_equal kls.object_id, Kernel::E.object_id end end def test_preexisting_constants_are_not_marked_as_autoloaded with_loading 'autoloading_fixtures' do require_dependency 'e' assert ActiveSupport::Dependencies.autoloaded?(:E) ActiveSupport::Dependencies.clear end Object.const_set :E, Class.new with_loading 'autoloading_fixtures' do require_dependency 'e' assert ! ActiveSupport::Dependencies.autoloaded?(:E), "E shouldn't be marked autoloaded!" ActiveSupport::Dependencies.clear end ensure Object.class_eval { remove_const :E } end def test_unloadable with_loading 'autoloading_fixtures' do Object.const_set :M, Module.new M.unloadable ActiveSupport::Dependencies.clear assert ! defined?(M) Object.const_set :M, Module.new ActiveSupport::Dependencies.clear assert ! defined?(M), "Dependencies should unload unloadable constants each time" end end def test_unloadable_should_fail_with_anonymous_modules with_loading 'autoloading_fixtures' do m = Module.new assert_raises(ArgumentError) { m.unloadable } end end def test_unloadable_should_return_change_flag with_loading 'autoloading_fixtures' do Object.const_set :M, Module.new assert_equal true, M.unloadable assert_equal false, M.unloadable end end def test_new_contants_in_without_constants assert_equal [], (ActiveSupport::Dependencies.new_constants_in(Object) { }) assert ActiveSupport::Dependencies.constant_watch_stack.empty? end def test_new_constants_in_with_a_single_constant assert_equal ["Hello"], ActiveSupport::Dependencies.new_constants_in(Object) { Object.const_set :Hello, 10 }.map(&:to_s) assert ActiveSupport::Dependencies.constant_watch_stack.empty? ensure Object.class_eval { remove_const :Hello } end def test_new_constants_in_with_nesting outer = ActiveSupport::Dependencies.new_constants_in(Object) do Object.const_set :OuterBefore, 10 assert_equal ["Inner"], ActiveSupport::Dependencies.new_constants_in(Object) { Object.const_set :Inner, 20 }.map(&:to_s) Object.const_set :OuterAfter, 30 end assert_equal ["OuterAfter", "OuterBefore"], outer.sort.map(&:to_s) assert ActiveSupport::Dependencies.constant_watch_stack.empty? ensure %w(OuterBefore Inner OuterAfter).each do |name| Object.class_eval { remove_const name if const_defined?(name) } end end def test_new_constants_in_module Object.const_set :M, Module.new outer = ActiveSupport::Dependencies.new_constants_in(M) do M.const_set :OuterBefore, 10 inner = ActiveSupport::Dependencies.new_constants_in(M) do M.const_set :Inner, 20 end assert_equal ["M::Inner"], inner M.const_set :OuterAfter, 30 end assert_equal ["M::OuterAfter", "M::OuterBefore"], outer.sort assert ActiveSupport::Dependencies.constant_watch_stack.empty? ensure Object.class_eval { remove_const :M } end def test_new_constants_in_module_using_name outer = ActiveSupport::Dependencies.new_constants_in(:M) do Object.const_set :M, Module.new M.const_set :OuterBefore, 10 inner = ActiveSupport::Dependencies.new_constants_in(:M) do M.const_set :Inner, 20 end assert_equal ["M::Inner"], inner M.const_set :OuterAfter, 30 end assert_equal ["M::OuterAfter", "M::OuterBefore"], outer.sort assert ActiveSupport::Dependencies.constant_watch_stack.empty? ensure Object.class_eval { remove_const :M } end def test_new_constants_in_with_inherited_constants m = ActiveSupport::Dependencies.new_constants_in(:Object) do Object.class_eval { include ModuleWithConstant } end assert_equal [], m end def test_new_constants_in_with_illegal_module_name_raises_correct_error assert_raises(NameError) do ActiveSupport::Dependencies.new_constants_in("Illegal-Name") {} end end def test_file_with_multiple_constants_and_require_dependency with_loading 'autoloading_fixtures' do assert ! defined?(MultipleConstantFile) assert ! defined?(SiblingConstant) require_dependency 'multiple_constant_file' assert defined?(MultipleConstantFile) assert defined?(SiblingConstant) assert ActiveSupport::Dependencies.autoloaded?(:MultipleConstantFile) assert ActiveSupport::Dependencies.autoloaded?(:SiblingConstant) ActiveSupport::Dependencies.clear assert ! defined?(MultipleConstantFile) assert ! defined?(SiblingConstant) end end def test_file_with_multiple_constants_and_auto_loading with_loading 'autoloading_fixtures' do assert ! defined?(MultipleConstantFile) assert ! defined?(SiblingConstant) assert_equal 10, MultipleConstantFile assert defined?(MultipleConstantFile) assert defined?(SiblingConstant) assert ActiveSupport::Dependencies.autoloaded?(:MultipleConstantFile) assert ActiveSupport::Dependencies.autoloaded?(:SiblingConstant) ActiveSupport::Dependencies.clear assert ! defined?(MultipleConstantFile) assert ! defined?(SiblingConstant) end end def test_nested_file_with_multiple_constants_and_require_dependency with_loading 'autoloading_fixtures' do assert ! defined?(ClassFolder::NestedClass) assert ! defined?(ClassFolder::SiblingClass) require_dependency 'class_folder/nested_class' assert defined?(ClassFolder::NestedClass) assert defined?(ClassFolder::SiblingClass) assert ActiveSupport::Dependencies.autoloaded?("ClassFolder::NestedClass") assert ActiveSupport::Dependencies.autoloaded?("ClassFolder::SiblingClass") ActiveSupport::Dependencies.clear assert ! defined?(ClassFolder::NestedClass) assert ! defined?(ClassFolder::SiblingClass) end end def test_nested_file_with_multiple_constants_and_auto_loading with_loading 'autoloading_fixtures' do assert ! defined?(ClassFolder::NestedClass) assert ! defined?(ClassFolder::SiblingClass) assert_kind_of Class, ClassFolder::NestedClass assert defined?(ClassFolder::NestedClass) assert defined?(ClassFolder::SiblingClass) assert ActiveSupport::Dependencies.autoloaded?("ClassFolder::NestedClass") assert ActiveSupport::Dependencies.autoloaded?("ClassFolder::SiblingClass") ActiveSupport::Dependencies.clear assert ! defined?(ClassFolder::NestedClass) assert ! defined?(ClassFolder::SiblingClass) end end def test_autoload_doesnt_shadow_no_method_error_with_relative_constant with_loading 'autoloading_fixtures' do assert !defined?(::RaisesNoMethodError), "::RaisesNoMethodError is defined but it hasn't been referenced yet!" 2.times do assert_raise(NoMethodError) { RaisesNoMethodError } assert !defined?(::RaisesNoMethodError), "::RaisesNoMethodError is defined but it should have failed!" end end ensure Object.class_eval { remove_const :RaisesNoMethodError if const_defined?(:RaisesNoMethodError) } end def test_autoload_doesnt_shadow_no_method_error_with_absolute_constant with_loading 'autoloading_fixtures' do assert !defined?(::RaisesNoMethodError), "::RaisesNoMethodError is defined but it hasn't been referenced yet!" 2.times do assert_raise(NoMethodError) { ::RaisesNoMethodError } assert !defined?(::RaisesNoMethodError), "::RaisesNoMethodError is defined but it should have failed!" end end ensure Object.class_eval { remove_const :RaisesNoMethodError if const_defined?(:RaisesNoMethodError) } end def test_autoload_doesnt_shadow_error_when_mechanism_not_set_to_load with_loading 'autoloading_fixtures' do ActiveSupport::Dependencies.mechanism = :require 2.times do assert_raise(NameError) {"RaisesNameError".constantize} end end end def test_autoload_doesnt_shadow_name_error with_loading 'autoloading_fixtures' do assert !defined?(::RaisesNameError), "::RaisesNameError is defined but it hasn't been referenced yet!" 2.times do begin ::RaisesNameError.object_id flunk 'should have raised NameError when autoloaded file referenced FooBarBaz' rescue NameError => e assert_equal 'uninitialized constant RaisesNameError::FooBarBaz', e.message end assert !defined?(::RaisesNameError), "::RaisesNameError is defined but it should have failed!" end assert !defined?(RaisesNameError) 2.times do assert_raise(NameError) { RaisesNameError } assert !defined?(::RaisesNameError), "::RaisesNameError is defined but it should have failed!" end end ensure Object.class_eval { remove_const :RaisesNoMethodError if const_defined?(:RaisesNoMethodError) } end def test_remove_constant_handles_double_colon_at_start Object.const_set 'DeleteMe', Module.new DeleteMe.const_set 'OrMe', Module.new ActiveSupport::Dependencies.remove_constant "::DeleteMe::OrMe" assert ! defined?(DeleteMe::OrMe) assert defined?(DeleteMe) ActiveSupport::Dependencies.remove_constant "::DeleteMe" assert ! defined?(DeleteMe) end def test_load_once_constants_should_not_be_unloaded with_loading 'autoloading_fixtures' do ActiveSupport::Dependencies.load_once_paths = ActiveSupport::Dependencies.load_paths ::A.to_s assert defined?(A) ActiveSupport::Dependencies.clear assert defined?(A) end ensure ActiveSupport::Dependencies.load_once_paths = [] Object.class_eval { remove_const :A if const_defined?(:A) } end def test_load_once_paths_should_behave_when_recursively_loading with_loading 'dependencies', 'autoloading_fixtures' do ActiveSupport::Dependencies.load_once_paths = [ActiveSupport::Dependencies.load_paths.last] assert !defined?(CrossSiteDependency) assert_nothing_raised { CrossSiteDepender.nil? } assert defined?(CrossSiteDependency) assert !ActiveSupport::Dependencies.autoloaded?(CrossSiteDependency), "CrossSiteDependency shouldn't be marked as autoloaded!" ActiveSupport::Dependencies.clear assert defined?(CrossSiteDependency), "CrossSiteDependency shouldn't have been unloaded!" end ensure ActiveSupport::Dependencies.load_once_paths = [] end def test_hook_called_multiple_times assert_nothing_raised { ActiveSupport::Dependencies.hook! } end def test_unhook ActiveSupport::Dependencies.unhook! assert !Module.new.respond_to?(:const_missing_without_dependencies) assert !Module.new.respond_to?(:load_without_new_constant_marking) ensure ActiveSupport::Dependencies.hook! end end
35.303342
133
0.744266
f8a90a74cb82dc63df9e66308e5c7cede7db52a0
264
class Api::V0::PledgesController < Api::V0::BaseController def index @pledges = Pledge.order('created_at desc').limit(100) render "api/v0/pledges/index" end def show @pledge = Pledge.find(params[:id]) render "api/v0/pledges/show" end end
20.307692
58
0.67803
1c1e5369eedc245c09ca307dec9095c04eaa0e73
331
class CreatePatientRecords < ActiveRecord::Migration[6.0] def change create_table :patient_records do |t| t.string :last_name t.string :first_name t.date :dob t.string :member_id t.date :effective_date t.date :expiry_date t.string :phone_number t.timestamps end end end
20.6875
57
0.65861
388afe2ae8972548eb87728573c1c938492f16dc
1,110
class Openfortivpn < Formula desc "Open Fortinet client for PPP+SSL VPN tunnel services" homepage "https://github.com/adrienverge/openfortivpn" url "https://github.com/adrienverge/openfortivpn/archive/v1.5.0.tar.gz" sha256 "a96016826bf85435c26ef0e58d14ae91990a08aaf67c701dfa56345dd851c185" bottle do sha256 "64e74a9365601be04eceb6a9a6122aeac621360fb7b6c477f74dbb92991d1814" => :sierra sha256 "ecb13f914741c5a0edcb43a006f016731428d23ffebea94b4a7b20522a04ef09" => :el_capitan sha256 "dd96c9f517a603e2a352a632a801e4d87fbc5588f0f01b6b62764924482732fd" => :yosemite sha256 "bda38438ecd7cefb2176a2182365948e224f373588ad5d05228e6677046fbbb2" => :x86_64_linux end depends_on "automake" => :build depends_on "autoconf" => :build depends_on "pkg-config" => :build depends_on "openssl" def install system "./autogen.sh" system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make", "install" end test do system bin/"openfortivpn", "--version" end end
37
94
0.731532
39c6102d85ceeae7b40aea8e5ee10340a7cab3f1
136
# frozen_string_literal: true $LOAD_PATH.unshift File.expand_path("../lib", __dir__) require "quicksort_c" require "minitest/autorun"
19.428571
54
0.779412
6acecad3b91cc8eb0c403053298efb0525b050ad
380
#require_relative "" #defining the reservation class path = File.dirname(__FILE__).split("/") path.pop DATABASE = "#{path.join("/")}/public/database.json" class Reservation attr_reader :name, :phone, :notes def initialize(time, name, phone, notes) @time = time @name = name @phone = phone @notes = notes end end class InvalidTextInput < StandardError end
19
51
0.692105