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
1c4016f7bb6c79dc7a7069f80e378f582555a4d8
211
# frozen_string_literal: true module Agave module Local module FieldType class Json def self.parse(value, _repo) value && JSON.parse(value) end end end end end
15.071429
36
0.601896
03aa72f811f76770d5f52bd35484e15cc733b3af
4,245
class PasswordRetrievalController < ApplicationController def action_allowed? true end def forgotten render template: 'password_retrieval/forgotten' end def send_password if params[:user][:email].nil? || params[:user][:email].strip.empty? flash[:error] = 'Please enter an e-mail address.' else user = User.find_by(email: params[:user][:email]) if user url_format = '/password_edit/check_reset_url?token=' token = SecureRandom.urlsafe_base64 PasswordReset.save_token(user, token) url = request.base_url + url_format + token MailerHelper.send_mail_to_user(user, 'Expertiza password reset', 'send_password', url).deliver_now ExpertizaLogger.info LoggerMessage.new(controller_name, user.name, 'A link to reset your password has been sent to users e-mail address.', request) flash[:success] = 'A link to reset your password has been sent to your e-mail address.' redirect_to '/' else ExpertizaLogger.error LoggerMessage.new(controller_name, params[:user][:email], 'No user is registered with provided email id!', request) flash[:error] = 'No account is associated with the e-mail address: "' + params[:user][:email] + '". Please try again.' render template: 'password_retrieval/forgotten' end end end # The token obtained from the reset url is first checked if it is valid ( if actually generated by the application), then checks if the token is active. def check_reset_url if params[:token].nil? flash[:error] = 'Password reset page can only be accessed with a generated link, sent to your email' render template: 'password_retrieval/forgotten' else @token = Digest::SHA1.hexdigest(params[:token]) password_reset = PasswordReset.find_by(token: @token) if password_reset # URL expires after 1 day expired_url = password_reset.updated_at + 1.day if Time.now < expired_url # redirect_to action: 'reset_password', email: password_reset.user_email @email = password_reset.user_email render template: 'password_retrieval/reset_password' else ExpertizaLogger.error LoggerMessage.new(controller_name, '', 'User tried to access expired link!', request) flash[:error] = 'Link expired . Please request to reset password again' render template: 'password_retrieval/forgotten' end else ExpertizaLogger.error LoggerMessage.new(controller_name, '', 'User tried to access either expired link or wrong token!', request) flash[:error] = 'Link either expired or wrong Token. Please request to reset password again' render template: 'password_retrieval/forgotten' end end end # avoid users to access this page without a valid token def reset_password flash[:error] = 'Password reset page can only be accessed with a generated link, sent to your email' render template: 'password_retrieval/forgotten' end # called after entering password and repassword, checks for validation and updates the password of the email def update_password if params[:reset][:password] == params[:reset][:repassword] user = User.find_by(email: params[:reset][:email]) user.password = params[:reset][:password] user.password_confirmation = params[:reset][:repassword] if user.save PasswordReset.delete_all(user_email: user.email) ExpertizaLogger.info LoggerMessage.new(controller_name, user.name, 'Password was reset for the user', request) flash[:success] = 'Password was successfully reset' else ExpertizaLogger.error LoggerMessage.new(controller_name, user.name, 'Password reset operation failed for the user while saving record', request) flash[:error] = 'Password cannot be updated. Please try again' end redirect_to '/' else ExpertizaLogger.error LoggerMessage.new(controller_name, '', 'Password provided by the user did not match', request) flash[:error] = 'Password and confirm-password do not match. Try again' @email = params[:reset][:email] render template: 'password_retrieval/reset_password' end end end
47.696629
155
0.70106
f86f4e6bf85df835512748558ddf19f48af6a6ae
1,596
$:.push File.expand_path("lib", __dir__) # Maintain gem's version: require "tiny_fake_redis/version" Gem::Specification.new do |spec| spec.name = "tiny_fake_redis" spec.version = TinyFakeRedis::VERSION spec.authors = ["Sampson Crowley"] spec.email = ["[email protected]"] spec.summary = "Pretend to Access a Redis Server" spec.description = <<~BODY The class in this Gem mimics the calls of `redis-rb` to allow running commands in development and test environments without the need to run a redis server instance It purposefully only implements a small subset of the most useful redis commands To create a fake instance: `redis = TinyFakeRedis.new` BODY spec.homepage = "https://github.com/SampsonCrowley/tiny_fake_redis" spec.license = "MIT" spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0") spec.metadata["homepage_uri"] = spec.homepage spec.metadata["source_code_uri"] = spec.homepage spec.metadata["changelog_uri"] = "#{spec.homepage}/blob/master/CHANGELOG.md" # Specify which files should be added to the gem when it is released. # The `git ls-files -z` loads the files in the RubyGem that have been added into git. spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_dependency "zeitwerk", "~> 2", ">= 2.2.2" end
40.923077
167
0.681078
e85fb0b725fca89e035f95bde335a33c81c22788
190
class TreeNode attr_accessor :value, :left_child, :right_child def initialize(value, left: nil, right: nil) @value = value @left_child = left @right_child = right end end
19
49
0.689474
e9d9c765cd833d37168db63fd6f171c0df59f965
2,884
module Fog module AWS class Compute class Real require 'fog/compute/parsers/aws/create_volume' # Create an EBS volume # # ==== Parameters # * availability_zone<~String> - availability zone to create volume in # * size<~Integer> - Size in GiBs for volume. Must be between 1 and 1024. # * snapshot_id<~String> - Optional, snapshot to create volume from # # ==== Returns # * response<~Excon::Response>: # * body<~Hash>: # * 'availabilityZone'<~String> - Availability zone for volume # * 'createTime'<~Time> - Timestamp for creation # * 'size'<~Integer> - Size in GiBs for volume # * 'snapshotId'<~String> - Snapshot volume was created from, if any # * 'status's<~String> - State of volume # * 'volumeId'<~String> - Reference to volume def create_volume(availability_zone, size, snapshot_id = nil) request( 'Action' => 'CreateVolume', 'AvailabilityZone' => availability_zone, 'Size' => size, 'SnapshotId' => snapshot_id, :parser => Fog::Parsers::AWS::Compute::CreateVolume.new ) end end class Mock def create_volume(availability_zone, size, snapshot_id = nil) response = Excon::Response.new if availability_zone && size if snapshot_id && !@data[:snapshots][snapshot_id] raise Fog::AWS::Compute::NotFound.new("The snapshot '#{snapshot_id}' does not exist.") end response.status = 200 volume_id = Fog::AWS::Mock.volume_id data = { 'availabilityZone' => availability_zone, 'attachmentSet' => [], 'createTime' => Time.now, 'size' => size, 'snapshotId' => snapshot_id, 'status' => 'creating', 'tagSet' => {}, 'volumeId' => volume_id } @data[:volumes][volume_id] = data response.body = { 'requestId' => Fog::AWS::Mock.request_id }.merge!(data.reject {|key,value| !['availabilityZone','createTime','size','snapshotId','status','volumeId'].include?(key) }) else response.status = 400 response.body = { 'Code' => 'MissingParameter' } unless availability_zone response.body['Message'] = 'The request must contain the parameter availability_zone' else response.body['Message'] = 'The request must contain the parameter size' end end response end end end end end
36.506329
137
0.511442
919d1b9f630cf6017fb733cccea299f8b480b3cb
2,317
lib = File.expand_path("../life-story", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |spec| spec.name = "life-story" spec.version = "0.1.0" spec.authors = ["'Sophie Gu'"] spec.email = ["'[email protected]'"] spec.summary = %q{A Sinatra app recording your important memories.} spec.description = %q{This Sinatra app allows you to write stories recorded that are meaningful in various aspects of life. Record things that matter to you at that moment. Read later to reflect on what is really important in life. Browse by date, category and users to see what others have been through. Visualize your life and those that are connected to you in a single app.} spec.homepage = "https://github.com/sophieqgu/life-story" spec.license = "MIT" # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host' # to allow pushing to a single host or delete this section to allow pushing to any host. if spec.respond_to?(:metadata) spec.metadata["allowed_push_host"] = "https://www.rubygems.org" spec.metadata["homepage_uri"] = spec.homepage spec.metadata["source_code_uri"] = "https://github.com/sophieqgu/life-story" spec.metadata["changelog_uri"] = "https://github.com/sophieqgu/life-story" else raise "RubyGems 2.0 or newer is required to protect against " \ "public gem pushes." end # Specify which files should be added to the gem when it is released. # The `git ls-files -z` loads the files in the RubyGem that have been added into git. spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["life-story"] spec.add_development_dependency "bundler", "~> 2.0" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "pry" spec.add_development_dependency "sinatra" spec.add_development_dependency "activerecord", "~> 4.2" spec.add_development_dependency "sinatra-activerecord" spec.add_dependency "sqlite3", "~> 1.3.6" spec.add_dependency "sinatra-flash" end
50.369565
382
0.702201
3870c6819336c18866d41216c290f209e79deb67
1,527
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "edn" s.version = "1.0.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Clinton N. Dreisbach"] s.date = "2013-05-24" s.description = "'edn implements a reader for Extensible Data Notation by Rich Hickey.'" s.email = ["[email protected]"] s.homepage = "" s.require_paths = ["lib"] s.rubygems_version = "1.8.25" s.summary = "'edn implements a reader for Extensible Data Notation by Rich Hickey.'" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<parslet>, ["~> 1.4.0"]) s.add_development_dependency(%q<pry>, ["~> 0.9.10"]) s.add_development_dependency(%q<rspec>, ["~> 2.11.0"]) s.add_development_dependency(%q<rantly>, ["~> 0.3.1"]) s.add_development_dependency(%q<rake>, ["~> 10.0.3"]) else s.add_dependency(%q<parslet>, ["~> 1.4.0"]) s.add_dependency(%q<pry>, ["~> 0.9.10"]) s.add_dependency(%q<rspec>, ["~> 2.11.0"]) s.add_dependency(%q<rantly>, ["~> 0.3.1"]) s.add_dependency(%q<rake>, ["~> 10.0.3"]) end else s.add_dependency(%q<parslet>, ["~> 1.4.0"]) s.add_dependency(%q<pry>, ["~> 0.9.10"]) s.add_dependency(%q<rspec>, ["~> 2.11.0"]) s.add_dependency(%q<rantly>, ["~> 0.3.1"]) s.add_dependency(%q<rake>, ["~> 10.0.3"]) end end
37.243902
105
0.610347
7943a18397a306d1d19cbc5913a5f8799f3da126
6,264
require 'date' module GraphHopper class Address # Unique identifier of location attr_accessor :location_id # name of location, e.g. street name plus house number attr_accessor :name # longitude attr_accessor :lon # latitude attr_accessor :lat # Optional parameter. Specifies a hint for each address to better snap the coordinates (lon,lat) to road network. E.g. if there is an address or house with two or more neighboring streets you can control for which street the closest location is looked up. attr_accessor :street_hint # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'location_id' => :'location_id', :'name' => :'name', :'lon' => :'lon', :'lat' => :'lat', :'street_hint' => :'street_hint' } end # Attribute type mapping. def self.swagger_types { :'location_id' => :'String', :'name' => :'String', :'lon' => :'Float', :'lat' => :'Float', :'street_hint' => :'String' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} if attributes.has_key?(:'location_id') self.location_id = attributes[:'location_id'] end if attributes.has_key?(:'name') self.name = attributes[:'name'] end if attributes.has_key?(:'lon') self.lon = attributes[:'lon'] end if attributes.has_key?(:'lat') self.lat = attributes[:'lat'] end if attributes.has_key?(:'street_hint') self.street_hint = attributes[:'street_hint'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new return invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? return true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && location_id == o.location_id && name == o.name && lon == o.lon && lat == o.lat && street_hint == o.street_hint end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [location_id, name, lon, lat, street_hint].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BOOLEAN if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model temp_model = GraphHopper.const_get(type).new temp_model.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map{ |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
28.733945
259
0.604885
1db3693f296218ad0c656ffda3fa4e1de32114c8
12,635
# frozen_string_literal: true # 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 rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) # Disable email while seeding ActionMailer::Base.delivery_method = :test ActionMailer::Base.perform_deliveries = false def tc_seed apt = Apartment.create( :name => 'WHAADADUPUPP', :address => '9500 Gilman Dr, La Jolla, CA 92093', ) apt.update(:access_code => '12345') puts 'Created apartment with access code 12345' user1 = User.create( :email => '[email protected]', :password => 'password123', :display_name => 'John Smith', :apartment_id => apt.id ) user2 = User.create( :email => '[email protected]', :password => 'password234', :display_name => 'Yalta Appolo', :apartment_id => apt.id ) user3 = User.create( :email => '[email protected]', :password => 'password345', :display_name => 'Jonathan Xie', :apartment_id => apt.id ) user4 = User.create( :email => '[email protected]', :password => 'password456', :display_name => 'Barry Allen', :apartment_id => apt.id ) user5 = User.create( :email => '[email protected]', :password => 'password567', :display_name => 'Eren Yeager', :apartment_id => apt.id ) user_ids = [user1, user2, user3, user4, user5].map {|x| x.id} puts 'Created users' Faker::Config.random = Random.new(42) rng = Random.new(42) notification1 = Notification.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :title => 'Stove', :message => 'Hey guys. Someone left the stove running overnight. Not cool guys. Please turn it off when you guys cook next time' ) notification2 = Notification.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :title => 'Rent', :message => 'Hey guys, remember to pay your share of the rent soon.' ) notification3 = Notification.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :title => 'Party', :message => "Hey everyone. I'm gonna have a party here from 5pm to 12am. We might be loud, so please let me know if there will be any issues with that." ) notification4 = Notification.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :title => 'Leaving for the weekend', :message => 'Im gonna be gone for the weekend to visit my family. Just wanted to let you guys know.' ) notification5 = Notification.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :title => 'Restaurant', :message => 'What time do you guys want to go out to celebrate?' ) notification6 = Notification.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :title => 'Larry the Cable Guy', :message => 'Hey guys just as a reminder, Larry will be coming over to fix our internet and TV tomorrow.' ) notification7 = Notification.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :title => 'Larry the Cable Guy', :message => 'Hey guys just as a reminder, Larry will be coming over to fix our internet and TV tomorrow.' ) notification8 = Notification.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :title => 'Remember to clean our the sink', :message => "Hey guys remember to clean out the sink. There are so many dirty dishes in there that Im pretty sure that it's starting to mold" ) notification9 = Notification.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :title => 'Darryl the Plumber', :message => "Hey guys Darryl will be coming over tomorrow to fix the plumbing. Don't use the bathroom until then." ) notification10 = Notification.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :title => 'Missing socks', :message => 'Hey so Ive been missing some socks in the dryers. Has anyone been taking them?' ) notification11 = Notification.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :title => 'SPRING BREAK WHOOO', :message => 'LETS GO SPRING BREAK WHOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' ) notification12 = Notification.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :title => 'SUN GOD WHOOOOOOO', :message => 'LETS GO SUN GOOD WHOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO' ) notification13 = Notification.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :title => 'Subleasing', :message => 'If anyone has any plans to sublease their room, remember to run by it with Gary first' ) notification14 = Notification.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :title => 'Coffee Table', :message => 'The sellers will be coming over to give us the coffee table. If anyone is going to be home at around 3pm please try to help bring it in' ) notification15 = Notification.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :title => 'Jacket', :message => 'Theres a jacket on top of the washing machine. Anyone know whose it is?' ) puts 'Created notifications' item1 = Item.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :name => 'Toaster', :bought => true, :description => 'Toaster', ) item2 = Item.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :name => 'Kettle', :bought => true, :description => 'Kettle', ) item3 = Item.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :name => 'Spatula', :bought => true, :description => 'Spatula', ) item4 = Item.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :name => 'Toaster Oven', :bought => true, :description => 'Toaster Oven', ) item5 = Item.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :name => 'Tv', :bought => true, :description => 'Tv', ) item6 = Item.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :name => 'Coffee Table', :bought => true, :description => 'Coffee Table', ) item7 = Item.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :name => 'Couch', :bought => true, :description => 'Couch', ) item8 = Item.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :name => 'Strainer', :bought => true, :description => 'Strainer', ) item9 = Item.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :name => 'Shoe Rack', :bought => true, :description => 'Shoe Rack', ) item10 = Item.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :name => 'Blender', :bought => true, :description => 'Blender', ) item11 = Item.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :name => 'Bird Feeder', :bought => true, :description => 'Bird Feeder', ) item12 = Item.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :name => 'Pot', :bought => true, :description => 'Pot', ) item13 = Item.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :name => 'Pan', :bought => true, :description => 'Pan', ) item14 = Item.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :name => 'Fridge', :bought => true, :description => 'Fridge', ) item15 = Item.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :name => 'Kettle', :bought => true, :description => 'Kettle', ) item16 = Item.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :name => 'Foreman Grill', :bought => true, :description => 'Foreman Grill', ) item17 = Item.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :name => 'Lamp', :bought => true, :description => 'Lamp', ) puts 'Created items' 40.times do |_| rand_users = user_ids.sample(2, :random => rng) rand_num = rng.rand expense_info = if rand_num < 0.5 {:title => 'Rent', :amount => 50000 + rng.rand(30000)} elsif rand_num < 0.8 {:title => 'Groceries', :amount => 1000 + rng.rand(1000)} else {:title => 'Restaurant', :amount => 1000 + rng.rand(1000)} end expense = Expense.create( :apartment_id => apt.id, :payer_id => rand_users[0], :issuer_id => rand_users[1], :title => expense_info[:title], :description => Faker::Lorem.sentence, :amount => expense_info[:amount], :paid => rng.rand < 0.5 ) end puts 'Created expenses' files = [ {:filename => 'adentudmsnd.pdf', :title => 'Lease Addendum'}, {:filename => 'lease.pdf', :title => 'Lease'}, {:filename => 'rules.pdf', :title => 'Apartment Rules'}, {:filename => 'room.jpg', :title => 'Living Room'} ] files.each do |x| file = File.open(File.join(Rails.root, 'db', 'seeddata', x[:filename]), 'rb') {|io| io.read} Document.create( :apartment_id => apt.id, :user_id => user_ids.sample(:random => rng), :title => x[:title], :apartmentwide => true, :file_data => {:io => StringIO.new(file), :filename => x[:filename]} ) end puts 'Created documents' # Other seeds, not in the main apartment # Not in an apartment # [email protected] # password123 User.create( :email => '[email protected]', :password => 'password123', :display_name => 'Test NoApartment' ) # In apartment with nothing # [email protected] # password123 apt2 = Apartment.create( :name => 'Test Apartment', :address => 'Test Address', ) User.create( :email => '[email protected]', :password => 'password123', :display_name => 'Test Change', :apartment_id => apt2.id ) # Account to be deleted, in an apartment # [email protected] # password123 apt3 = Apartment.create( :name => 'Test Apartment', :address => 'Test Address', ) User.create( :email => '[email protected]', :password => 'password123', :display_name => 'Test Delete', :apartment_id => apt3.id ) # Account for recovery, not in an apartment # [email protected] # password123 User.create( :email => '[email protected]', :password => 'password123', :display_name => 'Test Recovery' ) # Account for leave apartment, is in an apartment # [email protected] # password123 apt4 = Apartment.create( :name => 'Test Apartment', :address => 'Test Address', ) User.create( :email => '[email protected]', :password => 'password123', :display_name => 'Test Leave', :apartment_id => apt4.id ) puts "Create misc. TC seeds" end case Rails.env when 'development' # development-specific seeds ... # (anything you need to interactively play around with in the rails console) tc_seed when 'test' # test-specific seeds ... # (Consider having your tests set up the data they need # themselves instead of seeding it here!) when 'production' # production seeds (if any) ... tc_seed else pass end # common seeds ... # (data your application needs in all environments)
29.799528
158
0.59256
1d772f6373ec8f903355c552b8049c306dc76d62
7,368
require 'spec/spec_helper' describe ThinkingSphinx::Index do describe "to_config method" do before :each do @index = ThinkingSphinx::Index.new(Person) @index.stub_methods( :attributes => [ ThinkingSphinx::Attribute.stub_instance(:to_sphinx_clause => "attr a"), ThinkingSphinx::Attribute.stub_instance(:to_sphinx_clause => "attr b") ], :link! => true, :adapter => :mysql, :to_sql_query_pre => "sql_query_pre", :to_sql => "SQL", :to_sql_query_range => "sql_query_range", :to_sql_query_info => "sql_query_info", :delta? => false ) @database = { :host => "localhost", :username => "username", :password => "blank", :database => "db" } end it "should call link!" do @index.to_config(0, @database, "utf-8") @index.should have_received(:link!) end it "should raise an exception if the adapter isn't mysql or postgres" do @index.stub_method(:adapter => :sqlite) lambda { @index.to_config(0, @database, "utf-8") }.should raise_error end it "should set the core source name to {model}_{index}_core" do @index.to_config(0, @database, "utf-8").should match( /source person_0_core/ ) end it "should include the database config supplied" do conf = @index.to_config(0, @database, "utf-8") conf.should match(/type\s+= mysql/) conf.should match(/sql_host\s+= localhost/) conf.should match(/sql_user\s+= username/) conf.should match(/sql_pass\s+= blank/) conf.should match(/sql_db\s+= db/) end it "should have a pre query 'SET NAMES utf8' if using mysql and utf8 charset" do @index.to_config(0, @database, "utf-8").should match( /sql_query_pre\s+= SET NAMES utf8/ ) @index.stub_method(:delta? => true) @index.to_config(0, @database, "utf-8").should match( /source person_0_delta.+sql_query_pre\s+= SET NAMES utf8/m ) @index.stub_method(:delta? => false) @index.to_config(0, @database, "non-utf-8").should_not match( /SET NAMES utf8/ ) @index.stub_method(:adapter => :postgres) @index.to_config(0, @database, "utf-8").should_not match( /SET NAMES utf8/ ) end it "should use the pre query from the index" do @index.to_config(0, @database, "utf-8").should match( /sql_query_pre\s+= sql_query_pre/ ) end it "should not set group_concat_max_len if not specified" do @index.to_config(0, @database, "utf-8").should_not match( /group_concat_max_len/ ) end it "should set group_concat_max_len if specified" do @index.options.merge! :group_concat_max_len => 2056 @index.to_config(0, @database, "utf-8").should match( /sql_query_pre\s+= SET SESSION group_concat_max_len = 2056/ ) @index.stub_method(:delta? => true) @index.to_config(0, @database, "utf-8").should match( /source person_0_delta.+sql_query_pre\s+= SET SESSION group_concat_max_len = 2056/m ) end it "should use the main query from the index" do @index.to_config(0, @database, "utf-8").should match( /sql_query\s+= SQL/ ) end it "should use the range query from the index" do @index.to_config(0, @database, "utf-8").should match( /sql_query_range\s+= sql_query_range/ ) end it "should use the info query from the index" do @index.to_config(0, @database, "utf-8").should match( /sql_query_info\s+= sql_query_info/ ) end it "should include the attribute sources" do @index.to_config(0, @database, "utf-8").should match( /attr a\n\s+attr b/ ) end it "should add a delta index with name {model}_{index}_delta if requested" do @index.stub_method(:delta? => true) @index.to_config(0, @database, "utf-8").should match( /source person_0_delta/ ) end it "should not add a delta index unless requested" do @index.to_config(0, @database, "utf-8").should_not match( /source person_0_delta/ ) end it "should have the delta index inherit from the core index" do @index.stub_method(:delta? => true) @index.to_config(0, @database, "utf-8").should match( /source person_0_delta : person_0_core/ ) end it "should redefine the main query for the delta index" do @index.stub_method(:delta? => true) @index.to_config(0, @database, "utf-8").should match( /source person_0_delta.+sql_query\s+= SQL/m ) end it "should redefine the range query for the delta index" do @index.stub_method(:delta? => true) @index.to_config(0, @database, "utf-8").should match( /source person_0_delta.+sql_query_range\s+= sql_query_range/m ) end it "should redefine the pre query for the delta index" do @index.stub_method(:delta? => true) @index.to_config(0, @database, "utf-8").should match( /source person_0_delta.+sql_query_pre\s+=\s*\n/m ) end end describe "to_sql_query_range method" do before :each do @index = ThinkingSphinx::Index.new(Person) end it "should add COALESCE around MIN and MAX calls if using PostgreSQL" do @index.stub_method(:adapter => :postgres) @index.to_sql_query_range.should match(/COALESCE\(MIN.+COALESCE\(MAX/) puts @index.to_sql_query_range end it "shouldn't add COALESCE if using MySQL" do @index.to_sql_query_range.should_not match(/COALESCE/) puts @index.to_sql_query_range end end describe "prefix_fields method" do before :each do @index = ThinkingSphinx::Index.new(Person) @field_a = ThinkingSphinx::Field.stub_instance(:prefixes => true) @field_b = ThinkingSphinx::Field.stub_instance(:prefixes => false) @field_c = ThinkingSphinx::Field.stub_instance(:prefixes => true) @index.fields = [@field_a, @field_b, @field_c] end it "should return fields that are flagged as prefixed" do @index.prefix_fields.should include(@field_a) @index.prefix_fields.should include(@field_c) end it "should not return fields that aren't flagged as prefixed" do @index.prefix_fields.should_not include(@field_b) end end describe "infix_fields" do before :each do @index = ThinkingSphinx::Index.new(Person) @field_a = ThinkingSphinx::Field.stub_instance(:infixes => true) @field_b = ThinkingSphinx::Field.stub_instance(:infixes => false) @field_c = ThinkingSphinx::Field.stub_instance(:infixes => true) @index.fields = [@field_a, @field_b, @field_c] end it "should return fields that are flagged as infixed" do @index.infix_fields.should include(@field_a) @index.infix_fields.should include(@field_c) end it "should not return fields that aren't flagged as infixed" do @index.infix_fields.should_not include(@field_b) end end end
31.758621
91
0.614007
18b20dc77ad92ec2428548bc3af5eed69eb4ca13
11,061
opal_filter "BigDecimal" do fails "BigDecimal#% raises TypeError if the argument cannot be coerced to BigDecimal" fails "BigDecimal#% returns NaN if NaN is involved" fails "BigDecimal#% returns NaN if the dividend is Infinity" fails "BigDecimal#% returns a [Float value] when the argument is Float" fails "BigDecimal#% returns self modulo other" fails "BigDecimal#% returns the dividend if the divisor is Infinity" fails "BigDecimal#** 0 to power of 0 is 1" fails "BigDecimal#** 0 to powers < 0 is Infinity" fails "BigDecimal#** other powers of 0 are 0" fails "BigDecimal#** powers of 1 equal 1" fails "BigDecimal#** powers of self" fails "BigDecimal#** returns 0.0 if self is infinite and argument is negative" fails "BigDecimal#** returns NaN if self is NaN" fails "BigDecimal#** returns infinite if self is infinite and argument is positive" fails "BigDecimal#-@ properly handles special values" fails "BigDecimal#/ returns a / b" #fails a single assertion: @one.send(@method, BigDecimal('-2E5555'), *@object).should == BigDecimal('-0.5E-5555') fails "BigDecimal#< properly handles infinity values" #fails only with mock object fails "BigDecimal#<= properly handles infinity values" #fails only with mock object fails "BigDecimal#<=> returns -1 if a < b" #fails only with mock object fails "BigDecimal#<=> returns 1 if a > b" #fails only with mock object fails "BigDecimal#> properly handles infinity values" #fails only with mock object fails "BigDecimal#>= properly handles infinity values" #fails only with mock object fails "BigDecimal#ceil returns n digits right of the decimal point if given n > 0" fails "BigDecimal#ceil returns the smallest integer greater or equal to self, if n is unspecified" fails "BigDecimal#ceil sets n digits left of the decimal point to 0, if given n < 0" fails "BigDecimal#coerce returns [other, self] both as BigDecimal" fails "BigDecimal#div returns a / b with optional precision" #fails the case of > 20 decimal places for to_s('F') fails "BigDecimal#div with precision set to 0 returns a / b" #fails a single assertion: @one.send(@method, BigDecimal('-2E5555'), *@object).should == BigDecimal('-0.5E-5555') fails "BigDecimal#divmod Can be reversed with * and +" fails "BigDecimal#divmod array contains quotient and modulus as BigDecimal" fails "BigDecimal#divmod divides value, returns an array" fails "BigDecimal#divmod raises TypeError if the argument cannot be coerced to BigDecimal" fails "BigDecimal#divmod returns an array of Infinity and NaN if the dividend is Infinity" fails "BigDecimal#divmod returns an array of two NaNs if NaN is involved" fails "BigDecimal#divmod returns an array of zero and the dividend if the divisor is Infinity" fails "BigDecimal#exponent is n if number can be represented as 0.xxx*10**n" fails "BigDecimal#exponent returns 0 if self is 0" fails "BigDecimal#exponent returns an Integer" fails "BigDecimal#fix correctly handles special values" fails "BigDecimal#fix does not allow any arguments" fails "BigDecimal#fix returns 0 if the absolute value is < 1" fails "BigDecimal#fix returns a BigDecimal" fails "BigDecimal#fix returns the integer part of the absolute value" fails "BigDecimal#floor raise exception, if self is special value" fails "BigDecimal#floor returns n digits right of the decimal point if given n > 0" fails "BigDecimal#floor returns the greatest integer smaller or equal to self" fails "BigDecimal#floor sets n digits left of the decimal point to 0, if given n < 0" fails "BigDecimal#frac correctly handles special values" fails "BigDecimal#frac returns 0 if the value is 0" fails "BigDecimal#frac returns 0 if the value is an integer" fails "BigDecimal#frac returns a BigDecimal" fails "BigDecimal#frac returns the fractional part of the absolute value" fails "BigDecimal#inspect encloses information in angle brackets" fails "BigDecimal#inspect is comma separated list of three items" fails "BigDecimal#inspect last part is number of significant digits" fails "BigDecimal#inspect looks like this" fails "BigDecimal#inspect returns String starting with #" fails "BigDecimal#inspect value after first comma is value as string" fails "BigDecimal#mod_part_of_divmod raises TypeError if the argument cannot be coerced to BigDecimal" fails "BigDecimal#mod_part_of_divmod returns NaN if NaN is involved" fails "BigDecimal#mod_part_of_divmod returns NaN if the dividend is Infinity" fails "BigDecimal#mod_part_of_divmod returns a [Float value] when the argument is Float" fails "BigDecimal#mod_part_of_divmod returns self modulo other" fails "BigDecimal#mod_part_of_divmod returns the dividend if the divisor is Infinity" fails "BigDecimal#power 0 to power of 0 is 1" fails "BigDecimal#power 0 to powers < 0 is Infinity" fails "BigDecimal#power other powers of 0 are 0" fails "BigDecimal#power powers of 1 equal 1" fails "BigDecimal#power powers of self" fails "BigDecimal#power returns 0.0 if self is infinite and argument is negative" fails "BigDecimal#power returns NaN if self is NaN" fails "BigDecimal#power returns infinite if self is infinite and argument is positive" fails "BigDecimal#precs returns Integers as array values" fails "BigDecimal#precs returns array of two values" fails "BigDecimal#precs returns the current value of significant digits as the first value" fails "BigDecimal#precs returns the maximum number of significant digits as the second value" fails "BigDecimal#quo returns a / b" #fails a single assertion: @one.send(@method, BigDecimal('-2E5555'), *@object).should == BigDecimal('-0.5E-5555') fails "BigDecimal#remainder coerces arguments to BigDecimal if possible" fails "BigDecimal#remainder it equals modulo, if both values are of same sign" fails "BigDecimal#remainder means self-arg*(self/arg).truncate" fails "BigDecimal#remainder raises TypeError if the argument cannot be coerced to BigDecimal" fails "BigDecimal#remainder returns NaN if Infinity is involved" fails "BigDecimal#remainder returns NaN if NaN is involved" fails "BigDecimal#remainder returns NaN used with zero" fails "BigDecimal#remainder returns zero if used on zero" fails "BigDecimal#round BigDecimal::ROUND_CEILING rounds values towards +infinity" fails "BigDecimal#round BigDecimal::ROUND_DOWN rounds values towards zero" fails "BigDecimal#round BigDecimal::ROUND_FLOOR rounds values towards -infinity" fails "BigDecimal#round BigDecimal::ROUND_HALF_DOWN rounds values > 5 up, otherwise down" fails "BigDecimal#round BigDecimal::ROUND_HALF_EVEN rounds values > 5 up, < 5 down and == 5 towards even neighbor" fails "BigDecimal#round BigDecimal::ROUND_HALF_UP rounds values >= 5 up, otherwise down" fails "BigDecimal#round BigDecimal::ROUND_UP rounds values away from zero" fails "BigDecimal#round uses default rounding method unless given" fails "BigDecimal#sign returns negative value if BigDecimal less than 0" fails "BigDecimal#sign returns positive value if BigDecimal greater than 0" fails "BigDecimal#split First value: -1 for numbers < 0" fails "BigDecimal#split First value: 0 if BigDecimal is NaN" fails "BigDecimal#split First value: 1 for numbers > 0" fails "BigDecimal#split Fourth value: The exponent" fails "BigDecimal#split Second value: a string with the significant digits" fails "BigDecimal#split Third value: the base (currently always ten)" fails "BigDecimal#split splits BigDecimal in an array with four values" fails "BigDecimal#sqrt raises ArgumentError if 2 arguments are given" fails "BigDecimal#sqrt raises ArgumentError if a negative number is given" fails "BigDecimal#sqrt raises ArgumentError when no argument is given" fails "BigDecimal#sqrt raises FloatDomainError for NaN" fails "BigDecimal#sqrt raises FloatDomainError for negative infinity" fails "BigDecimal#sqrt raises FloatDomainError on negative values" fails "BigDecimal#sqrt raises TypeError if a plain Object is given" fails "BigDecimal#sqrt raises TypeError if a string is given" fails "BigDecimal#sqrt raises TypeError if nil is given" fails "BigDecimal#sqrt returns 0 for 0, +0.0 and -0.0" fails "BigDecimal#sqrt returns 1 if precision is 0 or 1" fails "BigDecimal#sqrt returns positive infitinity for infinity" fails "BigDecimal#sqrt returns square root of 0.9E-99999 with desired precision" fails "BigDecimal#sqrt returns square root of 121 with desired precision" fails "BigDecimal#sqrt returns square root of 2 with desired precision" fails "BigDecimal#sqrt returns square root of 3 with desired precision" fails "BigDecimal#to_f properly handles special values" fails "BigDecimal#to_f remembers negative zero when converted to float" fails "BigDecimal#to_i raises FloatDomainError if BigDecimal is infinity or NaN" fails "BigDecimal#to_i returns Integer or Bignum otherwise" fails "BigDecimal#to_int raises FloatDomainError if BigDecimal is infinity or NaN" fails "BigDecimal#to_int returns Integer or Bignum otherwise" fails "BigDecimal#to_s can return a leading space for values > 0" fails "BigDecimal#to_s can use conventional floating point notation" fails "BigDecimal#to_s can use engineering notation" fails "BigDecimal#to_s inserts a space every n chars, if integer n is supplied" fails "BigDecimal#to_s removes trailing spaces in floating point notation" fails "BigDecimal#to_s starts with + if + is supplied and value is positive" fails "BigDecimal#to_s the default format looks like 0.xxxxEnn" fails "BigDecimal#truncate returns Infinity if self is infinite" fails "BigDecimal#truncate returns NaN if self is NaN" fails "BigDecimal#truncate returns the same value if self is special value" fails "BigDecimal#truncate returns value of given precision otherwise" fails "BigDecimal#truncate sets n digits left of the decimal point to 0, if given n < 0" fails "BigDecimal.double_fig returns the number of digits a Float number is allowed to have" fails "BigDecimal.limit returns the value before set if the passed argument is nil or is not specified" fails "BigDecimal.limit use the global limit if no precision is specified" fails "BigDecimal.mode raise an exception if the flag is true" fails "BigDecimal.mode returns Infinity when too big" fails "BigDecimal.mode returns the appropriate value and continue the computation if the flag is false" fails "BigDecimal.new Number of significant digits >= given precision" fails "BigDecimal.new allows for [eEdD] as exponent separator" fails "BigDecimal.new allows for underscores in all parts" fails "BigDecimal.new creates a new object of class BigDecimal" fails "BigDecimal.new determines precision from initial value" fails "BigDecimal.new ignores leading whitespace" fails "BigDecimal.new ignores trailing garbage" fails "BigDecimal.new raises ArgumentError when Float is used without precision" fails "BigDecimal.new treats invalid strings as 0.0" fails "BigDecimal.ver returns the Version number" end
71.36129
176
0.779043
d572f8685f246e722b655596a74ef14dae13953c
107
require 'spec_helper' describe Registrant do pending "add some examples to (or delete) #{__FILE__}" end
17.833333
56
0.757009
1c8e991566ba90155cdc5e321f94c2abbdc077bb
42,719
# # Author:: Adam Jacob (<[email protected]>) # Author:: Christopher Walters (<[email protected]>) # Author:: Tim Hinderliter (<[email protected]>) # Author:: Seth Chisamore (<[email protected]>) # Copyright:: Copyright 2008-2018, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "spec_helper" describe Chef::Resource do let(:cookbook_repo_path) { File.join(CHEF_SPEC_DATA, "cookbooks") } let(:cookbook_collection) { Chef::CookbookCollection.new(Chef::CookbookLoader.new(cookbook_repo_path)) } let(:node) { Chef::Node.new } let(:events) { Chef::EventDispatch::Dispatcher.new } let(:run_context) { Chef::RunContext.new(node, cookbook_collection, events) } let(:resource) { resource_class.new("funk", run_context) } let(:resource_class) { Chef::Resource } it "should mixin shell_out" do expect(resource.respond_to?(:shell_out)).to be true end it "should mixin shell_out!" do expect(resource.respond_to?(:shell_out!)).to be true end describe "when inherited" do it "adds an entry to a list of subclasses" do subclass = Class.new(Chef::Resource) expect(Chef::Resource.resource_classes).to include(subclass) end it "keeps track of subclasses of subclasses" do subclass = Class.new(Chef::Resource) subclass_of_subclass = Class.new(subclass) expect(Chef::Resource.resource_classes).to include(subclass_of_subclass) end end describe "when declaring the identity attribute" do it "has :name as identity attribute by default" do expect(Chef::Resource.identity_attr).to eq(:name) end it "sets an identity attribute" do resource_class = Class.new(Chef::Resource) resource_class.identity_attr(:path) expect(resource_class.identity_attr).to eq(:path) end it "inherits an identity attribute from a superclass" do resource_class = Class.new(Chef::Resource) resource_subclass = Class.new(resource_class) resource_class.identity_attr(:package_name) expect(resource_subclass.identity_attr).to eq(:package_name) end it "overrides the identity attribute from a superclass when the identity attr is set" do resource_class = Class.new(Chef::Resource) resource_subclass = Class.new(resource_class) resource_class.identity_attr(:package_name) resource_subclass.identity_attr(:something_else) expect(resource_subclass.identity_attr).to eq(:something_else) end end describe "when no identity attribute has been declared" do let(:resource_sans_id) { Chef::Resource.new("my-name") } # Would rather force identity attributes to be set for everything, # but that's not plausible for back compat reasons. it "uses the name as the identity" do expect(resource_sans_id.identity).to eq("my-name") end end describe "when an identity attribute has been declared" do let(:file_resource) do file_resource_class = Class.new(Chef::Resource) do identity_attr :path attr_accessor :path end file_resource = file_resource_class.new("identity-attr-test") file_resource.path = "/tmp/foo.txt" file_resource end it "gives the value of its identity attribute" do expect(file_resource.identity).to eq("/tmp/foo.txt") end end describe "when declaring state attributes" do it "has no state_attrs by default" do expect(Chef::Resource.state_attrs).to be_empty end it "sets a list of state attributes" do resource_class = Class.new(Chef::Resource) resource_class.state_attrs(:checksum, :owner, :group, :mode) expect(resource_class.state_attrs).to match_array([:checksum, :owner, :group, :mode]) end it "inherits state attributes from the superclass" do resource_class = Class.new(Chef::Resource) resource_subclass = Class.new(resource_class) resource_class.state_attrs(:checksum, :owner, :group, :mode) expect(resource_subclass.state_attrs).to match_array([:checksum, :owner, :group, :mode]) end it "combines inherited state attributes with non-inherited state attributes" do resource_class = Class.new(Chef::Resource) resource_subclass = Class.new(resource_class) resource_class.state_attrs(:checksum, :owner) resource_subclass.state_attrs(:group, :mode) expect(resource_subclass.state_attrs).to match_array([:checksum, :owner, :group, :mode]) end end describe "when a set of state attributes has been declared" do let(:file_resource) do file_resource_class = Class.new(Chef::Resource) do state_attrs :checksum, :owner, :group, :mode attr_accessor :checksum attr_accessor :owner attr_accessor :group attr_accessor :mode end file_resource = file_resource_class.new("describe-state-test") file_resource.checksum = "abc123" file_resource.owner = "root" file_resource.group = "wheel" file_resource.mode = "0644" file_resource end it "describes its state" do resource_state = file_resource.state_for_resource_reporter expect(resource_state.keys).to match_array([:checksum, :owner, :group, :mode]) expect(resource_state[:checksum]).to eq("abc123") expect(resource_state[:owner]).to eq("root") expect(resource_state[:group]).to eq("wheel") expect(resource_state[:mode]).to eq("0644") end end describe "#state_for_resource_reporter" do context "when a property is marked as sensitive" do it "suppresses the sensitive property's value" do resource_class = Class.new(Chef::Resource) { property :foo, String, sensitive: true } resource = resource_class.new("sensitive_property_tests") resource.foo = "some value" expect(resource.state_for_resource_reporter[:foo]).to eq("*sensitive value suppressed*") end end context "when a property is not marked as sensitive" do it "does not suppress the property's value" do resource_class = Class.new(Chef::Resource) { property :foo, String } resource = resource_class.new("sensitive_property_tests") resource.foo = "some value" expect(resource.state_for_resource_reporter[:foo]).to eq("some value") end end end describe "load_from" do let(:prior_resource) do prior_resource = Chef::Resource.new("funk") prior_resource.source_line prior_resource.allowed_actions << :funkytown prior_resource.action(:funkytown) prior_resource end before(:each) do resource.allowed_actions << :funkytown run_context.resource_collection << prior_resource end it "should load the attributes of a prior resource" do resource.load_from(prior_resource) end it "should not inherit the action from the prior resource" do resource.load_from(prior_resource) expect(resource.action).not_to eq(prior_resource.action) end end describe "name" do it "should have a name" do expect(resource.name).to eql("funk") end it "should let you set a new name" do resource.name "monkey" expect(resource.name).to eql("monkey") end it "coerces arrays to names" do expect(resource.name %w{a b}).to eql("a, b") end it "should coerce objects to a string" do expect(resource.name Object.new).to be_a(String) end end describe "notifies" do it "should make notified resources appear in the actions hash" do run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") resource.notifies :reload, run_context.resource_collection.find(zen_master: "coffee") expect(resource.delayed_notifications.detect { |e| e.resource.name == "coffee" && e.action == :reload }).not_to be_nil end it "should make notified resources be capable of acting immediately" do run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") resource.notifies :reload, run_context.resource_collection.find(zen_master: "coffee"), :immediate expect(resource.immediate_notifications.detect { |e| e.resource.name == "coffee" && e.action == :reload }).not_to be_nil end it "should raise an exception if told to act in other than :delay or :immediate(ly)" do run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") expect do resource.notifies :reload, run_context.resource_collection.find(zen_master: "coffee"), :someday end.to raise_error(ArgumentError) end it "should allow multiple notified resources appear in the actions hash" do run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") resource.notifies :reload, run_context.resource_collection.find(zen_master: "coffee") expect(resource.delayed_notifications.detect { |e| e.resource.name == "coffee" && e.action == :reload }).not_to be_nil run_context.resource_collection << Chef::Resource::ZenMaster.new("beans") resource.notifies :reload, run_context.resource_collection.find(zen_master: "beans") expect(resource.delayed_notifications.detect { |e| e.resource.name == "beans" && e.action == :reload }).not_to be_nil end it "creates a notification for a resource that is not yet in the resource collection" do resource.notifies(:restart, service: "apache") expected_notification = Chef::Resource::Notification.new({ service: "apache" }, :restart, resource) expect(resource.delayed_notifications).to include(expected_notification) end it "notifies another resource immediately" do resource.notifies_immediately(:restart, service: "apache") expected_notification = Chef::Resource::Notification.new({ service: "apache" }, :restart, resource) expect(resource.immediate_notifications).to include(expected_notification) end it "notifies a resource to take action at the end of the chef run" do resource.notifies_delayed(:restart, service: "apache") expected_notification = Chef::Resource::Notification.new({ service: "apache" }, :restart, resource) expect(resource.delayed_notifications).to include(expected_notification) end it "notifies a resource with an array for its name via its prettified string name" do run_context.resource_collection << Chef::Resource::ZenMaster.new(%w{coffee tea}) resource.notifies :reload, run_context.resource_collection.find(zen_master: "coffee, tea") expect(resource.delayed_notifications.detect { |e| e.resource.name == "coffee, tea" && e.action == :reload }).not_to be_nil end it "notifies a resource without a name via a string name with brackets" do run_context.resource_collection << Chef::Resource::ZenMaster.new("") resource.notifies :reload, "zen_master[]" end it "notifies a resource without a name via a string name without brackets" do run_context.resource_collection << Chef::Resource::ZenMaster.new("") resource.notifies :reload, "zen_master" expect(resource.delayed_notifications.first.resource).to eql("zen_master") end it "notifies a resource without a name via a hash name with an empty string" do run_context.resource_collection << Chef::Resource::ZenMaster.new("") resource.notifies :reload, zen_master: "" expect(resource.delayed_notifications.first.resource).to eql(zen_master: "") end end describe "subscribes" do it "should make resources appear in the actions hash of subscribed nodes" do run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") zr = run_context.resource_collection.find(zen_master: "coffee") resource.subscribes :reload, zr expect(zr.delayed_notifications.detect { |e| e.resource.name == "funk" && e.action == :reload }).not_to be_nil end it "should make resources appear in the actions hash of subscribed nodes" do run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") zr = run_context.resource_collection.find(zen_master: "coffee") resource.subscribes :reload, zr expect(zr.delayed_notifications.detect { |e| e.resource.name == resource.name && e.action == :reload }).not_to be_nil run_context.resource_collection << Chef::Resource::ZenMaster.new("bean") zrb = run_context.resource_collection.find(zen_master: "bean") zrb.subscribes :reload, zr expect(zr.delayed_notifications.detect { |e| e.resource.name == resource.name && e.action == :reload }).not_to be_nil end it "should make subscribed resources be capable of acting immediately" do run_context.resource_collection << Chef::Resource::ZenMaster.new("coffee") zr = run_context.resource_collection.find(zen_master: "coffee") resource.subscribes :reload, zr, :immediately expect(zr.immediate_notifications.detect { |e| e.resource.name == resource.name && e.action == :reload }).not_to be_nil end end describe "defined_at" do it "should correctly parse source_line on unix-like operating systems" do resource.source_line = "/some/path/to/file.rb:80:in `wombat_tears'" expect(resource.defined_at).to eq("/some/path/to/file.rb line 80") end it "should correctly parse source_line on Windows" do resource.source_line = "C:/some/path/to/file.rb:80 in 1`wombat_tears'" expect(resource.defined_at).to eq("C:/some/path/to/file.rb line 80") end it "should include the cookbook and recipe when it knows it" do resource.source_line = "/some/path/to/file.rb:80:in `wombat_tears'" resource.recipe_name = "wombats" resource.cookbook_name = "animals" expect(resource.defined_at).to eq("animals::wombats line 80") end it "should recognize dynamically defined resources" do expect(resource.defined_at).to eq("dynamically defined") end end describe "to_s" do it "should become a string like resource_name[name]" do zm = Chef::Resource::ZenMaster.new("coffee") expect(zm.to_s).to eql("zen_master[coffee]") end end describe "to_text" do it "prints nice message" do resource_class = Class.new(Chef::Resource) { property :foo, String } resource = resource_class.new("sensitive_property_tests") resource.foo = "some value" expect(resource.to_text).to match(/foo "some value"/) end context "when property is sensitive" do it "supresses that properties value" do resource_class = Class.new(Chef::Resource) { property :foo, String, sensitive: true } resource = resource_class.new("sensitive_property_tests") resource.foo = "some value" expect(resource.to_text).to match(/foo "\*sensitive value suppressed\*"/) end end context "when property is required" do it "does not propagate vailidation errors" do resource_class = Class.new(Chef::Resource) { property :foo, String, required: true } resource = resource_class.new("required_property_tests") expect { resource.to_text }.to_not raise_error Chef::Exceptions::ValidationFailed end end end context "Documentation of resources" do it "can have a description" do c = Class.new(Chef::Resource) do description "my description" end expect(c.description).to eq "my description" end it "can say when it was introduced" do c = Class.new(Chef::Resource) do introduced "14.0" end expect(c.introduced).to eq "14.0" end it "can have some examples" do c = Class.new(Chef::Resource) do examples <<~EOH resource "foo" do foo foo end EOH end expect(c.examples).to eq <<~EOH resource "foo" do foo foo end EOH end end describe "self.resource_name" do context "When resource_name is not set" do it "and there are no provides lines, resource_name is nil" do c = Class.new(Chef::Resource) do end r = c.new("hi") r.declared_type = :d expect(c.resource_name).to be_nil expect(r.resource_name).to be_nil expect(r.declared_type).to eq :d end it "and there are no provides lines, resource_name is used" do c = Class.new(Chef::Resource) do def initialize(*args, &block) @resource_name = :blah super end end r = c.new("hi") r.declared_type = :d expect(c.resource_name).to be_nil expect(r.resource_name).to eq :blah expect(r.declared_type).to eq :d end it "and the resource class gets a late-bound name, resource_name is nil" do c = Class.new(Chef::Resource) do def self.name "ResourceSpecNameTest" end end r = c.new("hi") r.declared_type = :d expect(c.resource_name).to be_nil expect(r.resource_name).to be_nil expect(r.declared_type).to eq :d end end it "resource_name without provides is honored" do c = Class.new(Chef::Resource) do resource_name "blah" end r = c.new("hi") r.declared_type = :d expect(c.resource_name).to eq :blah expect(r.resource_name).to eq :blah expect(r.declared_type).to eq :d end it "setting class.resource_name with 'resource_name = blah' overrides declared_type" do c = Class.new(Chef::Resource) do provides :self_resource_name_test_2 end c.resource_name = :blah r = c.new("hi") r.declared_type = :d expect(c.resource_name).to eq :blah expect(r.resource_name).to eq :blah expect(r.declared_type).to eq :d end it "setting class.resource_name with 'resource_name blah' overrides declared_type" do c = Class.new(Chef::Resource) do resource_name :blah provides :self_resource_name_test_3 end r = c.new("hi") r.declared_type = :d expect(c.resource_name).to eq :blah expect(r.resource_name).to eq :blah expect(r.declared_type).to eq :d end end describe "to_json" do it "should serialize to json" do json = resource.to_json expect(json).to match(/json_class/) expect(json).to match(/instance_vars/) end include_examples "to_json equivalent to Chef::JSONCompat.to_json" do let(:jsonable) { resource } end end describe "to_hash" do context "when the resource has a property with a default" do let(:resource_class) { Class.new(Chef::Resource) { property :a, default: 1 } } it "should include the default in the hash" do expect(resource.to_hash.keys.sort).to eq([:a, :allowed_actions, :params, :provider, :updated, :updated_by_last_action, :before, :name, :source_line, :action, :elapsed_time, :default_guard_interpreter, :guard_interpreter].sort) expect(resource.to_hash[:name]).to eq "funk" expect(resource.to_hash[:a]).to eq 1 end end it "should convert to a hash" do hash = resource.to_hash expected_keys = [ :allowed_actions, :params, :provider, :updated, :updated_by_last_action, :before, :name, :source_line, :action, :elapsed_time, :default_guard_interpreter, :guard_interpreter ] expect(hash.keys - expected_keys).to eq([]) expect(expected_keys - hash.keys).to eq([]) expect(hash[:name]).to eql("funk") end end describe "self.json_create" do it "should deserialize itself from json" do json = Chef::JSONCompat.to_json(resource) serialized_node = Chef::Resource.from_json(json) expect(serialized_node).to be_a_kind_of(Chef::Resource) expect(serialized_node.name).to eql(resource.name) end end describe "ignore_failure" do it "should default to throwing an error if a provider fails for a resource" do expect(resource.ignore_failure).to eq(false) end it "should allow you to set whether a provider should throw exceptions with ignore_failure" do resource.ignore_failure(true) expect(resource.ignore_failure).to eq(true) end it "should allow you to set quiet ignore_failure as a symbol" do resource.ignore_failure(:quiet) expect(resource.ignore_failure).to eq(:quiet) end it "should allow you to set quiet ignore_failure as a string" do resource.ignore_failure("quiet") expect(resource.ignore_failure).to eq("quiet") end end describe "retries" do let(:retriable_resource) do retriable_resource = Chef::Resource::Cat.new("precious", run_context) retriable_resource.provider = Chef::Provider::SnakeOil retriable_resource.action = :purr retriable_resource end before do node.automatic_attrs[:platform] = "fubuntu" node.automatic_attrs[:platform_version] = "10.04" end it "should default to not retrying if a provider fails for a resource" do expect(retriable_resource.retries).to eq(0) end it "should allow you to set how many retries a provider should attempt after a failure" do retriable_resource.retries(2) expect(retriable_resource.retries).to eq(2) end it "should default to a retry delay of 2 seconds" do expect(retriable_resource.retry_delay).to eq(2) end it "should allow you to set the retry delay" do retriable_resource.retry_delay(10) expect(retriable_resource.retry_delay).to eq(10) end it "should keep given value of retries intact after the provider fails for a resource" do retriable_resource.retries(3) retriable_resource.retry_delay(0) # No need to wait. provider = Chef::Provider::SnakeOil.new(retriable_resource, run_context) allow(Chef::Provider::SnakeOil).to receive(:new).and_return(provider) allow(provider).to receive(:action_purr).and_raise expect(retriable_resource).to receive(:sleep).exactly(3).times expect { retriable_resource.run_action(:purr) }.to raise_error(RuntimeError) expect(retriable_resource.retries).to eq(3) end it "should not rescue from non-StandardError exceptions" do retriable_resource.retries(3) retriable_resource.retry_delay(0) # No need to wait. provider = Chef::Provider::SnakeOil.new(retriable_resource, run_context) allow(Chef::Provider::SnakeOil).to receive(:new).and_return(provider) allow(provider).to receive(:action_purr).and_raise(LoadError) expect(retriable_resource).not_to receive(:sleep) expect { retriable_resource.run_action(:purr) }.to raise_error(LoadError) end end it "runs an action by finding its provider, loading the current resource and then running the action" do skip end describe "when updated by a provider" do before do resource.updated_by_last_action(true) end it "records that it was updated" do expect(resource).to be_updated end it "records that the last action updated the resource" do expect(resource).to be_updated_by_last_action end describe "and then run again without being updated" do before do resource.updated_by_last_action(false) end it "reports that it is updated" do expect(resource).to be_updated end it "reports that it was not updated by the last action" do expect(resource).not_to be_updated_by_last_action end end end describe "when invoking its action" do let(:resource) do resource = Chef::Resource.new("provided", run_context) resource.provider = Chef::Provider::SnakeOil resource end before do node.automatic_attrs[:platform] = "fubuntu" node.automatic_attrs[:platform_version] = "10.04" end it "does not run only_if if no only_if command is given" do expect_any_instance_of(Chef::Resource::Conditional).not_to receive(:evaluate) resource.only_if.clear resource.run_action(:purr) end it "runs runs an only_if when one is given" do snitch_variable = nil resource.only_if { snitch_variable = true } expect(resource.only_if.first.positivity).to eq(:only_if) # Chef::Mixin::Command.should_receive(:only_if).with(true, {}).and_return(false) resource.run_action(:purr) expect(snitch_variable).to be_truthy end it "runs multiple only_if conditionals" do snitch_var1, snitch_var2 = nil, nil resource.only_if { snitch_var1 = 1 } resource.only_if { snitch_var2 = 2 } resource.run_action(:purr) expect(snitch_var1).to eq(1) expect(snitch_var2).to eq(2) end it "accepts command options for only_if conditionals" do expect_any_instance_of(Chef::Resource::Conditional).to receive(:evaluate_command).at_least(1).times resource.only_if("true", cwd: "/tmp") expect(resource.only_if.first.command_opts).to eq({ cwd: "/tmp" }) resource.run_action(:purr) end it "runs not_if as a command when it is a string" do expect_any_instance_of(Chef::Resource::Conditional).to receive(:evaluate_command).at_least(1).times resource.not_if "pwd" resource.run_action(:purr) end it "runs not_if as a block when it is a ruby block" do expect_any_instance_of(Chef::Resource::Conditional).to receive(:evaluate_block).at_least(1).times resource.not_if { puts "foo" } resource.run_action(:purr) end it "does not run not_if if no not_if command is given" do expect_any_instance_of(Chef::Resource::Conditional).not_to receive(:evaluate) resource.not_if.clear resource.run_action(:purr) end it "accepts command options for not_if conditionals" do resource.not_if("pwd" , cwd: "/tmp") expect(resource.not_if.first.command_opts).to eq({ cwd: "/tmp" }) end it "accepts multiple not_if conditionals" do snitch_var1, snitch_var2 = true, true resource.not_if { snitch_var1 = nil } resource.not_if { snitch_var2 = false } resource.run_action(:purr) expect(snitch_var1).to be_nil expect(snitch_var2).to be_falsey end it "reports 0 elapsed time if actual elapsed time is < 0" do expected = Time.now allow(Time).to receive(:now).and_return(expected, expected - 1) resource.run_action(:purr) expect(resource.elapsed_time).to eq(0) end describe "guard_interpreter attribute" do it "should be set to :default by default" do expect(resource.guard_interpreter).to eq(:default) end it "if set to :default should return :default when read" do resource.guard_interpreter(:default) expect(resource.guard_interpreter).to eq(:default) end it "should raise Chef::Exceptions::ValidationFailed on an attempt to set the guard_interpreter attribute to something other than a Symbol" do expect { resource.guard_interpreter("command_dot_com") }.to raise_error(Chef::Exceptions::ValidationFailed) end it "should not raise an exception when setting the guard interpreter attribute to a Symbol" do allow(Chef::GuardInterpreter::ResourceGuardInterpreter).to receive(:new).and_return(nil) expect { resource.guard_interpreter(:command_dot_com) }.not_to raise_error end end end describe "should_skip?" do before do resource = Chef::Resource::Cat.new("sugar", run_context) end it "should return false by default" do expect(resource.should_skip?(:purr)).to be_falsey end it "should return false when only_if is met" do resource.only_if { true } expect(resource.should_skip?(:purr)).to be_falsey end it "should return true when only_if is not met" do resource.only_if { false } expect(resource.should_skip?(:purr)).to be_truthy end it "should return true when not_if is met" do resource.not_if { true } expect(resource.should_skip?(:purr)).to be_truthy end it "should return false when not_if is not met" do resource.not_if { false } expect(resource.should_skip?(:purr)).to be_falsey end it "should return true when only_if is met but also not_if is met" do resource.only_if { true } resource.not_if { true } expect(resource.should_skip?(:purr)).to be_truthy end it "should return false when only_if is met and also not_if is not met" do resource.only_if { true } resource.not_if { false } expect(resource.should_skip?(:purr)).to be_falsey end it "should return true when one of multiple only_if's is not met" do resource.only_if { true } resource.only_if { false } resource.only_if { true } expect(resource.should_skip?(:purr)).to be_truthy end it "should return true when one of multiple not_if's is met" do resource.not_if { false } resource.not_if { true } resource.not_if { false } expect(resource.should_skip?(:purr)).to be_truthy end it "should return false when all of multiple only_if's are met" do resource.only_if { true } resource.only_if { true } resource.only_if { true } expect(resource.should_skip?(:purr)).to be_falsey end it "should return false when all of multiple not_if's are not met" do resource.not_if { false } resource.not_if { false } resource.not_if { false } expect(resource.should_skip?(:purr)).to be_falsey end it "should return true when action is :nothing" do expect(resource.should_skip?(:nothing)).to be_truthy end it "should return true when action is :nothing ignoring only_if/not_if conditionals" do resource.only_if { true } resource.not_if { false } expect(resource.should_skip?(:nothing)).to be_truthy end it "should print \"skipped due to action :nothing\" message for doc formatter when action is :nothing" do fdoc = Chef::Formatters.new(:doc, STDOUT, STDERR) allow(run_context).to receive(:events).and_return(fdoc) expect(fdoc).to receive(:puts).with(" (skipped due to action :nothing)", anything()) resource.should_skip?(:nothing) end end describe "when resource action is :nothing" do let(:resource1) do resource1 = Chef::Resource::Cat.new("sugar", run_context) resource1.action = :nothing resource1 end before do node.automatic_attrs[:platform] = "fubuntu" node.automatic_attrs[:platform_version] = "10.04" end it "should not run only_if/not_if conditionals (CHEF-972)" do snitch_var1 = 0 resource1.only_if { snitch_var1 = 1 } resource1.not_if { snitch_var1 = 2 } resource1.run_action(:nothing) expect(snitch_var1).to eq(0) end it "should run only_if/not_if conditionals when notified to run another action (CHEF-972)" do snitch_var1 = snitch_var2 = 0 runner = Chef::Runner.new(run_context) Chef::Provider::SnakeOil.provides :cat resource1.only_if { snitch_var1 = 1 } resource1.not_if { snitch_var2 = 2 } resource2 = Chef::Resource::Cat.new("coffee", run_context) resource2.notifies :purr, resource1 resource2.action = :purr run_context.resource_collection << resource1 run_context.resource_collection << resource2 runner.converge expect(snitch_var1).to eq(1) expect(snitch_var2).to eq(2) end end describe "building the platform map" do let(:klz) { Class.new(Chef::Resource) } before do Chef::Resource::Klz = klz end after do Chef::Resource.send(:remove_const, :Klz) end it "adds mappings for a single platform" do expect(Chef.resource_handler_map).to receive(:set).with( :dinobot, Chef::Resource::Klz, { platform: ["autobots"] } ) klz.provides :dinobot, platform: ["autobots"] end it "adds mappings for multiple platforms" do expect(Chef.resource_handler_map).to receive(:set).with( :energy, Chef::Resource::Klz, { platform: %w{autobots decepticons} } ) klz.provides :energy, platform: %w{autobots decepticons} end it "adds mappings for all platforms" do expect(Chef.resource_handler_map).to receive(:set).with( :tape_deck, Chef::Resource::Klz, {} ) klz.provides :tape_deck end end describe "resource_for_node" do describe "lookups from the platform map" do let(:klz1) { Class.new(Chef::Resource) } before(:each) do Chef::Resource::Klz1 = klz1 node = Chef::Node.new node.name("bumblebee") node.automatic[:platform] = "autobots" node.automatic[:platform_version] = "6.1" Object.const_set("Soundwave", klz1) klz1.provides :soundwave end after(:each) do Object.send(:remove_const, :Soundwave) Chef::Resource.send(:remove_const, :Klz1) end it "returns a resource by short_name if nothing else matches" do expect(Chef::Resource.resource_for_node(:soundwave, node)).to eql(klz1) end end describe "lookups from the platform map" do let(:klz2) { Class.new(Chef::Resource) } before(:each) do Chef::Resource::Klz2 = klz2 node.name("bumblebee") node.automatic[:platform] = "autobots" node.automatic[:platform_version] = "6.1" klz2.provides :dinobot, platform: ["autobots"] Object.const_set("Grimlock", klz2) klz2.provides :grimlock end after(:each) do Object.send(:remove_const, :Grimlock) Chef::Resource.send(:remove_const, :Klz2) end it "returns a resource by short_name and node" do expect(Chef::Resource.resource_for_node(:dinobot, node)).to eql(klz2) end end describe "chef_version constraints and the platform map" do let(:klz3) { Class.new(Chef::Resource) } it "doesn't wire up the provides when chef_version is < 1" do klz3.provides :bulbasaur, chef_version: "< 1.0" # this should be false expect { Chef::Resource.resource_for_node(:bulbasaur, node) }.to raise_error(Chef::Exceptions::NoSuchResourceType) end it "wires up the provides when chef_version is > 1" do klz3.provides :bulbasaur, chef_version: "> 1.0" # this should be true expect(Chef::Resource.resource_for_node(:bulbasaur, node)).to eql(klz3) end it "wires up the default when chef_version is < 1" do klz3.chef_version_for_provides("< 1.0") # this should be false klz3.provides :bulbasaur expect { Chef::Resource.resource_for_node(:bulbasaur, node) }.to raise_error(Chef::Exceptions::NoSuchResourceType) end it "wires up the default when chef_version is > 1" do klz3.chef_version_for_provides("> 1.0") # this should be true klz3.provides :bulbasaur expect(Chef::Resource.resource_for_node(:bulbasaur, node)).to eql(klz3) end end end describe "when creating notifications" do describe "with a string resource spec" do it "creates a delayed notification when timing is not specified" do resource.notifies(:run, "execute[foo]") expect(run_context.delayed_notification_collection.size).to eq(1) end it "creates a delayed notification when :delayed is not specified" do resource.notifies(:run, "execute[foo]", :delayed) expect(run_context.delayed_notification_collection.size).to eq(1) end it "creates an immediate notification when :immediate is specified" do resource.notifies(:run, "execute[foo]", :immediate) expect(run_context.immediate_notification_collection.size).to eq(1) end it "creates an immediate notification when :immediately is specified" do resource.notifies(:run, "execute[foo]", :immediately) expect(run_context.immediate_notification_collection.size).to eq(1) end describe "with a syntax error in the resource spec" do it "raises an exception immmediately" do expect do resource.notifies(:run, "typo[missing-closing-bracket") end.to raise_error(Chef::Exceptions::InvalidResourceSpecification) end end end describe "with a resource reference" do let(:notified_resource) { Chef::Resource.new("punk", run_context) } it "creates a delayed notification when timing is not specified" do resource.notifies(:run, notified_resource) expect(run_context.delayed_notification_collection.size).to eq(1) end it "creates a delayed notification when :delayed is not specified" do resource.notifies(:run, notified_resource, :delayed) expect(run_context.delayed_notification_collection.size).to eq(1) end it "creates an immediate notification when :immediate is specified" do resource.notifies(:run, notified_resource, :immediate) expect(run_context.immediate_notification_collection.size).to eq(1) end it "creates an immediate notification when :immediately is specified" do resource.notifies(:run, notified_resource, :immediately) expect(run_context.immediate_notification_collection.size).to eq(1) end end end describe "resource sensitive attribute" do let(:resource_file) { Chef::Resource::File.new("/nonexistent/CHEF-5098/file", run_context) } let(:action) { :create } def compiled_resource_data(resource, action, err) error_inspector = Chef::Formatters::ErrorInspectors::ResourceFailureInspector.new(resource, action, err) description = Chef::Formatters::ErrorDescription.new("test") error_inspector.add_explanation(description) Chef::Log.info("descrtiption: #{description.inspect},error_inspector: #{error_inspector}") description.sections[1]["Compiled Resource:"] end it "set to false by default" do expect(resource.sensitive).to be_falsey end it "when set to false should show compiled resource for failed resource" do expect { resource_file.run_action(action) }.to raise_error { |err| expect(compiled_resource_data(resource_file, action, err)).to match 'path "/nonexistent/CHEF-5098/file"' } end it "when set to true should show compiled resource for failed resource" do resource_file.sensitive true expect { resource_file.run_action(action) }.to raise_error { |err| expect(compiled_resource_data(resource_file, action, err)).to eql("suppressed sensitive resource output") } end end describe "#action" do let(:resource_class) do Class.new(described_class) do allowed_actions(%i{one two}) end end let(:resource) { resource_class.new("test", nil) } subject { resource.action } context "with a no action" do it { is_expected.to eq [:nothing] } end context "with a default action" do let(:resource_class) do Class.new(described_class) do default_action(:one) end end it { is_expected.to eq [:one] } end context "with a symbol action" do before { resource.action(:one) } it { is_expected.to eq [:one] } end context "with a string action" do before { resource.action("two") } it { is_expected.to eq [:two] } end context "with an array action" do before { resource.action([:two, :one]) } it { is_expected.to eq [:two, :one] } end context "with an assignment" do before { resource.action = :one } it { is_expected.to eq [:one] } end context "with an array assignment" do before { resource.action = [:two, :one] } it { is_expected.to eq [:two, :one] } end context "with an invalid action" do it { expect { resource.action(:three) }.to raise_error Chef::Exceptions::ValidationFailed } end context "with an invalid assignment action" do it { expect { resource.action = :three }.to raise_error Chef::Exceptions::ValidationFailed } end end describe ".default_action" do let(:default_action) {} let(:resource_class) do actions = default_action Class.new(described_class) do default_action(actions) if actions end end subject { resource_class.default_action } context "with no default actions" do it { is_expected.to eq [:nothing] } end context "with a symbol default action" do let(:default_action) { :one } it { is_expected.to eq [:one] } end context "with a string default action" do let(:default_action) { "one" } it { is_expected.to eq [:one] } end context "with an array default action" do let(:default_action) { [:two, :one] } it { is_expected.to eq [:two, :one] } end end describe ".preview_resource" do let(:klass) { Class.new(Chef::Resource) } before do allow(Chef::DSL::Resources).to receive(:add_resource_dsl).with(:test_resource) end it "defaults to false" do expect(klass.preview_resource).to eq false end it "can be set to true" do klass.preview_resource(true) expect(klass.preview_resource).to eq true end it "does not affect provides by default" do expect(Chef.resource_handler_map).to receive(:set).with(:test_resource, klass, { canonical: true }) klass.resource_name(:test_resource) end end describe "tagged" do let(:recipe) do Chef::Recipe.new("hjk", "test", run_context) end describe "with the default node object" do let(:node) { Chef::Node.new } it "should return false for any tags" do expect(resource.tagged?("foo")).to be(false) end end it "should return true from tagged? if node is tagged" do recipe.tag "foo" expect(resource.tagged?("foo")).to be(true) end it "should return false from tagged? if node is not tagged" do expect(resource.tagged?("foo")).to be(false) end end end
35.044299
147
0.678995
2815c7b63dd499e86daecfc507340e15524e7307
63
require 'gitbook/version' require 'omniauth/strategies/gitbook'
31.5
37
0.84127
4aab21b46906bb7529dc1dcbdc2f82f447f08287
1,039
cask "hazel" do version "5.0.6" sha256 "c5b6bdec84eb8111a402d323419f52e64a7bf72f6c1e8e95bd22d38da0728779" url "https://s3.amazonaws.com/Noodlesoft/Hazel-#{version}.dmg", verified: "s3.amazonaws.com/Noodlesoft/" name "Hazel" desc "Automated organization" homepage "https://www.noodlesoft.com/" livecheck do url "https://www.noodlesoft.com/Products/Hazel/generate-appcast.php" strategy :sparkle end auto_updates true app "Hazel.app" uninstall quit: "86Z3GCJ4MF.com.noodlesoft.HazelHelper" zap trash: [ "~/Library/Logs/Hazel", "~/Library/Application Support/Hazel", "~/Library/Caches/com.noodlesoft.HazelHelper", "~/Library/Preferences/com.noodlesoft.Hazel.plist", "~/Library/Preferences/com.noodlesoft.HazelHelper.plist", "~/Library/Preferences/86Z3GCJ4MF.com.noodlesoft.HazelHelper.plist", "~/Library/Saved Application State/com.noodlesoft.Hazel.savedState", "/Applications/Hazel.app/Contents/Library/LoginItems/86Z3GCJ4MF.com.noodlesoft.HazelHelper.app", ] end
31.484848
100
0.739172
915b47234027b66b1c7d7d3e27ace9099359f4dd
260
Rails.application.routes.draw do root to: 'orders#index' resources :orders scope :api, module: 'api' do resources :orders, only: :show end # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
28.888889
101
0.719231
e88fc87b9cd981bcb21e8f167e2040f6e79e01ce
895
class MicropostsController < ApplicationController before_action :logged_in_user, only: [:create, :destroy] before_action :correct_user, only: :destroy def create @micropost = current_user.microposts.build(micropost_params) @micropost.image.attach(params[:micropost][:image]) if @micropost.save flash[:success] = "Micropost created!" redirect_to root_url else @feed_items = current_user.feed.paginate(page: params[:page]) render 'static_pages/home' end end def destroy @micropost.destroy flash[:success] = "Micropost deleted" redirect_to request.referrer || root_url end private def micropost_params params.require(:micropost).permit(:content, :image) end def correct_user @micropost = current_user.microposts.find_by(id: params[:id]) redirect_to root_url if @micropost.nil? end end
27.121212
67
0.705028
7a77ec5bd5333c4f1c09f465acd87d9b44c1027c
2,978
module Solargraph module Pin class BlockParameter < Base include Localized # @return [Pin::Block] attr_reader :block def initialize location, namespace, name, comments, block super(location, namespace, name, comments) @block = block @presence = block.location.range end # @return [Integer] def kind Pin::BLOCK_PARAMETER end # @return [Integer] def completion_item_kind Solargraph::LanguageServer::CompletionItemKinds::VARIABLE end # @return [Integer] def symbol_kind Solargraph::LanguageServer::SymbolKinds::VARIABLE end # The parameter's zero-based location in the block's signature. # # @return [Integer] def index block.parameters.index(self) end def nearly? other return false unless super block.nearly?(other.block) end def try_merge! other return false unless super @block = other.block @presence = other.block.location.range @return_complex_type = nil true end # @return [Array<Solargraph::ComplexType>] def return_complex_type if @return_complex_type.nil? @return_complex_type = ComplexType.new found = nil params = block.docstring.tags(:param) params.each do |p| next unless p.name == name found = p break end if found.nil? and !index.nil? found = params[index] if params[index] && (params[index].name.nil? || params[index].name.empty?) end @return_complex_type = ComplexType.parse(*found.types) unless found.nil? or found.types.nil? end super @return_complex_type end def context block end # @param api_map [ApiMap] def infer api_map return return_complex_type unless return_complex_type.undefined? chain = Source::NodeChainer.chain(block.receiver, filename) clip = api_map.clip_at(location.filename, location.range.start) locals = clip.locals - [self] meths = chain.define(api_map, block, locals) meths.each do |meth| if (Solargraph::CoreFills::METHODS_WITH_YIELDPARAM_SUBTYPES.include?(meth.path)) bmeth = chain.base.define(api_map, context, locals).first return ComplexType::UNDEFINED if bmeth.nil? or bmeth.return_complex_type.undefined? or bmeth.return_complex_type.subtypes.empty? return bmeth.return_complex_type.subtypes.first.qualify(api_map, bmeth.context.namespace) else yps = meth.docstring.tags(:yieldparam) unless yps[index].nil? or yps[index].types.nil? or yps[index].types.empty? return ComplexType.parse(yps[index].types[0]).first end end end ComplexType::UNDEFINED end end end end
30.387755
140
0.614506
bf96bd92ab0671c901c910ded555c2c2793fee6b
18,811
require 'spec_helper' require 'net/ssh/gateway' describe Bosh::Cli::Command::Ssh do include FakeFS::SpecHelpers let(:command) { described_class.new } let(:net_ssh) { double('ssh') } let(:director) { double(Bosh::Cli::Client::Director, uuid: 'director-uuid') } let(:deployment) { 'mycloud' } let(:ssh_session) {instance_double(Bosh::Cli::SSHSession)} let(:manifest) do { 'name' => deployment, 'director_uuid' => 'director-uuid', 'releases' => [], 'jobs' => [ { 'name' => 'dea', 'instances' => 1 } ] } end before do allow(command).to receive_messages(director: director, public_key: 'public_key', show_current_state: nil) File.open('fake-deployment', 'w') { |f| f.write(manifest.to_yaml) } allow(command).to receive(:deployment).and_return('fake-deployment') allow(Process).to receive(:waitpid) allow(command).to receive(:encrypt_password).with('').and_return('encrypted_password') allow(Bosh::Cli::SSHSession).to receive(:new).and_return(ssh_session) allow(ssh_session).to receive(:public_key).and_return("public_key") allow(ssh_session).to receive(:user).and_return("testable_user") allow(ssh_session).to receive(:set_host_session) allow(ssh_session).to receive(:cleanup) allow(ssh_session).to receive(:ssh_private_key_option).and_return("-i/tmp/.bosh/tmp/random_uuid_key") allow(ssh_session).to receive(:ssh_known_host_option).and_return("") end context 'shell' do describe 'invalid arguments' do it 'should fail if there is no deployment set' do allow(command).to receive_messages(deployment: nil) expect { command.shell('dea/1') }.to raise_error(Bosh::Cli::CliError, 'Please choose deployment first') end it 'should fail to setup ssh when a job index is not an Integer' do expect { command.shell('dea/dea') }.to raise_error(Bosh::Cli::CliError, 'Invalid job index, integer number expected') end context 'when there is no instance with that job name in the deployment' do let(:manifest) do { 'name' => deployment, 'director_uuid' => 'director-uuid', 'releases' => [], 'jobs' => [ { 'name' => 'uaa', 'instances' => 1 } ] } end context 'when specifying incorrect the job index' do it 'should fail to setup ssh' do expect { command.shell('dea/0') }.to raise_error(Bosh::Cli::CliError, "Job `dea' doesn't exist") end end context 'when not specifying the job index' do it 'should fail to setup ssh' do expect { command.shell('dea') }.to raise_error(Bosh::Cli::CliError, "Job `dea' doesn't exist") end end end context 'when there is only one instance with that job name in the deployment' do let(:manifest) do { 'name' => deployment, 'director_uuid' => 'director-uuid', 'releases' => [], 'jobs' => [ { 'name' => 'dea', 'instances' => 1 } ] } end it 'should implicitly chooses the only instance if job index not provided' do expect(command).not_to receive(:choose) expect(command).to receive(:setup_interactive_shell).with('mycloud', 'dea', 0) command.shell('dea') end it 'should implicitly chooses the only instance if job name not provided' do expect(command).not_to receive(:choose) expect(command).to receive(:setup_interactive_shell).with('mycloud', 'dea', 0) command.shell end end context 'when there are many instances with that job name in the deployment' do let(:manifest) do { 'name' => deployment, 'director_uuid' => 'director-uuid', 'releases' => [], 'jobs' => [ { 'name' => 'dea', 'instances' => 5 } ] } end it 'should fail to setup ssh when a job index is not given' do expect { command.shell('dea') }.to raise_error(Bosh::Cli::CliError, 'You should specify the job index. There is more than one instance of this job type.') end it 'should prompt for an instance if job name not given' do expect(command).to receive(:choose).and_return(['dea', 3]) expect(command).to receive(:setup_interactive_shell).with('mycloud', 'dea', 3) command.shell end end end describe 'exec' do it 'should try to execute given command remotely' do allow(Net::SSH).to receive(:start) allow(director).to receive(:get_task_result_log).and_return(JSON.dump([{'status' => 'success', 'ip' => '127.0.0.1'}])) allow(director).to receive(:cleanup_ssh) expect(director).to receive(:setup_ssh). with('mycloud', 'dea', 0, 'testable_user', 'public_key', 'encrypted_password'). and_return([:done, 1234]) expect(ssh_session).to receive(:ssh_known_host_path).and_return("fake_path") expect(ssh_session).to receive(:ssh_private_key_path) command.shell('dea/0', 'ls -l') end end describe 'session' do it 'should try to setup interactive shell when a job index is given' do expect(command).to receive(:setup_interactive_shell).with('mycloud', 'dea', 0) command.shell('dea', '0') end it 'should try to setup interactive shell when a job index is given as part of the job name' do expect(command).to receive(:setup_interactive_shell).with('mycloud', 'dea', 0) command.shell('dea/0') end it 'should setup ssh' do expect(Process).to receive(:spawn).with('ssh', '[email protected]', '-i/tmp/.bosh/tmp/random_uuid_key', '-o StrictHostKeyChecking=yes', '') expect(director).to receive(:setup_ssh).and_return([:done, 42]) expect(director).to receive(:get_task_result_log).with(42). and_return(JSON.generate([{'status' => 'success', 'ip' => '127.0.0.1'}])) expect(ssh_session).to receive(:set_host_session).with({'status' => 'success', 'ip' => '127.0.0.1'}) expect(director).to receive(:cleanup_ssh) expect(ssh_session).to receive(:cleanup) command.shell('dea/0') end context 'when strict host key checking is overriden to false' do before do command.add_option(:strict_host_key_checking, 'false') end it 'should disable strict host key checking' do expect(Process).to receive(:spawn).with('ssh', '[email protected]', '-i/tmp/.bosh/tmp/random_uuid_key', "-o StrictHostKeyChecking=no", "") allow(director).to receive(:setup_ssh).and_return([:done, 42]) allow(director).to receive(:get_task_result_log).with(42). and_return(JSON.generate([{'status' => 'success', 'ip' => '127.0.0.1'}])) allow(director).to receive(:cleanup_ssh) command.shell('dea/0') end end it 'should setup ssh with gateway from bosh director' do expect(Net::SSH::Gateway).to receive(:new).with('dummy-host', 'vcap', {}).and_return(net_ssh) expect(net_ssh).to receive(:open).with(anything, 22).and_return(2345) expect(Process).to receive(:spawn).with('ssh', 'testable_user@localhost', '-p', '2345', '-i/tmp/.bosh/tmp/random_uuid_key', "-o StrictHostKeyChecking=yes", "") expect(director).to receive(:setup_ssh).and_return([:done, 42]) expect(director).to receive(:get_task_result_log).with(42). and_return(JSON.generate([{'status' => 'success', 'ip' => '127.0.0.1', 'gateway_host' => 'dummy-host', 'gateway_user' => 'vcap' }])) expect(director).to receive(:cleanup_ssh) expect(ssh_session).to receive(:cleanup) expect(net_ssh).to receive(:close) expect(net_ssh).to receive(:shutdown!) command.shell('dea/0') end it 'should not setup ssh with gateway from bosh director when no_gateway is specified' do allow(Net::SSH::Gateway).to receive(:new){expect(true).to equal?(false)} expect(Process).to receive(:spawn).with('ssh', '[email protected]', "-i/tmp/.bosh/tmp/random_uuid_key", "-o StrictHostKeyChecking=yes", "") expect(director).to receive(:setup_ssh).and_return([:done, 42]) expect(director).to receive(:get_task_result_log).with(42). and_return(JSON.generate([{'status' => 'success', 'ip' => '127.0.0.1', 'gateway_host' => 'dummy-host', 'gateway_user' => 'vcap' }])) expect(director).to receive(:cleanup_ssh) expect(ssh_session).to receive(:cleanup) command.add_option(:no_gateway, true) command.shell('dea/0') end context 'with a gateway host' do let(:gateway_host) { 'gateway-host' } let(:gateway_user) { ENV['USER'] } before do command.add_option(:gateway_host, gateway_host) end it 'should setup ssh with gateway host' do expect(Net::SSH::Gateway).to receive(:new).with(gateway_host, gateway_user, {}).and_return(net_ssh) expect(net_ssh).to receive(:open).with(anything, 22).and_return(2345) expect(Process).to receive(:spawn).with('ssh', 'testable_user@localhost', '-p', '2345', '-i/tmp/.bosh/tmp/random_uuid_key', "-o StrictHostKeyChecking=yes", "") expect(director).to receive(:setup_ssh).and_return([:done, 42]) expect(director).to receive(:get_task_result_log).with(42). and_return(JSON.generate([{'status' => 'success', 'ip' => '127.0.0.1'}])) expect(director).to receive(:cleanup_ssh) expect(ssh_session).to receive(:cleanup) expect(net_ssh).to receive(:close) expect(net_ssh).to receive(:shutdown!) command.shell('dea/0') end it 'should still setup ssh with gateway host even if no_gateway is specified' do command.add_option(:no_gateway, true) expect(Net::SSH::Gateway).to receive(:new).with(gateway_host, gateway_user, {}).and_return(net_ssh) expect(net_ssh).to receive(:open).with(anything, 22).and_return(2345) expect(Process).to receive(:spawn).with('ssh', 'testable_user@localhost', '-p', '2345', '-i/tmp/.bosh/tmp/random_uuid_key', "-o StrictHostKeyChecking=yes", "") expect(director).to receive(:setup_ssh).and_return([:done, 42]) expect(director).to receive(:get_task_result_log).with(42). and_return(JSON.generate([{'status' => 'success', 'ip' => '127.0.0.1'}])) expect(director).to receive(:cleanup_ssh) expect(ssh_session).to receive(:cleanup) expect(net_ssh).to receive(:close) expect(net_ssh).to receive(:shutdown!) command.shell('dea/0') end context 'with a gateway user' do let(:gateway_user) { 'gateway-user' } before do command.add_option(:gateway_user, gateway_user) end it 'should setup ssh with gateway host and user' do expect(Net::SSH::Gateway).to receive(:new).with(gateway_host, gateway_user, {}).and_return(net_ssh) expect(net_ssh).to receive(:open).with(anything, 22).and_return(2345) expect(Process).to receive(:spawn).with('ssh', 'testable_user@localhost', '-p', '2345', '-i/tmp/.bosh/tmp/random_uuid_key', "-o StrictHostKeyChecking=yes", "") expect(director).to receive(:setup_ssh).and_return([:done, 42]) expect(director).to receive(:get_task_result_log).with(42). and_return(JSON.generate([{'status' => 'success', 'ip' => '127.0.0.1'}])) expect(director).to receive(:cleanup_ssh) expect(ssh_session).to receive(:cleanup) expect(net_ssh).to receive(:close) expect(net_ssh).to receive(:shutdown!) command.shell('dea/0') end it 'should setup ssh with gateway host and user and identity file' do expect(Net::SSH::Gateway).to receive(:new).with(gateway_host, gateway_user, {keys: ['/tmp/private_file']}).and_return(net_ssh) expect(net_ssh).to receive(:open).with(anything, 22).and_return(2345) expect(Process).to receive(:spawn).with('ssh', 'testable_user@localhost', '-p', '2345', '-i/tmp/.bosh/tmp/random_uuid_key', "-o StrictHostKeyChecking=yes", "") expect(director).to receive(:setup_ssh).and_return([:done, 42]) expect(director).to receive(:get_task_result_log).with(42). and_return(JSON.generate([{'status' => 'success', 'ip' => '127.0.0.1'}])) expect(director).to receive(:cleanup_ssh) expect(ssh_session).to receive(:cleanup) expect(net_ssh).to receive(:close) expect(net_ssh).to receive(:shutdown!) command.add_option(:gateway_identity_file, '/tmp/private_file') command.shell('dea/0') end it 'should fail to setup ssh with gateway host and user when authentication fails' do expect(Net::SSH::Gateway).to receive(:new).with(gateway_host, gateway_user, {}).and_raise(Net::SSH::AuthenticationFailed) expect(director).to receive(:setup_ssh).and_return([:done, 42]) expect(director).to receive(:get_task_result_log).with(42). and_return(JSON.generate([{'status' => 'success', 'ip' => '127.0.0.1'}])) expect(director).to receive(:cleanup_ssh) expect(ssh_session).to receive(:cleanup) expect { command.shell('dea/0') }.to raise_error(Bosh::Cli::CliError, "Authentication failed with gateway #{gateway_host} and user #{gateway_user}.") end context 'when ssh gateway is setup' do before do allow(Net::SSH::Gateway).to receive(:new).with(gateway_host, gateway_user, {}).and_return(net_ssh) allow(net_ssh).to receive(:open).with(anything, 22).and_return(2345) allow(director).to receive(:setup_ssh).and_return([:done, 42]) allow(director).to receive(:cleanup_ssh) allow(net_ssh).to receive(:close) allow(net_ssh).to receive(:shutdown!) end context 'when strict host key checking is overriden to false' do before do command.add_option(:strict_host_key_checking, 'false') end it 'should disable strict host key checking' do expect(Process).to receive(:spawn).with('ssh', 'testable_user@localhost', '-p', '2345', '-i/tmp/.bosh/tmp/random_uuid_key', "-o StrictHostKeyChecking=no", "") allow(director).to receive(:get_task_result_log).with(42). and_return(JSON.generate([{'status' => 'success', 'ip' => '127.0.0.1'}])) command.shell('dea/0') end end context 'when host returns a host_public_key' do before do allow(ssh_session).to receive(:ssh_known_host_option).and_return("-o UserKnownHostsFile=/tmp/.bosh/tmp/random_uuid_known_hosts") allow(director).to receive(:get_task_result_log).and_return(JSON.dump([{'status' => 'success', 'ip' => '127.0.0.1', 'host_public_key' => 'fake_public_key'}])) end after do allow(director).to receive(:get_task_result_log).and_return(JSON.dump([{'status' => 'success', 'ip' => '127.0.0.1'}])) end it 'should call ssh with bosh known hosts path' do expect(Process).to receive(:spawn).with('ssh', 'testable_user@localhost','-p', '2345', '-i/tmp/.bosh/tmp/random_uuid_key', '-o StrictHostKeyChecking=yes', "-o UserKnownHostsFile=/tmp/.bosh/tmp/random_uuid_known_hosts") command.shell('dea/0') end end end end end end end context '#scp' do context 'when the job name does not exist' do let(:manifest) do { 'name' => deployment, 'director_uuid' => 'director-uuid', 'releases' => [], 'jobs' => [ { 'name' => 'uaa', 'instances' => 1 } ] } end it 'should fail to setup ssh when a job name does not exists in deployment' do command.add_option(:upload, true) allow(command).to receive(:job_exists_in_deployment?).and_return(false) expect { command.scp('dea/0') }.to raise_error(Bosh::Cli::CliError, "Job `dea' doesn't exist") end end it 'sets up ssh to copy files' do allow(Net::SSH).to receive(:start) allow(director).to receive(:get_task_result_log).and_return(JSON.dump([{'status' => 'success', 'ip' => '127.0.0.1'}])) allow(director).to receive(:cleanup_ssh) expect(director).to receive(:setup_ssh). with('mycloud', 'dea', 0, 'testable_user', 'public_key', 'encrypted_password'). and_return([:done, 1234]) command.add_option(:upload, false) allow(command).to receive(:job_exists_in_deployment?).and_return(true) expect(ssh_session).to receive(:ssh_known_host_path).and_return("fake_path") expect(ssh_session).to receive(:ssh_private_key_path) command.scp('dea', '0', 'test', 'test') end end context '#cleanup' do context 'when the job name does not exist' do let(:manifest) do { 'name' => deployment, 'director_uuid' => 'director-uuid', 'releases' => [], 'jobs' => [ { 'name' => 'uaa', 'instances' => 1 } ] } end it 'should fail to setup ssh when a job name does not exists in deployment' do allow(command).to receive(:job_exists_in_deployment?).and_return(false) expect { command.cleanup('dea/0') }.to raise_error(Bosh::Cli::CliError, "Job `dea' doesn't exist") end end end end
41.617257
234
0.585721
28c565b9baec463a09196b4a86dd27a89db32aac
5,216
# rubocop:disable RSpec/MultipleMemoizedHelpers RSpec.describe QuotaSearchService do subject(:service) { described_class.new(filter, current_page, per_page) } around do |example| TimeMachine.now { example.run } end let(:validity_start_date) { Date.yesterday } let(:quota_order_number1) { create :quota_order_number } let!(:measure1) { create :measure, ordernumber: quota_order_number1.quota_order_number_id, validity_start_date: validity_start_date } let!(:quota_definition1) do create :quota_definition, quota_order_number_sid: quota_order_number1.quota_order_number_sid, quota_order_number_id: quota_order_number1.quota_order_number_id, critical_state: 'Y', validity_start_date: validity_start_date end let!(:quota_order_number_origin1) do create :quota_order_number_origin, :with_geographical_area, quota_order_number_sid: quota_order_number1.quota_order_number_sid end let(:quota_order_number2) { create :quota_order_number } let!(:measure2) { create :measure, ordernumber: quota_order_number2.quota_order_number_id, validity_start_date: validity_start_date } let!(:quota_definition2) do create :quota_definition, quota_order_number_sid: quota_order_number2.quota_order_number_sid, quota_order_number_id: quota_order_number2.quota_order_number_id, critical_state: 'N', validity_start_date: validity_start_date end let!(:quota_order_number_origin2) do create :quota_order_number_origin, :with_geographical_area, quota_order_number_sid: quota_order_number2.quota_order_number_sid end let(:current_page) { 1 } let(:per_page) { 20 } before do measure1.update(geographical_area_id: quota_order_number_origin1.geographical_area_id) measure2.update(geographical_area_id: quota_order_number_origin2.geographical_area_id) end describe '#status' do let(:filter) { { 'status' => 'not+exhausted' } } it 'unescapes status values' do expect(service.status).to eq('not_exhausted') end end describe '#call' do context 'when filtering by a fully-qualified goods_nomenclature_item_id' do let(:filter) { { 'goods_nomenclature_item_id' => measure1.goods_nomenclature_item_id } } it 'returns the correct quota definition' do expect(service.call).to eq([quota_definition1]) end end context 'when filtering by a NOT fully-qualified goods_nomenclature_item_id' do let(:filter) { { 'goods_nomenclature_item_id' => measure1.goods_nomenclature_item_id[0..6] } } it 'returns the correct quota definition' do expect(service.call).to eq([quota_definition1]) end end context 'when filtering by the geographical_area_id' do let(:filter) { { 'geographical_area_id' => quota_order_number_origin1.geographical_area_id } } it 'returns the correct quota definition' do expect(service.call).to eq([quota_definition1]) end end context 'when filtering by the order number' do let(:filter) { { 'order_number' => quota_order_number1.quota_order_number_id } } it 'returns the correct quota definition' do expect(service.call).to eq([quota_definition1]) end end context 'when filtering by the quota definition critical state' do let(:filter) { { 'critical' => 'Y' } } it 'returns the correct quota definition' do expect(service.call).to eq([quota_definition1]) end end context 'when filtering by status exhausted' do let(:filter) { { 'status' => 'exhausted' } } before do create :quota_exhaustion_event, quota_definition: quota_definition1 end it 'returns the correct quota definition' do expect(service.call).to eq([quota_definition1]) end end context 'when filtering by status not exhausted' do let(:filter) { { 'status' => 'not_exhausted' } } before do create :quota_exhaustion_event, quota_definition: quota_definition1 end it 'returns the correct quota definition' do expect(service.call).to eq([quota_definition2]) end end context 'when filtering by status blocked' do let(:filter) { { 'status' => 'blocked' } } before do create :quota_blocking_period, quota_definition_sid: quota_definition1.quota_definition_sid, blocking_start_date: Date.current, blocking_end_date: 1.year.from_now end it 'returns the correct quota definition' do expect(service.call).to eq([quota_definition1]) end end context 'when filtering by status not blocked' do let(:filter) { { 'status' => 'not_blocked' } } before do create :quota_blocking_period, quota_definition_sid: quota_definition1.quota_definition_sid, blocking_start_date: Date.current, blocking_end_date: 1.year.from_now end it 'returns the correct quota definition' do expect(service.call).to eq([quota_definition2]) end end end end # rubocop:enable RSpec/MultipleMemoizedHelpers
34.315789
135
0.699003
1ac9e3e3fd345ff801d804020a0c714906337bb7
250
# testing local development require 'compass-blend-modes' add_import_path '../stylesheets' # testing installed gem # require 'color-schemer' # Set this to the root of your project when deployed: http_path = 'html' css_dir = 'css' sass_dir = 'sass'
20.833333
53
0.748
1d39fcf7b0726ac3063f1dd14a29cc3761e4386e
487
require_relative "test_helper" require "cassandra" class CassandraDriverTest < Minitest::Test def test_connect assert_timeout(Cassandra::Errors::NoHostsAvailable) do Cassandra.cluster(hosts: [connect_host], connect_timeout: 1) end end def test_read # unable to test Cassandra::Errors::TimeoutError assert_timeout(Cassandra::Errors::NoHostsAvailable, timeout: 2) do Cassandra.cluster(hosts: [read_host], port: read_port, timeout: 1) end end end
25.631579
72
0.743326
7ac5434fa501446b8eb4d1dc623a8b096e3f80f5
2,314
module TeamSchedule class Task # Team of the task # @!method team # @return [Team] the team # Task from where to calculate the schedule # @!method task # @return [Task] the task # Local time when the task will be begun # @!method local_time # @return [Float] local time of the team in hours attr_reader :team, :task, :local_time # Initializes a team schedule task # # @param [Task] task the task # @param [Float] local_time local time of the team in hours def initialize(task:, local_time:) @task = task @team = task.team @local_time = local_time end # Name of the team # # @return [String] the name of the team def team_name team.name end # Calculates local schedule when the task will begin and end # # @return [String] the local schedule in 12 hour format def local_schedule "#{format_hours(local_time)}" \ " - #{format_hours(local_time + task.team_cost)}" end # Calculates schedule in UTC when the task will begin and end # # @return [String] the schedule in UTC in 12 hour format def utc_schedule "#{format_hours(utc_time)}" \ " - #{format_hours(utc_time + task.team_cost)}" end # External ID of the task # # @return [String] the external id def external_id task.external_id end # Converts the scheduled task to a hash # # @return [Hash] def to_h { team_name: team_name, local_schedule: local_schedule, utc_schedule: utc_schedule, external_id: external_id } end private # Formats an hour into 12 hour format # # @param [Float] time_in_hours hours in number # @return [String] string representation of the hours in 12 hour format def format_hours(time_in_hours) total_minutes = time_in_hours * 60 hours = total_minutes.to_i / 60 minutes = total_minutes - hours * 60 long_time_format = "#{hours.to_i}:#{minutes.to_i}" Time.parse(long_time_format).strftime("%l:%M%P").lstrip end # Calculates the hour in UTC when the task will begin # # @return [Float] hour of the day when the task will begin def utc_time self.local_time - team.timezone end end end
25.711111
75
0.632671
396f0959f6bd633428d059ee7063d4a5d2d9d6c5
1,747
# frozen_string_literal: true # @api private # @since 0.1.0 class Siege::System::DSL::CommandSet # @since 0.1.0 include Enumerable # @return [void] # # @api private # @since 0.1.0 def initialize @lock = Siege::Core::Lock.new @commands = [] end # @param command [Siege::System::DSL::Command::Abstract] # @return [void] # # @api private # @since 0.1.0 def add(command) thread_safe { commands.push(command) } end alias_method :<<, :add # @return [Enumerable] # # @api private # @since 0.1.0 def each(&block) thread_safe { block_given? ? commands.each(&block) : commands.each } end # @return [Siege::System::DSL::CommandSet] # # @api private # @since 0.1.0 def dup thread_safe do self.class.new.tap do |duplicate| each { |command| duplicate.add(command.dup) } end end end # @param command_set [Siege::System::DSL::CommandSet] # @param concat_condition [Block] # @yield [command] # @yieldparam command [Siege::System::DSL::Commands::Abstract] # @return [void] # # @api private # @since 0.1.0 def concat(command_set, &concat_condition) thread_safe do if block_given? command_set.each do |command| command.dup.tap { |cmd| add(cmd) if yield(cmd) } end else # :nocov: command_set.each { |command| add(command.dup) } # NOTE: unreachable at this moment # :nocov: end end end private # @return [Array<Siege::System::DSL::Command::Abstract>] # # @api private # @since 0.1.0 attr_reader :commands # @param block [Block] # @return [Any] # # @api private # @since 0.1.0 def thread_safe(&block) @lock.synchronize(&block) end end
20.08046
90
0.609044
11054d55dd85a0f80005549a78e1492803def3a4
1,983
class GenericJourney attr_reader :steps, :params def initialize(first_step_class, framework, slug, params, paths) @steps = [] @params = HashWithIndifferentAccess.new @paths = paths @framework = framework @slug = slug klass = first_step_class loop do permitted = params.permit(klass.permit_list) step = klass.new(permitted) @params.merge! permitted @steps << step return if step.slug == slug || step.invalid? || step.final? klass = step.next_step_class end end def first_step steps.first end def current_step steps.last end def previous_step steps[-2] end def next_step current_step.next_step_class&.new end def first_step_path @paths.question @framework, first_step.slug end def current_step_path @paths.question @framework, current_slug, params end def previous_step_path if previous_slug.present? @paths.question @framework, previous_slug, params else start_path end end def previous_step_text return 'Return to your account' if @slug == 'choose-services' return 'Return to services' if @slug == 'choose-locations' nil end def next_step_path @paths.question @framework, next_slug, params end def form_path @paths.answer @framework, current_slug end def start_path @paths.home end def previous_questions_and_answers return params if current_step.final? || current_step.try(:all_keys_needed?) params.except(*current_step.class.permitted_keys) end def template [self.class.journey_name.underscore, @framework.downcase, current_step.template].join('/') end delegate :slug, to: :current_step, prefix: :current, allow_nil: true delegate :slug, to: :previous_step, prefix: :previous, allow_nil: true delegate :slug, to: :next_step, prefix: :next, allow_nil: true delegate :valid?, :errors, to: :current_step delegate :inputs, to: :current_step end
21.791209
94
0.698941
79b9c80aeaedcdce28674ee0efd72eb1e9aad220
304
# frozen_string_literal: true module DogBiscuits module AwardingInstitution extend ActiveSupport::Concern included do property :awarding_institution, predicate: ::RDF::Vocab::BF2.grantingInstitution do |index| index.as :stored_searchable, :facetable end end end end
21.714286
97
0.730263
79c7dedcc3a1d17b4c7bef95dd88241f7a547489
1,247
class User < ActiveRecord::Base has_many :contacts devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable, :registerable, :omniauthable MESSAGE = "Happy Birthday!!" def add_contact(options_hash) self.contacts.build(options_hash) end def self.trigger_birthday_messages! self.all.each do |user| user.message ? m = user.message : m = MESSAGE user.contacts.birthdays_today.each do |contact| UserMailer.sms_sent_notification(user, contact).deliver if contact.send_message(m) end end end def self.find_for_google_oauth2(access_token, signed_in_resource=nil) data = access_token.info user = User.where(:provider => access_token.provider, :uid => access_token.uid ).first if user return user else registered_user = User.where(:email => access_token.info.email).first if registered_user return registered_user else user = User.create(first_name: data["first_name"], last_name: data["last_name"], provider:access_token.provider, email: data["email"], uid: access_token.uid , password: Devise.friendly_token[0,20] ) end end end end
28.340909
90
0.675221
115df908b14b0d154e2f472af58911bd8092e584
1,586
# -*- coding:binary -*- require 'spec_helper' RSpec.describe Msf::Exploit::Remote::HTTP::Wordpress::Base do subject do mod = ::Msf::Exploit.new mod.extend ::Msf::Exploit::Remote::HTTP::Wordpress mod.send(:initialize) mod end describe '#wordpress_and_online?' do before :example do allow(subject).to receive(:send_request_cgi) do res = Rex::Proto::Http::Response.new res.code = wp_code res.body = wp_body res end end let(:wp_code) { 200 } context 'when wp-content in body' do let(:wp_body) { '<a href="http://domain.com/wp-content/themes/a/style.css">' } it { expect(subject.wordpress_and_online?).to be_kind_of Rex::Proto::Http::Response } end context 'when wlwmanifest in body' do let(:wp_body) { '<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="https://domain.com/wp-includes/wlwmanifest.xml" />' } it { expect(subject.wordpress_and_online?).to be_kind_of Rex::Proto::Http::Response } end context 'when pingback in body' do let(:wp_body) { '<link rel="pingback" href="https://domain.com/xmlrpc.php" />' } it { expect(subject.wordpress_and_online?).to be_kind_of Rex::Proto::Http::Response } end context 'when status code != 200' do let(:wp_body) { nil } let(:wp_code) { 404 } it { expect(subject.wordpress_and_online?).to be_nil } end context 'when no match in body' do let(:wp_body) { 'Invalid body' } it { expect(subject.wordpress_and_online?).to be_nil } end end end
29.37037
141
0.642497
d5014b59420532cdfd7a5f078ae006294ce780a1
23,059
require 'test_helper' class RemoteLitleTest < Test::Unit::TestCase def setup @gateway = LitleGateway.new(fixtures(:litle)) @credit_card_hash = { first_name: 'John', last_name: 'Smith', month: '01', year: '2012', brand: 'visa', number: '4457010000000009', verification_value: '349' } @options = { order_id: '1', email: '[email protected]', billing_address: { company: 'testCompany', address1: '1 Main St.', city: 'Burlington', state: 'MA', country: 'USA', zip: '01803-3747', phone: '1234567890' } } @credit_card1 = CreditCard.new(@credit_card_hash) @credit_card2 = CreditCard.new( first_name: 'Joe', last_name: 'Green', month: '06', year: '2012', brand: 'visa', number: '4457010100000008', verification_value: '992' ) @credit_card_nsf = CreditCard.new( first_name: 'Joe', last_name: 'Green', month: '06', year: '2012', brand: 'visa', number: '4488282659650110', verification_value: '992' ) @decrypted_apple_pay = ActiveMerchant::Billing::NetworkTokenizationCreditCard.new( { month: '01', year: '2012', brand: 'visa', number: '44444444400009', payment_cryptogram: 'BwABBJQ1AgAAAAAgJDUCAAAAAAA=' }) @decrypted_android_pay = ActiveMerchant::Billing::NetworkTokenizationCreditCard.new( { source: :android_pay, month: '01', year: '2021', brand: 'visa', number: '4457000300000007', payment_cryptogram: 'BwABBJQ1AgAAAAAgJDUCAAAAAAA=' }) @check = check( name: 'Tom Black', routing_number: '011075150', account_number: '4099999992', account_type: 'checking' ) @authorize_check = check( name: 'John Smith', routing_number: '011075150', account_number: '1099999999', account_type: 'checking' ) @store_check = check( routing_number: '011100012', account_number: '1099999998' ) end def test_successful_authorization assert response = @gateway.authorize(10010, @credit_card1, @options) assert_success response assert_equal 'Approved', response.message end def test_successful_authorization_with_merchant_data options = @options.merge( affiliate: 'some-affiliate', campaign: 'super-awesome-campaign', merchant_grouping_id: 'brilliant-group' ) assert @gateway.authorize(10010, @credit_card1, options) end def test_successful_authorization_with_echeck options = @options.merge({ order_id: '38', order_source: 'telephone' }) assert response = @gateway.authorize(3002, @authorize_check, options) assert_success response assert_equal 'Approved', response.message end def test_successful_authorization_with_paypage_registration_with_month_year_verification paypage_registration = ActiveMerchant::Billing::LitlePaypageRegistration.new( 'XkNDRGZDTGZyS2RBSTVCazJNSmdWam5TQ2gyTGhydFh0Mk5qZ0Z3cVp5VlNBN00rcGRZdHF6amFRWEttbVBnYw==', month: '11', year: '12', verification_value: '123', name: 'Joe Payer' ) assert response = @gateway.authorize(5090, paypage_registration, billing_address: address) assert_success response assert_equal 'Approved', response.message end def test_successful_authorization_with_paypage_registration_without_month_year_verification_name paypage_registration = ActiveMerchant::Billing::LitlePaypageRegistration.new( 'XkNDRGZDTGZyS2RBSTVCazJNSmdWam5TQ2gyTGhydFh0Mk5qZ0Z3cVp5VlNBN00rcGRZdHF6amFRWEttbVBnYw==' ) assert response = @gateway.authorize(5090, paypage_registration, billing_address: address) assert_success response assert_equal 'Approved', response.message end def test_avs_and_cvv_result assert response = @gateway.authorize(10010, @credit_card1, @options) assert_equal 'X', response.avs_result['code'] assert_equal 'M', response.cvv_result['code'] end def test_unsuccessful_authorization assert response = @gateway.authorize(60060, @credit_card2, { :order_id=>'6', :billing_address=>{ :name => 'Joe Green', :address1 => '6 Main St.', :city => 'Derry', :state => 'NH', :zip => '03038', :country => 'US' }, } ) assert_failure response assert_equal 'Insufficient Funds', response.message end def test_successful_purchase assert response = @gateway.purchase(10010, @credit_card1, @options) assert_success response assert_equal 'Approved', response.message end def test_successful_purchase_with_some_empty_address_parts assert response = @gateway.purchase(10010, @credit_card1, { order_id: '1', email: '[email protected]', billing_address: { } }) assert_success response assert_equal 'Approved', response.message end def test_successful_purchase_with_debt_repayment_flag assert response = @gateway.purchase(10010, @credit_card1, @options.merge(debt_repayment: true)) assert_success response assert_equal 'Approved', response.message end def test_successful_purchase_with_3ds_fields options = @options.merge({ order_source: '3dsAuthenticated', xid: 'BwABBJQ1AgAAAAAgJDUCAAAAAAA=', cavv: 'BwABBJQ1AgAAAAAgJDUCAAAAAAA=' }) assert response = @gateway.purchase(10010, @credit_card1, options) assert_success response assert_equal 'Approved', response.message end def test_successful_purchase_with_apple_pay assert response = @gateway.purchase(10010, @decrypted_apple_pay) assert_success response assert_equal 'Approved', response.message end def test_successful_purchase_with_android_pay assert response = @gateway.purchase(10000, @decrypted_android_pay) assert_success response assert_equal 'Approved', response.message end def test_successful_purchase_with_paypage_registration_with_month_year_verification paypage_registration = ActiveMerchant::Billing::LitlePaypageRegistration.new( 'XkNDRGZDTGZyS2RBSTVCazJNSmdWam5TQ2gyTGhydFh0Mk5qZ0Z3cVp5VlNBN00rcGRZdHF6amFRWEttbVBnYw==', month: '11', year: '12', verification_value: '123', name: 'Joe Payer' ) assert response = @gateway.purchase(5090, paypage_registration, billing_address: address) assert_success response assert_equal 'Approved', response.message end def test_successful_purchase_with_merchant_data options = @options.merge( affiliate: 'some-affiliate', campaign: 'super-awesome-campaign', merchant_grouping_id: 'brilliant-group' ) assert response = @gateway.purchase(10010, @credit_card1, options) assert_success response assert_equal 'Approved', response.message end def test_successful_purchase_with_echeck options = @options.merge({ order_id: '42', order_source: 'telephone' }) assert response = @gateway.purchase(2004, @check, options) assert_success response assert_equal 'Approved', response.message end def test_successful_purchase_with_paypage_registration_without_month_year_verification paypage_registration = ActiveMerchant::Billing::LitlePaypageRegistration.new( 'XkNDRGZDTGZyS2RBSTVCazJNSmdWam5TQ2gyTGhydFh0Mk5qZ0Z3cVp5VlNBN00rcGRZdHF6amFRWEttbVBnYw==' ) assert response = @gateway.purchase(5090, paypage_registration, billing_address: address) assert_success response assert_equal 'Approved', response.message end def test_unsuccessful_purchase assert response = @gateway.purchase(60060, @credit_card2, { :order_id=>'6', :billing_address=>{ :name => 'Joe Green', :address1 => '6 Main St.', :city => 'Derry', :state => 'NH', :zip => '03038', :country => 'US' }, }) assert_failure response assert_equal 'Insufficient Funds', response.message end def test_authorize_capture_refund_void assert auth = @gateway.authorize(10010, @credit_card1, @options) assert_success auth assert_equal 'Approved', auth.message assert capture = @gateway.capture(nil, auth.authorization) assert_success capture assert_equal 'Approved', capture.message assert refund = @gateway.refund(nil, capture.authorization) assert_success refund assert_equal 'Approved', refund.message assert void = @gateway.void(refund.authorization) assert_success void assert_equal 'Approved', void.message end def test_authorize_and_capture_with_stored_credential_recurring credit_card = CreditCard.new(@credit_card_hash.merge( number: '4100200300011001', month: '05', year: '2021', verification_value: '463' )) initial_options = @options.merge( order_id: 'Net_Id1', stored_credential: { initial_transaction: true, reason_type: 'recurring', initiator: 'merchant', network_transaction_id: nil } ) assert auth = @gateway.authorize(4999, credit_card, initial_options) assert_success auth assert_equal 'Approved', auth.message assert network_transaction_id = auth.params['networkTransactionId'] assert capture = @gateway.capture(4999, auth.authorization) assert_success capture assert_equal 'Approved', capture.message used_options = @options.merge( order_id: 'Net_Id1a', stored_credential: { initial_transaction: false, reason_type: 'recurring', initiator: 'merchant', network_transaction_id: network_transaction_id } ) assert auth = @gateway.authorize(4999, credit_card, used_options) assert_success auth assert_equal 'Approved', auth.message assert capture = @gateway.capture(4999, auth.authorization) assert_success capture assert_equal 'Approved', capture.message end def test_authorize_and_capture_with_stored_credential_installment credit_card = CreditCard.new(@credit_card_hash.merge( number: '4457010000000009', month: '01', year: '2021', verification_value: '349' )) initial_options = @options.merge( order_id: 'Net_Id2', stored_credential: { initial_transaction: true, reason_type: 'installment', initiator: 'merchant', network_transaction_id: nil } ) assert auth = @gateway.authorize(5500, credit_card, initial_options) assert_success auth assert_equal 'Approved', auth.message assert network_transaction_id = auth.params['networkTransactionId'] assert capture = @gateway.capture(5500, auth.authorization) assert_success capture assert_equal 'Approved', capture.message used_options = @options.merge( order_id: 'Net_Id2a', stored_credential: { initial_transaction: false, reason_type: 'installment', initiator: 'merchant', network_transaction_id: network_transaction_id } ) assert auth = @gateway.authorize(5500, credit_card, used_options) assert_success auth assert_equal 'Approved', auth.message assert capture = @gateway.capture(5500, auth.authorization) assert_success capture assert_equal 'Approved', capture.message end def test_authorize_and_capture_with_stored_credential_mit_card_on_file credit_card = CreditCard.new(@credit_card_hash.merge( number: '4457000800000002', month: '01', year: '2021', verification_value: '349' )) initial_options = @options.merge( order_id: 'Net_Id3', stored_credential: { initial_transaction: true, reason_type: 'unscheduled', initiator: 'merchant', network_transaction_id: nil } ) assert auth = @gateway.authorize(5500, credit_card, initial_options) assert_success auth assert_equal 'Approved', auth.message assert network_transaction_id = auth.params['networkTransactionId'] assert capture = @gateway.capture(5500, auth.authorization) assert_success capture assert_equal 'Approved', capture.message used_options = @options.merge( order_id: 'Net_Id3a', stored_credential: { initial_transaction: false, reason_type: 'unscheduled', initiator: 'merchant', network_transaction_id: network_transaction_id } ) assert auth = @gateway.authorize(2500, credit_card, used_options) assert_success auth assert_equal 'Approved', auth.message assert capture = @gateway.capture(2500, auth.authorization) assert_success capture assert_equal 'Approved', capture.message end def test_authorize_and_capture_with_stored_credential_cit_card_on_file credit_card = CreditCard.new(@credit_card_hash.merge( number: '4457000800000002', month: '01', year: '2021', verification_value: '349' )) initial_options = @options.merge( order_id: 'Net_Id3', stored_credential: { initial_transaction: true, reason_type: 'unscheduled', initiator: 'cardholder', network_transaction_id: nil } ) assert auth = @gateway.authorize(5500, credit_card, initial_options) assert_success auth assert_equal 'Approved', auth.message assert network_transaction_id = auth.params['networkTransactionId'] assert capture = @gateway.capture(5500, auth.authorization) assert_success capture assert_equal 'Approved', capture.message used_options = @options.merge( order_id: 'Net_Id3b', stored_credential: { initial_transaction: false, reason_type: 'unscheduled', initiator: 'cardholder', network_transaction_id: network_transaction_id } ) assert auth = @gateway.authorize(4000, credit_card, used_options) assert_success auth assert_equal 'Approved', auth.message assert capture = @gateway.capture(4000, auth.authorization) assert_success capture assert_equal 'Approved', capture.message end def test_purchase_with_stored_credential_cit_card_on_file_non_ecommerce credit_card = CreditCard.new(@credit_card_hash.merge( number: '4457000800000002', month: '01', year: '2021', verification_value: '349' )) initial_options = @options.merge( order_id: 'Net_Id3', order_source: '3dsAuthenticated', xid: 'BwABBJQ1AgAAAAAgJDUCAAAAAAA=', cavv: 'BwABBJQ1AgAAAAAgJDUCAAAAAAA=', stored_credential: { initial_transaction: true, reason_type: 'unscheduled', initiator: 'cardholder', network_transaction_id: nil } ) assert auth = @gateway.purchase(5500, credit_card, initial_options) assert_success auth assert_equal 'Approved', auth.message assert network_transaction_id = auth.params['networkTransactionId'] used_options = @options.merge( order_id: 'Net_Id3b', order_source: '3dsAuthenticated', xid: 'BwABBJQ1AgAAAAAgJDUCAAAAAAA=', cavv: 'BwABBJQ1AgAAAAAgJDUCAAAAAAA=', stored_credential: { initial_transaction: false, reason_type: 'unscheduled', initiator: 'cardholder', network_transaction_id: network_transaction_id } ) assert auth = @gateway.purchase(4000, credit_card, used_options) assert_success auth assert_equal 'Approved', auth.message end def test_void_with_echeck options = @options.merge({ order_id: '42', order_source: 'telephone' }) assert sale = @gateway.purchase(2004, @check, options) assert void = @gateway.void(sale.authorization) assert_success void assert_equal 'Approved', void.message end def test_void_authorization assert auth = @gateway.authorize(10010, @credit_card1, @options) assert void = @gateway.void(auth.authorization) assert_success void assert_equal 'Approved', void.message end def test_unsuccessful_void assert void = @gateway.void('123456789012345360;authorization;100') assert_failure void assert_equal 'No transaction found with specified litleTxnId', void.message end def test_partial_refund assert purchase = @gateway.purchase(10010, @credit_card1, @options) assert refund = @gateway.refund(444, purchase.authorization) assert_success refund assert_equal 'Approved', refund.message end def test_partial_refund_with_echeck options = @options.merge({ order_id: '82', order_source: 'telephone' }) assert purchase = @gateway.purchase(2004, @check, options) assert refund = @gateway.refund(444, purchase.authorization) assert_success refund assert_equal 'Approved', refund.message end def test_partial_capture assert auth = @gateway.authorize(10010, @credit_card1, @options) assert_success auth assert_equal 'Approved', auth.message assert capture = @gateway.capture(5005, auth.authorization) assert_success capture assert_equal 'Approved', capture.message end def test_full_amount_capture assert auth = @gateway.authorize(10010, @credit_card1, @options) assert_success auth assert_equal 'Approved', auth.message assert capture = @gateway.capture(10010, auth.authorization) assert_success capture assert_equal 'Approved', capture.message end def test_nil_amount_capture assert auth = @gateway.authorize(10010, @credit_card1, @options) assert_success auth assert_equal 'Approved', auth.message assert capture = @gateway.capture(nil, auth.authorization) assert_success capture assert_equal 'Approved', capture.message end def test_capture_unsuccessful assert capture_response = @gateway.capture(10010, '123456789012345360') assert_failure capture_response assert_equal 'No transaction found with specified litleTxnId', capture_response.message end def test_refund_unsuccessful assert credit_response = @gateway.refund(10010, '123456789012345360') assert_failure credit_response assert_equal 'No transaction found with specified litleTxnId', credit_response.message end def test_void_unsuccessful assert void_response = @gateway.void('123456789012345360') assert_failure void_response assert_equal 'No transaction found with specified litleTxnId', void_response.message end def test_store_successful credit_card = CreditCard.new(@credit_card_hash.merge(:number => '4457119922390123')) assert store_response = @gateway.store(credit_card, :order_id => '50') assert_success store_response assert_equal 'Account number was successfully registered', store_response.message assert_equal '445711', store_response.params['bin'] assert_equal 'VI', store_response.params['type'] assert_equal '801', store_response.params['response'] assert_equal '1111222233330123', store_response.params['litleToken'] end def test_store_with_paypage_registration_id_successful paypage_registration_id = 'cDZJcmd1VjNlYXNaSlRMTGpocVZQY1NNlYE4ZW5UTko4NU9KK3p1L1p1VzE4ZWVPQVlSUHNITG1JN2I0NzlyTg=' assert store_response = @gateway.store(paypage_registration_id, :order_id => '50') assert_success store_response assert_equal 'Account number was successfully registered', store_response.message assert_equal '801', store_response.params['response'] assert_equal '1111222233334444', store_response.params['litleToken'] end def test_store_unsuccessful credit_card = CreditCard.new(@credit_card_hash.merge(:number => '4457119999999999')) assert store_response = @gateway.store(credit_card, :order_id => '51') assert_failure store_response assert_equal 'Credit card number was invalid', store_response.message assert_equal '820', store_response.params['response'] end def test_store_and_purchase_with_token_successful credit_card = CreditCard.new(@credit_card_hash.merge(:number => '4100280190123000')) assert store_response = @gateway.store(credit_card, :order_id => '50') assert_success store_response token = store_response.authorization assert_equal store_response.params['litleToken'], token assert response = @gateway.purchase(10010, token) assert_success response assert_equal 'Approved', response.message end def test_echeck_store_and_purchase assert store_response = @gateway.store(@store_check) assert_success store_response assert_equal 'Account number was successfully registered', store_response.message token = store_response.authorization assert_equal store_response.params['litleToken'], token assert response = @gateway.purchase(10010, token) assert_success response assert_equal 'Approved', response.message end def test_successful_verify assert response = @gateway.verify(@credit_card1, @options) assert_success response assert_equal 'Approved', response.message assert_success response.responses.last, 'The void should succeed' end def test_unsuccessful_verify assert response = @gateway.verify(@credit_card_nsf, @options) assert_failure response assert_match %r{Insufficient Funds}, response.message end def test_successful_purchase_with_dynamic_descriptors assert response = @gateway.purchase(10010, @credit_card1, @options.merge( descriptor_name: 'SuperCompany', descriptor_phone: '9193341121' )) assert_success response assert_equal 'Approved', response.message end def test_unsuccessful_xml_schema_validation credit_card = CreditCard.new(@credit_card_hash.merge(:number => '123456')) assert store_response = @gateway.store(credit_card, :order_id => '51') assert_failure store_response assert_match(/^Error validating xml data against the schema/, store_response.message) assert_equal '1', store_response.params['response'] end def test_purchase_scrubbing credit_card = CreditCard.new(@credit_card_hash.merge(verification_value: '999')) transcript = capture_transcript(@gateway) do @gateway.purchase(10010, credit_card, @options) end transcript = @gateway.scrub(transcript) assert_scrubbed(credit_card.number, transcript) assert_scrubbed(credit_card.verification_value, transcript) assert_scrubbed(@gateway.options[:login], transcript) assert_scrubbed(@gateway.options[:password], transcript) end def test_echeck_scrubbing options = @options.merge({ order_id: '42', order_source: 'telephone' }) transcript = capture_transcript(@gateway) do @gateway.purchase(2004, @check, options) end transcript = @gateway.scrub(transcript) assert_scrubbed(@check.account_number, transcript) assert_scrubbed(@check.routing_number, transcript) assert_scrubbed(@gateway.options[:login], transcript) assert_scrubbed(@gateway.options[:password], transcript) end end
32.431786
119
0.711739
878cc526a3e7ca219b88c8f807aaad537a58b5b0
384
class AddBackIndexes < ActiveRecord::Migration def self.up # reduce index size add_index :photos, :status_message_guid add_index :comments, [:commentable_id, :commentable_type] end def self.down remove_index :comments, :column => [:commentable_id, :commentable_type] remove_index :photos, :column => :status_message_guid # reduce index size end end
24
75
0.726563
6a409ab0be96705e9aefd37ced4f2cbc0e748f3b
6,848
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require 'thor/base' class Amazing desc "hello", "say hello" def hello puts "Hello" end end describe Thor::Base do describe "#initialize" do it "sets arguments array" do base = MyCounter.new [1, 2] base.first.must == 1 base.second.must == 2 end it "sets arguments default values" do base = MyCounter.new [1] base.second.must == 2 end it "sets options default values" do base = MyCounter.new [1, 2] base.options[:third].must == 3 end it "allows options to be given as symbols or strings" do base = MyCounter.new [1, 2], :third => 4 base.options[:third].must == 4 base = MyCounter.new [1, 2], "third" => 4 base.options[:third].must == 4 end it "creates options with indifferent access" do base = MyCounter.new [1, 2], :third => 3 base.options['third'].must == 3 end it "creates options with magic predicates" do base = MyCounter.new [1, 2], :third => 3 base.options.third.must == 3 end end describe "#no_tasks" do it "avoids methods being added as tasks" do MyScript.tasks.keys.must include("animal") MyScript.tasks.keys.must_not include("this_is_not_a_task") end end describe "#argument" do it "sets a value as required and creates an accessor for it" do MyCounter.start(["1", "2", "--third", "3"])[0].must == 1 Scripts::MyScript.start(["zoo", "my_special_param", "--param=normal_param"]).must == "my_special_param" end it "does not set a value in the options hash" do BrokenCounter.start(["1", "2", "--third", "3"])[0].must be_nil end end describe "#arguments" do it "returns the arguments for the class" do MyCounter.arguments.must have(2).items end end describe "#class_option" do it "sets options class wise" do MyCounter.start(["1", "2", "--third", "3"])[2].must == 3 end it "does not create an acessor for it" do BrokenCounter.start(["1", "2", "--third", "3"])[3].must be_false end end describe "#class_options" do it "sets default options overwriting superclass definitions" do options = Scripts::MyScript.class_options options[:force].must_not be_required end end describe "#remove_argument" do it "removes previous defined arguments from class" do ClearCounter.arguments.must be_empty end it "undefine accessors if required" do ClearCounter.new.must_not respond_to(:first) ClearCounter.new.must_not respond_to(:second) end end describe "#remove_class_option" do it "removes previous defined class option" do ClearCounter.class_options[:third].must be_nil end end describe "#class_options_help" do before(:each) do @content = capture(:stdout) { MyCounter.help(Thor::Base.shell.new) } end it "shows options description" do @content.must =~ /# The third argument/ end it "shows usage with banner content" do @content.must =~ /\[\-\-third=THREE\]/ end it "shows default values below description" do @content.must =~ /# Default: 3/ end it "shows options in different groups" do @content.must =~ /Options\:/ @content.must =~ /Runtime options\:/ @content.must =~ /\-p, \[\-\-pretend\]/ end it "use padding in options that does not have aliases" do @content.must =~ /^ -t, \[--third/ @content.must =~ /^ \[--fourth/ end it "allows extra options to be given" do hash = { "Foo" => B.class_options.values } content = capture(:stdout) { MyCounter.send(:class_options_help, Thor::Base.shell.new, hash) } content.must =~ /Foo options\:/ content.must =~ /--last-name=LAST_NAME/ end end describe "#namespace" do it "returns the default class namespace" do Scripts::MyScript.namespace.must == "scripts:my_script" end it "sets a namespace to the class" do Scripts::MyDefaults.namespace.must == "default" end end describe "#group" do it "sets a group" do MyScript.group.must == "script" end it "inherits the group from parent" do MyChildScript.group.must == "script" end it "defaults to standard if no group is given" do Amazing.group.must == "standard" end end describe "#subclasses" do it "tracks its subclasses in an Array" do Thor::Base.subclasses.must include(MyScript) Thor::Base.subclasses.must include(MyChildScript) Thor::Base.subclasses.must include(Scripts::MyScript) end end describe "#subclass_files" do it "returns tracked subclasses, grouped by the files they come from" do thorfile = File.join(File.dirname(__FILE__), "fixtures", "script.thor") Thor::Base.subclass_files[File.expand_path(thorfile)].must == [ MyScript, MyScript::AnotherScript, MyChildScript, Scripts::MyScript, Scripts::MyDefaults, Scripts::ChildDefault ] end it "tracks a single subclass across multiple files" do thorfile = File.join(File.dirname(__FILE__), "fixtures", "task.thor") Thor::Base.subclass_files[File.expand_path(thorfile)].must include(Amazing) Thor::Base.subclass_files[File.expand_path(__FILE__)].must include(Amazing) end end describe "#tasks" do it "returns a list with all tasks defined in this class" do MyChildScript.new.must respond_to("animal") MyChildScript.tasks.keys.must include("animal") end it "raises an error if a task with reserved word is defined" do lambda { klass = Class.new(Thor::Group) klass.class_eval "def shell; end" }.must raise_error(RuntimeError, /"shell" is a Thor reserved word and cannot be defined as task/) end end describe "#all_tasks" do it "returns a list with all tasks defined in this class plus superclasses" do MyChildScript.new.must respond_to("foo") MyChildScript.all_tasks.keys.must include("foo") end end describe "#remove_task" do it "removes the task from its tasks hash" do MyChildScript.tasks.keys.must_not include("bar") MyChildScript.tasks.keys.must_not include("boom") end it "undefines the method if desired" do MyChildScript.new.must_not respond_to("boom") end end describe "#from_superclass" do it "does not send a method to the superclass if the superclass does not respond to it" do MyCounter.get_from_super.must == 13 end end describe "#start" do it "raises an error instead of rescueing if --debug is given" do lambda { MyScript.start ["what", "--debug"] }.must raise_error(Thor::UndefinedTaskError, /the 'what' task of MyScript is private/) end end end
28.894515
109
0.651431
018325f5d53c9d2bb8038b26bf9e8fc6fb0dc348
5,147
# # Author:: Ezra Zygmuntowicz (<[email protected]>) # Copyright:: Copyright 2008-2016, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "chef/provider/package" require "chef/mixin/command" require "chef/resource/package" require "chef/util/path_helper" class Chef class Provider class Package class Portage < Chef::Provider::Package provides :package, platform: "gentoo" provides :portage_package PACKAGE_NAME_PATTERN = %r{(?:([^/]+)/)?([^/]+)} def load_current_resource @current_resource = Chef::Resource::Package.new(@new_resource.name) @current_resource.package_name(@new_resource.package_name) category, pkg = %r{^#{PACKAGE_NAME_PATTERN}$}.match(@new_resource.package_name)[1, 2] globsafe_category = category ? Chef::Util::PathHelper.escape_glob_dir(category) : nil globsafe_pkg = Chef::Util::PathHelper.escape_glob_dir(pkg) possibilities = Dir["/var/db/pkg/#{globsafe_category || "*"}/#{globsafe_pkg}-*"].map { |d| d.sub(%r{/var/db/pkg/}, "") } versions = possibilities.map do |entry| if entry =~ %r{[^/]+/#{Regexp.escape(pkg)}\-(\d[\.\d]*[a-z]?((_(alpha|beta|pre|rc|p)\d*)*)?(-r\d+)?)} [$&, $1] end end.compact if versions.size > 1 atoms = versions.map { |v| v.first }.sort categories = atoms.map { |v| v.split("/")[0] }.uniq if !category && categories.size > 1 raise Chef::Exceptions::Package, "Multiple packages found for #{@new_resource.package_name}: #{atoms.join(" ")}. Specify a category." end elsif versions.size == 1 @current_resource.version(versions.first.last) Chef::Log.debug("#{@new_resource} current version #{$1}") end @current_resource end def parse_emerge(package, txt) availables = {} found_package_name = nil txt.each_line do |line| if line =~ /\*\s+#{PACKAGE_NAME_PATTERN}/ found_package_name = $&.delete("*").strip if package =~ /\// #the category is specified if found_package_name == package availables[found_package_name] = nil end else #the category is not specified if found_package_name.split("/").last == package availables[found_package_name] = nil end end end if line =~ /Latest version available: (.*)/ && availables.has_key?(found_package_name) availables[found_package_name] = $1.strip end end if availables.size > 1 # shouldn't happen if a category is specified so just use `package` raise Chef::Exceptions::Package, "Multiple emerge results found for #{package}: #{availables.keys.join(" ")}. Specify a category." end availables.values.first end def candidate_version return @candidate_version if @candidate_version status = shell_out("emerge --color n --nospinner --search #{@new_resource.package_name.split('/').last}") available, installed = parse_emerge(@new_resource.package_name, status.stdout) @candidate_version = available unless status.exitstatus == 0 raise Chef::Exceptions::Package, "emerge --search failed - #{status.inspect}!" end @candidate_version end def install_package(name, version) pkg = "=#{name}-#{version}" if version =~ /^\~(.+)/ # If we start with a tilde pkg = "~#{name}-#{$1}" end shell_out!( "emerge -g --color n --nospinner --quiet#{expand_options(@new_resource.options)} #{pkg}" ) end def upgrade_package(name, version) install_package(name, version) end def remove_package(name, version) if version pkg = "=#{@new_resource.package_name}-#{version}" else pkg = "#{@new_resource.package_name}" end shell_out!( "emerge --unmerge --color n --nospinner --quiet#{expand_options(@new_resource.options)} #{pkg}" ) end def purge_package(name, version) remove_package(name, version) end end end end end
36.503546
148
0.578007
4a07de3d54d4e1871451b7b5ed19ce477f9517b2
4,502
# frozen_string_literal: true module ActsAsTaggableOnMongoid module Taggable class TagTypeDefinition # This module adds methods to a model for the tag_list fields for the Mongoid::Changable attributes of a field # including: # * tag_list? # * tag_list_change # * tag_list_changed? # * tag_list_will_change! # * tag_list_changed_from_default? # * tag_list_was # * tagger_tag_list_was # * tag_lists_was # * reset_tag_list! # * reset_tag_list_to_default! # :reek:FeatureEnvy # :reek:DuplicateMethodCall module Changeable def default_tagger_tag_list(taggable) list = ActsAsTaggableOnMongoid::TaggerTagList.new(self, nil) list_default = default.dup list_default.taggable = taggable list_default.tagger = list_default.tagger list[list_default.tagger] = list_default list.taggable = taggable list end private def add_list_exists tag_definition = self tag_list_name = tag_definition.tag_list_name owner.taggable_mixin.module_eval do define_method("#{tag_list_name}?") do tag_list_cache_on(tag_definition).values.any?(&:present?) end end end def add_list_change tag_definition = self tag_list_name = tag_definition.tag_list_name owner.taggable_mixin.module_eval do define_method("#{tag_list_name}_change") do get_tag_list_change(tag_definition) end end end def add_list_changed tag_definition = self tag_list_name = tag_definition.tag_list_name owner.taggable_mixin.module_eval do define_method("#{tag_list_name}_changed?") do get_tag_list_changed(tag_definition) end end end def add_will_change tag_definition = self tag_list_name = tag_definition.tag_list_name owner.taggable_mixin.module_eval do define_method("#{tag_list_name}_will_change!") do attribute_will_change! tag_list_name end end end def add_changed_from_default? tag_definition = self tag_list_name = tag_definition.tag_list_name owner.taggable_mixin.module_eval do define_method("#{tag_list_name}_changed_from_default?") do changed_value = tag_definition.default_tagger_tag_list(self) current_value = tag_list_cache_on(tag_definition) !(changed_value <=> current_value)&.zero? end end end def add_get_was tag_definition = self tag_list_name = tag_definition.tag_list_name owner.taggable_mixin.module_eval do define_method("#{tag_list_name}_was") do get_tag_list_was tag_definition end end end def add_get_lists_was tag_definition = self owner.taggable_mixin.module_eval do define_method("#{tag_definition.tagger_tag_lists_name}_was") do get_tag_lists_was(tag_definition) end end end def add_tagger_get_was tag_definition = self tag_list_name = tag_definition.tag_list_name owner.taggable_mixin.module_eval do define_method("tagger_#{tag_list_name}_was") do |tagger| get_tagger_list_was(tag_definition, tagger) end end end def add_reset_list tag_definition = self tag_list_name = tag_definition.tag_list_name owner.taggable_mixin.module_eval do define_method("reset_#{tag_list_name}!") do return unless public_send("#{tag_list_name}_changed?") tagger_tag_list_set(changed_attributes[tag_list_name].dup) end end end def add_reset_to_default tag_definition = self tag_list_name = tag_definition.tag_list_name owner.taggable_mixin.module_eval do define_method("reset_#{tag_list_name}_to_default!") do tagger_tag_list_set(tag_definition.default_tagger_tag_list(self)) end end end end end end end
29.233766
116
0.608396
4ab693d1ebba676c768b7de7798b2569113f5d2c
159
require_relative './database_connection' if ENV['RACK'] == 'test' DatabaseConnection.setup("aircouch_test") else DatabaseConnection.setup("aircouch") end
19.875
43
0.767296
91b667906a939c6d13407724cb452b83fb700e2a
324
module UsersHelper #引数で与えられたユーザーのGravatar画像を返す def gravatar_for(user,options = { size:80}) gravatar_id = Digest::MD5::hexdigest(user.email.downcase) size = options[:size] gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}" image_tag(gravatar_url,alt: user.name,class:"gravatar") end end
29.454545
78
0.75
3992a2dccc7bd8cf71f64bbed9b5b8038976b07c
202
class AddTranslationToKeywords < ActiveRecord::Migration def self.up add_column :keywords, :title_dz, :string, :limit => 100 end def self.down remove_column :keywords, :title_dz end end
20.2
59
0.732673
ed6f33e81ba7660820ea065d19ed1a9b396e4fb4
1,264
class Ship < Formula desc "Reducing the overhead of maintaining 3rd-party applications in Kubernetes" homepage "https://www.replicated.com/ship" url "https://github.com/replicatedhq/ship/archive/v0.49.0.tar.gz" sha256 "8c2516affcea3df8525e3c7c6361191dd065f68337332ecf90150f0f798a406f" bottle do cellar :any_skip_relocation sha256 "b6704868731685a3b7c61ea37f4689f3dd62136a5a8e2ff7017e0461ded6e6eb" => :mojave sha256 "a5e13785da153743a42faa16fddce30af147e8849286e3409e0c204e22ae0c9c" => :high_sierra sha256 "ac220633ec132a245c5b4521e775b790425126aa71f401764b82b91620c412eb" => :sierra end depends_on "go" => :build depends_on "node@8" => :build depends_on "yarn" => :build def install ENV["GOPATH"] = buildpath srcpath = buildpath/"src/github.com/replicatedhq/ship" srcpath.install buildpath.children srcpath.cd do system "make", "VERSION=#{version}", "build-minimal" bin.install "bin/ship" end end test do assert_match(/#{version}/, shell_output("#{bin}/ship version")) assert_match(/Usage:/, shell_output("#{bin}/ship --help")) test_chart = "https://github.com/replicatedhq/test-charts/tree/master/plain-k8s" system bin/"ship", "init", "--headless", test_chart end end
35.111111
93
0.736551
28fdea0f060d240a7cf085479f87d5a02f7011da
6,116
require 'fog/identity/telefonica' module Fog module Identity class Telefonica class V2 < Fog::Service requires :telefonica_auth_url recognizes :telefonica_auth_token, :telefonica_management_url, :persistent, :telefonica_service_type, :telefonica_service_name, :telefonica_tenant, :telefonica_tenant_id, :telefonica_api_key, :telefonica_username, :telefonica_identity_endpoint, :current_user, :current_tenant, :telefonica_region, :telefonica_endpoint_type, :telefonica_cache_ttl, :telefonica_project_name, :telefonica_project_id, :telefonica_project_domain, :telefonica_user_domain, :telefonica_domain_name, :telefonica_project_domain_id, :telefonica_user_domain_id, :telefonica_domain_id, :telefonica_identity_prefix, :telefonica_endpoint_path_matches model_path 'fog/identity/telefonica/v2/models' model :tenant collection :tenants model :user collection :users model :role collection :roles model :ec2_credential collection :ec2_credentials request_path 'fog/identity/telefonica/v2/requests' request :check_token request :validate_token request :list_tenants request :create_tenant request :get_tenant request :get_tenants_by_id request :get_tenants_by_name request :update_tenant request :delete_tenant request :list_users request :create_user request :update_user request :delete_user request :get_user_by_id request :get_user_by_name request :add_user_to_tenant request :remove_user_from_tenant request :list_endpoints_for_token request :list_roles_for_user_on_tenant request :list_user_global_roles request :create_role request :delete_role request :delete_user_role request :create_user_role request :get_role request :list_roles request :set_tenant request :create_ec2_credential request :delete_ec2_credential request :get_ec2_credential request :list_ec2_credentials class Mock attr_reader :auth_token attr_reader :auth_token_expiration attr_reader :current_user attr_reader :current_tenant attr_reader :unscoped_token def self.data @users ||= {} @roles ||= {} @tenants ||= {} @ec2_credentials ||= Hash.new { |hash, key| hash[key] = {} } @user_tenant_membership ||= {} @data ||= Hash.new do |hash, key| hash[key] = { :users => @users, :roles => @roles, :tenants => @tenants, :ec2_credentials => @ec2_credentials, :user_tenant_membership => @user_tenant_membership } end end def self.reset! @data = nil @users = nil @roles = nil @tenants = nil @ec2_credentials = nil end def initialize(options = {}) @telefonica_username = options[:telefonica_username] || 'admin' @telefonica_tenant = options[:telefonica_tenant] || 'admin' @telefonica_auth_uri = URI.parse(options[:telefonica_auth_url]) @telefonica_management_url = @telefonica_auth_uri.to_s @auth_token = Fog::Mock.random_base64(64) @auth_token_expiration = (Time.now.utc + 86400).iso8601 @admin_tenant = data[:tenants].values.find do |u| u['name'] == 'admin' end if @telefonica_tenant @current_tenant = data[:tenants].values.find do |u| u['name'] == @telefonica_tenant end if @current_tenant @current_tenant_id = @current_tenant['id'] else @current_tenant_id = Fog::Mock.random_hex(32) @current_tenant = data[:tenants][@current_tenant_id] = { 'id' => @current_tenant_id, 'name' => @telefonica_tenant } end else @current_tenant = @admin_tenant end @current_user = data[:users].values.find do |u| u['name'] == @telefonica_username end @current_tenant_id = Fog::Mock.random_hex(32) if @current_user @current_user_id = @current_user['id'] else @current_user_id = Fog::Mock.random_hex(32) @current_user = data[:users][@current_user_id] = { 'id' => @current_user_id, 'name' => @telefonica_username, 'email' => "#{@telefonica_username}@mock.com", 'tenantId' => Fog::Mock.random_numbers(6).to_s, 'enabled' => true } end end def data self.class.data[@telefonica_username] end def reset_data self.class.data.delete(@telefonica_username) end def credentials {:provider => 'telefonica', :telefonica_auth_url => @telefonica_auth_uri.to_s, :telefonica_auth_token => @auth_token, :telefonica_management_url => @telefonica_management_url, :telefonica_current_user_id => @telefonica_current_user_id, :current_user => @current_user, :current_tenant => @current_tenant} end end class Real < Fog::Identity::Telefonica::Real private def default_service_type(_) DEFAULT_SERVICE_TYPE end end end end end end
33.604396
100
0.556736
289c796d0e341c390858d6c50f03ae29c6038f6b
127
require 'rails_helper' RSpec.describe Person, :type => :model do pending "add some examples to (or delete) #{__FILE__}" end
21.166667
56
0.724409
61f70337c2c1614b596527ecdea2c767cf484e4a
431
# used just for windows currently if(ARGV[0] != '-t') puts "format: -t secs, command arg1 arg2..." exit end require 'timeout' out = nil begin Timeout::timeout(ARGV[1].to_f) { out = IO.popen ARGV[2..-1].join(' ') while !out.eof? print out.read 1024 end Process.wait out.pid } rescue Timeout::Error puts 'timed out' Process.kill "KILL", out.pid # if this fails it may have died right then end
19.590909
74
0.635731
39cb08f9e4f03f6d35401b18d9e59397072258a5
318
# frozen_string_literal: true require 'securenative' require 'rspec' RSpec.describe SecureNative::Utils::DateUtils do it 'converts to timestamp' do iso_8601_date = '2020-05-20T15:07:13Z' result = SecureNative::Utils::DateUtils.to_timestamp(iso_8601_date) expect(result).to eq(iso_8601_date) end end
22.714286
71
0.757862
7a327fcb413ce1434412f3ad09f239d6817451fc
227
class CreateChallenges < ActiveRecord::Migration[5.2] def change create_table :challenges do |t| t.integer :sub1 t.integer :sub2 t.integer :status t.text :log t.timestamps end end end
17.461538
53
0.634361
5d86d8a497d4d15e0493908e1095abd2c8390a52
3,190
# Questions Controller class QuestionsController < ApplicationController before_action :set_question, except: [:reassign] before_action :set_quizzes, only: [:reassign] before_action :check_solution_errors, only: [:update] authorize_resource layout 'administration' def edit I18n.locale = @question.locale_with_inheritance end def update return if @errors @success = true if @question.update(question_params) if question_params[:question_sort] == 'free' answer = @question.answers.first @question.answers.where.not(id: answer.id).destroy_all end if question_params[:solution] answer = @question.answers.first @question.answers.where.not(id: answer.id).destroy_all answer.update(text: question_params[:solution].tex_mc_answer, value: true, explanation: question_params[:solution].explanation) end @no_solution_update = question_params[:solution].nil? @errors = @question.errors end def reassign question_old = Question.find_by_id(params[:id]) I18n.locale = question_old.locale_with_inheritance @question, answer_map = question_old.duplicate @question.editors = [current_user] @quizzes.each do |q| Quiz.find_by_id(q).replace_reference!(question_old, @question, answer_map) end I18n.locale = @question.locale_with_inheritance if question_params[:type] == 'edit' redirect_to edit_question_path(@question) return end @quizzable = @question @mode = 'reassigned' render 'events/fill_quizzable_area' end def set_solution_type content = if params[:type] == 'MampfExpression' MampfExpression.trivial_instance elsif params[:type] == 'MampfMatrix' MampfMatrix.trivial_instance elsif params[:type] == 'MampfTuple' MampfTuple.trivial_instance elsif params[:type] == 'MampfSet' MampfSet.trivial_instance end @solution = Solution.new(content) end private def set_question @question = Question.find_by_id(params[:id]) return if @question.present? redirect_to :root, alert: I18n.t('controllers.no_question') end def set_quizzes @quizzes = params[:question].select { |k, v| v == '1' && k.start_with?('quiz-') } .keys.map { |k| k.remove('quiz-').to_i } end def check_solution_errors return unless params[:question][:solution_error].present? @errors = ActiveModel::Errors.new(@question) @errors.add(:base, params[:question][:solution_error]) end def question_params result = params.require(:question) .permit(:label, :text, :type, :hint, :level, :question_sort, :independent, :vertex_id, :solution_type, solution_content: {}) if result[:solution_type] && result[:solution_content] result[:solution] = Solution.from_hash(result[:solution_type], result[:solution_content]) end result.except(:solution_type, :solution_content) end end
33.93617
85
0.646708
e8b696114fbd72a0c6f4b9b2773d8accf7dedada
1,635
require 'openssl' require 'net/ssh/errors' require 'net/ssh/transport/algorithms' require 'net/ssh/transport/constants' require 'net/ssh/transport/kex' module Net module BloomfireSSH module Test # An implementation of a key-exchange strategy specifically for unit tests. # (This strategy would never really work against a real SSH server--it makes # too many assumptions about the server's response.) # # This registers itself with the transport key-exchange system as the # "test" algorithm. class Kex include Net::BloomfireSSH::Transport::Constants # Creates a new instance of the testing key-exchange algorithm with the # given arguments. def initialize(algorithms, connection, data) @connection = connection end # Exchange keys with the server. This returns a hash of constant values, # and does not actually exchange keys. def exchange_keys result = Net::BloomfireSSH::Buffer.from(:byte, NEWKEYS) @connection.send_message(result) buffer = @connection.next_message raise Net::BloomfireSSH::Exception, "expected NEWKEYS" unless buffer.type == NEWKEYS { session_id: "abc-xyz", server_key: OpenSSL::PKey::RSA.new(512), shared_secret: OpenSSL::BN.new("1234567890", 10), hashing_algorithm: OpenSSL::Digest::SHA1 } end end end end end Net::BloomfireSSH::Transport::Algorithms::ALGORITHMS[:kex] << "test" Net::BloomfireSSH::Transport::Kex::MAP["test"] = Net::BloomfireSSH::Test::Kex
33.367347
94
0.659327
28a085cc58b66677f6ce2f5e007dce6e441132a0
13,870
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::RedundantRegexpCharacterClass, :config do context 'with a character class containing a single character' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = /[a]/ ^^^ Redundant single-element character class, `[a]` can be replaced with `a`. RUBY expect_correction(<<~RUBY) foo = /a/ RUBY end end context 'with multiple character classes containing single characters' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = /[a]b[c]d/ ^^^ Redundant single-element character class, `[a]` can be replaced with `a`. ^^^ Redundant single-element character class, `[c]` can be replaced with `c`. RUBY expect_correction(<<~RUBY) foo = /abcd/ RUBY end end context 'with a character class containing a single character inside a group' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = /([a])/ ^^^ Redundant single-element character class, `[a]` can be replaced with `a`. RUBY expect_correction(<<~RUBY) foo = /(a)/ RUBY end end context 'with a character class containing a single character before `+` quantifier' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = /[a]+/ ^^^ Redundant single-element character class, `[a]` can be replaced with `a`. RUBY expect_correction(<<~RUBY) foo = /a+/ RUBY end end context 'with a character class containing a single character before `{n,m}` quantifier' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = /[a]{2,10}/ ^^^ Redundant single-element character class, `[a]` can be replaced with `a`. RUBY expect_correction(<<~RUBY) foo = /a{2,10}/ RUBY end end context 'with %r{} regexp' do context 'with a character class containing a single character' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = %r{[a]} ^^^ Redundant single-element character class, `[a]` can be replaced with `a`. RUBY expect_correction(<<~RUBY) foo = %r{a} RUBY end end context 'with multiple character classes containing single characters' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = %r{[a]b[c]d} ^^^ Redundant single-element character class, `[a]` can be replaced with `a`. ^^^ Redundant single-element character class, `[c]` can be replaced with `c`. RUBY expect_correction(<<~RUBY) foo = %r{abcd} RUBY end end context 'with a character class containing a single character inside a group' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = %r{([a])} ^^^ Redundant single-element character class, `[a]` can be replaced with `a`. RUBY expect_correction(<<~RUBY) foo = %r{(a)} RUBY end end context 'with a character class containing a single character before `+` quantifier' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = %r{[a]+} ^^^ Redundant single-element character class, `[a]` can be replaced with `a`. RUBY expect_correction(<<~RUBY) foo = %r{a+} RUBY end end context 'with a character class containing a single character before `{n,m}` quantifier' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = %r{[a]{2,10}} ^^^ Redundant single-element character class, `[a]` can be replaced with `a`. RUBY expect_correction(<<~RUBY) foo = %r{a{2,10}} RUBY end end end context 'with a character class containing a single range' do it 'does not register an offense' do expect_no_offenses('foo = /[a-z]/') end end context 'with a character class containing a posix bracket expression' do it 'does not register an offense' do expect_no_offenses('foo = /[[:alnum:]]/') end end context 'with a character class containing a negated posix bracket expression' do it 'does not register an offense' do expect_no_offenses('foo = /[[:^alnum:]]/') end end context 'with a character class containing set intersection' do it 'does not register an offense' do expect_no_offenses('foo = /[[:alnum:]&&a-d]/') end end context "with a regexp containing invalid \g escape" do it 'registers an offense and corrects' do # See https://ruby-doc.org/core-2.7.1/Regexp.html#class-Regexp-label-Subexpression+Calls # \g should be \g<name> expect_offense(<<~'RUBY') foo = /[a]\g/ ^^^ Redundant single-element character class, `[a]` can be replaced with `a`. RUBY expect_correction(<<~'RUBY') foo = /a\g/ RUBY end end context 'with a character class containing an escaped ]' do it 'registers an offense and corrects' do expect_offense(<<~'RUBY') foo = /[\]]/ ^^^^ Redundant single-element character class, `[\]]` can be replaced with `\]`. RUBY expect_correction(<<~'RUBY') foo = /\]/ RUBY end end context 'with a character class containing an escaped [' do it 'registers an offense and corrects' do expect_offense(<<~'RUBY') foo = /[\[]/ ^^^^ Redundant single-element character class, `[\[]` can be replaced with `\[`. RUBY expect_correction(<<~'RUBY') foo = /\[/ RUBY end end context 'with a character class containing a space meta-character' do it 'registers an offense and corrects' do expect_offense(<<~'RUBY') foo = /[\s]/ ^^^^ Redundant single-element character class, `[\s]` can be replaced with `\s`. RUBY expect_correction(<<~'RUBY') foo = /\s/ RUBY end end context 'with a character class containing a negated-space meta-character' do it 'registers an offense and corrects' do expect_offense(<<~'RUBY') foo = /[\S]/ ^^^^ Redundant single-element character class, `[\S]` can be replaced with `\S`. RUBY expect_correction(<<~'RUBY') foo = /\S/ RUBY end end context 'with a character class containing a single unicode code-point' do it 'registers an offense and corrects' do expect_offense(<<~'RUBY') foo = /[\u{06F2}]/ ^^^^^^^^^^ Redundant single-element character class, `[\u{06F2}]` can be replaced with `\u{06F2}`. RUBY expect_correction(<<~'RUBY') foo = /\u{06F2}/ RUBY end end context 'with a character class containing multiple unicode code-points' do it 'does not register an offense and corrects' do expect_no_offenses(<<~'RUBY') foo = /[\u{0061 0062}]/ RUBY end end context 'with a character class containing a single unicode character property' do it 'registers an offense and corrects' do expect_offense(<<~'RUBY') foo = /[\p{Digit}]/ ^^^^^^^^^^^ Redundant single-element character class, `[\p{Digit}]` can be replaced with `\p{Digit}`. RUBY expect_correction(<<~'RUBY') foo = /\p{Digit}/ RUBY end end context 'with a character class containing a single negated unicode character property' do it 'registers an offense and corrects' do expect_offense(<<~'RUBY') foo = /[\P{Digit}]/ ^^^^^^^^^^^ Redundant single-element character class, `[\P{Digit}]` can be replaced with `\P{Digit}`. RUBY expect_correction(<<~'RUBY') foo = /\P{Digit}/ RUBY end end context 'with a character class containing an escaped-#' do it 'registers an offense and corrects' do expect_offense(<<~'RUBY') foo = /[\#]/ ^^^^ Redundant single-element character class, `[\#]` can be replaced with `\#`. RUBY expect_correction(<<~'RUBY') foo = /\#/ RUBY end end context 'with a character class containing an unescaped-#' do it 'registers an offense and corrects' do expect_offense(<<~'RUBY') foo = /[#]{0}/ ^^^ Redundant single-element character class, `[#]` can be replaced with `\#`. RUBY expect_correction(<<~'RUBY') foo = /\#{0}/ RUBY end end context 'with a character class containing an escaped-b' do # See https://github.com/rubocop/rubocop/issues/8193 for details - in short \b != [\b] - the # former matches a word boundary, the latter a backspace character. it 'does not register an offense' do expect_no_offenses('foo = /[\b]/') end end context 'with a character class containing a character requiring escape outside' do # Not implemented for now, since we would have to escape on autocorrect, and the cop message # would need to be dynamic to not be misleading. it 'does not register an offense' do expect_no_offenses('foo = /[+]/') end end context 'with a character class containing escaped character requiring escape outside' do it 'registers an offense and corrects' do expect_offense(<<~'RUBY') foo = /[\+]/ ^^^^ Redundant single-element character class, `[\+]` can be replaced with `\+`. RUBY expect_correction(<<~'RUBY') foo = /\+/ RUBY end end context 'with an interpolated unnecessary-character-class regexp' do it 'registers an offense and corrects' do expect_offense(<<~'RUBY') foo = /a#{/[b]/}c/ ^^^ Redundant single-element character class, `[b]` can be replaced with `b`. RUBY expect_correction(<<~'RUBY') foo = /a#{/b/}c/ RUBY end end context 'with a character class with first element an escaped ]' do it 'does not register an offense' do expect_no_offenses('foo = /[\])]/') end end context 'with a negated character class with a single element' do it 'does not register an offense' do expect_no_offenses('foo = /[^x]/') end end context 'with a character class containing an interpolation' do it 'does not register an offense' do expect_no_offenses('foo = /[#{foo}]/') end end context 'with consecutive escaped square brackets' do it 'does not register an offense' do expect_no_offenses('foo = /\[\]/') end end context 'with consecutive escaped square brackets inside a character class' do it 'does not register an offense' do expect_no_offenses('foo = /[\[\]]/') end end context 'with escaped square brackets surrounding a single character' do it 'does not register an offense' do expect_no_offenses('foo = /\[x\]/') end end context 'with a character class containing two characters' do it 'does not register an offense' do expect_no_offenses('foo = /[ab]/') end end context 'with an array index inside an interpolation' do it 'does not register an offense' do expect_no_offenses('foo = /a#{b[0]}c/') end end context 'with a redundant character class after an interpolation' do it 'registers an offense and corrects' do expect_offense(<<~'RUBY') foo = /#{x}[a]/ ^^^ Redundant single-element character class, `[a]` can be replaced with `a`. RUBY expect_correction(<<~'RUBY') foo = /#{x}a/ RUBY end end context 'with a multi-line interpolation' do it 'ignores offenses in the interpolated expression' do expect_no_offenses(<<~'RUBY') /#{Regexp.union( %w"( ) { } [ ] < > $ ! ^ ` ... + * ? ," )}/o RUBY end end context 'with a character class containing a space' do context 'when not using free-spaced mode' do it 'registers an offense and corrects' do expect_offense(<<~RUBY) foo = /[ ]/ ^^^ Redundant single-element character class, `[ ]` can be replaced with ` `. RUBY expect_correction(<<~RUBY) foo = / / RUBY end end context 'with an unnecessary-character-class after a comment' do it 'registers an offense and corrects' do expect_offense(<<~'RUBY') foo = / a # This comment shouldn't affect the position of the offense [b] ^^^ Redundant single-element character class, `[b]` can be replaced with `b`. /x RUBY expect_correction(<<~'RUBY') foo = / a # This comment shouldn't affect the position of the offense b /x RUBY end end context 'when using free-spaced mode' do context 'with a commented single-element character class' do it 'does not register an offense' do expect_no_offenses('foo = /foo # [a]/x') end end context 'with a single space character class' do it 'does not register an offense with only /x' do expect_no_offenses('foo = /[ ]/x') end it 'does not register an offense with /ix' do expect_no_offenses('foo = /[ ]/ix') end it 'does not register an offense with /iux' do expect_no_offenses('foo = /[ ]/iux') end end end end end
29.447983
116
0.590988
ff870f5fd19a54f155afb15fed5a43671c2b1e3c
1,845
require 'active_support/core_ext/kernel/singleton_class' require 'active_support/core_ext/module/remove_method' class Class def superclass_delegating_accessor(name, options = {}) # Create private _name and _name= methods that can still be used if the public # methods are overridden. This allows _superclass_delegating_accessor("_#{name}") # Generate the public methods name, name=, and name? # These methods dispatch to the private _name, and _name= methods, making them # overridable singleton_class.send(:define_method, name) { send("_#{name}") } singleton_class.send(:define_method, "#{name}?") { !!send("_#{name}") } singleton_class.send(:define_method, "#{name}=") { |value| send("_#{name}=", value) } # If an instance_reader is needed, generate methods for name and name= on the # class itself, so instances will be able to see them define_method(name) { send("_#{name}") } if options[:instance_reader] != false define_method("#{name}?") { !!send("#{name}") } if options[:instance_reader] != false end private # Take the object being set and store it in a method. This gives us automatic # inheritance behavior, without having to store the object in an instance # variable and look up the superclass chain manually. def _stash_object_in_method(object, method, instance_reader = true) singleton_class.remove_possible_method(method) singleton_class.send(:define_method, method) { object } remove_possible_method(method) define_method(method) { object } if instance_reader end def _superclass_delegating_accessor(name, options = {}) singleton_class.send(:define_method, "#{name}=") do |value| _stash_object_in_method(value, name, options[:instance_reader] != false) end send("#{name}=", nil) end end
45
89
0.707317
87ed427dc715d26543be2ea7041b981493aa5d85
2,503
# frozen_string_literal: true module ImageHelper def ann_image_url(record, field, options = {}) path = image_path(record, field) width, _height = options[:size].split("x").map do |s| s.present? ? (s.to_i * (options[:size_rate].presence || 1)) : nil end ix_options = { auto: "format" } ix_options[:w] = width if width.present? ix_image_url(path, ix_options) end def ann_email_image_url(record, field, options = {}) path = image_path(record, field) width, height = options[:size]&.split("x") ix_options = { auto: "format" } ix_options[:w] = width if width.present? ix_options[:h] = height if height.present? ix_image_url(path, ix_options) end def ann_image_tag(record, field, options = {}) url = ann_image_url(record, field, options) url2x = ann_image_url(record, field, options.merge(size_rate: 2)) options["v-lazy"] = "{ src: '#{url}' }" options[:class] = if options[:class].present? options[:class].split(" ").push("c-vue-lazyload").join(" ") else "c-vue-lazyload" end options["data-srcset"] = "#{url} 320w, #{url2x} 640w" image_tag("", options) end def profile_background_image_url(profile, options) background_image = profile.tombo_background_image field = background_image.present? ? :tombo_background_image : :tombo_avatar image = profile.send(field) if background_image.present? && profile.background_image_animated? path = image.path(:original).sub(%r{\A.*paperclip/}, "paperclip/") return "#{ENV.fetch('ANNICT_FILE_STORAGE_URL')}/#{path}" end ann_image_url(profile, field, options) end def ann_api_assets_url(record, field) path = image_path(record, field) "#{ENV.fetch('ANNICT_API_ASSETS_URL')}/#{path}" end def ann_api_assets_background_image_url(record, field) background_image = record&.send(field) field = background_image.present? ? :tombo_background_image : :tombo_avatar image = record&.send(field) if background_image.present? && record.background_image_animated? path = image.path(:original).sub(%r{\A.*paperclip/}, "paperclip/") return "#{ENV.fetch('ANNICT_API_ASSETS_URL')}/#{path}" end ann_api_assets_url(record, field) end private def image_path(record, field) path = if Rails.env.test? record&.send(field)&.url(:master) else record&.send(field)&.path(:master) end path.presence || "no-image.jpg" end end
27.811111
79
0.661606
f74513499f6689a7777c301a0ef4d304abb40db1
1,898
class UniversalCtags < Formula desc "Maintained ctags implementation" homepage "https://github.com/universal-ctags/ctags" url "https://github.com/universal-ctags/ctags/archive/refs/tags/p5.9.20210704.0.tar.gz" version "p5.9.20210704.0" sha256 "07c01e3ed8163100c9f17d6e74683cdb676a803b43f9ae3c3f2f828c027131d9" license "GPL-2.0-only" head "https://github.com/universal-ctags/ctags.git" livecheck do url :stable regex(/^(p\d+(?:\.\d+)+)$/i) end bottle do sha256 cellar: :any, arm64_big_sur: "9ff4b3e0eb16ab0899b899cf835b0dc9a537f29616831b135ce13b76d1a6a769" sha256 cellar: :any, big_sur: "6916c96a4cc8ddcc226750edac2193cc01c5c32012bbd0dd49ef99c11c537909" sha256 cellar: :any, catalina: "ad7e7d6be8182f77c57677b8599bd5cb6b6ab33e7ec05a17bad185ea4b379ba1" sha256 cellar: :any, mojave: "09329630ec33c4811995d04f22b27951bb860f3717ffbcfbd238550ed4e19462" sha256 cellar: :any_skip_relocation, x86_64_linux: "e54a50e7f51752f62b8cd076d7d5d335bdc06bc96be222a68615974972df63d4" end depends_on "autoconf" => :build depends_on "automake" => :build depends_on "docutils" => :build depends_on "pkg-config" => :build depends_on "jansson" depends_on "libyaml" uses_from_macos "libxml2" conflicts_with "ctags", because: "this formula installs the same executable as the ctags formula" def install system "./autogen.sh" system "./configure", *std_configure_args system "make" system "make", "install" end test do (testpath/"test.c").write <<~EOS #include <stdio.h> #include <stdlib.h> void func() { printf("Hello World!"); } int main() { func(); return 0; } EOS system bin/"ctags", "-R", "." assert_match(/func.*test\.c/, File.read("tags")) end end
31.114754
122
0.675448
ab2f47cabb50cc2f8cbfae04cf464af7a4082139
16,838
require "stringio" class TestConsumer < Racecar::Consumer subscribes_to "greetings" attr_reader :messages def initialize @messages = [] @processor_queue = [] @torn_down = false end def on_message(&block) @processor_queue << block self end def process(message) raise message.value if message.value.is_a?(StandardError) @messages << message processor = @processor_queue.shift || proc {} processor.call(message) end def teardown @torn_down = true end def torn_down? @torn_down end end class TestBatchConsumer < Racecar::Consumer subscribes_to "greetings" attr_reader :messages def initialize @messages = [] @processor_queue = [] end def on_message(&block) @processor_queue << block self end def process_batch(messages) @messages += messages messages.each do |message| processor = @processor_queue.shift || proc {} raise message.value if message.value.is_a?(StandardError) processor.call(message) end end end class TestMultiConsumer < TestBatchConsumer subscribes_to "greetings" subscribes_to "second" attr_reader :messages end class TestProducingConsumer < Racecar::Consumer subscribes_to "numbers" def process(message) value = Integer(message.value) * 2 produce value, topic: "doubled", key: value, create_time: 123 end end class TestNilConsumer < Racecar::Consumer subscribes_to "greetings" end class FakeConsumer def initialize(kafka, runner) @kafka = kafka @runner = runner @topic = nil @committed_offset = "not set yet" @internal_offset = 0 @_paused = false @previous_messages = [] @poll_count = 0 end attr_reader :topic, :committed_offset, :_paused def subscribe(topic, **) @topic ||= topic raise "cannot handle more than one topic per consumer" if @topic != topic end def assignment Rdkafka::Consumer::TopicPartitionList.new.tap do |tpl| tpl.add_topic(topic, 1) end end def poll(timeout) # just stop after a big amount of messages read, which is easier to figure out when to # exactly stop when reading from multiple topics @runner.stop if (@poll_count += 1) >= 10 msg = @kafka.received_messages[@topic][@internal_offset] @internal_offset += 1 msg end def commit(partitions, async) end def close end def store_offset(message) raise "storing offset on wrong consumer. own topic: #{@topic} vs #{message.topic}" if @topic != message.topic # + 1 as per: https://github.com/edenhill/librdkafka/wiki/Consumer-offset-management#terminology @internal_offset = @committed_offset = message.offset + 1 end def pause(tpl) raise "not a TopicPartitionList" unless tpl.is_a?(Rdkafka::Consumer::TopicPartitionList) @_paused = true end def resume(tpl) raise "not a TopicPartitionList" unless tpl.is_a?(Rdkafka::Consumer::TopicPartitionList) @_paused = false end def seek(message) raise "seeking on wrong consumer. own topic: #{@topic} vs #{message.topic}" if @topic != message.topic @internal_offset = message.offset end end class FakeProducer def initialize(kafka, runner) @kafka = kafka @runner = runner @buffer = [] @position = -1 @delivery_callback = nil end def produce(payload:, topic:, key:, partition_key: nil, timestamp: nil, headers: nil) @buffer << FakeRdkafka::FakeMessage.new(payload, key, topic, 0, 0, timestamp, headers) FakeDeliveryHandle.new(@kafka, @buffer.last, @delivery_callback) end def delivery_callback=(handler) @delivery_callback = handler end end class FakeDeliveryHandle def initialize(kafka, msg, delivery_callback) @kafka = kafka @msg = msg @delivery_callback = delivery_callback end def [](key) @msg.public_send(key) end def wait @kafka.produced_messages << @msg @delivery_callback.call(self) if @delivery_callback end def offset 0 end def partition 0 end end class FakeRdkafka FakeMessage = Struct.new(:payload, :key, :topic, :partition, :offset, :timestamp, :headers) attr_accessor :received_messages attr_reader :produced_messages, :consumers def initialize(runner:) @runner = runner @received_messages = Hash.new { |h, k| h[k] = [] } @produced_messages = [] @consumers = [] end def deliver_message(payload, topic:, partition: 0) raise "topic may not be nil" if topic.nil? @received_messages[topic] << FakeMessage.new(payload, nil, topic, partition, received_messages[topic].size) end def messages_in(topic) produced_messages.select {|message| message.topic == topic } end def consumer(*options) consumers << FakeConsumer.new(self, @runner) consumers.last end def producer(*) FakeProducer.new(self, @runner) end end class FakeInstrumenter < Racecar::Instrumenter def initialize(*) super @backend = Racecar::NullInstrumenter end end RSpec.shared_examples "offset handling" do |topic| let(:consumers) do runner.send(:consumer).instance_variable_get(:@consumers) end it "stores offset after processing" do kafka.deliver_message("2", topic: topic) # offset 0 kafka.deliver_message("2", topic: topic) # offset 1 kafka.deliver_message("2", topic: topic) # offset 2 runner.run expect(consumers.first.committed_offset).to eq 3 end it "doesn't store offset on error" do kafka.deliver_message(StandardError.new("2"), topic: topic) runner.run rescue nil expect(consumers.first.committed_offset).to eq "not set yet" end end RSpec.shared_examples "pause handling" do after do Timecop.return end it "pauses on failing messages" do kafka.deliver_message(StandardError.new("surprise"), topic: "greetings") runner.run expect(kafka.consumers.first._paused).to eq true runner.run end it "resumes paused partitions" do now = Time.local(2019, 6, 18, 14, 0, 0) later = Time.local(2019, 6, 18, 14, 0, 30) Timecop.freeze(now) kafka.deliver_message(StandardError.new("surprise"), topic: "greetings") runner.run # expect no op runner.send(:resume_paused_partitions) expect(kafka.consumers.first._paused).to eq true # expect to resume Timecop.freeze(later) runner.send(:resume_paused_partitions) expect(kafka.consumers.first._paused).to eq false end it "seeks to given message and returns it on resume" do now = Time.local(2019, 6, 18, 14, 0, 0) later = Time.local(2019, 6, 18, 14, 0, 30) kafka.deliver_message(StandardError.new("surprise"), topic: "greetings") kafka.deliver_message("never get here", topic: "greetings") Timecop.freeze(now) runner.run expect(kafka.consumers.first._paused).to eq true Timecop.freeze(later) runner.send(:resume_paused_partitions) expect(kafka.consumers.first._paused).to eq false runner.run expect(kafka.consumers.first._paused).to eq true end context 'with instrumentation enabled' do let(:pause_instrumentation) do { topic: 'greetings', partition: 0, duration: kind_of(Float) } end before do allow(instrumenter).to receive(:instrument).and_call_original kafka.deliver_message(StandardError.new("surprise"), topic: "greetings") end it 'instruments pause status' do expect(instrumenter). to receive(:instrument). with("pause_status", hash_including(pause_instrumentation)) runner.run end end end RSpec.describe Racecar::Runner do let(:config) { Racecar::Config.new } let(:logger) { Logger.new(StringIO.new) } let(:kafka) { FakeRdkafka.new(runner: runner) } let(:instrumenter) { FakeInstrumenter.new } let(:runner) do Racecar::Runner.new(processor, config: config, logger: logger, instrumenter: instrumenter) end before do allow(Rdkafka::Config).to receive(:new) { kafka } config.load_consumer_class(processor.class) end context "with a consumer class with a #process method" do let(:processor) { TestConsumer.new } include_examples "offset handling", "greetings" include_examples "pause handling" it "builds producer with all config options" do config.producer = ["hello=world", "hi=all"] runner.run expect(Rdkafka::Config).to have_received(:new).with(hash_including("hello" => "world", "hi" => "all")) end it "processes messages with the specified consumer class" do kafka.deliver_message("hello world", topic: "greetings") runner.run expect(processor.messages.map(&:value)).to eq ["hello world"] end it "calls error handler when an exception is raised" do error = StandardError.new("surprise") info = { consumer_class: 'TestConsumer', topic: 'greetings', partition: 0, offset: 0, create_time: nil, key: nil, value: error, headers: nil, retries_count: anything } expect(config.error_handler).to receive(:call).at_least(:once).with(error, info) kafka.deliver_message(error, topic: "greetings") runner.run end it "keeps track of the number of retries when a message causes an exception" do error = StandardError.new("surprise") [0, 1, 2, anything].each do |arg| expect(config.error_handler).to receive(:call).at_least(:once).with(error, hash_including(retries_count: arg)).ordered end kafka.deliver_message(error, topic: "greetings") runner.run end context 'with instrumentation enabled' do let(:message_instrumentation) do { partition: 0, offset: 0, create_time: nil, headers: nil, key: nil, value: 'hello world', consumer_class: "TestConsumer", topic: "greetings" } end let(:loop_instrumentation) do { consumer_class: "TestConsumer" } end before do allow(instrumenter).to receive(:instrument).and_call_original kafka.deliver_message("hello world", topic: "greetings") end it 'instruments main_loop' do expect(instrumenter). to receive(:instrument). with("main_loop", hash_including(loop_instrumentation)) runner.run end it 'instruments the start of processing a message' do expect(instrumenter). to receive(:instrument). with("start_process_message", hash_including(message_instrumentation)) runner.run end it 'instruments a message being processed' do expect(instrumenter). to receive(:instrument). with("process_message", hash_including(message_instrumentation)) runner.run end end end context "with a consumer class with multiple subscriptions" do let(:processor) { TestMultiConsumer.new } include_examples "offset handling", "greetings" include_examples "pause handling" it "processes messages with the specified consumer class" do kafka.deliver_message("to_greet", topic: "greetings") kafka.deliver_message("to_second", topic: "second") runner.run expect(processor.messages.map(&:value)).to eq ["to_greet", "to_second"] end it "stores offset on correct consumer" do # Note: offset is generated from a global counter kafka.deliver_message("2", topic: "greetings") # offset 0 kafka.deliver_message("2", topic: "greetings") # offset 1 kafka.deliver_message("2", topic: "second") # offset 2 runner.run consumers = runner.send(:consumer).instance_variable_get(:@consumers) offsets = consumers.map { |c| [c.topic, c.committed_offset] }.to_h expect(offsets).to eq({"greetings" => 2, "second" => 1}) end end context "with a consumer class with a #process_batch method" do let(:processor) { TestBatchConsumer.new } include_examples "offset handling", "greetings" include_examples "pause handling" it "processes messages with the specified consumer class" do kafka.deliver_message("hello world", topic: "greetings") runner.run expect(processor.messages.map(&:value)).to eq ["hello world"] end it "calls error handler when an exception is raised" do error = StandardError.new("surprise") info = { consumer_class: 'TestBatchConsumer', topic: 'greetings', partition: 0, first_offset: 0, last_offset: 0, last_create_time: nil, message_count: 1, retries_count: anything } expect(config.error_handler).to receive(:call).at_least(:once).with(error, info) kafka.deliver_message(error, topic: "greetings") runner.run end it "keeps track of the number of retries when a message causes an exception" do error = StandardError.new("surprise") [0, 1, 2, anything].each do |arg| expect(config.error_handler).to receive(:call).at_least(:once).with(error, hash_including(retries_count: arg)).ordered end kafka.deliver_message(error, topic: "greetings") runner.run end context 'with instrumentation enabled' do let(:batch_instrumentation) do { consumer_class: 'TestBatchConsumer', topic: 'greetings', partition: 0, first_offset: 0, last_offset: 0, last_create_time: nil, message_count: 1 } end before do allow(instrumenter).to receive(:instrument).and_call_original kafka.deliver_message("hello world", topic: "greetings") end it 'instruments the main loop' do expect(instrumenter). to receive(:instrument). with("main_loop", hash_including(consumer_class: "TestBatchConsumer")) runner.run end it 'instruments the start of a batch processing' do expect(instrumenter). to receive(:instrument). with("start_process_batch", hash_including(batch_instrumentation)) runner.run end it 'instruments the batch processing' do expect(instrumenter). to receive(:instrument). with("process_batch", hash_including(batch_instrumentation)) runner.run end end it "batches per partition" do kafka.deliver_message("hello", topic: "greetings", partition: 0) kafka.deliver_message("world", topic: "greetings", partition: 1) kafka.deliver_message("!", topic: "greetings", partition: 1) payload = a_hash_including( :partition, :first_offset, consumer_class: "TestBatchConsumer", topic: "greetings" ) expect(processor).to receive(:process_batch).with([Racecar::Message.new(kafka.received_messages["greetings"][0])]) expect(processor).to receive(:process_batch).with(kafka.received_messages["greetings"][1, 2].map {|message| Racecar::Message.new(message) }) runner.run end end context "with a consumer class with neither a #process or a #process_batch method" do let(:processor) { TestNilConsumer.new } it "raises NotImplementedError" do kafka.deliver_message("hello world", topic: "greetings") expect { runner.run }.to raise_error(NotImplementedError) end end context "with a consumer that produces messages" do let(:processor) { TestProducingConsumer.new } include_examples "offset handling", "numbers" it "delivers the messages to Kafka", focus: true do kafka.deliver_message("2", topic: "numbers") runner.run messages = kafka.messages_in("doubled") expect(messages.map(&:payload)).to eq [4] expect(messages.map(&:timestamp)).to eq [123] end it "instruments produced messages" do allow(instrumenter).to receive(:instrument).and_call_original kafka.deliver_message("2", topic: "numbers") payload_start = a_hash_including(:create_time, topic: "doubled", key: 4, value: 4) payload_finish = a_hash_including(message_count: 1) runner.run expect(instrumenter).to have_received(:instrument).with("produce_message", payload_start) end it "instruments delivery notifications" do allow(instrumenter).to receive(:instrument).and_call_original kafka.deliver_message("2", topic: "numbers") runner.run expect(instrumenter).to have_received(:instrument) .with("acknowledged_message", {partition: 0, offset: 0}) end end context "#stop" do let(:processor) { TestConsumer.new } it "allows the processor to tear down resources" do runner.run expect(processor.torn_down?).to eq true end end end
26.105426
146
0.667538
f879669c3b13fc94068ea8e8dc2d251304e6ee53
6,680
# 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::DataFactory::Mgmt::V2018_06_01 module Models # # Salesforce Marketing Cloud linked service. # class SalesforceMarketingCloudLinkedService < LinkedService include MsRestAzure def initialize @type = "SalesforceMarketingCloud" end attr_accessor :type # @return The client ID associated with the Salesforce Marketing Cloud # application. Type: string (or Expression with resultType string). attr_accessor :client_id # @return [SecretBase] The client secret associated with the Salesforce # Marketing Cloud application. Type: string (or Expression with # resultType string). attr_accessor :client_secret # @return Specifies whether the data source endpoints are encrypted using # HTTPS. The default value is true. Type: boolean (or Expression with # resultType boolean). attr_accessor :use_encrypted_endpoints # @return Specifies whether to require the host name in the server's # certificate to match the host name of the server when connecting over # SSL. The default value is true. Type: boolean (or Expression with # resultType boolean). attr_accessor :use_host_verification # @return Specifies whether to verify the identity of the server when # connecting over SSL. The default value is true. Type: boolean (or # Expression with resultType boolean). attr_accessor :use_peer_verification # @return The encrypted credential used for authentication. Credentials # are encrypted using the integration runtime credential manager. Type: # string (or Expression with resultType string). attr_accessor :encrypted_credential # # Mapper for SalesforceMarketingCloudLinkedService class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'SalesforceMarketingCloud', type: { name: 'Composite', class_name: 'SalesforceMarketingCloudLinkedService', model_properties: { additional_properties: { client_side_validation: true, required: false, type: { name: 'Dictionary', value: { client_side_validation: true, required: false, serialized_name: 'ObjectElementType', type: { name: 'Object' } } } }, connect_via: { client_side_validation: true, required: false, serialized_name: 'connectVia', type: { name: 'Composite', class_name: 'IntegrationRuntimeReference' } }, description: { client_side_validation: true, required: false, serialized_name: 'description', type: { name: 'String' } }, parameters: { client_side_validation: true, required: false, serialized_name: 'parameters', type: { name: 'Dictionary', value: { client_side_validation: true, required: false, serialized_name: 'ParameterSpecificationElementType', type: { name: 'Composite', class_name: 'ParameterSpecification' } } } }, annotations: { client_side_validation: true, required: false, serialized_name: 'annotations', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'ObjectElementType', type: { name: 'Object' } } } }, type: { client_side_validation: true, required: true, serialized_name: 'type', type: { name: 'String' } }, client_id: { client_side_validation: true, required: true, serialized_name: 'typeProperties.clientId', type: { name: 'Object' } }, client_secret: { client_side_validation: true, required: false, serialized_name: 'typeProperties.clientSecret', type: { name: 'Composite', polymorphic_discriminator: 'type', uber_parent: 'SecretBase', class_name: 'SecretBase' } }, use_encrypted_endpoints: { client_side_validation: true, required: false, serialized_name: 'typeProperties.useEncryptedEndpoints', type: { name: 'Object' } }, use_host_verification: { client_side_validation: true, required: false, serialized_name: 'typeProperties.useHostVerification', type: { name: 'Object' } }, use_peer_verification: { client_side_validation: true, required: false, serialized_name: 'typeProperties.usePeerVerification', type: { name: 'Object' } }, encrypted_credential: { client_side_validation: true, required: false, serialized_name: 'typeProperties.encryptedCredential', type: { name: 'Object' } } } } } end end end end
33.908629
79
0.495359
6254e56e601e8c04b5cb89f8e33a7bab894b9c32
293
require('sinatra') require('./lib/word_count') get('/') do erb(:form) end get('/result') do word = params.fetch("word") sentence = params.fetch("sentence") @word = params.fetch("word") @sentence = params.fetch("sentence") @result = sentence.word_count(word) erb(:result) end
16.277778
38
0.65529
1127483d5738cbafe5be8fb8542ea441b109f97a
464
require_relative '../feed' class JCloudsJiraFeed < Feed register "https://issues.apache.org/jira/sr/jira.issueviews:searchrequest-rss/temp/SearchRequest.xml?jqlQuery=project+%3D+JCLOUDS&tempMax=100" KEYWORDS = %w{rackspace openstack} def items super.select do |item| downcased = item.body.downcase + item.title.downcase KEYWORDS.any? { |word| downcased.include? word } end.each do |item| item.tags << 'jclouds' end end end
27.294118
144
0.706897
e203b481701b83e5a09dadcd29ff31321c27162e
2,675
class H2o < Formula desc "HTTP server with support for HTTP/1.x and HTTP/2" homepage "https://github.com/h2o/h2o/" url "https://github.com/h2o/h2o/archive/v2.2.6.tar.gz" sha256 "f8cbc1b530d85ff098f6efc2c3fdbc5e29baffb30614caac59d5c710f7bda201" revision 1 bottle do sha256 "4f8f5c326d24dcfc95faf48849ae89721f1e19a407968cfa67efbc99dba33f76" => :mojave sha256 "80eac6a05ba27ce57142ad1a9211495fa3b044433623438b6319109e2852eb55" => :high_sierra sha256 "049e412820e6495cfb0906101cb00cea928543583cfc1b6986e0a52d1d215d0c" => :sierra sha256 "ab2cbe25feaff76cfdebac56aa6430d112059280dd120d31b9a01cf3e2c97711" => :x86_64_linux end depends_on "cmake" => :build depends_on "pkg-config" => :build depends_on "[email protected]" uses_from_macos "zlib" def install # https://github.com/Homebrew/homebrew-core/pull/1046 # https://github.com/Homebrew/brew/pull/251 ENV.delete("SDKROOT") system "cmake", *std_cmake_args, "-DWITH_BUNDLED_SSL=OFF", "-DOPENSSL_ROOT_DIR=#{Formula["[email protected]"].opt_prefix}" system "make", "install" (etc/"h2o").mkpath (var/"h2o").install "examples/doc_root/index.html" # Write up a basic example conf for testing. (buildpath/"brew/h2o.conf").write conf_example (etc/"h2o").install buildpath/"brew/h2o.conf" pkgshare.install "examples" end # This is simplified from examples/h2o/h2o.conf upstream. def conf_example; <<~EOS listen: 8080 hosts: "127.0.0.1.xip.io:8080": paths: /: file.dir: #{var}/h2o/ EOS end def caveats; <<~EOS A basic example configuration file has been placed in #{etc}/h2o. You can find fuller, unmodified examples in #{opt_pkgshare}/examples. EOS end plist_options :manual => "h2o" def plist; <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>RunAtLoad</key> <true/> <key>KeepAlive</key> <true/> <key>ProgramArguments</key> <array> <string>#{opt_bin}/h2o</string> <string>-c</string> <string>#{etc}/h2o/h2o.conf</string> </array> </dict> </plist> EOS end test do pid = fork do exec "#{bin}/h2o -c #{etc}/h2o/h2o.conf" end sleep 2 begin assert_match "Welcome to H2O", shell_output("curl localhost:8080") ensure Process.kill("SIGINT", pid) Process.wait(pid) end end end
28.457447
106
0.642991
1ac0653052fad9ef411a1ca6ed78bb371c714487
1,726
class MixesController < ApplicationController include MixesHelper before_action :logged_in?, :set_current_user def index @user = User.includes(:avatar_attachment, :following, :mixes => [:rich_text_description, {:comments => [:user, :rich_text_content]}, :contents] ).find(params[:user_id]) @mixes = @user.mixes end def new @mix = Mix.new end def create @mix = current_user.mixes.find_or_create_by(mix_params) @mix.description = params[:mix][:description] unless params[:mix][:description].blank? if @mix.save if params[:content] content = Content.find_or_create_by(content_params) @mix.contents << content unless @mix.contents.include?(content) else redirect_to user_mix_path(current_user, @mix) end else render :new end end def show @mix = Mix.includes(:user, {:comments => [:user, :rich_text_content]}).find(params[:id]) end def edit @mix = Mix.find(params[:id]) end def update @mix = Mix.find(params[:id]) if @mix.update(mix_update_params) redirect_to user_mix_path(current_user, @mix) else render :edit end end def destroy @mix = Mix.find(params[:id]) @mix.destroy redirect_to user_mixes_path(current_user) end private def set_current_user @current_user = current_user end def mix_params params.require(:mix).permit(:title) end def content_params params.require(:content).permit(:data_type, :title, {creators: []}, :date, :image, :url, :description) end def mix_update_params params.require(:mix).permit(:title, :description, notes_attributes: [:text, :content_id, :id]) end end
23.324324
106
0.659907
5d12f8fe9b61c99dee36b6c0501be89c02214e9d
300
# frozen_string_literal: true module Mongoid module Orderable module Generators class Base attr_reader :klass def initialize(klass) @klass = klass end protected def generate_method(name, &block) klass.send(:define_method, name, &block) end end end end end
13.636364
46
0.69
e8ed74ad74ad43535dae6d85c6538566e221583a
199
module TZInfo module Definitions module US module Eastern include TimezoneDefinition linked_timezone 'US/Eastern', 'America/New_York' end end end end
16.583333
56
0.633166
793f1ad6006a5f261abd549ceb744e16619097d0
700
class CommitmentsController < ApplicationController def new @commitment = Commitment.new end def show @commitment = Commitment.find(params[:id]) end def create commitment = Commitment.create(commitment_params) commitment.user_id = current_user.id commitment.save if !commitment.valid? redirect_to new_commitment_path, warning: "Invalid parameters!" else redirect_to plans_path end end private def commitment_params params.require(:commitment).permit( :name, :plan_id, :user_id, :passion_level ) end end
20.588235
75
0.59
4a2f13204580914c56c859e1d5b9afc847d46068
31,369
require 'active_support/core_ext/hash/slice' module ActiveMerchant #:nodoc: module Billing #:nodoc: # This gateway uses an older version of the Stripe API. # To utilize the updated {Payment Intents API}[https://stripe.com/docs/api/payment_intents], integrate with the StripePaymentIntents gateway class StripeGateway < Gateway self.live_url = 'https://api.stripe.com/v1/' AVS_CODE_TRANSLATOR = { 'line1: pass, zip: pass' => 'Y', 'line1: pass, zip: fail' => 'A', 'line1: pass, zip: unchecked' => 'B', 'line1: fail, zip: pass' => 'Z', 'line1: fail, zip: fail' => 'N', 'line1: unchecked, zip: pass' => 'P', 'line1: unchecked, zip: unchecked' => 'I' } CVC_CODE_TRANSLATOR = { 'pass' => 'M', 'fail' => 'N', 'unchecked' => 'P' } DEFAULT_API_VERSION = '2015-04-07' self.supported_countries = %w(AE AT AU BE BG BR CA CH CY CZ DE DK EE ES FI FR GB GR HK HU IE IN IT JP LT LU LV MT MX MY NL NO NZ PL PT RO SE SG SI SK US) self.default_currency = 'USD' self.money_format = :cents self.supported_cardtypes = %i[visa master american_express discover jcb diners_club maestro unionpay] self.currencies_without_fractions = %w(BIF CLP DJF GNF JPY KMF KRW MGA PYG RWF VND VUV XAF XOF XPF UGX) self.homepage_url = 'https://stripe.com/' self.display_name = 'Stripe' STANDARD_ERROR_CODE_MAPPING = { 'incorrect_number' => STANDARD_ERROR_CODE[:incorrect_number], 'invalid_number' => STANDARD_ERROR_CODE[:invalid_number], 'invalid_expiry_month' => STANDARD_ERROR_CODE[:invalid_expiry_date], 'invalid_expiry_year' => STANDARD_ERROR_CODE[:invalid_expiry_date], 'invalid_cvc' => STANDARD_ERROR_CODE[:invalid_cvc], 'expired_card' => STANDARD_ERROR_CODE[:expired_card], 'incorrect_cvc' => STANDARD_ERROR_CODE[:incorrect_cvc], 'incorrect_zip' => STANDARD_ERROR_CODE[:incorrect_zip], 'card_declined' => STANDARD_ERROR_CODE[:card_declined], 'call_issuer' => STANDARD_ERROR_CODE[:call_issuer], 'processing_error' => STANDARD_ERROR_CODE[:processing_error], 'incorrect_pin' => STANDARD_ERROR_CODE[:incorrect_pin], 'test_mode_live_card' => STANDARD_ERROR_CODE[:test_mode_live_card], 'pickup_card' => STANDARD_ERROR_CODE[:pickup_card] } BANK_ACCOUNT_HOLDER_TYPE_MAPPING = { 'personal' => 'individual', 'business' => 'company' } MINIMUM_AUTHORIZE_AMOUNTS = { 'USD' => 100, 'CAD' => 100, 'GBP' => 60, 'EUR' => 100, 'DKK' => 500, 'NOK' => 600, 'SEK' => 600, 'CHF' => 100, 'AUD' => 100, 'JPY' => 100, 'MXN' => 2000, 'SGD' => 100, 'HKD' => 800 } def initialize(options = {}) requires!(options, :login) @api_key = options[:login] @fee_refund_api_key = options[:fee_refund_login] super end def authorize(money, payment, options = {}) if ach?(payment) direct_bank_error = 'Direct bank account transactions are not supported for authorize.' return Response.new(false, direct_bank_error) end MultiResponse.run do |r| if payment.is_a?(ApplePayPaymentToken) r.process { tokenize_apple_pay_token(payment) } payment = StripePaymentToken.new(r.params['token']) if r.success? end r.process do post = create_post_for_auth_or_purchase(money, payment, options) add_application_fee(post, options) if emv_payment?(payment) post[:capture] = 'false' commit(:post, 'charges', post, options) end end.responses.last end # To create a charge on a card or a token, call # # purchase(money, card_hash_or_token, { ... }) # # To create a charge on a customer, call # # purchase(money, nil, { :customer => id, ... }) def purchase(money, payment, options = {}) if ach?(payment) direct_bank_error = 'Direct bank account transactions are not supported. Bank accounts must be stored and verified before use.' return Response.new(false, direct_bank_error) end MultiResponse.run do |r| if payment.is_a?(ApplePayPaymentToken) r.process { tokenize_apple_pay_token(payment) } payment = StripePaymentToken.new(r.params['token']) if r.success? end r.process do post = create_post_for_auth_or_purchase(money, payment, options) post[:card][:processing_method] = 'quick_chip' if quickchip_payment?(payment) commit(:post, 'charges', post, options) end end.responses.last end def capture(money, authorization, options = {}) post = {} if emv_tc_response = options.delete(:icc_data) # update the charge with emv data if card present update = {} update[:card] = { emv_approval_data: emv_tc_response } commit(:post, "charges/#{CGI.escape(authorization)}", update, options) else add_application_fee(post, options) add_amount(post, money, options) add_exchange_rate(post, options) end commit(:post, "charges/#{CGI.escape(authorization)}/capture", post, options) end def void(identification, options = {}) post = {} post[:metadata] = options[:metadata] if options[:metadata] post[:reason] = options[:reason] if options[:reason] post[:expand] = [:charge] commit(:post, "charges/#{CGI.escape(identification)}/refunds", post, options) end def refund(money, identification, options = {}) post = {} add_amount(post, money, options) post[:refund_application_fee] = true if options[:refund_application_fee] post[:reverse_transfer] = options[:reverse_transfer] if options[:reverse_transfer] post[:metadata] = options[:metadata] if options[:metadata] post[:reason] = options[:reason] if options[:reason] post[:expand] = [:charge] response = commit(:post, "charges/#{CGI.escape(identification)}/refunds", post, options) if response.success? && options[:refund_fee_amount] && options[:refund_fee_amount].to_s != '0' charge = api_request(:get, "charges/#{CGI.escape(identification)}", nil, options) if application_fee = charge['application_fee'] fee_refund_options = { currency: options[:currency], # currency isn't used by Stripe here, but we need it for #add_amount key: @fee_refund_api_key } refund_application_fee(options[:refund_fee_amount].to_i, application_fee, fee_refund_options) end end response end def verify(payment, options = {}) MultiResponse.run(:use_first_response) do |r| r.process { authorize(auth_minimum_amount(options), payment, options) } options[:idempotency_key] = nil r.process(:ignore_result) { void(r.authorization, options) } end end def refund_application_fee(money, identification, options = {}) post = {} add_amount(post, money, options) commit(:post, "application_fees/#{CGI.escape(identification)}/refunds", post, options) end # Note: creating a new credit card will not change the customer's existing default credit card (use :set_default => true) def store(payment, options = {}) params = {} post = {} if payment.is_a?(ApplePayPaymentToken) token_exchange_response = tokenize_apple_pay_token(payment) params = { card: token_exchange_response.params['token']['id'] } if token_exchange_response.success? elsif payment.is_a?(StripePaymentToken) add_payment_token(params, payment, options) elsif payment.is_a?(Check) bank_token_response = tokenize_bank_account(payment) return bank_token_response unless bank_token_response.success? params = { source: bank_token_response.params['token']['id'] } else add_creditcard(params, payment, options) end post[:validate] = options[:validate] unless options[:validate].nil? post[:description] = options[:description] if options[:description] post[:email] = options[:email] if options[:email] if options[:account] add_external_account(post, params, payment) commit(:post, "accounts/#{CGI.escape(options[:account])}/external_accounts", post, options) elsif options[:customer] MultiResponse.run(:first) do |r| # The /cards endpoint does not update other customer parameters. r.process { commit(:post, "customers/#{CGI.escape(options[:customer])}/cards", params, options) } post[:default_card] = r.params['id'] if options[:set_default] && r.success? && !r.params['id'].blank? r.process { update_customer(options[:customer], post) } if post.count > 0 end else commit(:post, 'customers', post.merge(params), options) end end def update(customer_id, card_id, options = {}) commit(:post, "customers/#{CGI.escape(customer_id)}/cards/#{CGI.escape(card_id)}", options, options) end def update_customer(customer_id, options = {}) commit(:post, "customers/#{CGI.escape(customer_id)}", options, options) end def unstore(identification, options = {}, deprecated_options = {}) customer_id, card_id = identification.split('|') if options.kind_of?(String) ActiveMerchant.deprecated 'Passing the card_id as the 2nd parameter is deprecated. The response authorization includes both the customer_id and the card_id.' card_id ||= options options = deprecated_options end commit(:delete, "customers/#{CGI.escape(customer_id)}/cards/#{CGI.escape(card_id)}", nil, options) end def tokenize_apple_pay_token(apple_pay_payment_token, options = {}) token_response = api_request(:post, "tokens?pk_token=#{CGI.escape(apple_pay_payment_token.payment_data.to_json)}") success = !token_response.key?('error') if success && token_response.key?('id') Response.new(success, nil, token: token_response) else Response.new(success, token_response['error']['message']) end end def verify_credentials begin ssl_get(live_url + 'charges/nonexistent', headers) rescue ResponseError => e return false if e.response.code.to_i == 401 end true end def supports_scrubbing? true end def scrub(transcript) transcript. gsub(%r((Authorization: Basic )\w+), '\1[FILTERED]'). gsub(%r((&?three_d_secure\[cryptogram\]=)[\w=]*(&?)), '\1[FILTERED]\2'). gsub(%r(((\[card\]|card)\[cryptogram\]=)[^&]+(&?)), '\1[FILTERED]\3'). gsub(%r(((\[card\]|card)\[cvc\]=)\d+), '\1[FILTERED]'). gsub(%r(((\[card\]|card)\[emv_approval_data\]=)[^&]+(&?)), '\1[FILTERED]\3'). gsub(%r(((\[card\]|card)\[emv_auth_data\]=)[^&]+(&?)), '\1[FILTERED]\3'). gsub(%r(((\[card\]|card)\[encrypted_pin\]=)[^&]+(&?)), '\1[FILTERED]\3'). gsub(%r(((\[card\]|card)\[encrypted_pin_key_id\]=)[\w=]+(&?)), '\1[FILTERED]\3'). gsub(%r(((\[card\]|card)\[number\]=)\d+), '\1[FILTERED]'). gsub(%r(((\[card\]|card)\[swipe_data\]=)[^&]+(&?)), '\1[FILTERED]\3'). gsub(%r(((\[bank_account\]|bank_account)\[account_number\]=)\d+), '\1[FILTERED]') end def supports_network_tokenization? true end private class StripePaymentToken < PaymentToken def type 'stripe' end end def create_source(money, payment, type, options = {}) post = {} add_amount(post, money, options, true) post[:type] = type if type == 'card' add_creditcard(post, payment, options, true) add_source_owner(post, payment, options) elsif type == 'three_d_secure' post[:three_d_secure] = { card: payment } post[:redirect] = { return_url: options[:redirect_url] } end commit(:post, 'sources', post, options) end def show_source(source_id, options) commit(:get, "sources/#{source_id}", nil, options) end def create_webhook_endpoint(options, events) post = {} post[:url] = options[:callback_url] post[:enabled_events] = events post[:connect] = true if options[:stripe_account] options.delete(:stripe_account) commit(:post, 'webhook_endpoints', post, options) end def delete_webhook_endpoint(options) commit(:delete, "webhook_endpoints/#{options[:webhook_id]}", {}, options) end def show_webhook_endpoint(options) options.delete(:stripe_account) commit(:get, "webhook_endpoints/#{options[:webhook_id]}", nil, options) end def list_webhook_endpoints(options) params = {} params[:limit] = options[:limit] if options[:limit] options.delete(:stripe_account) commit(:get, "webhook_endpoints?#{post_data(params)}", nil, options) end def create_post_for_auth_or_purchase(money, payment, options) post = {} if payment.is_a?(StripePaymentToken) add_payment_token(post, payment, options) else add_creditcard(post, payment, options) end add_charge_details(post, money, payment, options) post end # Used internally by Spreedly to populate the charge object for 3DS 1.0 transactions def add_charge_details(post, money, payment, options) if emv_payment?(payment) add_statement_address(post, options) add_emv_metadata(post, payment) else add_amount(post, money, options, true) add_customer_data(post, options) post[:description] = options[:description] post[:statement_descriptor] = options[:statement_description] post[:statement_descriptor_suffix] = options[:statement_descriptor_suffix] if options[:statement_descriptor_suffix] post[:receipt_email] = options[:receipt_email] if options[:receipt_email] add_customer(post, payment, options) add_flags(post, options) end add_metadata(post, options) add_application_fee(post, options) add_exchange_rate(post, options) add_destination(post, options) add_level_three(post, options) add_connected_account(post, options) add_radar_data(post, options) post end def add_amount(post, money, options, include_currency = false) currency = options[:currency] || currency(money) post[:amount] = localized_amount(money, currency) post[:currency] = currency.downcase if include_currency end def add_application_fee(post, options) post[:application_fee] = options[:application_fee] if options[:application_fee] end def add_exchange_rate(post, options) post[:exchange_rate] = options[:exchange_rate] if options[:exchange_rate] end def add_destination(post, options) if options[:destination] post[:destination] = {} post[:destination][:account] = options[:destination] post[:destination][:amount] = options[:destination_amount] if options[:destination_amount] end end def add_level_three(post, options) level_three = {} copy_when_present(level_three, [:merchant_reference], options) copy_when_present(level_three, [:customer_reference], options) copy_when_present(level_three, [:shipping_address_zip], options) copy_when_present(level_three, [:shipping_from_zip], options) copy_when_present(level_three, [:shipping_amount], options) copy_when_present(level_three, [:line_items], options) post[:level3] = level_three unless level_three.empty? end def add_expand_parameters(post, options) post[:expand] ||= [] post[:expand].concat(Array.wrap(options[:expand]).map(&:to_sym)).uniq! end def add_external_account(post, card_params, payment) external_account = {} external_account[:object] = 'card' external_account[:currency] = (options[:currency] || currency(payment)).downcase post[:external_account] = external_account.merge(card_params[:card]) end def add_customer_data(post, options) metadata_options = %i[description ip user_agent referrer] post.update(options.slice(*metadata_options)) post[:external_id] = options[:order_id] post[:payment_user_agent] = "Stripe/v1 ActiveMerchantBindings/#{ActiveMerchant::VERSION}" end def add_address(post, options) return unless post[:card]&.kind_of?(Hash) if address = options[:billing_address] || options[:address] post[:card][:address_line1] = address[:address1] if address[:address1] post[:card][:address_line2] = address[:address2] if address[:address2] post[:card][:address_country] = address[:country] if address[:country] post[:card][:address_zip] = address[:zip] if address[:zip] post[:card][:address_state] = address[:state] if address[:state] post[:card][:address_city] = address[:city] if address[:city] end end def add_statement_address(post, options) return unless statement_address = options[:statement_address] return unless %i[address1 city zip state].all? { |key| statement_address[key].present? } post[:statement_address] = {} post[:statement_address][:line1] = statement_address[:address1] post[:statement_address][:line2] = statement_address[:address2] if statement_address[:address2].present? post[:statement_address][:city] = statement_address[:city] post[:statement_address][:postal_code] = statement_address[:zip] post[:statement_address][:state] = statement_address[:state] end def add_creditcard(post, creditcard, options, use_sources = false) card = {} if emv_payment?(creditcard) add_emv_creditcard(post, creditcard.icc_data) post[:card][:read_method] = 'contactless' if creditcard.read_method == 'contactless' post[:card][:read_method] = 'contactless_magstripe_mode' if creditcard.read_method == 'contactless_magstripe' if creditcard.encrypted_pin_cryptogram.present? && creditcard.encrypted_pin_ksn.present? post[:card][:encrypted_pin] = creditcard.encrypted_pin_cryptogram post[:card][:encrypted_pin_key_id] = creditcard.encrypted_pin_ksn end elsif creditcard.respond_to?(:number) if creditcard.respond_to?(:track_data) && creditcard.track_data.present? card[:swipe_data] = creditcard.track_data if creditcard.respond_to?(:read_method) card[:fallback_reason] = 'no_chip' if creditcard.read_method == 'fallback_no_chip' card[:fallback_reason] = 'chip_error' if creditcard.read_method == 'fallback_chip_error' card[:read_method] = 'contactless_magstripe_mode' if creditcard.read_method == 'contactless_magstripe' end else card[:number] = creditcard.number card[:exp_month] = creditcard.month card[:exp_year] = creditcard.year card[:cvc] = creditcard.verification_value if creditcard.verification_value? card[:name] = creditcard.name if creditcard.name && !use_sources end if creditcard.is_a?(NetworkTokenizationCreditCard) card[:cryptogram] = creditcard.payment_cryptogram card[:eci] = creditcard.eci.rjust(2, '0') if creditcard.eci =~ /^[0-9]+$/ card[:tokenization_method] = creditcard.source.to_s end post[:card] = card add_address(post, options) unless use_sources elsif creditcard.kind_of?(String) if options[:track_data] card[:swipe_data] = options[:track_data] elsif creditcard.include?('|') customer_id, card_id = creditcard.split('|') card = card_id post[:customer] = customer_id else card = creditcard end post[:card] = card end end def add_emv_creditcard(post, icc_data, options = {}) post[:card] = { emv_auth_data: icc_data } end def add_payment_token(post, token, options = {}) post[:card] = token.payment_data['id'] end def add_customer(post, payment, options) post[:customer] = options[:customer] if options[:customer] && !payment.respond_to?(:number) end def add_flags(post, options) post[:uncaptured] = true if options[:uncaptured] post[:recurring] = true if options[:eci] == 'recurring' || options[:recurring] end def add_metadata(post, options = {}) post[:metadata] ||= {} post[:metadata].merge!(options[:metadata]) if options[:metadata] post[:metadata][:email] = options[:email] if options[:email] post[:metadata][:order_id] = options[:order_id] if options[:order_id] end def add_emv_metadata(post, creditcard) post[:metadata] ||= {} post[:metadata][:card_read_method] = creditcard.read_method if creditcard.respond_to?(:read_method) end def add_source_owner(post, creditcard, options) post[:owner] = {} post[:owner][:name] = creditcard.name if creditcard.name post[:owner][:email] = options[:email] if options[:email] if address = options[:billing_address] || options[:address] owner_address = {} owner_address[:line1] = address[:address1] if address[:address1] owner_address[:line2] = address[:address2] if address[:address2] owner_address[:country] = address[:country] if address[:country] owner_address[:postal_code] = address[:zip] if address[:zip] owner_address[:state] = address[:state] if address[:state] owner_address[:city] = address[:city] if address[:city] post[:owner][:phone] = address[:phone] if address[:phone] post[:owner][:address] = owner_address end end def add_connected_account(post, options = {}) post[:on_behalf_of] = options[:on_behalf_of] if options[:on_behalf_of] return unless options[:transfer_destination] post[:transfer_data] = { destination: options[:transfer_destination] } post[:transfer_data][:amount] = options[:transfer_amount] if options[:transfer_amount] post[:transfer_group] = options[:transfer_group] if options[:transfer_group] post[:application_fee_amount] = options[:application_fee_amount] if options[:application_fee_amount] end def add_radar_data(post, options = {}) return unless options[:radar_session_id] post[:radar_options] = { session: options[:radar_session_id] } end def parse(body) JSON.parse(body) end def post_data(params) return nil unless params flatten_params([], params).join('&') end def flatten_params(flattened, params, prefix = nil) params.each do |key, value| next if value != false && value.blank? flattened_key = prefix.nil? ? key : "#{prefix}[#{key}]" if value.is_a?(Hash) flatten_params(flattened, value, flattened_key) elsif value.is_a?(Array) flatten_array(flattened, value, flattened_key) else flattened << "#{flattened_key}=#{CGI.escape(value.to_s)}" end end flattened end def flatten_array(flattened, array, prefix) array.each_with_index do |item, idx| key = "#{prefix}[#{idx}]" if item.is_a?(Hash) flatten_params(flattened, item, key) elsif item.is_a?(Array) flatten_array(flattened, item, key) else flattened << "#{key}=#{CGI.escape(item.to_s)}" end end end def headers(options = {}) key = options[:key] || @api_key idempotency_key = options[:idempotency_key] headers = { 'Authorization' => 'Basic ' + Base64.strict_encode64(key.to_s + ':').strip, 'User-Agent' => "Stripe/v1 ActiveMerchantBindings/#{ActiveMerchant::VERSION}", 'Stripe-Version' => api_version(options), 'X-Stripe-Client-User-Agent' => stripe_client_user_agent(options), 'X-Stripe-Client-User-Metadata' => { ip: options[:ip] }.to_json } headers['Idempotency-Key'] = idempotency_key if idempotency_key headers['Stripe-Account'] = options[:stripe_account] if options[:stripe_account] headers end def stripe_client_user_agent(options) return user_agent unless options[:application] JSON.dump(JSON.parse(user_agent).merge!({ application: options[:application] })) end def api_version(options) options[:version] || @options[:version] || self.class::DEFAULT_API_VERSION end def api_request(method, endpoint, parameters = nil, options = {}) raw_response = response = nil begin raw_response = ssl_request(method, self.live_url + endpoint, post_data(parameters), headers(options)) response = parse(raw_response) rescue ResponseError => e raw_response = e.response.body response = response_error(raw_response) rescue JSON::ParserError response = json_error(raw_response) end response end def commit(method, url, parameters = nil, options = {}) add_expand_parameters(parameters, options) if parameters response = api_request(method, url, parameters, options) response['webhook_id'] = options[:webhook_id] if options[:webhook_id] success = success_from(response, options) card = card_from_response(response) avs_code = AVS_CODE_TRANSLATOR["line1: #{card['address_line1_check']}, zip: #{card['address_zip_check']}"] cvc_code = CVC_CODE_TRANSLATOR[card['cvc_check']] Response.new(success, message_from(success, response), response, test: response_is_test?(response), authorization: authorization_from(success, url, method, response), avs_result: { code: avs_code }, cvv_result: cvc_code, emv_authorization: emv_authorization_from_response(response), error_code: success ? nil : error_code_from(response)) end def authorization_from(success, url, method, response) return response.fetch('error', {})['charge'] unless success if url == 'customers' [response['id'], response.dig('sources', 'data').first&.dig('id')].join('|') elsif method == :post && (url.match(/customers\/.*\/cards/) || url.match(/payment_methods\/.*\/attach/)) [response['customer'], response['id']].join('|') else response['id'] end end def message_from(success, response) success ? 'Transaction approved' : response.fetch('error', { 'message' => 'No error details' })['message'] end def success_from(response, options) !response.key?('error') && response['status'] != 'failed' end def response_error(raw_response) parse(raw_response) rescue JSON::ParserError json_error(raw_response) end def json_error(raw_response) msg = 'Invalid response received from the Stripe API. Please contact [email protected] if you continue to receive this message.' msg += " (The raw response returned by the API was #{raw_response.inspect})" { 'error' => { 'message' => msg } } end def response_is_test?(response) if response.has_key?('livemode') !response['livemode'] elsif response['charge'].is_a?(Hash) && response['charge'].has_key?('livemode') !response['charge']['livemode'] else false end end def emv_payment?(payment) payment.respond_to?(:emv?) && payment.emv? end def quickchip_payment?(payment) payment.respond_to?(:read_method) && payment.read_method == 'contact_quickchip' end def card_from_response(response) response['card'] || response['active_card'] || response['source'] || {} end def emv_authorization_from_response(response) return response['error']['emv_auth_data'] if response['error'] card_from_response(response)['emv_auth_data'] end def error_code_from(response) return STANDARD_ERROR_CODE_MAPPING['processing_error'] unless response['error'] code = response['error']['code'] decline_code = response['error']['decline_code'] if code == 'card_declined' error_code = STANDARD_ERROR_CODE_MAPPING[decline_code] error_code ||= STANDARD_ERROR_CODE_MAPPING[code] error_code end def tokenize_bank_account(bank_account, options = {}) account_holder_type = BANK_ACCOUNT_HOLDER_TYPE_MAPPING[bank_account.account_holder_type] post = { bank_account: { account_number: bank_account.account_number, country: 'US', currency: 'usd', routing_number: bank_account.routing_number, name: bank_account.name, account_holder_type: account_holder_type } } token_response = api_request(:post, "tokens?#{post_data(post)}") success = token_response['error'].nil? if success && token_response['id'] Response.new(success, nil, token: token_response) else Response.new(success, token_response['error']['message']) end end def ach?(payment_method) case payment_method when String, nil false else card_brand(payment_method) == 'check' end end def auth_minimum_amount(options) return 100 unless options[:currency] return MINIMUM_AUTHORIZE_AMOUNTS[options[:currency].upcase] || 100 end def copy_when_present(dest, dest_path, source, source_path = nil) source_path ||= dest_path source_path.each do |key| return nil unless source[key] source = source[key] end if source dest_path.first(dest_path.size - 1).each do |key| dest[key] ||= {} dest = dest[key] end dest[dest_path.last] = source end end end end end
38.536855
167
0.620963
1d9b62baee9005d1a9646d0fa4d40efb41836ab0
151
class CreateLogos < ActiveRecord::Migration def change create_table :logos do |t| t.string :filename t.timestamps end end end
15.1
43
0.668874
913fdf78c3e396105f508774ecbaf7dbf16c5c11
2,001
Rails.application.routes.draw do devise_for :users, controllers: { registrations: 'registrations' } namespace :my do resource :details, only: [:show, :edit, :update] resource :password, only: [:update] resource :membership, only: [:destroy] resources :meetings, only: [:index] resources :access_requests, only: [:index] end resources :rsvps, only: [:show, :update, :destroy] do member { get :confirm, :decline } end resources :reactivations, only: [:new, :create] namespace :admin do resources :memberships, only: [:index] resources :access_requests, except: [:destroy] resources :imported_members, only: [:index, :create] resources :campaigns end resources :invitations, only: [] do member do get :unsubscribe, :new post :create end end resources :mailing_lists, only: [] do member { post :hook } end get '/forum', to: redirect('https://forum.ruby.org.au'), as: :forum get '/mailing-list', to: redirect('https://confirmsubscription.com/h/j/3DDD74A0ACC3DB22'), as: :roro_mailing_list get '/slack', to: redirect('https://ruby-au-join.herokuapp.com/'), as: :slack get '/videos', to: redirect('https://www.youtube.com/channel/UCr38SHAvOKMDyX3-8lhvJHA/videos'), as: :videos get "/events/rubyconf_au_2021" => "events#rubyconf_au_2021" get "/events/rails_camp_27" => "events#rails_camp_27" root to: 'pages#show', defaults: { id: 'welcome' } get "/policies" => "policies#index", as: :policies get "/policies/*id" => "policies#show", as: :policy get "/sponsorship" => 'sponsors#index' get "/sponsors/*id" => 'sponsors#show' get "/code-of-conduct", to: redirect("/policies/code-of-conduct") get "/code-of-conduct-enforcement", to: redirect("/policies/code-of-conduct-enforcement") get "/code-of-conduct-reporting", to: redirect("/policies/code-of-conduct-reporting") get "/*id" => 'pages#show', as: :page, format: false, constraints: RootRouteConstraints end
31.761905
97
0.672664
1829112dd83fe424e360412d2d226d3477a4c2a8
1,083
module GitCompound # Logger class # module Logger extend self def verbose=(value) load_debug_messages if value @verbose = value && true end def verbose @verbose.nil? ? false : @verbose end def colors=(value) String.disable_colors = !(@colors = value) end def colors @colors.nil? ? true : @colors end def inline(inline_message) print inline_message inline_message end def debug(debug_message) log debug_message.cyan end def info(information_message) log information_message end def warn(warning_message) log warning_message.red.bold end def error(error_message) log error_message.on_red.white.bold end private def log(message) puts message message end def load_debug_messages require 'git_compound/logger/debug/command' require 'git_compound/logger/debug/repository' require 'git_compound/logger/debug/task' require 'git_compound/logger/debug/procedure' end end end
18.05
52
0.65097
1a1d7d417838bf1ff2ca77d2d7f9c38b045f0f70
448
require "rails_helper" RSpec.describe DummyMailer, type: :mailer do it "parses the tags" do mail = described_class.with_tags expect(mail.tags).to eq ["hello_world"] end it "supports multiple tags" do mail = described_class.with_tags(["hello", "world"]) expect(mail.tags).to eq ["hello", "world"] end it "doesn't break with no tags at all" do mail = described_class.no_tags expect(mail.tags).to be_nil end end
23.578947
56
0.689732
26de745bb7c66a4310461779483a023a7421fdfa
1,874
require 'more_core_extensions/core_ext/numeric/math' module MoreCoreExtensions module MathSlope module ClassMethods # Finds the y coordinate given x, slope of the line and the y intercept # # `y = mx + b` # Where `m` is the slope of the line and `b` is the y intercept # # Math.slope_y_intercept(1, 0.5, 1) # => 1.5 def slope_y_intercept(x, slope, y_intercept) slope * x + y_intercept end # Finds the x coordinate given y, slope of the line and the y intercept # # `x = (y - b) / m` # Where `m` is the slope of the line and `b` is the y intercept # # Math.slope_x_intercept(1.5, 0.5, 1) # => 1.0 def slope_x_intercept(y, slope, y_intercept) (y - y_intercept) / slope.to_f end # Finds the linear regression of the given coordinates. Coordinates should be given as x, y pairs. # # Returns the slope of the line, the y intercept, and the R-squared value. # # Math.linear_regression([1.0, 1.0], [2.0, 2.0]) # => [1.0, 0.0, 1.0] def linear_regression(*coordinates) return if coordinates.empty? x_array, y_array = coordinates.transpose sum_x = x_array.sum sum_x2 = x_array.map(&:square).sum sum_y = y_array.sum sum_y2 = y_array.map(&:square).sum sum_xy = coordinates.map { |x, y| x * y }.sum n = coordinates.size.to_f slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x.square) return if slope.nan? y_intercept = (sum_y - slope * sum_x) / n r_squared = (n * sum_xy - sum_x * sum_y) / Math.sqrt((n * sum_x2 - sum_x.square) * (n * sum_y2 - sum_y.square)) rescue nil return slope, y_intercept, r_squared end end end end Math.send(:extend, MoreCoreExtensions::MathSlope::ClassMethods)
34.072727
132
0.60032
1dc9700ef722ec43c262086a5eef1e9c826a03d9
97
# frozen_string_literal: true require "cask/cask" require "cask/caskroom" require "cask/config"
16.166667
29
0.783505
1dd53236fbd651af1865f545e726dcb15a161b70
5,678
require 'spec_helper.rb' describe Issues::BuildService, services: true do let(:project) { create(:project) } let(:user) { create(:user) } before do project.team << [user, :developer] end context 'for a single discussion' do describe '#execute' do let(:merge_request) { create(:merge_request, title: "Hello world", source_project: project) } let(:discussion) { Discussion.new([create(:diff_note_on_merge_request, project: project, noteable: merge_request, note: "Almost done")]) } let(:service) { described_class.new(project, user, merge_request_to_resolve_discussions_of: merge_request.iid, discussion_to_resolve: discussion.id) } it 'references the noteable title in the issue title' do issue = service.execute expect(issue.title).to include('Hello world') end it 'adds the note content to the description' do issue = service.execute expect(issue.description).to include('Almost done') end end end context 'for discussions in a merge request' do let(:merge_request) { create(:merge_request_with_diff_notes, source_project: project) } let(:issue) { described_class.new(project, user, merge_request_to_resolve_discussions_of: merge_request.iid).execute } describe '#items_for_discussions' do it 'has an item for each discussion' do create(:diff_note_on_merge_request, noteable: merge_request, project: merge_request.source_project, line_number: 13) service = described_class.new(project, user, merge_request_to_resolve_discussions_of: merge_request.iid) service.execute expect(service.items_for_discussions.size).to eq(2) end end describe '#item_for_discussion' do let(:service) { described_class.new(project, user, merge_request_to_resolve_discussions_of: merge_request.iid) } it 'mentions the author of the note' do discussion = Discussion.new([create(:diff_note_on_merge_request, author: create(:user, username: 'author'))]) expect(service.item_for_discussion(discussion)).to include('@author') end it 'wraps the note in a blockquote' do note_text = "This is a string\n"\ ">>>\n"\ "with a blockquote\n"\ "> That has a quote\n"\ ">>>\n" note_result = " > This is a string\n"\ " > > with a blockquote\n"\ " > > > That has a quote\n" discussion = Discussion.new([create(:diff_note_on_merge_request, note: note_text)]) expect(service.item_for_discussion(discussion)).to include(note_result) end end describe '#execute' do it 'has the merge request reference in the title' do expect(issue.title).to include(merge_request.title) end it 'has the reference of the merge request in the description' do expect(issue.description).to include(merge_request.to_reference) end it 'does not assign title when a title was given' do issue = described_class.new(project, user, merge_request_to_resolve_discussions_of: merge_request, title: 'What an issue').execute expect(issue.title).to eq('What an issue') end it 'does not assign description when a description was given' do issue = described_class.new(project, user, merge_request_to_resolve_discussions_of: merge_request, description: 'Fix at your earliest conveignance').execute expect(issue.description).to eq('Fix at your earliest conveignance') end describe 'with multiple discussions' do before do create(:diff_note_on_merge_request, noteable: merge_request, project: merge_request.target_project, line_number: 15) end it 'mentions all the authors in the description' do authors = merge_request.diff_discussions.map(&:author) expect(issue.description).to include(*authors.map(&:to_reference)) end it 'has a link for each unresolved discussion in the description' do notes = merge_request.diff_discussions.map(&:first_note) links = notes.map { |note| Gitlab::UrlBuilder.build(note) } expect(issue.description).to include(*links) end it 'mentions additional notes' do create_list(:diff_note_on_merge_request, 2, noteable: merge_request, project: merge_request.target_project, line_number: 15) expect(issue.description).to include('(+2 comments)') end end end end context 'For a merge request without discussions' do let(:merge_request) { create(:merge_request, source_project: project) } describe '#execute' do it 'mentions the merge request in the description' do issue = described_class.new(project, user, merge_request_to_resolve_discussions_of: merge_request.iid).execute expect(issue.description).to include("Review the conversation in #{merge_request.to_reference}") end end end describe '#execute' do let(:milestone) { create(:milestone, project: project) } it 'builds a new issues with given params' do issue = described_class.new( project, user, title: 'Issue #1', description: 'Issue description', milestone_id: milestone.id, ).execute expect(issue.title).to eq('Issue #1') expect(issue.description).to eq('Issue description') expect(issue.milestone).to eq(milestone) end end end
37.853333
156
0.657802
399195f358ff03602b6a2c7019a05c15dd7f3d73
860
# frozen_string_literal: true module EE module API module Entities module Board extend ActiveSupport::Concern prepended do expose :group, using: ::API::Entities::BasicGroupDetails with_options if: ->(board, _) { board.resource_parent.feature_available?(:scoped_issue_board) } do # Default filtering configuration expose :milestone do |board| if board.milestone.is_a?(Milestone) ::API::Entities::Milestone.represent(board.milestone) else SpecialBoardFilter.represent(board.milestone) end end expose :assignee, using: ::API::Entities::UserBasic expose :labels, using: ::API::Entities::LabelBasic expose :weight end end end end end end
28.666667
108
0.588372
012e7dace7bbbbddd2abcb368cce294ee3dd74f8
3,399
require 'rails_helper' RSpec.feature "Fill in Earnings and Benefits Page", js: true do let(:response_page) { ET3::Test::ResponsePage.new } before do given_valid_user start_a_new_et3_response registration_start end scenario "correctly will enable user to continue to next page" do earnings_and_benefits_page.load(locale: current_locale_parameter) given_valid_data answer_earnings_and_benefits expect(response_page).to be_displayed end scenario "incorrectly will provide many errors" do earnings_and_benefits_page.load(locale: current_locale_parameter) given_invalid_data answer_earnings_and_benefits expect(earnings_and_benefits_page).to have_header expect(earnings_and_benefits_page).to have_error_header earnings_and_benefits_page.queried_hours.assert_error_message(t('errors.custom.queried_hours.not_a_number')) earnings_and_benefits_page.queried_pay_before_tax.assert_error_message(t('errors.custom.queried_pay_before_tax.not_a_number')) earnings_and_benefits_page.queried_take_home_pay.assert_error_message(t('errors.custom.queried_take_home_pay.not_a_number')) earnings_and_benefits_page.disagree_claimant_notice_reason.assert_error_message(t('errors.messages.too_long')) earnings_and_benefits_page.disagree_claimant_pension_benefits_reason.assert_error_message(t('errors.messages.too_long')) end scenario "correctly will enable user to check answers and return to edit them" do earnings_and_benefits_page.load(locale: current_locale_parameter) given_valid_data answer_earnings_and_benefits confirmation_of_supplied_details_page.load(locale: current_locale_parameter) confirmation_of_supplied_details_page.confirmation_of_earnings_and_benefits_answers.edit_earnings_and_benefit_page_link.click expect(earnings_and_benefits_page).to be_displayed user = @claimant earnings_and_benefits_page.tap do |p| expect(p.agree_with_claimants_hours_question.value).to eql(t(user.agree_with_claimants_hours)) if user.agree_with_claimants_hours.to_s.split('.').last == 'no' expect(p.queried_hours.value).to eql user.queried_hours.to_s end expect(p.agree_with_earnings_details_question.value).to eql(t(user.agree_with_earnings_details)) if user.agree_with_earnings_details.to_s.split('.').last == 'no' expect(p.queried_pay_before_tax.value.gsub(',', '')).to eql sprintf('%.2f', user.queried_pay_before_tax) expect(p.queried_pay_before_tax_period.value).to eql t(user.queried_pay_before_tax_period) expect(p.queried_take_home_pay.value).to eql sprintf('%.2f', user.queried_take_home_pay) expect(p.queried_take_home_pay_period.value).to eql t(user.queried_take_home_pay_period) end expect(p.agree_with_claimant_notice_question.value).to eql(t(user.agree_with_claimant_notice)) if user.agree_with_claimant_notice.to_s.split('.').last == 'no' expect(p.disagree_claimant_notice_reason.value).to eql user.disagree_claimant_notice_reason end expect(p.agree_with_claimant_pension_benefits_question.value).to eql(t(user.agree_with_claimant_pension_benefits)) if user.agree_with_claimant_pension_benefits.to_s.split('.').last == 'no' expect(p.disagree_claimant_pension_benefits_reason.value).to eql user.disagree_claimant_pension_benefits_reason end end end end
51.5
130
0.800824
f8c30b3203f5c6a3785b84ab8b12562108a9eebf
2,746
# # Author:: Ranjib Dey (<[email protected]>) # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. Ohai.plugin(:GCE) do require_relative "../mixin/gce_metadata" require_relative "../mixin/http_helper" include Ohai::Mixin::GCEMetadata include Ohai::Mixin::HttpHelper provides "gce" # look for GCE string in dmi vendor bios data within the sys tree. # this works even if the system lacks dmidecode use by the Dmi plugin # @return [Boolean] do we have Google Compute Engine DMI data? def has_gce_dmi? if /Google Compute Engine/.match?(file_val_if_exists("/sys/class/dmi/id/product_name")) logger.trace("Plugin GCE: has_gce_dmi? == true") true else logger.trace("Plugin GCE: has_gce_dmi? == false") false end end # return the contents of a file if the file exists # @param path[String] abs path to the file # @return [String] contents of the file if it exists def file_val_if_exists(path) if ::File.exist?(path) ::File.read(path) end end # looks at the Manufacturer and Model WMI values to see if they starts with Google. # @return [Boolean] Are the manufacturer and model Google? def has_gce_system_info? if RUBY_PLATFORM.match?(/mswin|mingw32|windows/) require "wmi-lite/wmi" wmi = WmiLite::Wmi.new computer_system = wmi.first_of("Win32_ComputerSystem") if computer_system["Manufacturer"] =~ /^Google/ && computer_system["Model"] =~ /^Google/ logger.trace("Plugin GCE: has_gce_system_info? == true") true end else logger.trace("Plugin GCE: has_gce_system_info? == false") false end end # Identifies gce # # === Return # true:: If gce can be identified # false:: Otherwise def looks_like_gce? return true if hint?("gce") if has_gce_dmi? || has_gce_system_info? return true if can_socket_connect?(Ohai::Mixin::GCEMetadata::GCE_METADATA_ADDR, 80) end end collect_data do if looks_like_gce? logger.trace("Plugin GCE: looks_like_gce? == true") gce Mash.new fetch_metadata.each { |k, v| gce[k] = v } else logger.trace("Plugin GCE: looks_like_gce? == false") false end end end
30.853933
94
0.690459
f8582df78f7f5821a2b033a755e31a8ef995de6a
65
require './config/environment' run App #class name in app.rb
16.25
31
0.707692
e2e5a6a66a8907d675b56c267cce8c33a0d01508
635
name 'consul-template-cookbook' issues_url 'https://github.com/ist-dsi/consul-template-cookbook/issues' source_url 'https://github.com/ist-dsi/consul-template-cookbook' maintainer 'Simão Martins' maintainer_email '[email protected]' license 'Apache-2.0' description 'Installs/Configures consul-template. This is a fork of the consul-template cookbook which fixes some errors and removes support for Windows.' version '1.0.0' chef_version '>= 14.10' supports 'ubuntu', '>= 18.04' supports 'debian', '>= 9.8' supports 'centos', '>= 7.6' depends 'tar', '~> 2.2.0'
39.6875
159
0.683465
acd2573e3218f9fc8501779b0420d77df02fac59
3,556
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. require "arrow/block-closable" module Arrow class Loader < GObjectIntrospection::Loader class << self def load super("Arrow", Arrow) end end private def post_load(repository, namespace) require_libraries end def require_libraries require "arrow/array" require "arrow/array-builder" require "arrow/chunked-array" require "arrow/column" require "arrow/compression-type" require "arrow/csv-loader" require "arrow/csv-read-options" require "arrow/data-type" require "arrow/date32-array" require "arrow/date32-array-builder" require "arrow/date64-array" require "arrow/date64-array-builder" require "arrow/decimal128-array-builder" require "arrow/decimal128-data-type" require "arrow/dense-union-data-type" require "arrow/dictionary-data-type" require "arrow/field" require "arrow/file-output-stream" require "arrow/list-array-builder" require "arrow/list-data-type" require "arrow/path-extension" require "arrow/record" require "arrow/record-batch" require "arrow/record-batch-file-reader" require "arrow/record-batch-stream-reader" require "arrow/rolling-window" require "arrow/schema" require "arrow/slicer" require "arrow/sparse-union-data-type" require "arrow/struct-array" require "arrow/struct-array-builder" require "arrow/struct-data-type" require "arrow/table" require "arrow/table-formatter" require "arrow/table-list-formatter" require "arrow/table-table-formatter" require "arrow/table-loader" require "arrow/table-saver" require "arrow/tensor" require "arrow/time32-data-type" require "arrow/time64-data-type" require "arrow/timestamp-array" require "arrow/timestamp-array-builder" require "arrow/timestamp-data-type" require "arrow/writable" end def load_object_info(info) super klass = @base_module.const_get(rubyish_class_name(info)) if klass.method_defined?(:close) klass.extend(BlockClosable) end end def load_method_info(info, klass, method_name) case klass.name when "Arrow::StringArray" case method_name when "get_value" method_name = "get_raw_value" when "get_string" method_name = "get_value" end super(info, klass, method_name) when "Arrow::TimestampArray", "Arrow::Date32Array", "Arrow::Date64Array" case method_name when "get_value" method_name = "get_raw_value" end super(info, klass, method_name) else super end end end end
31.75
78
0.676884
7af96dfb0ddcd09a2b19b864a6718da044c00923
1,596
module Forem module Admin class ForumsController < BaseController before_action :find_forum, :only => [:edit, :update, :destroy] def index @forums = Forem::Forum.all end def new @forum = Forem::Forum.new end def create @forum = Forem::Forum.new(forum_params) if @forum.save create_successful else create_failed end end def update if @forum.update_attributes(forum_params) update_successful else update_failed end end def destroy @forum.destroy destroy_successful end private def forum_params params.require(:forum).permit(:category_id, :title, :description, :position, { :moderator_ids => []}) end def find_forum @forum = Forem::Forum.friendly.find(params[:id]) end def create_successful flash[:notice] = t("forem.admin.forum.created") redirect_to admin_forums_path end def create_failed flash.now.alert = t("forem.admin.forum.not_created") render :action => "new" end def destroy_successful flash[:notice] = t("forem.admin.forum.deleted") redirect_to admin_forums_path end def update_successful flash[:notice] = t("forem.admin.forum.updated") redirect_to admin_forums_path end def update_failed flash.now.alert = t("forem.admin.forum.not_updated") render :action => "edit" end end end end
21.567568
109
0.587719
f857785c994cd43c0fc6da2cd3dfc61d1027bb80
2,001
module Fog module Parsers module AWS module CloudFormation class DescribeStacks < Fog::Parsers::Base def reset @stack = { 'Outputs' => [], 'Parameters' => [] } @output = {} @parameter = {} @response = { 'Stacks' => [] } end def start_element(name, attrs = []) super case name when 'Outputs' @in_outputs = true when 'Parameters' @in_parameters = true end end def end_element(name) if @in_outputs case name when 'OutputKey', 'OutputValue' @output[name] = @value when 'member' @stack['Outputs'] << @output @output = {} when 'Outputs' @in_outputs = false end elsif @in_parameters case name when 'ParameterKey', 'ParameterValue' @parameter[name] = @value when 'member' @stack['Parameters'] << @parameter @parameter = {} when 'Parameters' @in_parameters = false end else case name when 'member' @response['Stacks'] << @stack @stack = { 'Outputs' => [], 'Parameters' => [] } when 'RequestId' @response[name] = @value when 'CreationTime' @stack[name] = Time.parse(@value) when 'DisableRollback' case @value when 'false' @stack[name] = false when 'true' @stack[name] = true end when 'StackName', 'StackId', 'StackStatus' @stack[name] = @value end end end end end end end end
27.410959
64
0.406797
385832723748d4cc17215277555b9e3e3086e205
1,709
# frozen_string_literal: true module ChartBibz module ViewComponents # Generate the canvas view through the render method class CanvasViewComponent < ApplicationViewComponent # Constants WIDTH = 400 # Default width for the html canvas HEIGHT = 400 # Default height for the html canvas # Only html_options can be passed # # @example # ChartBibz::ViewComponents::CanvasViewComponent.new(class: 'test') # # @param [Hash] args The html options # @return [void] # # @api public def initialize(args = {}) @args = args end # Generate the html canvas # # @example # ChartBibz::ViewComponents::CanvasViewComponent.new(class: # 'test').render # # @return [String] The html canvas # # @api public def render tag.canvas(**html_options) end # Get the id # # @example # ChartBibz::ViewComponents::CanvasViewComponent.new(class: 'test').id # # @return [String] The canvas html id # # @api public def id html_options[:id] end private # Get all html options # # @return [String] The canvas html attributes # # @api private def html_options @html_options ||= base_html_options.merge(@args).merge(class: join_classes('chart-bibz', @args[:class])) end # Get the html options base # # @return [String] The canvas html attributes # # @api private def base_html_options { id: "chart-#{Random.uuid}", width: WIDTH, height: HEIGHT, role: 'img' } end end end end
23.736111
112
0.578701
bf3350183b92aed621382c8440d5a7150b72afee
3,497
#A block macro processor converting gherkin feature files to asciidoctor markup require 'asciidoctor' require 'asciidoctor/extensions' require 'erb' require 'java' class GherkinBlockMacroProcessor < Asciidoctor::Extensions::BlockMacroProcessor use_dsl named :gherkin name_positional_attributes 'template' def process parent, target, attributes doc = parent.document reader = parent.document.reader if attributes.key?("template-encoding") template_encoding = attributes["template-encoding"] elsif doc.attributes.key?("template-encoding") template_encoding = doc.attributes["template-encoding"] else template_encoding = "UTF-8" end if doc.attributes.key?('docdir') && attributes.key?('template') && File.exist?(File.expand_path(attributes['template'], doc.attributes['docdir'])) template_file = File.open(File.expand_path(attributes['template'], doc.attributes['docdir']), "rb", :encoding => template_encoding) template_content = template_file.read else template_content = com.github.domgold.doctools.asciidoctor.gherkin.MapFormatter.getDefaultTemplate() end erb_template = ERB.new(template_content) feature_file_name = target if doc.attributes.key?('docdir') feature_file_name = File.expand_path(feature_file_name, doc.attributes['docdir']) end if attributes.key?("encoding") encoding = attributes["encoding"] elsif doc.attributes.key?("encoding") encoding = doc.attributes["encoding"] else encoding = "UTF-8" end file = File.open(feature_file_name, "rb", :encoding => encoding) feature_file_content = file.read #parse feature and make the result available to the template via binding as 'feature' hash. feature = com.github.domgold.doctools.asciidoctor.gherkin.MapFormatter.parse(feature_file_content) preprocess_feature(feature) rendered_template_output = erb_template.result(binding()) reader.push_include rendered_template_output, target, target, 1, attributes nil end def preprocess_feature feature if feature.key?('background') preprocess_scenario feature['background'] end if feature.key?('scenarios') feature['scenarios'].each do | scenario | preprocess_scenario scenario end end end def preprocess_scenario scenario if scenario.key?('steps') preprocess_steplist scenario['steps'] end if scenario.key?('examples') preprocess_table_comments scenario['examples']['rows'] end end def preprocess_steplist steplist steplist.each do | step | if step.key?('rows') preprocess_table_comments step['rows'] end end end def preprocess_table_comments rows if rows.length > 0 && rows.first.key?('comments') && rows.first['comments'].length > 0 && rows.first['comments'].first['value'].match(/^#cols=/) cols = rows.first['comments'].first['value'][1..-1] rows.first['comments'].java_send :remove, [Java::int], 0 rows.first["cols"] = cols end rows.each do | row | if row.key?('comments') && row['comments'].length > 0 && row['comments'].first['value'].match(/^#cells=/) cells = row['comments'].first['value'][7..-1].split(/,/) row['cell-styles'] = cells row['comments'].java_send :remove, [Java::int], 0 end end end end
34.284314
150
0.668287
188262004900cc7fe2fa7c923847d149e8504e5f
655
# frozen_string_literal: true Gem::Specification.new do |spec| spec.name = 'find_dupes_extension' spec.version = File.read(File.expand_path('VERSION', __dir__)).strip spec.authors = ['Marcus Wyatt'] spec.email = ['[email protected]'] spec.summary = 'Adds `find_dupes` method to `Array`' spec.homepage = 'https://github.com/mlwyatt/rails-extensions' spec.license = 'MIT' spec.required_ruby_version = Gem::Requirement.new('>= 3.0.1') spec.metadata['source_code_uri'] = 'https://github.com/mlwyatt/rails-extensions' spec.files = Dir['LICENSE.txt', 'CHANGELOG.md', 'VERSION', 'lib/**/*.rb'] spec.require_paths = ['lib'] end
34.473684
82
0.705344
61a6d8a2e549c5cb78a79ff9acea7d86ad32ce57
533
class AddTitleAndLastModifiedToSubscription < ActiveRecord::Migration def change change_table :subscriptions do |t| t.string :title t.datetime :last_modified end Subscription.reset_column_information Subscription.all.each do |subs| subs.title = subs.feed.title || subs.feed.url || subs.feed.feed_url newest = subs.entries.first || Entry.new mod = newest.published || subs.feed.last_modified || subs.feed.updated_at subs.last_modified = mod subs.save! end end end
31.352941
79
0.69606
e2cd2e0560341e78853ee6e152a51054f6a1ee3a
525
Rails.application.routes.draw do get '/resorts', to: "resorts#index", as: 'resorts' get '/resorts/:slug', to: "resorts#show", as: 'resort' get 'resorts/:resort_slug/:slug', to: "parks#show", as: 'park' get 'resorts/:resort_slug/:park_slug/attractions/:slug', to: "attractions#show", as: 'attraction' get 'resorts/:resort_slug/:park_slug/entertainments/:slug', to: "entertainments#show", as: 'entertainment' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
47.727273
108
0.718095
876d61ddde770683353c2d77776ef0db5af4be47
1,314
# Sponge Knowledge Base # Using rules - synchronous and asynchronous java_import org.openksavi.sponge.examples.util.CorrelationEventsLog def onInit # Variables for assertions only $correlationEventsLog = CorrelationEventsLog.new $sponge.setVariable("correlationEventsLog", $correlationEventsLog) end class RuleFFF < Rule def onConfigure self.withEvents(["e1", "e2", "e3 :first"]).withSynchronous(true) end def onRun(event) self.logger.debug("Running rule for event: {}", event.name) $correlationEventsLog.addEvents("RuleFFF", self) end end class RuleFFL < Rule def onConfigure self.withEvents(["e1", "e2", "e3 :last"]).withDuration(Duration.ofSeconds(2)).withSynchronous(false) end def onRun(event) self.logger.debug("Running rule for event: {}", event.name) $correlationEventsLog.addEvents("RuleFFL", self) end end def onStartup $sponge.event("e1").set("label", "1").send() $sponge.event("e2").set("label", "2").send() $sponge.event("e2").set("label", "3").send() $sponge.event("e2").set("label", "4").send() $sponge.event("e3").set("label", "5").send() $sponge.event("e3").set("label", "6").send() $sponge.event("e3").set("label", "7").send() end
32.04878
109
0.638508
629284d9b611fec550af68191084cd6ca8bdfe44
132
class AddSetupCompleteToUser < ActiveRecord::Migration[5.1] def change add_column :users, :setup_complete, :boolean end end
22
59
0.765152
28cc27de6d3c8c3d6605f2c12bd6bf5a1d5d0cd1
99
default['chef_client']['sensu_api_url'] = nil default['chef_client']['sensu_stash_timeout'] = 3600
33
52
0.757576
61d37ee531185e9e7e8c31b7aac794a7d67cfa8e
1,313
module SpreeBoxesManagement module Generators class InstallGenerator < Rails::Generators::Base class_option :auto_run_migrations, :type => :boolean, :default => false def add_javascripts append_file 'vendor/assets/javascripts/spree/frontend/all.js', "//= require spree/frontend/spree_boxes_management\n" append_file 'vendor/assets/javascripts/spree/backend/all.js', "//= require spree/backend/spree_boxes_management\n" end def add_stylesheets inject_into_file 'vendor/assets/stylesheets/spree/frontend/all.css', " *= require spree/frontend/spree_boxes_management\n", :before => /\*\//, :verbose => true inject_into_file 'vendor/assets/stylesheets/spree/backend/all.css', " *= require spree/backend/spree_boxes_management\n", :before => /\*\//, :verbose => true end def add_migrations run 'bundle exec rake railties:install:migrations FROM=spree_boxes_management' end def run_migrations run_migrations = options[:auto_run_migrations] || ['', 'y', 'Y'].include?(ask 'Would you like to run the migrations now? [Y/n]') if run_migrations run 'bundle exec rake db:migrate' else puts 'Skipping rake db:migrate, don\'t forget to run it!' end end end end end
41.03125
167
0.681645
621f586838966b8cb626bc81873504b580158dad
780
require 'spec_helper' describe StringFieldsController do describe 'w routing to' do it '#edit' do expect(get: '/string_fields/1/edit').to route_to('string_fields#edit', id: '1') end it '#update' do expect(put: '/string_fields/1').to route_to('string_fields#update', id: '1') end end describe 'w/o routing to' do it '#index' do expect(get: '/string_fields').not_to be_routable end it '#show' do expect(get: '/string_fields/1').not_to be_routable end it '#new' do expect(get: '/string_fields/new').not_to be_routable end it '#create' do expect(post: '/string_fields').not_to be_routable end it '#destroy' do expect(delete: '/string_fields/1').not_to be_routable end end end
25.16129
85
0.641026
267dd952ba4347f355f3a0bb1ea29fcb020c8739
257
newproperty(:expirationpolicy) do include EasyType desc 'expirationpolicy of the topic' newvalues(:'Discard', :'Log', :'Redirect') defaultto 'Discard' to_translate_to_resource do | raw_resource| raw_resource['expirationpolicy'] end end
17.133333
45
0.735409
e9ae3e87f12273939f1a6afe0726ec98ded62805
22,474
require 'digest/sha1' require 'danbooru/has_bit_flags' class User < ActiveRecord::Base class Error < Exception ; end class PrivilegeError < Exception ; end module Levels BLOCKED = 10 MEMBER = 20 GOLD = 30 PLATINUM = 31 BUILDER = 32 JANITOR = 35 MODERATOR = 40 ADMIN = 50 end # Used for `before_filter :<role>_only`. Must have a corresponding `is_<role>?` method. Roles = Levels.constants.map(&:downcase) + [ :anonymous, :banned, :approver, :voter, :super_voter, :verified, ] BOOLEAN_ATTRIBUTES = %w( is_banned has_mail receive_email_notifications always_resize_images enable_post_navigation new_post_navigation_layout enable_privacy_mode enable_sequential_post_navigation hide_deleted_posts style_usernames enable_auto_complete show_deleted_children has_saved_searches can_approve_posts can_upload_free disable_categorized_saved_searches is_super_voter disable_tagged_filenames enable_recent_searches ) include Danbooru::HasBitFlags has_bit_flags BOOLEAN_ATTRIBUTES, :field => "bit_prefs" attr_accessor :password, :old_password attr_accessible :dmail_filter_attributes, :enable_privacy_mode, :enable_post_navigation, :new_post_navigation_layout, :password, :old_password, :password_confirmation, :password_hash, :email, :last_logged_in_at, :last_forum_read_at, :has_mail, :receive_email_notifications, :comment_threshold, :always_resize_images, :favorite_tags, :blacklisted_tags, :name, :ip_addr, :time_zone, :default_image_size, :enable_sequential_post_navigation, :per_page, :hide_deleted_posts, :style_usernames, :enable_auto_complete, :custom_style, :show_deleted_children, :disable_categorized_saved_searches, :disable_tagged_filenames, :enable_recent_searches, :as => [:moderator, :janitor, :gold, :platinum, :member, :anonymous, :default, :builder, :admin] attr_accessible :level, :as => :admin validates :name, user_name: true, on: :create validates_uniqueness_of :email, :case_sensitive => false, :if => lambda {|rec| rec.email.present? && rec.email_changed? } validates_length_of :password, :minimum => 5, :if => lambda {|rec| rec.new_record? || rec.password.present?} validates_inclusion_of :default_image_size, :in => %w(large original) validates_inclusion_of :per_page, :in => 1..100 validates_confirmation_of :password validates_presence_of :email, :if => lambda {|rec| rec.new_record? && Danbooru.config.enable_email_verification?} validates_presence_of :comment_threshold validate :validate_ip_addr_is_not_banned, :on => :create before_validation :normalize_blacklisted_tags before_validation :set_per_page before_validation :normalize_email before_create :encrypt_password_on_create before_update :encrypt_password_on_update before_create :initialize_default_boolean_attributes after_save :update_cache after_update :update_remote_cache before_create :promote_to_admin_if_first_user before_create :customize_new_user #after_create :notify_sock_puppets has_many :feedback, :class_name => "UserFeedback", :dependent => :destroy has_many :posts, :foreign_key => "uploader_id" has_many :post_approvals, :dependent => :destroy has_many :post_votes has_many :bans, lambda {order("bans.id desc")} has_one :recent_ban, lambda {order("bans.id desc")}, :class_name => "Ban" has_one :api_key has_one :dmail_filter has_one :super_voter has_one :token_bucket has_many :subscriptions, lambda {order("tag_subscriptions.name")}, :class_name => "TagSubscription", :foreign_key => "creator_id" has_many :note_versions, :foreign_key => "updater_id" has_many :dmails, lambda {order("dmails.id desc")}, :foreign_key => "owner_id" has_many :saved_searches has_many :forum_posts, lambda {order("forum_posts.created_at")}, :foreign_key => "creator_id" has_many :user_name_change_requests, lambda {visible.order("user_name_change_requests.created_at desc")} belongs_to :inviter, :class_name => "User" after_update :create_mod_action accepts_nested_attributes_for :dmail_filter module BanMethods def is_banned_or_ip_banned? return is_banned? || IpBan.is_banned?(CurrentUser.ip_addr) end def validate_ip_addr_is_not_banned if IpBan.is_banned?(CurrentUser.ip_addr) self.errors[:base] << "IP address is banned" return false end end def unban! self.is_banned = false save ban.destroy end end module InvitationMethods def invite!(level, can_upload_free) if can_upload_free self.can_upload_free = true else self.can_upload_free = false end if level.to_i <= Levels::BUILDER self.level = level self.inviter_id = CurrentUser.id save end end end module NameMethods extend ActiveSupport::Concern module ClassMethods def name_to_id(name) Cache.get("uni:#{Cache.sanitize(name)}", 4.hours) do select_value_sql("SELECT id FROM users WHERE lower(name) = ?", name.mb_chars.downcase.tr(" ", "_").to_s) end end def id_to_name(user_id) Cache.get("uin:#{user_id}", 4.hours) do select_value_sql("SELECT name FROM users WHERE id = ?", user_id) || Danbooru.config.default_guest_name end end def find_by_name(name) where("lower(name) = ?", name.mb_chars.downcase.tr(" ", "_")).first end def id_to_pretty_name(user_id) id_to_name(user_id).gsub(/([^_])_+(?=[^_])/, "\\1 \\2") end def normalize_name(name) name.to_s.mb_chars.downcase.strip.tr(" ", "_").to_s end end def pretty_name name.gsub(/([^_])_+(?=[^_])/, "\\1 \\2") end def update_cache Cache.put("uin:#{id}", name) Cache.put("uni:#{Cache.sanitize(name)}", id) end def update_remote_cache if name_changed? Danbooru.config.other_server_hosts.each do |server| Net::HTTP.delete(URI.parse("http://#{server}/users/#{id}/cache")) end end rescue Exception # swallow, since it'll be expired eventually anyway end end module PasswordMethods def bcrypt_password BCrypt::Password.new(bcrypt_password_hash) end def bcrypt_cookie_password_hash bcrypt_password_hash.slice(20, 100) end def encrypt_password_on_create self.password_hash = "" self.bcrypt_password_hash = User.bcrypt(password) end def encrypt_password_on_update return if password.blank? return if old_password.blank? if bcrypt_password == User.sha1(old_password) self.bcrypt_password_hash = User.bcrypt(password) return true else errors[:old_password] = "is incorrect" return false end end def reset_password consonants = "bcdfghjklmnpqrstvqxyz" vowels = "aeiou" pass = "" 6.times do pass << consonants[rand(21), 1] pass << vowels[rand(5), 1] end pass << rand(100).to_s update_column(:bcrypt_password_hash, User.bcrypt(pass)) pass end def reset_password_and_deliver_notice new_password = reset_password() Maintenance::User::PasswordResetMailer.confirmation(self, new_password).deliver_now end end module AuthenticationMethods extend ActiveSupport::Concern module ClassMethods def authenticate(name, pass) authenticate_hash(name, sha1(pass)) end def authenticate_api_key(name, api_key) key = ApiKey.where(:key => api_key).first return nil if key.nil? user = find_by_name(name) return nil if user.nil? return user if key.user_id == user.id nil end def authenticate_hash(name, hash) user = find_by_name(name) if user && user.bcrypt_password == hash user else nil end end def authenticate_cookie_hash(name, hash) user = find_by_name(name) if user && user.bcrypt_cookie_password_hash == hash user else nil end end def bcrypt(pass) BCrypt::Password.create(sha1(pass)) end def sha1(pass) Digest::SHA1.hexdigest("#{Danbooru.config.password_salt}--#{pass}--") end end end module FavoriteMethods def favorites Favorite.where("user_id % 100 = #{id % 100} and user_id = #{id}").order("id desc") end def clean_favorite_count? favorite_count < 0 || Kernel.rand(100) < [Math.log(favorite_count, 2), 5].min end def clean_favorite_count! update_column(:favorite_count, Favorite.for_user(id).count) end def add_favorite!(post) Favorite.add(post, self) clean_favorite_count! if clean_favorite_count? end def remove_favorite!(post) Favorite.remove(post, self) end def favorite_groups FavoriteGroup.for_creator(CurrentUser.user.id).order("updated_at desc") end end module LevelMethods extend ActiveSupport::Concern module ClassMethods def system Danbooru.config.system_user end def level_hash return { "Member" => Levels::MEMBER, "Gold" => Levels::GOLD, "Platinum" => Levels::PLATINUM, "Builder" => Levels::BUILDER, "Janitor" => Levels::JANITOR, "Moderator" => Levels::MODERATOR, "Admin" => Levels::ADMIN } end def level_string(value) case value when Levels::BLOCKED "Banned" when Levels::MEMBER "Member" when Levels::BUILDER "Builder" when Levels::GOLD "Gold" when Levels::PLATINUM "Platinum" when Levels::JANITOR "Janitor" when Levels::MODERATOR "Moderator" when Levels::ADMIN "Admin" else "" end end end def promote_to!(new_level, options = {}) UserPromotion.new(self, CurrentUser.user, new_level, options).promote! end def promote_to_admin_if_first_user return if Rails.env.test? if User.count == 0 self.level = Levels::ADMIN self.can_approve_posts = true self.can_upload_free = true self.is_super_voter = true else self.level = Levels::MEMBER end end def customize_new_user Danbooru.config.customize_new_user(self) end def role level_string.downcase.to_sym end def level_string_was level_string(level_was) end def level_string(value = nil) User.level_string(value || level) end def is_anonymous? false end def is_member? true end def is_blocked? is_banned? end def is_builder? level >= Levels::BUILDER end def is_gold? level >= Levels::GOLD end def is_platinum? level >= Levels::PLATINUM end def is_janitor? level >= Levels::JANITOR end def is_moderator? level >= Levels::MODERATOR end def is_mod? level >= Levels::MODERATOR end def is_admin? level >= Levels::ADMIN end def is_voter? is_gold? || is_super_voter? end def is_approver? can_approve_posts? end def create_mod_action if level_changed? ModAction.log(%{"#{name}":/users/#{id} level changed #{level_string_was} -> #{level_string}}) end end def set_per_page if per_page.nil? || !is_gold? self.per_page = Danbooru.config.posts_per_page end return true end def level_class "user-#{level_string.downcase}" end end module EmailMethods def is_verified? email_verification_key.blank? end def generate_email_verification_key self.email_verification_key = Digest::SHA1.hexdigest("#{Time.now.to_f}--#{name}--#{rand(1_000_000)}--") end def verify!(key) if email_verification_key == key self.update_column(:email_verification_key, nil) else raise User::Error.new("Verification key does not match") end end def normalize_email self.email = nil if email.blank? end end module BlacklistMethods def blacklisted_tag_array Tag.scan_query(blacklisted_tags) end def normalize_blacklisted_tags self.blacklisted_tags = blacklisted_tags.downcase if blacklisted_tags.present? end end module ForumMethods def has_forum_been_updated? return false unless is_gold? max_updated_at = ForumTopic.permitted.active.maximum(:updated_at) return false if max_updated_at.nil? return true if last_forum_read_at.nil? return max_updated_at > last_forum_read_at end end module LimitMethods def max_saved_searches if is_platinum? 1_000 else 250 end end def show_saved_searches? true end def can_upload? if can_upload_free? true elsif is_admin? true else upload_limit > 0 end end def upload_limited_reason "have reached your upload limit for the day" end def can_comment? if is_gold? true else created_at <= Danbooru.config.member_comment_time_threshold end end def is_comment_limited? if is_gold? false else Comment.where("creator_id = ? and created_at > ?", id, 1.hour.ago).count >= Danbooru.config.member_comment_limit end end def can_comment_vote? CommentVote.where("user_id = ? and created_at > ?", id, 1.hour.ago).count < 10 end def can_remove_from_pools? true end def base_upload_limit if created_at >= 1.month.ago 10 elsif created_at >= 2.months.ago 20 elsif created_at >= 3.months.ago 30 elsif created_at >= 4.months.ago 40 else 50 end end def max_upload_limit dcon = [deletion_confidence(60), 15].min [(base_upload_limit * (1 - (dcon / 15.0))).ceil, 10].max end def upload_limit @upload_limit ||= begin uploaded_count = Post.for_user(id).where("created_at >= ?", 24.hours.ago).count uploaded_comic_count = Post.for_user(id).tag_match("comic").where("created_at >= ?", 24.hours.ago).count / 3 limit = max_upload_limit - (uploaded_count - uploaded_comic_count) if limit < 0 limit = 0 end limit end end def tag_query_limit if is_platinum? Danbooru.config.base_tag_query_limit * 2 elsif is_gold? Danbooru.config.base_tag_query_limit else 2 end end def favorite_limit if is_platinum? nil elsif is_gold? 20_000 else 10_000 end end def favorite_group_limit if is_platinum? 10 elsif is_gold? 5 else 3 end end def api_regen_multiplier # regen this amount per second if is_platinum? && api_key.present? 4 elsif is_gold? && api_key.present? 2 else 1 end end def api_burst_limit # can make this many api calls at once before being bound by # api_regen_multiplier refilling your pool if is_platinum? && api_key.present? 60 elsif is_gold? && api_key.present? 30 else 10 end end def remaining_api_limit token_bucket.try(:token_count) || api_burst_limit end def statement_timeout if is_platinum? 9_000 elsif is_gold? 6_000 else 3_000 end end end module ApiMethods def hidden_attributes super + [:password_hash, :bcrypt_password_hash, :email, :email_verification_key, :time_zone, :updated_at, :receive_email_notifications, :last_logged_in_at, :last_forum_read_at, :has_mail, :default_image_size, :comment_threshold, :always_resize_images, :favorite_tags, :blacklisted_tags, :recent_tags, :enable_privacy_mode, :enable_post_navigation, :new_post_navigation_layout, :enable_sequential_post_navigation, :hide_deleted_posts, :per_page, :style_usernames, :enable_auto_complete, :custom_style, :show_deleted_children, :has_saved_searches, :last_ip_addr, :bit_prefs, :favorite_count] end def method_attributes list = super + [:is_banned, :can_approve_posts, :can_upload_free, :is_super_voter, :level_string] if id == CurrentUser.user.id list += [:remaining_api_limit, :api_burst_limit] end list end def to_legacy_json return { "name" => name, "id" => id, "level" => level, "created_at" => created_at.strftime("%Y-%m-%d %H:%M") }.to_json end end module CountMethods def wiki_page_version_count WikiPageVersion.for_user(id).count end def artist_version_count ArtistVersion.for_user(id).count end def artist_commentary_version_count ArtistCommentaryVersion.for_user(id).count end def pool_version_count PoolArchive.for_user(id).count end def forum_post_count ForumPost.for_user(id).count end def comment_count Comment.for_creator(id).count end def favorite_group_count FavoriteGroup.for_creator(id).count end def appeal_count PostAppeal.for_creator(id).count end def flag_count PostFlag.for_creator(id).count end def positive_feedback_count feedback.positive.count end def neutral_feedback_count feedback.neutral.count end def negative_feedback_count feedback.negative.count end end module SearchMethods def named(name) where("lower(name) = ?", name) end def name_matches(name) where("lower(name) like ? escape E'\\\\'", name.to_escaped_for_sql_like) end def admins where("level = ?", Levels::ADMIN) end # UserDeletion#rename renames deleted users to `user_<1234>~`. Tildes # are appended if the username is taken. def deleted where("name ~ 'user_[0-9]+~*'") end def undeleted where("name !~ 'user_[0-9]+~*'") end def with_email(email) if email.blank? where("FALSE") else where("email = ?", email) end end def find_for_password_reset(name, email) if email.blank? where("FALSE") else where(["name = ? AND email = ?", name, email]) end end def search(params) q = where("true") return q if params.blank? if params[:name].present? q = q.name_matches(params[:name].mb_chars.downcase.strip.tr(" ", "_")) end if params[:name_matches].present? q = q.name_matches(params[:name_matches].mb_chars.downcase.strip.tr(" ", "_")) end if params[:min_level].present? q = q.where("level >= ?", params[:min_level].to_i) end if params[:max_level].present? q = q.where("level <= ?", params[:max_level].to_i) end if params[:level].present? q = q.where("level = ?", params[:level].to_i) end if params[:id].present? q = q.where("id in (?)", params[:id].split(",").map(&:to_i)) end bitprefs_length = BOOLEAN_ATTRIBUTES.length bitprefs_include = nil bitprefs_exclude = nil [:can_approve_posts, :can_upload_free, :is_super_voter].each do |x| if params[x].present? attr_idx = BOOLEAN_ATTRIBUTES.index(x.to_s) if params[x] == "true" bitprefs_include ||= "0"*bitprefs_length bitprefs_include[attr_idx] = '1' elsif params[x] == "false" bitprefs_exclude ||= "0"*bitprefs_length bitprefs_exclude[attr_idx] = '1' end end end if bitprefs_include bitprefs_include.reverse! q = q.where("bit_prefs::bit(:len) & :bits::bit(:len) = :bits::bit(:len)", {:len => bitprefs_length, :bits => bitprefs_include}) end if bitprefs_exclude bitprefs_exclude.reverse! q = q.where("bit_prefs::bit(:len) & :bits::bit(:len) = 0::bit(:len)", {:len => bitprefs_length, :bits => bitprefs_exclude}) end if params[:current_user_first] == "true" && !CurrentUser.is_anonymous? q = q.order("id = #{CurrentUser.user.id.to_i} desc") end case params[:order] when "name" q = q.order("name") when "post_upload_count" q = q.order("post_upload_count desc") when "note_count" q = q.order("note_update_count desc") when "post_update_count" q = q.order("post_update_count desc") else q = q.order("created_at desc") end q end end module StatisticsMethods def deletion_confidence(days = 30) Reports::UserPromotions.deletion_confidence_interval_for(self, days) end end module SockPuppetMethods def notify_sock_puppets sock_puppet_suspects.each do |user| end end def sock_puppet_suspects if last_ip_addr.present? User.where(:last_ip_addr => last_ip_addr) end end end include BanMethods include NameMethods include PasswordMethods include AuthenticationMethods include FavoriteMethods include LevelMethods include EmailMethods include BlacklistMethods include ForumMethods include LimitMethods include InvitationMethods include ApiMethods include CountMethods extend SearchMethods include StatisticsMethods def initialize_default_image_size self.default_image_size = "large" end def can_update?(object, foreign_key = :user_id) is_moderator? || is_admin? || object.__send__(foreign_key) == id end def dmail_count if has_mail? "(#{dmails.unread.count})" else "" end end def hide_favorites? !CurrentUser.is_admin? && enable_privacy_mode? && CurrentUser.user.id != id end def initialize_default_boolean_attributes self.enable_post_navigation = true self.new_post_navigation_layout = true self.enable_sequential_post_navigation = true self.enable_auto_complete = true end end
24.860619
737
0.645457
9100c4e056ba3fa7fcda506dbcc815f79058b9f8
4,934
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/binaryauthorization/v1/service.proto require 'google/protobuf' require 'google/api/annotations_pb' require 'google/api/client_pb' require 'google/api/field_behavior_pb' require 'google/api/resource_pb' require 'google/cloud/binaryauthorization/v1/resources_pb' require 'google/protobuf/empty_pb' require 'grafeas/v1/attestation_pb' Google::Protobuf::DescriptorPool.generated_pool.build do add_file("google/cloud/binaryauthorization/v1/service.proto", :syntax => :proto3) do add_message "google.cloud.binaryauthorization.v1.GetPolicyRequest" do optional :name, :string, 1 end add_message "google.cloud.binaryauthorization.v1.UpdatePolicyRequest" do optional :policy, :message, 1, "google.cloud.binaryauthorization.v1.Policy" end add_message "google.cloud.binaryauthorization.v1.CreateAttestorRequest" do optional :parent, :string, 1 optional :attestor_id, :string, 2 optional :attestor, :message, 3, "google.cloud.binaryauthorization.v1.Attestor" end add_message "google.cloud.binaryauthorization.v1.GetAttestorRequest" do optional :name, :string, 1 end add_message "google.cloud.binaryauthorization.v1.UpdateAttestorRequest" do optional :attestor, :message, 1, "google.cloud.binaryauthorization.v1.Attestor" end add_message "google.cloud.binaryauthorization.v1.ListAttestorsRequest" do optional :parent, :string, 1 optional :page_size, :int32, 2 optional :page_token, :string, 3 end add_message "google.cloud.binaryauthorization.v1.ListAttestorsResponse" do repeated :attestors, :message, 1, "google.cloud.binaryauthorization.v1.Attestor" optional :next_page_token, :string, 2 end add_message "google.cloud.binaryauthorization.v1.DeleteAttestorRequest" do optional :name, :string, 1 end add_message "google.cloud.binaryauthorization.v1.GetSystemPolicyRequest" do optional :name, :string, 1 end add_message "google.cloud.binaryauthorization.v1.ValidateAttestationOccurrenceRequest" do optional :attestor, :string, 1 optional :attestation, :message, 2, "grafeas.v1.AttestationOccurrence" optional :occurrence_note, :string, 3 optional :occurrence_resource_uri, :string, 4 end add_message "google.cloud.binaryauthorization.v1.ValidateAttestationOccurrenceResponse" do optional :result, :enum, 1, "google.cloud.binaryauthorization.v1.ValidateAttestationOccurrenceResponse.Result" optional :denial_reason, :string, 2 end add_enum "google.cloud.binaryauthorization.v1.ValidateAttestationOccurrenceResponse.Result" do value :RESULT_UNSPECIFIED, 0 value :VERIFIED, 1 value :ATTESTATION_NOT_VERIFIABLE, 2 end end end module Google module Cloud module BinaryAuthorization module V1 GetPolicyRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.binaryauthorization.v1.GetPolicyRequest").msgclass UpdatePolicyRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.binaryauthorization.v1.UpdatePolicyRequest").msgclass CreateAttestorRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.binaryauthorization.v1.CreateAttestorRequest").msgclass GetAttestorRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.binaryauthorization.v1.GetAttestorRequest").msgclass UpdateAttestorRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.binaryauthorization.v1.UpdateAttestorRequest").msgclass ListAttestorsRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.binaryauthorization.v1.ListAttestorsRequest").msgclass ListAttestorsResponse = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.binaryauthorization.v1.ListAttestorsResponse").msgclass DeleteAttestorRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.binaryauthorization.v1.DeleteAttestorRequest").msgclass GetSystemPolicyRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.binaryauthorization.v1.GetSystemPolicyRequest").msgclass ValidateAttestationOccurrenceRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.binaryauthorization.v1.ValidateAttestationOccurrenceRequest").msgclass ValidateAttestationOccurrenceResponse = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.binaryauthorization.v1.ValidateAttestationOccurrenceResponse").msgclass ValidateAttestationOccurrenceResponse::Result = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.binaryauthorization.v1.ValidateAttestationOccurrenceResponse.Result").enummodule end end end end
58.047059
207
0.782529
21f4e467f80a7f50ee0e66e9a4cc0eb0746f0ae9
7,265
RSpec.describe Krane::Rbac::Graph::Node do subject { described_class } describe '#new' do context 'with correct attributes' do subject { build(:node) } it 'creates a new Node object' do expect { subject }.not_to raise_error expect(subject).not_to be nil end end context 'with invalid / not defined properties' do subject { build(:node, :invalid) } it 'fails to instantiate a new Node object and throws an exception' do expect { subject }.to raise_error( NoMethodError, "The property 'unknown_property' is not defined for Krane::Rbac::Graph::Node." ) end end end describe '#to_s' do subject { build(:node) } it 'returns string representation of the node to be indexed in the graph' do expected_attrs = subject.attrs.map {|k,v| "#{k.to_s}:'#{v.to_s}'"}.join(", ") expect(subject.to_s).to eq %Q((#{subject.label}:#{subject.kind} {#{expected_attrs}})) end end describe '#to_network' do context 'for :Psp node kind' do subject { build(:node, :psp) } it 'returns nil' do expect(subject.to_network).to be_nil end end context 'for :Rule node kind' do subject { build(:node, :rule) } it 'returns nil' do expect(subject.to_network).to be_nil end end context 'for :Role node kind' do subject { build(:node, :role) } it 'returns a map representation of a given node for use in the network view' do map = subject.to_network expect(map.keys.size).to eq 5 expect(map).to include( # group / title tested above id: subject.label, label: "#{subject.attrs[:kind]}: #{subject.attrs[:name]}", value: nil ) end context 'for default role' do subject { build(:node, :role, :default) } it 'builds network node title correctly' do title = subject.to_network[:title] expect(title).to include("#{subject.attrs[:kind]}: #{subject.attrs[:name]}") expect(title).to include("- Default k8s role") end it 'builds network node group attribure correctly' do group = subject.to_network[:group] expect(group).to eq [ described_class::GRAPH_NETWORK_NODE_GROUP[subject.kind], described_class::GRAPH_NETWORK_NODE_GROUP_BOOST[:is_default], ].sum end end context 'for composite role' do subject { build(:node, :role, :composite) } it 'builds network node title correctly' do title = subject.to_network[:title] expect(title).to include("#{subject.attrs[:kind]}: #{subject.attrs[:name]}") expect(title).to include("- Aggregates rules defined in other cluster roles") end it 'builds network node group attribure correctly' do group = subject.to_network[:group] expect(group).to eq [ described_class::GRAPH_NETWORK_NODE_GROUP[subject.kind], described_class::GRAPH_NETWORK_NODE_GROUP_BOOST[:is_composite], ].sum end end context 'for aggregable role' do subject { build(:node, :role, :aggregable, :aggregable_by_roles) } it 'builds network node title correctly' do title = subject.to_network[:title] expect(title).to include("#{subject.attrs[:kind]}: #{subject.attrs[:name]}") expect(title).to include("- Can be aggregated by cluster roles: #{subject.attrs[:aggregable_by]}") end it 'builds network node group attribure correctly' do group = subject.to_network[:group] expect(group).to eq [ described_class::GRAPH_NETWORK_NODE_GROUP[subject.kind], described_class::GRAPH_NETWORK_NODE_GROUP_BOOST[:is_aggregable], ].sum end end context 'for non default, non composite, non aggregable role' do subject { build(:node, :role, :not_default, :not_composite, :not_aggregable, :not_aggregable_by_roles) } it 'builds node title attribute correctly' do title = subject.to_network[:title] expect(title).to include("#{subject.attrs[:kind]}: #{subject.attrs[:name]}") expect(title).not_to include("- Default k8s role") expect(title).not_to include("- Aggregates rules defined in other cluster roles") expect(title).not_to include("- Can be aggregated by cluster roles: #{subject.attrs[:aggregable_by]}") end it 'builds node group attribure correctly' do group = subject.to_network[:group] expect(group).to eq described_class::GRAPH_NETWORK_NODE_GROUP[subject.kind] end end end context 'for :Subject node kind' do subject { build(:node, :subject) } it 'returns a map representation of a given node for use in the network view' do map = subject.to_network expect(map.keys.size).to eq 5 expect(map).to include( # group / title tested above id: subject.label, label: "#{subject.attrs[:kind]}: #{subject.attrs[:name]}", value: nil ) end it 'builds network node title correctly' do title = subject.to_network[:title] expect(title).to include("#{subject.attrs[:kind]}: #{subject.attrs[:name]}") end it 'builds node group attribure correctly' do group = subject.to_network[:group] expect(group).to eq described_class::GRAPH_NETWORK_NODE_GROUP[subject.kind] end end context 'for :Namespace node kind' do subject { build(:node, :namespace) } it 'returns a map representation of a given node for use in the network view' do map = subject.to_network expect(map.keys.size).to eq 5 expect(map).to include( # group / title tested above id: subject.label, label: "#{subject.kind}: #{subject.attrs[:name]}", value: nil ) end it 'builds network node title correctly' do title = subject.to_network[:title] expect(title).to include("#{subject.attrs[:kind]}: #{subject.attrs[:name]}") end it 'builds node group attribure correctly' do group = subject.to_network[:group] expect(group).to eq described_class::GRAPH_NETWORK_NODE_GROUP[subject.kind] end end context 'for all supported node kinds' do context 'with no :kind and :name keys present in node attrs' do subject { build(:node, :namespace, attrs: {} ) } it 'builds node title attribute correctly' do title = subject.to_network[:title] expect(title).to include("#{subject.kind}: #{subject.label}") end end context 'with :kind and :name keys present in node attrs' do let(:attr_kind) { 'some-kind' } let(:attr_name) { 'some-name' } subject { build(:node, :subject, attrs: { kind: attr_kind, name: attr_name } ) } it 'builds node title attribute correctly' do title = subject.to_network[:title] expect(title).to include("#{attr_kind}: #{attr_name}") end end end end end
29.77459
112
0.613214
33f25734148dabc9ee04fff2c224daf44556f3e2
71,966
# Copyright 2020 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'date' require 'google/apis/core/base_service' require 'google/apis/core/json_representation' require 'google/apis/core/hashable' require 'google/apis/errors' module Google module Apis module ContactcenterinsightsV1 class GoogleCloudContactcenterinsightsV1Analysis class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1AnalysisResult class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1AnalysisResultCallAnalysisMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1AnnotationBoundary class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1AnswerFeedback class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1ArticleSuggestionData class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1CalculateIssueModelStatsResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1CalculateStatsResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1CalculateStatsResponseTimeSeries class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1CalculateStatsResponseTimeSeriesInterval class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1CallAnnotation class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1Conversation class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1ConversationCallMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1ConversationDataSource class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1ConversationLevelSentiment class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1ConversationParticipant class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1ConversationTranscript class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1ConversationTranscriptTranscriptSegment class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1ConversationTranscriptTranscriptSegmentDialogflowSegmentMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1ConversationTranscriptTranscriptSegmentWordInfo class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1CreateAnalysisOperationMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1CreateIssueModelMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1CreateIssueModelRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1DeleteIssueModelMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1DeleteIssueModelRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1DeployIssueModelMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1DeployIssueModelRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1DeployIssueModelResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1DialogflowIntent class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1DialogflowInteractionData class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1DialogflowSource class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1Entity class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1EntityMentionData class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1ExactMatchConfig class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1ExportInsightsDataMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1ExportInsightsDataRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1ExportInsightsDataRequestBigQueryDestination class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1ExportInsightsDataResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1FaqAnswerData class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1GcsSource class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1HoldData class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1Intent class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1IntentMatchData class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1InterruptionData class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1Issue class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1IssueAssignment class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1IssueModel class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1IssueModelInputDataConfig class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1IssueModelLabelStats class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1IssueModelLabelStatsIssueStats class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1IssueModelResult class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1ListAnalysesResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1ListConversationsResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1ListIssueModelsResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1ListIssuesResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1ListPhraseMatchersResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1PhraseMatchData class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1PhraseMatchRule class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1PhraseMatchRuleConfig class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1PhraseMatchRuleGroup class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1PhraseMatcher class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1RuntimeAnnotation class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1SentimentData class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1Settings class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1SettingsAnalysisConfig class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1SilenceData class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1SmartComposeSuggestionData class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1SmartReplyData class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1UndeployIssueModelMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1UndeployIssueModelRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1UndeployIssueModelResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1alpha1CreateAnalysisOperationMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1alpha1CreateIssueModelMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1alpha1CreateIssueModelRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1alpha1DeleteIssueModelMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1alpha1DeleteIssueModelRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1alpha1DeployIssueModelMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1alpha1DeployIssueModelRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1alpha1DeployIssueModelResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1alpha1ExportInsightsDataMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1alpha1ExportInsightsDataRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1alpha1ExportInsightsDataRequestBigQueryDestination class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1alpha1ExportInsightsDataResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1alpha1IssueModel class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1alpha1IssueModelInputDataConfig class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1alpha1IssueModelLabelStats class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1alpha1IssueModelLabelStatsIssueStats class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1alpha1UndeployIssueModelMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1alpha1UndeployIssueModelRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1alpha1UndeployIssueModelResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleLongrunningListOperationsResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleLongrunningOperation class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleProtobufEmpty class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleRpcStatus class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudContactcenterinsightsV1Analysis # @private class Representation < Google::Apis::Core::JsonRepresentation property :analysis_result, as: 'analysisResult', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1AnalysisResult, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1AnalysisResult::Representation property :create_time, as: 'createTime' property :name, as: 'name' property :request_time, as: 'requestTime' end end class GoogleCloudContactcenterinsightsV1AnalysisResult # @private class Representation < Google::Apis::Core::JsonRepresentation property :call_analysis_metadata, as: 'callAnalysisMetadata', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1AnalysisResultCallAnalysisMetadata, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1AnalysisResultCallAnalysisMetadata::Representation property :end_time, as: 'endTime' end end class GoogleCloudContactcenterinsightsV1AnalysisResultCallAnalysisMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation collection :annotations, as: 'annotations', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1CallAnnotation, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1CallAnnotation::Representation hash :entities, as: 'entities', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1Entity, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1Entity::Representation hash :intents, as: 'intents', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1Intent, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1Intent::Representation property :issue_model_result, as: 'issueModelResult', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1IssueModelResult, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1IssueModelResult::Representation hash :phrase_matchers, as: 'phraseMatchers', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1PhraseMatchData, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1PhraseMatchData::Representation collection :sentiments, as: 'sentiments', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ConversationLevelSentiment, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ConversationLevelSentiment::Representation end end class GoogleCloudContactcenterinsightsV1AnnotationBoundary # @private class Representation < Google::Apis::Core::JsonRepresentation property :transcript_index, as: 'transcriptIndex' property :word_index, as: 'wordIndex' end end class GoogleCloudContactcenterinsightsV1AnswerFeedback # @private class Representation < Google::Apis::Core::JsonRepresentation property :clicked, as: 'clicked' property :correctness_level, as: 'correctnessLevel' property :displayed, as: 'displayed' end end class GoogleCloudContactcenterinsightsV1ArticleSuggestionData # @private class Representation < Google::Apis::Core::JsonRepresentation property :confidence_score, as: 'confidenceScore' hash :metadata, as: 'metadata' property :query_record, as: 'queryRecord' property :source, as: 'source' property :title, as: 'title' property :uri, as: 'uri' end end class GoogleCloudContactcenterinsightsV1CalculateIssueModelStatsResponse # @private class Representation < Google::Apis::Core::JsonRepresentation property :current_stats, as: 'currentStats', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1IssueModelLabelStats, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1IssueModelLabelStats::Representation end end class GoogleCloudContactcenterinsightsV1CalculateStatsResponse # @private class Representation < Google::Apis::Core::JsonRepresentation property :average_duration, as: 'averageDuration' property :average_turn_count, as: 'averageTurnCount' property :conversation_count, as: 'conversationCount' property :conversation_count_time_series, as: 'conversationCountTimeSeries', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1CalculateStatsResponseTimeSeries, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1CalculateStatsResponseTimeSeries::Representation hash :custom_highlighter_matches, as: 'customHighlighterMatches' hash :issue_matches, as: 'issueMatches' hash :smart_highlighter_matches, as: 'smartHighlighterMatches' end end class GoogleCloudContactcenterinsightsV1CalculateStatsResponseTimeSeries # @private class Representation < Google::Apis::Core::JsonRepresentation property :interval_duration, as: 'intervalDuration' collection :points, as: 'points', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1CalculateStatsResponseTimeSeriesInterval, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1CalculateStatsResponseTimeSeriesInterval::Representation end end class GoogleCloudContactcenterinsightsV1CalculateStatsResponseTimeSeriesInterval # @private class Representation < Google::Apis::Core::JsonRepresentation property :conversation_count, as: 'conversationCount' property :start_time, as: 'startTime' end end class GoogleCloudContactcenterinsightsV1CallAnnotation # @private class Representation < Google::Apis::Core::JsonRepresentation property :annotation_end_boundary, as: 'annotationEndBoundary', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1AnnotationBoundary, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1AnnotationBoundary::Representation property :annotation_start_boundary, as: 'annotationStartBoundary', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1AnnotationBoundary, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1AnnotationBoundary::Representation property :channel_tag, as: 'channelTag' property :entity_mention_data, as: 'entityMentionData', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1EntityMentionData, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1EntityMentionData::Representation property :hold_data, as: 'holdData', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1HoldData, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1HoldData::Representation property :intent_match_data, as: 'intentMatchData', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1IntentMatchData, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1IntentMatchData::Representation property :interruption_data, as: 'interruptionData', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1InterruptionData, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1InterruptionData::Representation property :phrase_match_data, as: 'phraseMatchData', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1PhraseMatchData, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1PhraseMatchData::Representation property :sentiment_data, as: 'sentimentData', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1SentimentData, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1SentimentData::Representation property :silence_data, as: 'silenceData', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1SilenceData, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1SilenceData::Representation end end class GoogleCloudContactcenterinsightsV1Conversation # @private class Representation < Google::Apis::Core::JsonRepresentation property :agent_id, as: 'agentId' property :call_metadata, as: 'callMetadata', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ConversationCallMetadata, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ConversationCallMetadata::Representation property :create_time, as: 'createTime' property :data_source, as: 'dataSource', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ConversationDataSource, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ConversationDataSource::Representation hash :dialogflow_intents, as: 'dialogflowIntents', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1DialogflowIntent, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1DialogflowIntent::Representation property :duration, as: 'duration' property :expire_time, as: 'expireTime' hash :labels, as: 'labels' property :language_code, as: 'languageCode' property :latest_analysis, as: 'latestAnalysis', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1Analysis, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1Analysis::Representation property :medium, as: 'medium' property :name, as: 'name' collection :runtime_annotations, as: 'runtimeAnnotations', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1RuntimeAnnotation, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1RuntimeAnnotation::Representation property :start_time, as: 'startTime' property :transcript, as: 'transcript', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ConversationTranscript, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ConversationTranscript::Representation property :ttl, as: 'ttl' property :turn_count, as: 'turnCount' property :update_time, as: 'updateTime' end end class GoogleCloudContactcenterinsightsV1ConversationCallMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation property :agent_channel, as: 'agentChannel' property :customer_channel, as: 'customerChannel' end end class GoogleCloudContactcenterinsightsV1ConversationDataSource # @private class Representation < Google::Apis::Core::JsonRepresentation property :dialogflow_source, as: 'dialogflowSource', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1DialogflowSource, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1DialogflowSource::Representation property :gcs_source, as: 'gcsSource', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1GcsSource, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1GcsSource::Representation end end class GoogleCloudContactcenterinsightsV1ConversationLevelSentiment # @private class Representation < Google::Apis::Core::JsonRepresentation property :channel_tag, as: 'channelTag' property :sentiment_data, as: 'sentimentData', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1SentimentData, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1SentimentData::Representation end end class GoogleCloudContactcenterinsightsV1ConversationParticipant # @private class Representation < Google::Apis::Core::JsonRepresentation property :dialogflow_participant, as: 'dialogflowParticipant' property :dialogflow_participant_name, as: 'dialogflowParticipantName' property :obfuscated_external_user_id, as: 'obfuscatedExternalUserId' property :role, as: 'role' property :user_id, as: 'userId' end end class GoogleCloudContactcenterinsightsV1ConversationTranscript # @private class Representation < Google::Apis::Core::JsonRepresentation collection :transcript_segments, as: 'transcriptSegments', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ConversationTranscriptTranscriptSegment, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ConversationTranscriptTranscriptSegment::Representation end end class GoogleCloudContactcenterinsightsV1ConversationTranscriptTranscriptSegment # @private class Representation < Google::Apis::Core::JsonRepresentation property :channel_tag, as: 'channelTag' property :confidence, as: 'confidence' property :dialogflow_segment_metadata, as: 'dialogflowSegmentMetadata', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ConversationTranscriptTranscriptSegmentDialogflowSegmentMetadata, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ConversationTranscriptTranscriptSegmentDialogflowSegmentMetadata::Representation property :language_code, as: 'languageCode' property :message_time, as: 'messageTime' property :segment_participant, as: 'segmentParticipant', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ConversationParticipant, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ConversationParticipant::Representation property :sentiment, as: 'sentiment', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1SentimentData, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1SentimentData::Representation property :text, as: 'text' collection :words, as: 'words', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ConversationTranscriptTranscriptSegmentWordInfo, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ConversationTranscriptTranscriptSegmentWordInfo::Representation end end class GoogleCloudContactcenterinsightsV1ConversationTranscriptTranscriptSegmentDialogflowSegmentMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation property :smart_reply_allowlist_covered, as: 'smartReplyAllowlistCovered' end end class GoogleCloudContactcenterinsightsV1ConversationTranscriptTranscriptSegmentWordInfo # @private class Representation < Google::Apis::Core::JsonRepresentation property :confidence, as: 'confidence' property :end_offset, as: 'endOffset' property :start_offset, as: 'startOffset' property :word, as: 'word' end end class GoogleCloudContactcenterinsightsV1CreateAnalysisOperationMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation property :conversation, as: 'conversation' property :create_time, as: 'createTime' property :end_time, as: 'endTime' end end class GoogleCloudContactcenterinsightsV1CreateIssueModelMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation property :create_time, as: 'createTime' property :end_time, as: 'endTime' property :request, as: 'request', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1CreateIssueModelRequest, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1CreateIssueModelRequest::Representation end end class GoogleCloudContactcenterinsightsV1CreateIssueModelRequest # @private class Representation < Google::Apis::Core::JsonRepresentation property :issue_model, as: 'issueModel', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1IssueModel, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1IssueModel::Representation property :parent, as: 'parent' end end class GoogleCloudContactcenterinsightsV1DeleteIssueModelMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation property :create_time, as: 'createTime' property :end_time, as: 'endTime' property :request, as: 'request', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1DeleteIssueModelRequest, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1DeleteIssueModelRequest::Representation end end class GoogleCloudContactcenterinsightsV1DeleteIssueModelRequest # @private class Representation < Google::Apis::Core::JsonRepresentation property :name, as: 'name' end end class GoogleCloudContactcenterinsightsV1DeployIssueModelMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation property :create_time, as: 'createTime' property :end_time, as: 'endTime' property :request, as: 'request', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1DeployIssueModelRequest, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1DeployIssueModelRequest::Representation end end class GoogleCloudContactcenterinsightsV1DeployIssueModelRequest # @private class Representation < Google::Apis::Core::JsonRepresentation property :name, as: 'name' end end class GoogleCloudContactcenterinsightsV1DeployIssueModelResponse # @private class Representation < Google::Apis::Core::JsonRepresentation end end class GoogleCloudContactcenterinsightsV1DialogflowIntent # @private class Representation < Google::Apis::Core::JsonRepresentation property :display_name, as: 'displayName' end end class GoogleCloudContactcenterinsightsV1DialogflowInteractionData # @private class Representation < Google::Apis::Core::JsonRepresentation property :confidence, as: 'confidence' property :dialogflow_intent_id, as: 'dialogflowIntentId' end end class GoogleCloudContactcenterinsightsV1DialogflowSource # @private class Representation < Google::Apis::Core::JsonRepresentation property :audio_uri, as: 'audioUri' property :dialogflow_conversation, as: 'dialogflowConversation' end end class GoogleCloudContactcenterinsightsV1Entity # @private class Representation < Google::Apis::Core::JsonRepresentation property :display_name, as: 'displayName' hash :metadata, as: 'metadata' property :salience, as: 'salience' property :sentiment, as: 'sentiment', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1SentimentData, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1SentimentData::Representation property :type, as: 'type' end end class GoogleCloudContactcenterinsightsV1EntityMentionData # @private class Representation < Google::Apis::Core::JsonRepresentation property :entity_unique_id, as: 'entityUniqueId' property :sentiment, as: 'sentiment', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1SentimentData, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1SentimentData::Representation property :type, as: 'type' end end class GoogleCloudContactcenterinsightsV1ExactMatchConfig # @private class Representation < Google::Apis::Core::JsonRepresentation property :case_sensitive, as: 'caseSensitive' end end class GoogleCloudContactcenterinsightsV1ExportInsightsDataMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation property :create_time, as: 'createTime' property :end_time, as: 'endTime' collection :partial_errors, as: 'partialErrors', class: Google::Apis::ContactcenterinsightsV1::GoogleRpcStatus, decorator: Google::Apis::ContactcenterinsightsV1::GoogleRpcStatus::Representation property :request, as: 'request', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ExportInsightsDataRequest, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ExportInsightsDataRequest::Representation end end class GoogleCloudContactcenterinsightsV1ExportInsightsDataRequest # @private class Representation < Google::Apis::Core::JsonRepresentation property :big_query_destination, as: 'bigQueryDestination', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ExportInsightsDataRequestBigQueryDestination, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ExportInsightsDataRequestBigQueryDestination::Representation property :filter, as: 'filter' property :kms_key, as: 'kmsKey' property :parent, as: 'parent' end end class GoogleCloudContactcenterinsightsV1ExportInsightsDataRequestBigQueryDestination # @private class Representation < Google::Apis::Core::JsonRepresentation property :dataset, as: 'dataset' property :project_id, as: 'projectId' property :table, as: 'table' end end class GoogleCloudContactcenterinsightsV1ExportInsightsDataResponse # @private class Representation < Google::Apis::Core::JsonRepresentation end end class GoogleCloudContactcenterinsightsV1FaqAnswerData # @private class Representation < Google::Apis::Core::JsonRepresentation property :answer, as: 'answer' property :confidence_score, as: 'confidenceScore' hash :metadata, as: 'metadata' property :query_record, as: 'queryRecord' property :question, as: 'question' property :source, as: 'source' end end class GoogleCloudContactcenterinsightsV1GcsSource # @private class Representation < Google::Apis::Core::JsonRepresentation property :audio_uri, as: 'audioUri' property :transcript_uri, as: 'transcriptUri' end end class GoogleCloudContactcenterinsightsV1HoldData # @private class Representation < Google::Apis::Core::JsonRepresentation end end class GoogleCloudContactcenterinsightsV1Intent # @private class Representation < Google::Apis::Core::JsonRepresentation property :display_name, as: 'displayName' property :id, as: 'id' end end class GoogleCloudContactcenterinsightsV1IntentMatchData # @private class Representation < Google::Apis::Core::JsonRepresentation property :intent_unique_id, as: 'intentUniqueId' end end class GoogleCloudContactcenterinsightsV1InterruptionData # @private class Representation < Google::Apis::Core::JsonRepresentation end end class GoogleCloudContactcenterinsightsV1Issue # @private class Representation < Google::Apis::Core::JsonRepresentation property :create_time, as: 'createTime' property :display_name, as: 'displayName' property :name, as: 'name' property :update_time, as: 'updateTime' end end class GoogleCloudContactcenterinsightsV1IssueAssignment # @private class Representation < Google::Apis::Core::JsonRepresentation property :display_name, as: 'displayName' property :issue, as: 'issue' property :score, as: 'score' end end class GoogleCloudContactcenterinsightsV1IssueModel # @private class Representation < Google::Apis::Core::JsonRepresentation property :create_time, as: 'createTime' property :display_name, as: 'displayName' property :input_data_config, as: 'inputDataConfig', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1IssueModelInputDataConfig, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1IssueModelInputDataConfig::Representation property :name, as: 'name' property :state, as: 'state' property :training_stats, as: 'trainingStats', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1IssueModelLabelStats, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1IssueModelLabelStats::Representation property :update_time, as: 'updateTime' end end class GoogleCloudContactcenterinsightsV1IssueModelInputDataConfig # @private class Representation < Google::Apis::Core::JsonRepresentation property :filter, as: 'filter' property :medium, as: 'medium' property :training_conversations_count, :numeric_string => true, as: 'trainingConversationsCount' end end class GoogleCloudContactcenterinsightsV1IssueModelLabelStats # @private class Representation < Google::Apis::Core::JsonRepresentation property :analyzed_conversations_count, :numeric_string => true, as: 'analyzedConversationsCount' hash :issue_stats, as: 'issueStats', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1IssueModelLabelStatsIssueStats, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1IssueModelLabelStatsIssueStats::Representation property :unclassified_conversations_count, :numeric_string => true, as: 'unclassifiedConversationsCount' end end class GoogleCloudContactcenterinsightsV1IssueModelLabelStatsIssueStats # @private class Representation < Google::Apis::Core::JsonRepresentation property :issue, as: 'issue' property :labeled_conversations_count, :numeric_string => true, as: 'labeledConversationsCount' end end class GoogleCloudContactcenterinsightsV1IssueModelResult # @private class Representation < Google::Apis::Core::JsonRepresentation property :issue_model, as: 'issueModel' collection :issues, as: 'issues', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1IssueAssignment, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1IssueAssignment::Representation end end class GoogleCloudContactcenterinsightsV1ListAnalysesResponse # @private class Representation < Google::Apis::Core::JsonRepresentation collection :analyses, as: 'analyses', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1Analysis, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1Analysis::Representation property :next_page_token, as: 'nextPageToken' end end class GoogleCloudContactcenterinsightsV1ListConversationsResponse # @private class Representation < Google::Apis::Core::JsonRepresentation collection :conversations, as: 'conversations', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1Conversation, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1Conversation::Representation property :next_page_token, as: 'nextPageToken' end end class GoogleCloudContactcenterinsightsV1ListIssueModelsResponse # @private class Representation < Google::Apis::Core::JsonRepresentation collection :issue_models, as: 'issueModels', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1IssueModel, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1IssueModel::Representation end end class GoogleCloudContactcenterinsightsV1ListIssuesResponse # @private class Representation < Google::Apis::Core::JsonRepresentation collection :issues, as: 'issues', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1Issue, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1Issue::Representation end end class GoogleCloudContactcenterinsightsV1ListPhraseMatchersResponse # @private class Representation < Google::Apis::Core::JsonRepresentation property :next_page_token, as: 'nextPageToken' collection :phrase_matchers, as: 'phraseMatchers', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1PhraseMatcher, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1PhraseMatcher::Representation end end class GoogleCloudContactcenterinsightsV1PhraseMatchData # @private class Representation < Google::Apis::Core::JsonRepresentation property :display_name, as: 'displayName' property :phrase_matcher, as: 'phraseMatcher' end end class GoogleCloudContactcenterinsightsV1PhraseMatchRule # @private class Representation < Google::Apis::Core::JsonRepresentation property :config, as: 'config', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1PhraseMatchRuleConfig, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1PhraseMatchRuleConfig::Representation property :negated, as: 'negated' property :query, as: 'query' end end class GoogleCloudContactcenterinsightsV1PhraseMatchRuleConfig # @private class Representation < Google::Apis::Core::JsonRepresentation property :exact_match_config, as: 'exactMatchConfig', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ExactMatchConfig, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ExactMatchConfig::Representation end end class GoogleCloudContactcenterinsightsV1PhraseMatchRuleGroup # @private class Representation < Google::Apis::Core::JsonRepresentation collection :phrase_match_rules, as: 'phraseMatchRules', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1PhraseMatchRule, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1PhraseMatchRule::Representation property :type, as: 'type' end end class GoogleCloudContactcenterinsightsV1PhraseMatcher # @private class Representation < Google::Apis::Core::JsonRepresentation property :activation_update_time, as: 'activationUpdateTime' property :active, as: 'active' property :display_name, as: 'displayName' property :name, as: 'name' collection :phrase_match_rule_groups, as: 'phraseMatchRuleGroups', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1PhraseMatchRuleGroup, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1PhraseMatchRuleGroup::Representation property :revision_create_time, as: 'revisionCreateTime' property :revision_id, as: 'revisionId' property :role_match, as: 'roleMatch' property :type, as: 'type' property :update_time, as: 'updateTime' property :version_tag, as: 'versionTag' end end class GoogleCloudContactcenterinsightsV1RuntimeAnnotation # @private class Representation < Google::Apis::Core::JsonRepresentation property :annotation_id, as: 'annotationId' property :answer_feedback, as: 'answerFeedback', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1AnswerFeedback, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1AnswerFeedback::Representation property :article_suggestion, as: 'articleSuggestion', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ArticleSuggestionData, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1ArticleSuggestionData::Representation property :create_time, as: 'createTime' property :dialogflow_interaction, as: 'dialogflowInteraction', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1DialogflowInteractionData, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1DialogflowInteractionData::Representation property :end_boundary, as: 'endBoundary', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1AnnotationBoundary, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1AnnotationBoundary::Representation property :faq_answer, as: 'faqAnswer', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1FaqAnswerData, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1FaqAnswerData::Representation property :smart_compose_suggestion, as: 'smartComposeSuggestion', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1SmartComposeSuggestionData, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1SmartComposeSuggestionData::Representation property :smart_reply, as: 'smartReply', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1SmartReplyData, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1SmartReplyData::Representation property :start_boundary, as: 'startBoundary', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1AnnotationBoundary, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1AnnotationBoundary::Representation end end class GoogleCloudContactcenterinsightsV1SentimentData # @private class Representation < Google::Apis::Core::JsonRepresentation property :magnitude, as: 'magnitude' property :score, as: 'score' end end class GoogleCloudContactcenterinsightsV1Settings # @private class Representation < Google::Apis::Core::JsonRepresentation property :analysis_config, as: 'analysisConfig', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1SettingsAnalysisConfig, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1SettingsAnalysisConfig::Representation property :conversation_ttl, as: 'conversationTtl' property :create_time, as: 'createTime' property :language_code, as: 'languageCode' property :name, as: 'name' hash :pubsub_notification_settings, as: 'pubsubNotificationSettings' property :update_time, as: 'updateTime' end end class GoogleCloudContactcenterinsightsV1SettingsAnalysisConfig # @private class Representation < Google::Apis::Core::JsonRepresentation property :runtime_integration_analysis_percentage, as: 'runtimeIntegrationAnalysisPercentage' end end class GoogleCloudContactcenterinsightsV1SilenceData # @private class Representation < Google::Apis::Core::JsonRepresentation end end class GoogleCloudContactcenterinsightsV1SmartComposeSuggestionData # @private class Representation < Google::Apis::Core::JsonRepresentation property :confidence_score, as: 'confidenceScore' hash :metadata, as: 'metadata' property :query_record, as: 'queryRecord' property :suggestion, as: 'suggestion' end end class GoogleCloudContactcenterinsightsV1SmartReplyData # @private class Representation < Google::Apis::Core::JsonRepresentation property :confidence_score, as: 'confidenceScore' hash :metadata, as: 'metadata' property :query_record, as: 'queryRecord' property :reply, as: 'reply' end end class GoogleCloudContactcenterinsightsV1UndeployIssueModelMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation property :create_time, as: 'createTime' property :end_time, as: 'endTime' property :request, as: 'request', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1UndeployIssueModelRequest, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1UndeployIssueModelRequest::Representation end end class GoogleCloudContactcenterinsightsV1UndeployIssueModelRequest # @private class Representation < Google::Apis::Core::JsonRepresentation property :name, as: 'name' end end class GoogleCloudContactcenterinsightsV1UndeployIssueModelResponse # @private class Representation < Google::Apis::Core::JsonRepresentation end end class GoogleCloudContactcenterinsightsV1alpha1CreateAnalysisOperationMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation property :conversation, as: 'conversation' property :create_time, as: 'createTime' property :end_time, as: 'endTime' end end class GoogleCloudContactcenterinsightsV1alpha1CreateIssueModelMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation property :create_time, as: 'createTime' property :end_time, as: 'endTime' property :request, as: 'request', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1CreateIssueModelRequest, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1CreateIssueModelRequest::Representation end end class GoogleCloudContactcenterinsightsV1alpha1CreateIssueModelRequest # @private class Representation < Google::Apis::Core::JsonRepresentation property :issue_model, as: 'issueModel', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1IssueModel, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1IssueModel::Representation property :parent, as: 'parent' end end class GoogleCloudContactcenterinsightsV1alpha1DeleteIssueModelMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation property :create_time, as: 'createTime' property :end_time, as: 'endTime' property :request, as: 'request', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1DeleteIssueModelRequest, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1DeleteIssueModelRequest::Representation end end class GoogleCloudContactcenterinsightsV1alpha1DeleteIssueModelRequest # @private class Representation < Google::Apis::Core::JsonRepresentation property :name, as: 'name' end end class GoogleCloudContactcenterinsightsV1alpha1DeployIssueModelMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation property :create_time, as: 'createTime' property :end_time, as: 'endTime' property :request, as: 'request', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1DeployIssueModelRequest, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1DeployIssueModelRequest::Representation end end class GoogleCloudContactcenterinsightsV1alpha1DeployIssueModelRequest # @private class Representation < Google::Apis::Core::JsonRepresentation property :name, as: 'name' end end class GoogleCloudContactcenterinsightsV1alpha1DeployIssueModelResponse # @private class Representation < Google::Apis::Core::JsonRepresentation end end class GoogleCloudContactcenterinsightsV1alpha1ExportInsightsDataMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation property :create_time, as: 'createTime' property :end_time, as: 'endTime' collection :partial_errors, as: 'partialErrors', class: Google::Apis::ContactcenterinsightsV1::GoogleRpcStatus, decorator: Google::Apis::ContactcenterinsightsV1::GoogleRpcStatus::Representation property :request, as: 'request', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1ExportInsightsDataRequest, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1ExportInsightsDataRequest::Representation end end class GoogleCloudContactcenterinsightsV1alpha1ExportInsightsDataRequest # @private class Representation < Google::Apis::Core::JsonRepresentation property :big_query_destination, as: 'bigQueryDestination', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1ExportInsightsDataRequestBigQueryDestination, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1ExportInsightsDataRequestBigQueryDestination::Representation property :filter, as: 'filter' property :kms_key, as: 'kmsKey' property :parent, as: 'parent' end end class GoogleCloudContactcenterinsightsV1alpha1ExportInsightsDataRequestBigQueryDestination # @private class Representation < Google::Apis::Core::JsonRepresentation property :dataset, as: 'dataset' property :project_id, as: 'projectId' property :table, as: 'table' end end class GoogleCloudContactcenterinsightsV1alpha1ExportInsightsDataResponse # @private class Representation < Google::Apis::Core::JsonRepresentation end end class GoogleCloudContactcenterinsightsV1alpha1IssueModel # @private class Representation < Google::Apis::Core::JsonRepresentation property :create_time, as: 'createTime' property :display_name, as: 'displayName' property :input_data_config, as: 'inputDataConfig', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1IssueModelInputDataConfig, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1IssueModelInputDataConfig::Representation property :name, as: 'name' property :state, as: 'state' property :training_stats, as: 'trainingStats', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1IssueModelLabelStats, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1IssueModelLabelStats::Representation property :update_time, as: 'updateTime' end end class GoogleCloudContactcenterinsightsV1alpha1IssueModelInputDataConfig # @private class Representation < Google::Apis::Core::JsonRepresentation property :filter, as: 'filter' property :medium, as: 'medium' property :training_conversations_count, :numeric_string => true, as: 'trainingConversationsCount' end end class GoogleCloudContactcenterinsightsV1alpha1IssueModelLabelStats # @private class Representation < Google::Apis::Core::JsonRepresentation property :analyzed_conversations_count, :numeric_string => true, as: 'analyzedConversationsCount' hash :issue_stats, as: 'issueStats', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1IssueModelLabelStatsIssueStats, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1IssueModelLabelStatsIssueStats::Representation property :unclassified_conversations_count, :numeric_string => true, as: 'unclassifiedConversationsCount' end end class GoogleCloudContactcenterinsightsV1alpha1IssueModelLabelStatsIssueStats # @private class Representation < Google::Apis::Core::JsonRepresentation property :issue, as: 'issue' property :labeled_conversations_count, :numeric_string => true, as: 'labeledConversationsCount' end end class GoogleCloudContactcenterinsightsV1alpha1UndeployIssueModelMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation property :create_time, as: 'createTime' property :end_time, as: 'endTime' property :request, as: 'request', class: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1UndeployIssueModelRequest, decorator: Google::Apis::ContactcenterinsightsV1::GoogleCloudContactcenterinsightsV1alpha1UndeployIssueModelRequest::Representation end end class GoogleCloudContactcenterinsightsV1alpha1UndeployIssueModelRequest # @private class Representation < Google::Apis::Core::JsonRepresentation property :name, as: 'name' end end class GoogleCloudContactcenterinsightsV1alpha1UndeployIssueModelResponse # @private class Representation < Google::Apis::Core::JsonRepresentation end end class GoogleLongrunningListOperationsResponse # @private class Representation < Google::Apis::Core::JsonRepresentation property :next_page_token, as: 'nextPageToken' collection :operations, as: 'operations', class: Google::Apis::ContactcenterinsightsV1::GoogleLongrunningOperation, decorator: Google::Apis::ContactcenterinsightsV1::GoogleLongrunningOperation::Representation end end class GoogleLongrunningOperation # @private class Representation < Google::Apis::Core::JsonRepresentation property :done, as: 'done' property :error, as: 'error', class: Google::Apis::ContactcenterinsightsV1::GoogleRpcStatus, decorator: Google::Apis::ContactcenterinsightsV1::GoogleRpcStatus::Representation hash :metadata, as: 'metadata' property :name, as: 'name' hash :response, as: 'response' end end class GoogleProtobufEmpty # @private class Representation < Google::Apis::Core::JsonRepresentation end end class GoogleRpcStatus # @private class Representation < Google::Apis::Core::JsonRepresentation property :code, as: 'code' collection :details, as: 'details' property :message, as: 'message' end end end end end
47.533686
392
0.723619
61bfe963c17fcb36f1c06cba3a22ffaf85287589
2,320
class MainCharacter < Character def initialize(map, options) super(map, options) @max_speed = MAX_SPEED @color = Gosu::Color::RED end def handle_collisions_with_enemies! @map.enemies.each do |enemy| handle_collision_with_enemy!(enemy, rebound_speed: 10) end end def handle_collision_with_enemy!(enemy, options={}) if collision?(enemy) came_from_up = previous_y1 >= enemy.previous_y2 came_from_down = previous_y2 <= enemy.previous_y1 came_from_right = previous_x1 >= enemy.previous_x2 came_from_left = previous_x2 <= enemy.previous_x1 rebound_speed = options[:rebound_speed] || 0 if came_from_up if can_move_out_of?(enemy, :up) move_out_of!(enemy, :up) elsif enemy.can_move_out_of?(self, :down) enemy.move_out_of!(self, :down) end @velocity_y = 0 @nb_jumps = 0 jump! stop_jump! enemy.die! end if came_from_down if can_move_out_of?(enemy, :down) move_out_of!(enemy, :down) elsif enemy.can_move_out_of?(self, :up) enemy.move_out_of!(self, :up) enemy.velocity_y = rebound_speed end @velocity_y = 0 die! end if came_from_right if can_move_out_of?(enemy, :right) move_out_of!(enemy, :right) elsif enemy.can_move_out_of?(self, :left) enemy.move_out_of!(self, :left) enemy.velocity_x = -rebound_speed end @velocity_x = rebound_speed die! end if came_from_left if can_move_out_of?(enemy, :left) move_out_of!(enemy, :left) elsif enemy.can_move_out_of?(self, :right) enemy.move_out_of!(self, :right) enemy.velocity_x = rebound_speed end @velocity_x = -rebound_speed die! end end end def move! super handle_collisions_with_enemies! draw_string(@life) end def die! super if @dead @map.reset end end def draw(window) super(window) draw_string("Life: " + @life.to_s) end def draw_string(str) @map.window.font.draw(str, 10, 10, -10000) end end
23.917526
63
0.581897
ff4cc216f2620458714c8495c7a56f85074640af
842
class Poll < ApplicationRecord belongs_to :user has_many :poll_options has_many :votes, through: :poll_options validates :poll_options, presence: true, length: { minimum: 2, too_short: "(minimum is 2)"} validates_presence_of :user_id, :question def poll_options=(poll_options) poll_options.reject(&:blank?).each do |option| self.poll_options.build(option: option) end end def results poll_options.map do |poll_option| [poll_option.option, poll_option.votes.count] end end def expired? self.expires_at < Time.now end def self.expired where "expires_at < ?", Time.now end def self.active where "expires_at >= ?", Time.now end def self.most_popular where("1 = 1").order('vote_count DESC') end def next poll = Poll.where("id > ?", id).first if poll poll else Poll.first end end end
17.914894
92
0.709026
919b0f09267f81f0c6bebffdf9d49bcabab41d35
687
# frozen_string_literal: true class DashboardController < ApplicationController before_action :get_dashboard_data protected def get_dashboard_data @user = User.find params[:user_id] authorize! :read, @user @events = @user.personas.includes(:events).map { |p| p.events.next_three_months }.flatten @awards = @user.personas.includes(:received_awards).map(&:received_awards).flatten.sort_by(&:received) @auths = @user.authorizations.includes(:authorization_type).sort { |a, b| a.authorization_type.martial_activity_type_id <=> b.authorization_type.martial_activity_type_id } @warrants = @user.warrants.includes(:warrant_type).order(:tenure_start) end end
38.166667
175
0.764192
628bb5a4aeac13615cad26bc6f0f06f935e7f71c
521
module Sipity module Controllers module WorkAreas module Ulra # Responsible for rendering a given work within the context of the Dashboard. # # @note This could be extracted outside of this namespace class WorkPresenter < Sipity::Controllers::WorkAreas::WorkPresenter presents :work def award_category repository.work_attribute_values_for(work: work, key: 'award_category', cardinality: 1) end end end end end end
27.421053
99
0.650672
393f072563bfdc80ce0148f1242ff884bdb75acd
534
require File.expand_path('../../../spec_helper', __FILE__) describe "Integer" do it "includes Comparable" do Integer.include?(Comparable).should == true end ruby_version_is "2.4" do it "is the class of both small and large integers" do 42.class.should equal(Integer) bignum_value.class.should equal(Integer) end end end describe "Integer#integer?" do it "returns true for Integers" do 0.integer?.should == true -1.integer?.should == true bignum_value.integer?.should == true end end
23.217391
58
0.687266
1d92d996acfd455b0431486ac75b36776231d4d7
8,936
require 'test_helper' class CreditCardTest < Test::Unit::TestCase def setup CreditCard.require_verification_value = false @visa = credit_card("4779139500118580", :type => "visa") @solo = credit_card("676700000000000000", :type => "solo", :issue_number => '01') end def teardown CreditCard.require_verification_value = false end def test_constructor_should_properly_assign_values c = credit_card assert_equal "4242424242424242", c.number assert_equal 9, c.month assert_equal Time.now.year + 1, c.year assert_equal "Longbob Longsen", c.name assert_equal "visa", c.type assert_valid c end def test_new_credit_card_should_not_be_valid c = CreditCard.new assert_not_valid c assert_false c.errors.empty? end def test_should_be_a_valid_visa_card assert_valid @visa assert @visa.errors.empty? end def test_should_be_a_valid_solo_card assert_valid @solo assert @solo.errors.empty? end def test_cards_with_empty_names_should_not_be_valid @visa.first_name = '' @visa.last_name = '' assert_not_valid @visa assert_false @visa.errors.empty? end def test_should_be_able_to_access_errors_indifferently @visa.first_name = '' assert_not_valid @visa assert @visa.errors.on(:first_name) assert @visa.errors.on("first_name") end def test_should_be_able_to_liberate_a_bogus_card c = credit_card('', :type => 'bogus') assert_valid c c.type = 'visa' assert_not_valid c end def test_should_be_able_to_identify_invalid_card_numbers @visa.number = nil assert_not_valid @visa @visa.number = "11112222333344ff" assert_not_valid @visa assert_false @visa.errors.on(:type) assert @visa.errors.on(:number) @visa.number = "111122223333444" assert_not_valid @visa assert_false @visa.errors.on(:type) assert @visa.errors.on(:number) @visa.number = "11112222333344444" assert_not_valid @visa assert_false @visa.errors.on(:type) assert @visa.errors.on(:number) end def test_should_have_errors_with_invalid_card_type_for_otherwise_correct_number @visa.type = 'master' assert_not_valid @visa assert_not_equal @visa.errors.on(:number), @visa.errors.on(:type) end def test_should_be_invalid_when_type_cannot_be_detected @visa.number = nil @visa.type = nil assert_not_valid @visa assert_match /is required/, @visa.errors.on(:type) assert @visa.errors.on(:type) end def test_should_be_a_valid_card_number @visa.number = "4242424242424242" assert_valid @visa end def test_should_require_a_valid_card_month @visa.month = Time.now.utc.month @visa.year = Time.now.utc.year assert_valid @visa end def test_should_not_be_valid_with_empty_month @visa.month = '' assert_not_valid @visa assert @visa.errors.on('month') end def test_should_not_be_valid_for_edge_month_cases @visa.month = 13 @visa.year = Time.now.year assert_not_valid @visa assert @visa.errors.on('month') @visa.month = 0 @visa.year = Time.now.year assert_not_valid @visa assert @visa.errors.on('month') end def test_should_be_invalid_with_empty_year @visa.year = '' assert_not_valid @visa assert @visa.errors.on('year') end def test_should_not_be_valid_for_edge_year_cases @visa.year = Time.now.year - 1 assert_not_valid @visa assert @visa.errors.on('year') @visa.year = Time.now.year + 21 assert_not_valid @visa assert @visa.errors.on('year') end def test_should_be_a_valid_future_year @visa.year = Time.now.year + 1 assert_valid @visa end def test_should_be_valid_with_start_month_and_year_as_string @solo.start_month = '2' @solo.start_year = '2007' assert_valid @solo end def test_should_identify_wrong_cardtype c = credit_card(:type => 'master') assert_not_valid c end def test_should_display_number assert_equal 'XXXX-XXXX-XXXX-1234', CreditCard.new(:number => '1111222233331234').display_number assert_equal 'XXXX-XXXX-XXXX-1234', CreditCard.new(:number => '111222233331234').display_number assert_equal 'XXXX-XXXX-XXXX-1234', CreditCard.new(:number => '1112223331234').display_number assert_equal 'XXXX-XXXX-XXXX-', CreditCard.new(:number => nil).display_number assert_equal 'XXXX-XXXX-XXXX-', CreditCard.new(:number => '').display_number assert_equal 'XXXX-XXXX-XXXX-123', CreditCard.new(:number => '123').display_number assert_equal 'XXXX-XXXX-XXXX-1234', CreditCard.new(:number => '1234').display_number assert_equal 'XXXX-XXXX-XXXX-1234', CreditCard.new(:number => '01234').display_number end def test_should_correctly_identify_card_type assert_equal 'visa', CreditCard.type?('4242424242424242') assert_equal 'american_express', CreditCard.type?('341111111111111') assert_nil CreditCard.type?('') end def test_should_be_able_to_require_a_verification_value CreditCard.require_verification_value = true assert CreditCard.requires_verification_value? end def test_should_not_be_valid_when_requiring_a_verification_value CreditCard.require_verification_value = true card = credit_card('4242424242424242', :verification_value => nil) assert_not_valid card card.verification_value = '123' assert_valid card end def test_should_require_valid_start_date_for_solo_or_switch @solo.start_month = nil @solo.start_year = nil @solo.issue_number = nil assert_not_valid @solo assert @solo.errors.on('start_month') assert @solo.errors.on('start_year') assert @solo.errors.on('issue_number') @solo.start_month = 2 @solo.start_year = 2007 assert_valid @solo end def test_should_require_a_valid_issue_number_for_solo_or_switch @solo.start_month = nil @solo.start_year = 2005 @solo.issue_number = nil assert_not_valid @solo assert @solo.errors.on('start_month') assert @solo.errors.on('issue_number') @solo.issue_number = 3 assert_valid @solo end def test_should_return_last_four_digits_of_card_number ccn = CreditCard.new(:number => "4779139500118580") assert_equal "8580", ccn.last_digits end def test_bogus_last_digits ccn = CreditCard.new(:number => "1") assert_equal "1", ccn.last_digits end def test_should_be_true_when_credit_card_has_a_first_name c = CreditCard.new assert_false c.first_name? c = CreditCard.new(:first_name => 'James') assert c.first_name? end def test_should_be_true_when_credit_card_has_a_last_name c = CreditCard.new assert_false c.last_name? c = CreditCard.new(:last_name => 'Herdman') assert c.last_name? end def test_should_test_for_a_full_name c = CreditCard.new assert_false c.name? c = CreditCard.new(:first_name => 'James', :last_name => 'Herdman') assert c.name? end # The following is a regression for a bug that raised an exception when # a new credit card was validated def test_validate_new_card credit_card = CreditCard.new assert_nothing_raised do credit_card.validate end end # The following is a regression for a bug where the keys of the # credit card card_companies hash were not duped when detecting the type def test_create_and_validate_credit_card_from_type credit_card = CreditCard.new(:type => CreditCard.type?('4242424242424242')) assert_nothing_raised do credit_card.valid? end end def test_autodetection_of_credit_card_type credit_card = CreditCard.new(:number => '4242424242424242') credit_card.valid? assert_equal 'visa', credit_card.type end def test_card_type_should_not_be_autodetected_when_provided credit_card = CreditCard.new(:number => '4242424242424242', :type => 'master') credit_card.valid? assert_equal 'master', credit_card.type end def test_detecting_bogus_card credit_card = CreditCard.new(:number => '1') credit_card.valid? assert_equal 'bogus', credit_card.type end def test_validating_bogus_card credit_card = credit_card('1', :type => nil) assert credit_card.valid? end def test_mask_number assert_equal 'XXXX-XXXX-XXXX-5100', CreditCard.mask('5105105105105100') end def test_strip_non_digit_characters card = credit_card('4242-4242 %%%%%%4242......4242') assert card.valid? assert_equal "4242424242424242", card.number end def test_before_validate_handles_blank_number card = credit_card(nil) assert !card.valid? assert_equal "", card.number end def test_type_is_aliased_as_brand assert_equal @visa.type, @visa.brand assert_equal @solo.type, @solo.brand end end
27.580247
100
0.714302
bf8bee6f7ea3893afdbfd066d9cfeaa3ddb6ce3d
259
class CreateExportsTable < ActiveRecord::Migration[5.1] def change create_table :exports do |t| t.string :export_type, null: false t.integer :exported_by_id, null: false, index: true t.string :file t.timestamps end end end
23.545455
57
0.675676
ac26adee8ccc3c484345c3ac90c334a361a3375c
920
# Settings specified here will take precedence over those in config/environment.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and caching is turned off, but ResponseCache caching is on config.action_controller.consider_all_requests_local = true config.action_view.debug_rjs = true config.action_controller.perform_caching = false config.action_view.cache_template_extensions = false ResponseCache.defaults[:perform_caching] = false # Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false
46
84
0.76087
2848169353574aafc7490086495b122c832071d6
1,227
require File.dirname(__FILE__) + '/spec_helper' describe XsdReader do let(:reader){ XsdReader::XML.new(:xsd_file => File.expand_path(File.join(File.dirname(__FILE__), 'examples', 'ddex-v36', 'ddex-ern-v36.xsd'))) } let(:mlc_reader){ XsdReader::XML.new(:xsd_file => File.expand_path(File.join(File.dirname(__FILE__), 'examples', 'ddex-mlc', 'music-licensing-companies.xsd'))) } describe XsdReader::XML do it "gives a schema_node" do expect(reader.schema_node.name).to eq 'schema' expect(reader.schema_node.namespaces).to eq({"xmlns:xs"=>"http://www.w3.org/2001/XMLSchema", "xmlns:ern"=>"http://ddex.net/xml/ern/36", "xmlns:avs"=>"http://ddex.net/xml/avs/avs"}) end it "gives a schema reader" do expect(reader.schema.class).to eq XsdReader::Schema end it "reads referenced schemas which bind the xmlschema namespace to the root namespace instead of xs" do expect(mlc_reader['DeclarationOfSoundRecordingRightsClaimMessage'].elements.first.name).to eq 'MessageHeader' end it "gives an elements shortcut to its schema's shortcuts" do expect(reader.elements.map(&:name)).to eq reader.schema.elements.map(&:name) end end end # describe XsdReader
39.580645
186
0.705786
28faa5fb5fe3dd1f8137bd5ac0730314a3adeb20
933
# # Be sure to run `pod lib lint PALVersionCheck.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'PALVersionCheck' s.version = '0.1.0' s.summary = 'PALVersionCheck' s.description = <<-DESC This is My lib AppStore App Version Check DESC s.homepage = 'https://github.com/pikachu987/PALVersionCheck' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'pikachu987' => '[email protected]' } s.source = { :git => 'https://github.com/pikachu987/PALVersionCheck.git', :tag => s.version.to_s } s.ios.deployment_target = '9.0' s.source_files = 'PALVersionCheck/Classes/**/*' s.swift_version = '5.0' end
37.32
110
0.622722
d5da8aeffb25e8f78f570d05959a84593f4ac9a6
3,707
require 'spec_helper' describe 'users_test::default' do let(:stat) { double('stat') } let(:stat_nfs) { double('stat_nfs') } before do allow(stat).to receive(:run_command).and_return(stat) allow(stat).to receive(:stdout).and_return('none') allow(stat_nfs).to receive(:run_command).and_return(stat_nfs) allow(stat_nfs).to receive(:stdout).and_return('nfs') allow(Mixlib::ShellOut).to receive(:new).with('stat -f -L -c %T /home/user_with_local_home 2>&1').and_return(stat) allow(Mixlib::ShellOut).to receive(:new).with('stat -f -L -c %T /home/user_with_nfs_home_first 2>&1').and_return(stat_nfs) allow(Mixlib::ShellOut).to receive(:new).with('stat -f -L -c %T /home/user_with_nfs_home_second 2>&1').and_return(stat_nfs) allow(File).to receive(:exist?).and_call_original allow(File).to receive(:exist?).with('/usr/bin/bash').and_return(true) end cached(:chef_run) do ChefSpec::ServerRunner.new( step_into: %w(users_manage), platform: 'ubuntu', version: '16.04' ) do |_node, server| server.create_data_bag('test_home_dir', 'user_with_dev_null_home' => { id: 'user_with_dev_null_home', groups: ['testgroup'], shell: '/usr/bin/bash', home: '/dev/null', }, 'user_with_nfs_home_first' => { id: 'user_with_nfs_home_first', groups: ['testgroup'], }, 'user_with_nfs_home_second' => { id: 'user_with_nfs_home_second', groups: ['nfsgroup'], }, 'user_with_local_home' => { id: 'user_with_local_home', ssh_keys: ["ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAklOUpkDHrfHY17SbrmTIpNLTGK9Tjom/BWDSU\nGPl+nafzlHDTYW7hdI4yZ5ew18JH4JW9jbhUFrviQzM7xlELEVf4h9lFX5QVkbPppSwg0cda3\nPbv7kOdJ/MTyBlWXFCR+HAo3FXRitBqxiX1nKhXpHAZsMciLq8V6RjsNAQwdsdMFvSlVK/7XA\nt3FaoJoAsncM1Q9x5+3V0Ww68/eIFmb1zuUFljQJKprrX88XypNDvjYNby6vw/Pb0rwert/En\nmZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbx\nNrRFi9wrf+M7Q== [email protected]"], groups: ['testgroup'], }) end.converge(described_recipe) end context 'Resource "users_manage"' do it 'creates users' do expect(chef_run).to create_user('user_with_dev_null_home') expect(chef_run).to create_user('user_with_local_home') expect(chef_run).to create_user('user_with_nfs_home_first') expect(chef_run).to create_user('user_with_nfs_home_second') end it 'creates groups' do expect(chef_run).to create_group('testgroup') expect(chef_run).to create_group('nfsgroup') end it 'not supports managing /dev/null home dir' do expect(chef_run).to create_user('user_with_dev_null_home') .with(manage_home: false) end it 'supports managing local home dir' do expect(chef_run).to create_user('user_with_local_home') .with(manage_home: true) end it 'not tries to manage .ssh dir for user "user_with_dev_null_home"' do expect(chef_run).to_not create_directory('/dev/null') end it 'manages .ssh dir for local user' do expect(chef_run).to create_directory('/home/user_with_local_home/.ssh') end it 'manages nfs home dir if manage_nfs_home_dirs is set to true' do expect(chef_run).to_not create_directory('/home/user_with_nfs_home_first/.ssh') end it 'does not manage nfs home dir if manage_nfs_home_dirs is set to false' do expect(chef_run).to_not create_directory('/home/user_with_nfs_home_second/.ssh') end it 'manages groups' do expect(chef_run).to create_users_manage('testgroup') expect(chef_run).to create_users_manage('nfsgroup') end end end
38.614583
439
0.695441
4a0108d6abce94835d612719f58f647c751739fa
310
# frozen_string_literal: true module EE module Deployments module AfterCreateService extend ::Gitlab::Utils::Override override :execute def execute super.tap do |deployment| deployment.project.repository.log_geo_updated_event end end end end end
18.235294
61
0.667742