text
stringlengths
10
2.61M
require_relative '../spec_helper' require_relative '../../helpers/email' require_relative '../../helpers/logger' require_relative '../../helpers/link' describe 'Email Helper' do include Email include MagicLogger include Link attr_reader :settings before(:all) do @owner = User.new( username: 'owner_email_spec_tests_user', password: 'test-password', email: 'owner_email_spec_tests_user@magic-stick.herokuapp.com', name: 'owner_email specuser' ) raise 'failed to save owner' unless @owner.save @season = Season.new( name: 'email_spec_tests', description: 'sweet season', invite_only: true, owner: @owner, starts: Time.now, ends: (Time.now + 10_000) ) @user = User.new( username: 'email_spec_tests_user', password: 'test-password', email: 'email_spec_tests_user@magic-stick.herokuapp.com', name: 'email specuser' ) raise 'failed to save user' unless @user.save @user2 = User.new( username: 'email_spec_tests_user2', password: 'test-password', email: 'email_spec_tests_user2@magic-stick.herokuapp.com', name: 'email specuser2' ) raise 'failed to save user2' unless @user2.save raise 'failed to save season' unless @season.save @comment = SeasonComment.new( season: @season, comment: 'hey, what is up?', user: @owner ) raise 'failed to save comment' unless @comment.save @season.add_member @user @season.add_member @user2 @smg = SeasonMatchGroup.new(season: @season, name: 'another-group') raise 'failed to save smg' unless @smg.save @match = Match.new(season_match_group: @smg, best_of: 3, scheduled_for: Time.now + 3_124, description: 'sweetness') raise 'failed to save match' unless @match.save @match.add_member @user @match.add_member @user2 end before(:each) do @settings = double('settings') clear_deliveries expect(delivery_count).to eq(0) end def expect_settings_check expect(settings).to receive(:development?).and_return(false) expect(settings).to receive(:test?).and_return(true) end context 'can send' do it 'user create' do expect_settings_check email_welcome(@user) expect(delivery_count).to eq(1) expect(deliveries).to include(@user.email) end it 'user create with password' do expect_settings_check email_welcome(@user, password: 'some-pass-secret') expect(delivery_count).to eq(1) expect(deliveries).to include(@user.email) expect(email_deliveries.first.to_s).to include('some-pass-secret') end it 'season member add' do expect_settings_check email_user_added_to_season(@season, @user, @owner) expect(delivery_count).to eq(2) expect(deliveries).to include(@user.email, @season.owner.email) end it 'season member remove' do expect_settings_check email_user_removed_from_season(@season, @user, @owner) expect(delivery_count).to eq(2) expect(deliveries).to include(@user.email, @season.owner.email) end it 'match member add' do expect_settings_check email_user_added_to_match(@match, @user, @owner) expect(delivery_count).to eq(1) expect(deliveries).to include(@user.email) end it 'match member remove' do expect_settings_check email_user_removed_from_match(@match, @user, @owner) expect(delivery_count).to eq(1) expect(deliveries).to include(@user.email) end it 'password reset' do expect_settings_check email_password_reset_link(@user, 'http://some/link') expect(delivery_count).to eq(1) expect(deliveries).to include(@user.email) end it 'password changed' do expect_settings_check email_password_changed(@user) expect(delivery_count).to eq(1) expect(deliveries).to include(@user.email) end it 'season comment' do expect_settings_check email_season_comment(@season, @comment, @comment.user) expect(delivery_count).to eq(3) expect(deliveries).to include(@season.owner.email, @comment.user.email, *@season.members.map(&:email)) end it 'match status updated' do expect_settings_check email_match_status_updated(@match, @user) expect(delivery_count).to eq(2) expect(deliveries).to include(@user.email, @user2.email) end end end
require 'spec_helper' describe PrimeTable do before do @prime_table = PrimeTable.new end describe 'prime_number? method' do it 'returns true for prime number' do expect(@prime_table.prime_number?(5)).to eq true end it 'returns false for non prime numbers' do expect(@prime_table.prime_number?(4)).to eq false expect(@prime_table.prime_number?(1)).to eq false expect(@prime_table.prime_number?(0)).to eq false expect(@prime_table.prime_number?(32)).to eq false end end describe 'prime_multiplicand_array method' do it 'returns appropriate number of rows and columns for multiplicands' do expect(@prime_table.prime_multiplicand_array(5).length).to eq 5 expect(@prime_table.prime_multiplicand_array(25).length).to eq 25 expect(@prime_table.prime_multiplicand_array(200).length).to eq 200 end end describe 'Command Line Output' do it 'should print the exact formatted table' do capture_stdout { @prime_table.display_prime_table(2) }.should eq "\n\n\n PRIME NUMBERS MULTIPLICATION TABLE\n\n\n X 2 3 \n\n 2 | 4 6 \n\n 3 | 6 9 \n\n" capture_stdout { @prime_table.display_prime_table(3) }.should eq "\n\n\n PRIME NUMBERS MULTIPLICATION TABLE\n\n\n X 2 3 5 \n\n 2 | 4 6 10 \n\n 3 | 6 9 15 \n\n 5 | 10 15 25 \n\n" end end end
module Vanilla module Resource # Delegate to a Vanilla::Client # # @return [Vanilla::Client] def client @client ||= Vanilla::Client.new end private def method_missing(method_name, *args, &block) return super unless client.respond_to?(method_name) client.send(method_name, *args, &block) end end end
require 'rails_helper' describe Contact do describe "Validations" do context "invalid attributes" do it "is invalid without a name" do contact = Contact.new(position: "To be filled", email: "no@no.no") expect(contact).to be_invalid end it "is invalid without a position" do contact = Contact.new(name: "To be filled", email: "no@no.no") expect(contact).to be_invalid end it "is invalid without a email" do contact = Contact.new(name: "To be filled", position: "no@no.no") expect(contact).to be_invalid end end context "valid attributes" do it "is valid with all attributes present" do contact = create(:contact) expect(contact).to be_valid end end end describe "Relationships" do it "belongs to a company" do contact = create(:contact) expect(contact).to respond_to(:company) end end end
class ArticleComment < ActiveRecord::Base attr_accessible :article_id, :content, :email, :name, :author_id, :website belongs_to :article belongs_to :author, :class_name => 'User' after_save :after_save after_destroy :after_destroy validates :name, :length => { :maximum => 250, :too_long => "Maximum is %{count} characters" }, :presence => { :message => 'This cannot be blank'} validates :email, :length => { :maximum => 250, :too_long => "Maximum is %{count} characters" }, :presence => { :message => 'This cannot be blank'}, :email_format => { :message => 'This is not valid' } validates :content, :presence => { :message => 'This cannot be blank'} def after_save self.update_counter_cache end def after_destroy self.update_counter_cache end def update_counter_cache self.article.public_comments_count = ArticleComment.count( :conditions => ["is_approved = ? AND article_id = ?", true, self.article_id]) self.article.save end def self.all_for_agent(author_id, offset, limit) self .select('article_comments.*, articles.id as article_id, articles.name as article_name') .joins(:article) .where('articles.author_id = ?', author_id) .order('is_approved ASC, created_at DESC') .offset(offset) .limit(limit) .all end def self.count_by_article_author(user_id) self .select('COUNT(article_comments.id)') .joins(:article) .where('articles.author_id = ?', user_id) .first.count end def self.count_unapproved_by_article_author(user_id) self .select('COUNT(article_comments.id)') .joins(:article) .where('articles.author_id = ? and article_comments.is_approved = ?', user_id, false) .first.count end def self.all_public_for_article(article_id) self .where('article_id = ? AND is_approved = ?', article_id, true) .order('created_at ASC') .all end end
begin require 'ipaddress' rescue => e puts e.message puts e.backtrace.inspect end require_relative '../../puppet_x/bsd' require_relative '../../puppet_x/bsd/puppet_interface' class Rc_conf < PuppetX::BSD::PuppetInterface def initialize(config) validation :name options :desc, :addresses, :options, :raw_values, :mtu integers :mtu multiopts :addresses, :options, :raw_values oneof :name, :desc configure(config) # Ugly junk @name = @config[:name] @desc = @config[:desc] @addresses = [@config[:addresses]].flatten @options = [@config[:options]].flatten @addresses.reject!{ |i| i == nil or i == :undef } @options.reject!{ |i| i == nil or i == :undef } # The blob @data = load_hash() end def options_string result = '' if @options and @options.size > 0 result = @options.join(' ') end result = result.to_s + "mtu #{@config[:mtu]}" if @config.keys.include? :mtu result end def get_hash @data end # Return a hash formatted for the create_resources() function # in puppet see shellvar resource def to_create_resources resources = {} @data.each_key {|topkey| # The top level key is the interface name ifname = topkey.to_sym if @data[topkey][:addrs] if @data[topkey][:addrs].is_a? Array @data[topkey][:addrs].each {|i| if i =~ /inet6 / key = "ifconfig_#{ifname}_ipv6" elsif i =~ /inet / key = "ifconfig_#{ifname}" else key = "ifconfig_#{ifname}" end # Set the value property on the resource resources[key] = { "value" => i, } } else key = "ifconfig_#{ifname}" resources[key] = { "value" => @data[topkey][:addrs], } end end if @data[topkey][:aliases] and @data[topkey][:aliases].is_a? Array @data[topkey][:aliases].each_with_index {|a,i| key = "ifconfig_#{ifname}_alias#{i}" resources[key] = { "value" => a, } } end } Puppet.debug("Returning resources: #{resources}") resources end private # Load the ifconfig has that will contain all addresses (v4 and v6), and # alias addresses. def load_hash ifconfig = {} aliases = [] addrs = [] # Initially, the IP and IP6 has not been set. This helps track whether # we are creating aliases or the first of the addresses. ip6set = false ipset = false process_addresses(@addresses) {|addr| if addr =~ /DHCP/ addrs << addr elsif addr =~ /inet6 / if ip6set aliases << addr else addrs << addr ip6set = true end elsif addr =~ /inet / if ipset aliases << addr else addrs << addr ipset = true end else raise ArgumentError("unhandled address family") end } # append the options to the first address opts = options_string() if addrs.size > 0 ifconfig[:addrs] = addrs if opts and opts.size > 0 ifconfig[:addrs][0] = [ifconfig[:addrs][0],opts].join(' ') end else if opts and opts.size > 0 ifconfig[:addrs] = options_string() end end if aliases.size > 0 ifconfig[:aliases] = aliases end {@name.to_sym => ifconfig} end def process_addresses(addresses) addresses.each {|a| if a =~ /^(DHCP|dhcp)/ yield 'DHCP' else begin ip = IPAddress a if ip.ipv6? value = ['inet6'] value << ip.to_string elsif ip.ipv4? value = ['inet'] value << ip.to_string end if value yield value.join(' ') else raise "Value not found" end rescue Exception => e raise "addr is #{a} of class #{a.class}: #{e.message}" end end } end end
=begin * **************************************************************************** * BRSE-SCHOOL * ADMIN - RegistCourseController * * 処理概要 : * 作成日 : 2017/08/18 * 作成者 : quypn – quypn@ans-asia.com * * 更新日 : * 更新者 : * 更新内容 : * * @package : ADMIN * @copyright : Copyright (c) ANS-ASIA * @version : 1.0.0 * **************************************************************************** =end module Admin class RegistcoursesController < AdminController include ApplicationHelper include RegistcoursesHelper ### # index # ----------------------------------------------- # @author : quypn - 2017/08/18 - create # @param : null # @return : null # @access : public # @see : remark ### def index lang = Helper.getLang @classes = CourseClass.where(lang: lang) @status = Helper.getLibraries(4, lang) notVerify = RegisterCourse.where(deleted_at: nil, status: 0).where("timeout < ?", Time.now).select(:id) notVerify.each do |item| RegistCoursesHlp.delete(item.id, true) end render 'admin/registCourses/index' end ### # search list regist course follow search condition # ----------------------------------------------- # @author : quypn - 2017/08/21 - create # @param : null # @return : null # @access : public # @see : remark ### def search result = Hash.new result['status'] = true begin # try search_result = RegistCoursesHlp.getRegists(params[:search]) if(search_result['status']) lang = Helper.getLang @status = Helper.getLibraries(4, lang) @regists = search_result['data'] result['data'] = render_to_string(partial: "admin/registCourses/list_regist") else result = search_result end rescue # catch result['status'] = false result['error'] = "#{$!}" ensure # finally render json: result end end ### # update status of regist course follow id # ----------------------------------------------- # @author : quypn - 2017/08/21 - create # @param : null # @return : null # @access : public # @see : remark ### def updateStatus result = Hash.new result['status'] = true begin # try result['status'] = RegistCoursesHlp.updateStatus(params[:id],params[:status]) rescue # catch result['status'] = false result['error'] = "#{$!}" ensure # finally # byebug render json: result end end ### # delete a regist course by id # ----------------------------------------------- # @author : quypn - 2017/08/21 - create # @param : null # @return : null # @access : public # @see : remark ### def delete result = Hash.new begin # try result = RegistCoursesHlp.delete(params[:id]) rescue # catch result['status'] = false result['error'] = "#{$!}" ensure # finally render json: result end end end end
class Favorite < ApplicationRecord validates_uniqueness_of :user_id, :scope => :video_id belongs_to :user belongs_to :video end
class RemoveAddress2FromCity < ActiveRecord::Migration def change remove_column :cities, :address_2, :string end end
class DeleteAppUserIdInAppSessions < ActiveRecord::Migration def up AppSession.find_each do |app_session| next if app_session.app_user_id.nil? app_session.update_properties app_user_id: app_session.app_user_id end remove_column :app_sessions, :app_user_id end def down add_column :app_sessions, :app_user_id, :string Property.where(:key => :app_user_id).find_each do |property| property.app_session.update_attributes app_user_id: property.value end end end
class Photo < ApplicationRecord validates_format_of :photo_url, with: URI.regexp(['http', 'https']) validate :one_profile_photo belongs_to :pet def one_profile_photo return if profile_photo == false || self.class.where(pet_id: self.pet_id).where(profile_photo: true).size == 0 errors.add(:pet_id, 'already has a profile photo') end end
class AddPosterToProjects < ActiveRecord::Migration def change add_column :entries, :poster, :string end end
class AddDefaultPriceToTshirt < ActiveRecord::Migration[5.2] def change change_column :tshirts, :price, :float, :default => 10.00 end end
class RemoveColumnFromInventoryItems < ActiveRecord::Migration[6.0] def change remove_column :inventory_items, :is_sellable, :boolean end end
# -*- encoding: utf-8 -*- # stub: hanami 1.2.0 ruby lib Gem::Specification.new do |s| s.name = "hanami" s.version = "1.2.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.metadata = { "allowed_push_host" => "https://rubygems.org" } if s.respond_to? :metadata= s.require_paths = ["lib"] s.authors = ["Luca Guidi"] s.date = "2018-04-11" s.description = "Hanami is a web framework for Ruby" s.email = ["me@lucaguidi.com"] s.executables = ["hanami"] s.files = ["bin/hanami"] s.homepage = "http://hanamirb.org" s.licenses = ["MIT"] s.required_ruby_version = Gem::Requirement.new(">= 2.3.0") s.rubygems_version = "2.5.1" s.summary = "The web, with simplicity" s.installed_by_version = "2.5.1" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<hanami-utils>, ["~> 1.2"]) s.add_runtime_dependency(%q<hanami-validations>, ["~> 1.2"]) s.add_runtime_dependency(%q<hanami-router>, ["~> 1.2"]) s.add_runtime_dependency(%q<hanami-controller>, ["~> 1.2"]) s.add_runtime_dependency(%q<hanami-view>, ["~> 1.2"]) s.add_runtime_dependency(%q<hanami-helpers>, ["~> 1.2"]) s.add_runtime_dependency(%q<hanami-mailer>, ["~> 1.2"]) s.add_runtime_dependency(%q<hanami-assets>, ["~> 1.2"]) s.add_runtime_dependency(%q<hanami-cli>, ["~> 0.2"]) s.add_runtime_dependency(%q<concurrent-ruby>, ["~> 1.0"]) s.add_runtime_dependency(%q<bundler>, [">= 0"]) s.add_development_dependency(%q<rspec>, ["~> 3.7"]) s.add_development_dependency(%q<rack-test>, ["~> 0.6"]) s.add_development_dependency(%q<aruba>, ["~> 0.14"]) s.add_development_dependency(%q<rake>, ["~> 12.0"]) else s.add_dependency(%q<hanami-utils>, ["~> 1.2"]) s.add_dependency(%q<hanami-validations>, ["~> 1.2"]) s.add_dependency(%q<hanami-router>, ["~> 1.2"]) s.add_dependency(%q<hanami-controller>, ["~> 1.2"]) s.add_dependency(%q<hanami-view>, ["~> 1.2"]) s.add_dependency(%q<hanami-helpers>, ["~> 1.2"]) s.add_dependency(%q<hanami-mailer>, ["~> 1.2"]) s.add_dependency(%q<hanami-assets>, ["~> 1.2"]) s.add_dependency(%q<hanami-cli>, ["~> 0.2"]) s.add_dependency(%q<concurrent-ruby>, ["~> 1.0"]) s.add_dependency(%q<bundler>, [">= 0"]) s.add_dependency(%q<rspec>, ["~> 3.7"]) s.add_dependency(%q<rack-test>, ["~> 0.6"]) s.add_dependency(%q<aruba>, ["~> 0.14"]) s.add_dependency(%q<rake>, ["~> 12.0"]) end else s.add_dependency(%q<hanami-utils>, ["~> 1.2"]) s.add_dependency(%q<hanami-validations>, ["~> 1.2"]) s.add_dependency(%q<hanami-router>, ["~> 1.2"]) s.add_dependency(%q<hanami-controller>, ["~> 1.2"]) s.add_dependency(%q<hanami-view>, ["~> 1.2"]) s.add_dependency(%q<hanami-helpers>, ["~> 1.2"]) s.add_dependency(%q<hanami-mailer>, ["~> 1.2"]) s.add_dependency(%q<hanami-assets>, ["~> 1.2"]) s.add_dependency(%q<hanami-cli>, ["~> 0.2"]) s.add_dependency(%q<concurrent-ruby>, ["~> 1.0"]) s.add_dependency(%q<bundler>, [">= 0"]) s.add_dependency(%q<rspec>, ["~> 3.7"]) s.add_dependency(%q<rack-test>, ["~> 0.6"]) s.add_dependency(%q<aruba>, ["~> 0.14"]) s.add_dependency(%q<rake>, ["~> 12.0"]) end end
require 'spec_helper' describe 'balloons/edit' do let(:balloon) { Balloon.create!(name: 'Jorge') } before do assign(:balloon, balloon) render end subject { rendered } it { should match 'Edit Balloon' } specify { expect(view).to render_template(partial: 'balloons/_form') } end
class AddColToTickets < ActiveRecord::Migration[6.0] def change add_column :tickets, :seat_class, :string add_column :tickets, :seat_no, :string end end
require 'spec_helper' describe KeyRedis, type: :model do describe 'KeyRedis#create_key' do it '创建一个key, 同时更新长度' do key_redis = KeyRedis.create _key = key_redis.create_key expect(_key).to eq '000001' key_redis.key_length = 5 _key = key_redis.create_key expect(_key).to eq '00002' key_redis.key_length = 4 _key = key_redis.create_key expect(_key).to eq '0003' end end describe 'KeyRedis.get_key' do it '获取key' do _key_8bit = KeyRedis.get_key(8) expect(_key_8bit).to eq '00000001' _key_8bit = KeyRedis.get_key(8) expect(_key_8bit).to eq '00000002' _key_4bit = KeyRedis.get_key(4) expect(_key_4bit).to eq '0001' _key_4bit = KeyRedis.get_key(4) expect(_key_4bit).to eq '0002' _key_1bit = KeyRedis.get_key(1) expect(_key_1bit).to eq '1' #32位,去除0,去除下面即将取的最后一位,再去除前面key位1生成的值 (32 - 1 - 1 - 1).times {KeyRedis.get_key(1)} _key_1bit = KeyRedis.get_key(1) expect(_key_1bit).to eq 'v' end it 'key结束一轮后,重新从首位开始使用' do keys = [] 31.times{keys << KeyRedis.get_key(1)} _val = (1..9).to_a.map(&:to_s)+('a'..'v').to_a expect(keys).to eq _val keys << KeyRedis.get_key(1) _val << '1' expect(keys).to eq _val end end end
# -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure("2") do |config| config.vm.define "nginx" do |nginx| nginx.vm.hostname = "nginx.example.com" nginx.vm.box = "generic/centos7" nginx.vm.network "forwarded_port", guest: 80, host:8080, host_ip: "127.0.0.1" nginx.vm.network "private_network", ip: "10.10.10.11" nginx.vm.synced_folder ".", "/vagrant", type: "rsync" nginx.vm.provision "shell", inline: <<-SHELL sudo yum install epel-release -y sudo yum install nginx -y sudo systemctl --now enable nginx sudo firewall-cmd --permanent --zone=public --add-service=http sudo firewall-cmd --permanent --zone=public --add-service=https sudo firewall-cmd --reload # Setup DNS client with vagranting-dns ETH0=$(sudo nmcli connection show | grep eth0 | cut -d ' ' -f 4) ETH1=$(sudo nmcli connection show | grep eth1 | cut -d ' ' -f 4) sudo nmcli connection modify $ETH1 ipv4.dns 10.10.10.2 sudo nmcli connection modify $ETH1 ipv4.dns-search example.com sudo nmcli connection modify $ETH1 ipv4.dns-priority 1 sudo nmcli connection modify $ETH0 ipv4.dns-priority 10 sudo nmcli connection up $ETH1 sudo nmcli connection up $ETH0 SHELL nginx.vm.provider "virtualbox" do |vb| vb.cpus = "1" vb.memory = "512" vb.customize ["modifyvm", :id, "--groups", "/vagranting"] #If you have problems with folder exist error -> Comment out this line vb.name = "nginx" end end end
class AddUserIdToProductos < ActiveRecord::Migration def change add_reference :productos, :user, index: true end end
class MoveFreightChargeToOrder < ActiveRecord::Migration def up add_column :orders, :freight_charge, :decimal, precision: 9, scale: 2 remove_column :order_items, :freight_charge end def down add_column :order_items, :freight_charge, :decimal remove_column :orders, :freight_charge end end
class User < ActiveRecord::Base has_many :lists has_many :tasks, through: :lists def self.the_current_user_method recent_user = self.all.sort_by { |user| user.last_log_in }.reverse.first if (Time.now - recent_user.last_log_in)/10000000 > 3600.0 raise "You need to sign someone in, try passing 'sign_in(<name>)'" else @user = recent_user end @user end def self.sign_in(user_name) user = self.find_by_name(user_name) user.last_log_in = Time.now user.save end def self.check_password(user) user_to_verify = self.find_by_name(user) puts "Enter your password: " password = $stdin.gets.chomp Base64.decode64(user_to_verify.password) == password end end
require 'helper' require 'active_record' require 'integration/helper' class ArSqliteTest < MiniTest::Unit::TestCase DBNAME = 'lmapper.sqlite' def init_db if File.directory?('tmp') File.unlink('tmp/#{DBNAME}') if File.exists?('tmp/#{DBNAME}') else Dir.mkdir('tmp') end ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => 'tmp/test.sqlite') create_tables @_db_initialized = true end def create_tables CreatePeople.new.up CreatePhoneNumbers.new.up CreateCats.new.up end def clear_tables Persistent::Person.delete_all end def setup init_db unless @_db_initialized clear_tables end def test_round_trip p = Person.new(:name => 'John', :age => 27) LittleMapper[Person] << p assert_equal 1, LittleMapper[Person].find_all.length found = LittleMapper[Person].last assert_equal p.name, found.name assert_equal p.age, found.age refute_nil found.id assert_equal p.id, found.id end def test_find_all LittleMapper[Person] << Person.new(:name => 'John', :age => 27) LittleMapper[Person] << Person.new(:name => 'Jane', :age => 67) assert_equal 2, LittleMapper[Person].find_all.length end def test_simple_one_to_many_association p = Person.new(:name => 'John', :age => 27) p.phone_numbers << PhoneNumber.new(:code => '099', :number => '987654321') p.phone_numbers << PhoneNumber.new(:code => '123', :number => '123456789') LittleMapper[Person] << p found = LittleMapper[Person].find_by_id(p.id) assert_equal 2, found.phone_numbers.length end def test_one_to_many_with_custom_setters_getters p = Person.new(:name => 'John', :age => 27) p.receive_cat(Cat.new(:moniker => 'Meaw', :color => 'Tabby')) LittleMapper[Person] << p found = LittleMapper[Person].find_by_id(p.id) assert_equal 1, found.all_cats.length end def test_one_to_one_with_another_entity o = Person.new(:name => 'Jane', :age => 28) LittleMapper[Person] << o p = Person.new(:name => 'John', :age => 27, :spouse => o) LittleMapper[Person] << p found = LittleMapper[Person].find_by_id(p.id) assert_equal found.spouse, o end def test_sets_up_reflexive_mapping_by_default_on_related_entities p = Person.new(:name => 'John', :age => 27) number1 = PhoneNumber.new(:code => '099', :number => '987654321') p.phone_numbers << number1 p.phone_numbers << PhoneNumber.new(:code => '123', :number => '123456789') LittleMapper[Person] << p found = LittleMapper[Person].find_by_id(p.id) assert_equal found, found.phone_numbers.first.person end end
# Copyright (c) 2013 Altiscale, inc. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License require 'spec_helper' describe MRBenchmark do include Logging context 'constructed from mock configuration hashes' do platform = 'emr' benchmark = 'fake' benchmark_config = {} benchmark_config['benchmark'] = benchmark benchmark_config['platformspec'] = {} benchmark_config['platformspec'][platform] = {} benchmark_config['platformspec'][platform]['input'] = 'someInput' benchmark_config['platformspec'][platform]['output'] = 'someOutput' benchmark_config['run_option'] = 'runSomething' benchmark_config['platformspec'][platform]['hadoop_jar'] = '/path/to/runjob.jar' platform_config = {} platform_config['platform'] = platform platform_config['hadoop_slaves'] = 13 platform_config['jobflow_id'] = 'j-2342' platform_config['host'] = 'my.fake.host' platform_config['user'] = 'fake_user' platform_config['ssh_key'] = 'fake_key' platform_config['node_type'] = 'm2_very_large' label = 'myNewJob' output = benchmark_config['platformspec'][platform]['output'] describe MRBenchmark, '#populate_output' do it 'returns a populated hash' do mock_parser = double(MRValidator) mock_parser.stub(:job_num).and_return('job_122') mock_parser.stub(:application_num).and_return('application_num') result = {} result[:label] = label result[:benchmark] = benchmark_config['benchmark'] result[:platform] = platform_config['platform'] result[:run_options] = benchmark_config['run_options'] result[:input] = benchmark_config['platformspec'][platform]['input'] result[:output] = benchmark_config['platformspec'][platform]['output'] result[:hadoop_jar] = benchmark_config['platformspec'][platform]['hadoop_jar'].split('/')[-1] result[:num_nodes] = platform_config['hadoop_slaves'] result[:node_type] = platform_config['node_type'] result[:jobflow_id] = platform_config['jobflow_id'] result[:job_num] = mock_parser.job_num result[:application_num] = mock_parser.application_num benchmark = MRBenchmark.new benchmark_config benchmark.parser = mock_parser benchmark.instance_variable_set(:@platform, platform_config['platform']) expect(benchmark.populate_output output, platform_config.merge(label: label)).to eq(result) end end describe MRBenchmark, '#run' do it 'cleans output directory in hdfs' do benchmark_config['platformspec'][platform]['cleanup_command'] = 'cleanup command' cleanup_command = benchmark_config['platformspec'][platform]['cleanup_command'] mock_parser = double(MRValidator).as_null_object mock_ssh = double(SSHRun) mock_ssh.stub(:execute).with(an_instance_of(String)) do {} end SSHRun.stub(:new).with(platform_config['host'], platform_config['user'], platform_config['ssh_key']).and_return(mock_ssh) hdfs_cleanup = "hadoop fs #{cleanup_command} #{output}" mock_ssh.should_receive(:execute).with(hdfs_cleanup) benchmark = MRBenchmark.new benchmark_config benchmark.parser = mock_parser benchmark.run platform_config.merge(label: label) end it 'swallows exception during cleaning of output directory in hdfs' do benchmark_config['platformspec'][platform]['cleanup_command'] = 'cleanup command' cleanup_command = benchmark_config['platformspec'][platform]['cleanup_command'] mock_parser = double(MRValidator).as_null_object mock_ssh = double(SSHRun) mock_ssh.stub(:execute).with(an_instance_of(String)) do {} end SSHRun.stub(:new).with(platform_config['host'], platform_config['user'], platform_config['ssh_key']).and_return(mock_ssh) hdfs_cleanup = "hadoop fs #{cleanup_command} #{output}" mock_ssh.stub(:execute).with(hdfs_cleanup) do fail 'I will be swallowed' end benchmark = MRBenchmark.new benchmark_config benchmark.parser = mock_parser benchmark.run platform_config.merge(label: label) end it 'runs a hadoop job' do hadoop_jar = benchmark_config['platformspec'][platform]['hadoop_jar'] main_class = benchmark_config['platformspec'][platform]['main_class'] run_options = benchmark_config['run_options'] input = benchmark_config['platformspec'][platform]['input'] mock_parser = double(MRValidator).as_null_object mock_ssh = double(SSHRun) mock_ssh.stub(:execute).with(an_instance_of(String)) do {} end SSHRun.stub(:new).with(platform_config['host'], platform_config['user'], platform_config['ssh_key']).and_return(mock_ssh) hadoop_command = "hadoop jar #{hadoop_jar} #{main_class} #{run_options} #{input} #{output}" job_status = { exit_code: 0 } mock_ssh.stub(:execute).with(hadoop_command) do job_status end mock_ssh.should_receive(:execute).with(hadoop_command) benchmark = MRBenchmark.new benchmark_config benchmark.parser = mock_parser result = {} result[:label] = "#{benchmark_config["benchmark"]}"\ "_#{platform_config["platform"]}_#{platform_config["node_type"]}"\ "_#{platform_config["hadoop_slaves"]}" result[:benchmark] = benchmark_config['benchmark'] result[:platform] = platform_config['platform'] result[:run_options] = benchmark_config['run_options'] result[:input] = benchmark_config['platformspec'][platform]['input'] result[:output] = benchmark_config['platformspec'][platform]['output'] result[:hadoop_jar] = benchmark_config['platformspec'][platform]['hadoop_jar'].split('/')[-1] result[:num_nodes] = platform_config['hadoop_slaves'] result[:node_type] = platform_config['node_type'] result[:jobflow_id] = platform_config['jobflow_id'] result[:job_num] = mock_parser.job_num result[:application_num] = mock_parser.application_num result[:exit_code] = 0 logger.debug "result #{result[:label]}" expect(benchmark.run platform_config).to eq(result) end end end end
module Meiosis class Config class << self attr_accessor :wallet, :api attr_reader :privkey def init(env_vars) if !env_vars["privkey"] @privkey = SecureRandom.random_bytes(32) @keyclass = Secp256k1::PrivateKey.new({privkey: @privkey}) else @privkey = env_vars["privkey"] @keyclass = Secp256k1::PrivateKey.new({privkey: env_vars["privkey"]}) end @api = Meiosis::API.new @wallet = Meiosis::Wallet.new(api, privkey) if ENV["always_success"] @wallet.lock = { binary_hash: "0x0000000000000000000000000000000000000000000000000000000000000001", args: [], version: 0 } end if !api.system_script_cell wallet.install_system_script_cell(env_vars["system_script_cell_path"]) end end end end class Runner @@stop_scheduled = false @@setup_routine = nil @@subscriber = Meiosis::Subscription @@setup_checked = false def self.setup_routine @@setup_routine end def self.run while true check_for_setup unless @@setup_checked break if stop_scheduled? check_for_subscription_results break if stop_scheduled? end end def self.setup &blk @@setup_routine = blk end def self.check_for_setup @@setup_routine.call if @@setup_routine @@setup_checked = true end def self.stop_scheduled? @@stop_scheduled end def self.check_for_subscription_results while !@@subscriber.results.empty? res = @@subscriber.results.pop cback = res.callback cback.call(res.result) @@subscriber.remove_subscription(res) end end def self.stop @@stop_scheduled = true end end end
require 'rails_helper' require 'factories' describe "get all states route", :type => :request do let!(:states) { FactoryBot.create_list(:state, 29)} before { get '/states'} it 'returns all states' do expect(JSON.parse(response.body).size).to eq(29) end it 'returns status code 200' do expect(response).to have_http_status(:success) end end
require "rails_helper" RSpec.describe Api::LtiLaunchesController, type: :controller do before do setup_lti_users setup_application_instance @content_item = { "@context" => "http://purl.imsglobal.org/ctx/lti/v1/ContentItem", "@graph" => [{ "@type" => "ContentItem", "mediaType" => "text/html", "text" => "<div>test</div>", "placementAdvice" => { "presentationDocumentTarget" => "embed", }, }], } end context "no jwt" do describe "POST create" do it "returns unauthorized" do post :create, format: :json expect(response).to have_http_status(401) end end end context "as user" do before do request.headers["Authorization"] = @student_token end describe "POST create" do it "creates a new lti launch and return the result" do post :create, params: { lti_launch: FactoryBot.attributes_for(:lti_launch), content_item: @content_item, content_item_return_url: "http://www.example.com/return", }, format: :json expect(response).to have_http_status(200) end it "sets the lti launch with the correct config" do post :create, params: { lti_launch: { config: { test: "value" } }, content_item: @content_item, content_item_return_url: "http://www.example.com/return", }, format: :json json = JSON.parse(response.body) config = json["lti_launch"]["config"] expect(config["test"]).to eq("value") end end end end
# ------------ # Question #1 # ------------ # Ben is right. He is using an attr_reader, which sets up a getter method called balance behind the scenes. balance in the positive_balance? method calls the getter method and returns the @balance variable. # ------------ # Question #2 # ------------ # Alyssa's mistake is that she is using an attr_reader, which only creates a getter method. Because she wants to change the value of the @quality variable, she needs to use an attr_accessor, which will create a getter and a setter method for @quality. When using an attr_accessor, Alyssa will also need to change quantity in the update_quantity method to self.quantity. # ------------ # Question #3 # ------------ # The only thing I see potentially wrong is that its unneccessary to use attr_accessor on @product_name because it's value is not being changed anywhere. # ------------ # Question #4 # ------------ # class Greeting # def greet(msg) # puts msg # end # end # class Hello < Greeting # def hi # greet("Hello") # end # end # class Goodbye < Greeting # def bye # greet("Goodbye") # end # end # greeting1 = Hello.new # greeting2 = Goodbye.new # greeting1.hi # greeting2.bye # ------------ # Question #5 # ------------ # class KrispyKreme # attr_reader :filling_type, :glazing # def initialize(filling_type, glazing) # @filling_type = filling_type # @glazing = glazing # end # def to_s # if filling_type && glazing # "#{filling_type} with #{glazing}" # elsif filling_type # filling_type # elsif glazing # "Plain with #{glazing}" # else # "Plain" # end # end # end # donut1 = KrispyKreme.new(nil, nil) # donut2 = KrispyKreme.new("Vanilla", nil) # donut3 = KrispyKreme.new(nil, "sugar") # donut4 = KrispyKreme.new(nil, "chocolate sprinkles") # donut5 = KrispyKreme.new("Custard", "icing") # puts donut1 #=> "Plain" # puts donut2 #=> "Vanilla" # puts donut3 #=> "Plain with sugar" # puts donut4 #=> "Plain with chocolate sprinkles" # puts donut5 #=> "Custard with icing" # ------------ # Question #6 # ------------ # class Computer # attr_accessor :template # def create_template # @template = "template 14231" # end # def show_template # template # end # end # In the above code, the @template is assigned a value directly in the create_template method (even though there are getter and setter methods for it). Additionally, the value of @template is retrieved using the getter method in show_template. # class Computer # attr_accessor :template # def create_template # self.template = "template 14231" # end # def show_template # self.template # end # end # In this code, the @template is assigned a value using the setter method. Secondly, the value of @template is retrieved using the getter method in show_template. # ------------ # Question #7 # ------------ class Light attr_accessor :brightness, :color def initialize(brightness, color) @brightness = brightness @color = color end def self.information "I want to turn on the light with a brightness level of super high and a colour of green" end end
json.all_persons_info @persons do |person| json.person_id person.id json.first_name person.first_name json.last_name person.last_name json.birthday person.birthday json.email person.email json.password person.password json.phone person.phone json.address person.address json.city person.city json.state person.state json.past_id person.past_id json.notes person.notes end
class CurrenciesController < ApplicationController before_action :set_currency, only: [:edit, :update] before_action :logged_in_user def index @q = current_user.currencies.search(params[:q]) @currencies = @q.result(distinct: true) @currency = current_user.currencies.build end def new @currencies = current_user.currencies.all @currency = current_user.currencies.build end def create current_user.currencies.create(currency_params) redirect_to currencies_path end def edit @currencies = current_user.currencies.all @currency = @update_currency end def update @update_currency.update(currency_params) redirect_to currencies_path end def destroy current_user.currencies.where(destroy_check: true).destroy_all redirect_to currencies_path end private def currency_params params.require(:currency).permit(:country, :method, :destroy_check) end def set_currency @update_currency = current_user.currencies.find(params[:id]) end end
# require 'Clipboard' When(/^The customer selects the "([^"]*)" dispute reason$/) do |arg| on(DisputesPage).select_surcharge_radio_no_option on(DisputesPage).surcharge_radio_no_option_selected?.should be true on(DisputesPage).reason_option_selection = arg end Then(/^The page will display selected reason description$/) do on(DisputesPage).reason_description_text.should == data_for(:reason_description_helpful_text)['i_am_still_being_charged_for_something_i_cancelled'] end And(/^the page will display the Date service was received field$/) do puts on(DisputesPage).date_service_received_question_element.text # on(DisputesPage).date_service_received_question.should == data_for(:questions_for_i_am_still_being_charged_for_something_i_cancelled)['date_service_received_question'] # puts data_for(:responses_for_i_am_still_being_charged_for_something_i_cancelled)['date_service_received_question_response'] # on(DisputesPage).date_service_was_received_question_response= data_for(:responses_for_i_am_still_being_charged_for_something_i_cancelled)['date_service_received_question_response'] end And(/^the page will display the Reason for cancellation field$/) do on(DisputesPage).reason_for_cancellation_question.should == data_for(:questions_for_i_am_still_being_charged_for_something_i_cancelled)['reason_for_cancellation_question'] end And(/^the page will display the Were you advised of the cancellation policy\? field$/) do on(DisputesPage).where_you_advised_of_cancellation_policy_question.should == data_for(:questions_for_i_am_still_being_charged_for_something_i_cancelled)['where_you_advised_of_cancellation_policy_question'] end And(/^the page will display the Date of cancellation field$/) do on(DisputesPage).date_of_cancellation_question.should == data_for(:questions_for_i_am_still_being_charged_for_something_i_cancelled)['date_of_cancellation_question'] end And(/^the page will display the Please provide details of the cancellation, such as how you cancelled, confirmation number, etc\. field$/) do on(DisputesPage).details_of_cancellation_question.should == data_for(:questions_for_i_am_still_being_charged_for_something_i_cancelled)['details_of_cancellation_question'] end And(/^the page will display the Did the merchant accept the cancellation\? field$/) do on(DisputesPage).did_merchant_accept_cancellation_question.should == data_for(:questions_for_i_am_still_being_charged_for_something_i_cancelled)['did_merchant_accept_cancellation_question'] end And(/^the page will display the What is the document you have supporting that credit is due\? field$/) do on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).what_supporting_document_you_have_question.should == data_for(:questions_for_i_am_still_being_charged_for_something_i_cancelled)['what_supporting_document_you_have_question'] end And(/^the page will display the Does the document have a date on it\? field$/) do on(DisputesPage).does_document_have_date_on_it_question.should == data_for(:questions_for_i_am_still_being_charged_for_something_i_cancelled)['does_document_have_date_on_it_question'] end And(/^the page will display the What is the date on the document\? field$/) do on(DisputesPage).select_does_document_have_date_on_it_response_yes # on(DisputesPage).what_is_the_date_on_the_document_question.should == data_for(:questions_for_i_am_still_being_charged_for_something_i_cancelled)['what_is_the_date_on_the_document_question'] end Then(/^i fill rest of the element values$/) do on(DisputesPage).details_of_cancellation_question_response = 'dfdsfdsfdsfsdfsdfdsfds' #on(DisputesPage).select_where_you_advised_of_cancellation_policy_response_yes #on(DisputesPage).select_did_merchant_accept_cancellation_response_yes # sleep(5) on(DisputesPage).where_you_advised_of_cancellation_policy_question_element.hover on(DisputesPage).date_service_received_question_element.hover on(DisputesPage).where_you_advised_of_cancellation_policy_question_element.exists? # on(DisputesPage).select_was_your_cancellation_within_merchants_policy_response_yes sleep(2) end And(/^the customer enters less than '500' characters into the Reason for cancellation field$/) do on(DisputesPage).reason_for_cancellation_question_response = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' end And(/^leaves focus from the field$/) do on(DisputesPage).reason_for_cancellation_question_element.focus end And(/^the characters remaining counter will be updated based on what the customer entered$/) do puts on(DisputesPage).reason_for_cancellation_field_characters_remaining.split("\s").last on(DisputesPage).reason_for_cancellation_field_characters_remaining.split("\s").last.should == '474' end And(/^the page will display the Do you have documentation from the merchant to support that credit is due, such as a credit voucher, voided receipt, etc\? field$/) do on(DisputesPage).did_merchant_issue_credit_voucher_question.should == data_for(:questions_for_i_am_still_being_charged_for_something_i_cancelled)['did_merchant_issue_credit_voucher_question'] end Then(/^i fill all the answers for the questions$/) do on(DisputesPage).select_where_you_advised_of_cancellation_policy_response_yes on(DisputesPage).select_was_your_cancellation_within_merchants_policy_response_yes on(DisputesPage).select_did_merchant_accept_cancellation_response_yes on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).select_does_document_have_date_on_it_response_yes # on(DisputesPage).select_where_you_advised_of_cancellation_policy_response_no # on(DisputesPage).select_was_your_cancellation_within_merchants_policy_response_no # on(DisputesPage).select_did_merchant_accept_cancellation_response_no # on(DisputesPage).select_does_document_have_date_on_it_response_no # on(DisputesPage).select_merchant_issued_credit_voucher_response_no Clipboard.copy("this is a dummy text to be copied to clipboard this is a dummy text to be copied to clipboard this is a dummy text to be copied to clipboard this is a dummy text to be copied to clipboard this is a dummy text to be copied to clipboard") on(DisputesPage).reason_for_cancellation_question_response = Clipboard.paste sleep (10) #on(DisputesPage).reason_for_cancellation_question_response = data_for(:responses_for_i_am_still_being_charged_for_something_i_cancelled)['reason_for_cancellation_question_response'] on(DisputesPage).date_of_cancellation_question_response = data_for(:responses_for_i_am_still_being_charged_for_something_i_cancelled)['date_service_received_question_response'] on(DisputesPage).details_of_cancellation_question_response = data_for(:responses_for_i_am_still_being_charged_for_something_i_cancelled)['reason_for_cancellation_question_response'] on(DisputesPage).what_supporting_document_you_have_question_response = data_for(:responses_for_i_am_still_being_charged_for_something_i_cancelled)['reason_for_cancellation_question_response'] on(DisputesPage).what_is_the_date_on_the_document_question_response = data_for(:responses_for_i_am_still_being_charged_for_something_i_cancelled)['date_service_received_question_response'] on(DisputesPage).reason_option_selection_element.hover on(DisputesPage).reason_for_cancellation_question_element.hover puts number_of_characters_remaining= on(DisputesPage).reason_for_cancellation_field_characters_remaining.delete('Characters Remaining: ') # puts number_of_characters_remaining.should == '1' puts on(DisputesPage).details_of_cancellation_characters_remaining.delete('Characters Remaining: ').should == '0' sleep(10) end And(/^the characters remaining counter will be display "([^"]*)"$/) do |arg| on(DisputesPage).reason_for_cancellation_field_characters_remaining.delete('Characters Remaining: ').should == arg end Then(/^the characters remaining counter will be updated based on what the customer pasted$/) do puts on(DisputesPage).reason_for_cancellation_field_characters_remaining.split("\s").last on(DisputesPage).reason_for_cancellation_field_characters_remaining.split("\s").last.should == '441' end And(/^the customer pastes less than '500' characters into the Reason for cancellation field$/) do Clipboard.copy("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|\}{[]``~!@#$%^&*()") on(DisputesPage).reason_for_cancellation_question_response = Clipboard.paste end When(/^the customer enters '500' characters into the Reason for cancellation field$/) do on(DisputesPage).reason_for_cancellation_question_response = data_for(:responses_for_i_am_still_being_charged_for_something_i_cancelled)['reason_for_cancellation_question_response'] end When(/^the customer pastes '500' characters into the Reason for cancellation field$/) do Clipboard.copy("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|\}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ12") on(DisputesPage).reason_for_cancellation_question_response = Clipboard.paste puts Clipboard.paste end When(/^the customer attempts to enter more than '500' characters into the Reason for cancellation field$/) do on(DisputesPage).reason_for_cancellation_question_response = data_for(:responses_for_i_am_still_being_charged_for_something_i_cancelled)['reason_for_cancellation_question_response_greaterthan_500'] end When(/^the customer attempts to paste more than '500' characters into the Reason for cancellation field$/) do Clipboard.copy("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|\}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") on(DisputesPage).reason_for_cancellation_question_response = Clipboard.paste puts Clipboard.paste end And(/^'Were you advised of the cancellation policy\?' buttons are not selected$/) do on(DisputesPage).where_you_advised_of_cancellation_policy_response_yes_selected?.should be false on(DisputesPage).where_you_advised_of_cancellation_policy_response_no_selected?.should be false end And(/^I select the 'Yes' option for 'Were you advised of the cancellation policy\?' radio button$/) do on(DisputesPage).select_where_you_advised_of_cancellation_policy_response_yes end Then(/^'Was your cancellation within the merchant's policy\?' radio selection is displayed$/) do on(DisputesPage).was_your_cancellation_within_merchants_policy_response_yes_element.exists?.should be true on(DisputesPage).was_your_cancellation_within_merchants_policy_response_no_element.exists?.should be true end And(/^I select the 'No' option for 'Were you advised of the cancellation policy\?' radio button$/) do on(DisputesPage).select_where_you_advised_of_cancellation_policy_response_no end Then(/^'Was your cancellation within the merchant's policy\?' radio selection is not displayed$/) do on(DisputesPage).text.should_not include "Was your cancellation within the merchant's policy?" end When(/^the customer enters less than '500' characters into the Please provide details of the cancellation such as how you cancelled, confirmation number, etc field$/) do on(DisputesPage).details_of_cancellation_question_response = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' end And(/^the characters remaining counter will be updated based on what the customer entered in Details of the cancellation field$/) do puts on(DisputesPage).details_of_cancellation_characters_remaining.split("\s").last on(DisputesPage).details_of_cancellation_characters_remaining.split("\s").last.should == '474' end When(/^the customer pastes less than '500' characters into the Please provide details of the cancellation such as how you cancelled, confirmation number, etc field$/) do Clipboard.copy("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|\}{[]``~!@#$%^&*()") on(DisputesPage).details_of_cancellation_question_response = Clipboard.paste end And(/^the characters remaining counter will be updated based on what the customer pasted in Details of the cancellation field$/) do puts on(DisputesPage).details_of_cancellation_characters_remaining.split("\s").last on(DisputesPage).details_of_cancellation_characters_remaining.split("\s").last.should == '441' end When(/^the customer enters '500' characters into the Please provide details of the cancellation such as how you cancelled, confirmation number, etc field$/) do on(DisputesPage).details_of_cancellation_question_response = data_for(:responses_for_i_am_still_being_charged_for_something_i_cancelled)['details_of_cancellation_question_response'] end And(/^the characters remaining counter will be display "([^"]*)" for Details of the cancellation$/) do |arg| puts on(DisputesPage).details_of_cancellation_characters_remaining on(DisputesPage).details_of_cancellation_characters_remaining.delete('Characters Remaining: ').should == arg end When(/^the customer pastes '500' characters into the Please provide details of the cancellation such as how you cancelled, confirmation number, etc field$/) do Clipboard.copy("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|\}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ12") on(DisputesPage).details_of_cancellation_question_response = Clipboard.paste puts Clipboard.paste end When(/^the customer attempts to enter more than '500' characters into the Please provide details of the cancellation such as how you cancelled, confirmation number, etc field$/) do on(DisputesPage).details_of_cancellation_question_response = data_for(:responses_for_i_am_still_being_charged_for_something_i_cancelled)['details_of_cancellation_question_response_greaterhan_500'] on(DisputesPage).date_service_received_question_element.focus end When(/^the customer attempts to paste more than '500' characters into the Please provide details of the cancellation such as how you cancelled, confirmation number, etc field$/) do Clipboard.copy("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|\}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789;?></|}{[]``~!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ12erwerwerwerew") on(DisputesPage).details_of_cancellation_question_response = Clipboard.paste puts Clipboard.paste end And(/^I select the 'Yes' 'Was your cancellation within the merchant's policy\?' radio button$/) do on(DisputesPage).select_was_your_cancellation_within_merchants_policy_response_yes on(DisputesPage).was_your_cancellation_within_merchants_policy_response_yes_selected?.should be true end And(/^I select the 'No' 'Was your cancellation within the merchant's policy\?' radio button$/) do on(DisputesPage).select_was_your_cancellation_within_merchants_policy_response_no on(DisputesPage).was_your_cancellation_within_merchants_policy_response_no_selected?.should be true end And(/^I select the 'Yes' 'Did the merchant accept the cancellation\?' radio button$/) do on(DisputesPage).select_did_merchant_accept_cancellation_response_yes on(DisputesPage).did_merchant_accept_cancellation_response_yes_selected?.should be true end And(/^I select the 'No' 'Did the merchant accept the cancellation\?' radio button$/) do on(DisputesPage).select_did_merchant_accept_cancellation_response_no on(DisputesPage).did_merchant_accept_cancellation_response_no_selected?.should be true end And(/^I select the 'Yes' option for 'Do you have documentation from the merchant to support that credit is due, such as a credit voucher, voided receipt, etc\?' radio button$/) do on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).merchant_issued_credit_voucher_response_yes_selected?.should be true end Then(/^'What is the document you have supporting that credit is due\?' text field will be displayed$/) do on(DisputesPage).what_supporting_document_you_have_question_element.text.should == data_for(:questions_for_i_am_still_being_charged_for_something_i_cancelled)['what_supporting_document_you_have_question'] on(DisputesPage).what_supporting_document_you_have_question_element.visible?.should be true end And(/^'Does the document have a date on it\?' radio selection will be displayed$/) do on(DisputesPage).does_document_have_date_on_it_question_element.text.should == data_for(:questions_for_i_am_still_being_charged_for_something_i_cancelled)['does_document_have_date_on_it_question'] on(DisputesPage).does_document_have_date_on_it_question_element.visible?.should be true end And(/^I select the 'No' 'Do you have documentation from the merchant to support that credit is due, such as a credit voucher, voided receipt, etc\?' radio button$/) do on(DisputesPage).select_merchant_issued_credit_voucher_response_no on(DisputesPage).merchant_issued_credit_voucher_response_no_selected?.should be true end Then(/^the 'What is the document you have supporting that credit is due\?' text field will not be displayed$/) do on(DisputesPage).text.should_not include "What is the document you have supporting that credit is due?" end And(/^'Does the document have a date on it\?' radio selection will be not displayed$/) do on(DisputesPage).text.should_not include "Does the document have a date on it?" end And(/^I select the 'Yes' 'Does the document have a date on it\?' radio button$/) do on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).merchant_issued_credit_voucher_response_yes_selected?.should be true on(DisputesPage).select_does_document_have_date_on_it_response_yes on(DisputesPage).does_document_have_date_on_it_response_yes_selected?.should be true end And(/^I select the 'No' 'Does the document have a date on it\?' radio button$/) do on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).merchant_issued_credit_voucher_response_yes_selected?.should be true on(DisputesPage).select_does_document_have_date_on_it_response_no on(DisputesPage).does_document_have_date_on_it_response_no_selected?.should be true end When(/^the customer enters less than '40' characters into the What is the document you have supporting that credit is due\? field$/) do on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).merchant_issued_credit_voucher_response_yes_selected?.should be true on(DisputesPage).select_does_document_have_date_on_it_response_yes on(DisputesPage).does_document_have_date_on_it_response_yes_selected?.should be true on(DisputesPage).what_supporting_document_you_have_question_response = data_for(:responses_for_i_am_still_being_charged_for_something_i_cancelled)['what_supporting_document_you_have_question_response_lessthan_40'] end And(/^leaves focus from the field supporting documentation text field$/) do on(DisputesPage).what_supporting_document_you_have_question_element.focus on(DisputesPage).select_does_document_have_date_on_it_response_no end Then(/^the system will allow the user to continue without throwing an error$/) do puts "No Error after focusing out. Need to refactor this step after page submission logic is implemented" sleep (5) end When(/^the customer pastes less than '40' characters into the What is the document you have supporting that credit is due\? field$/) do on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).merchant_issued_credit_voucher_response_yes_selected?.should be true on(DisputesPage).select_does_document_have_date_on_it_response_yes on(DisputesPage).does_document_have_date_on_it_response_yes_selected?.should be true Clipboard.copy("ABCDEFGHKLMNOPQRWXYZ1230123456789") on(DisputesPage).what_supporting_document_you_have_question_response = Clipboard.paste end When(/^the customer enters '40' characters into the What is the document you have supporting that credit is due\? field$/) do on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).merchant_issued_credit_voucher_response_yes_selected?.should be true on(DisputesPage).select_does_document_have_date_on_it_response_yes on(DisputesPage).does_document_have_date_on_it_response_yes_selected?.should be true on(DisputesPage).what_supporting_document_you_have_question_response = data_for(:responses_for_i_am_still_being_charged_for_something_i_cancelled)['what_supporting_document_you_have_question_response'] end When(/^the customer pastes '40' characters into the What is the document you have supporting that credit is due\? field$/) do on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).merchant_issued_credit_voucher_response_yes_selected?.should be true on(DisputesPage).select_does_document_have_date_on_it_response_yes on(DisputesPage).does_document_have_date_on_it_response_yes_selected?.should be true Clipboard.copy("DEFGHKLMNOPQRWXYZ12301234567890098765432112") on(DisputesPage).what_supporting_document_you_have_question_response = Clipboard.paste end When(/^the customer attempts to enter more than '40' characters into the What is the document you have supporting that credit is due\? field$/) do on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).merchant_issued_credit_voucher_response_yes_selected?.should be true on(DisputesPage).select_does_document_have_date_on_it_response_yes on(DisputesPage).does_document_have_date_on_it_response_yes_selected?.should be true on(DisputesPage).what_supporting_document_you_have_question_response = data_for(:responses_for_i_am_still_being_charged_for_something_i_cancelled)['what_supporting_document_you_have_question_response_greaterthan_40'] end Then(/^the field will truncate the entry to (\d+) characters$/) do |arg| on(DisputesPage).what_supporting_document_you_have_question_response.length.to_i.should == arg.to_i end When(/^the customer attempts to paste more than '40' characters into the What is the document you have supporting that credit is due\? field$/) do on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).merchant_issued_credit_voucher_response_yes_selected?.should be true on(DisputesPage).select_does_document_have_date_on_it_response_yes on(DisputesPage).does_document_have_date_on_it_response_yes_selected?.should be true Clipboard.copy("DEFGHKLMNOPQRWXYZ123012345678901234567890987ABCDabcd") on(DisputesPage).what_supporting_document_you_have_question_response = Clipboard.paste end When(/^the customer enters a special character that are allowed for the field "([^"]*)"$/) do on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).merchant_issued_credit_voucher_response_yes_selected?.should be true on(DisputesPage).select_does_document_have_date_on_it_response_yes on(DisputesPage).does_document_have_date_on_it_response_yes_selected?.should be true on(DisputesPage).what_supporting_document_you_have_question_response = data_for(:responses_for_i_am_still_being_charged_for_something_i_cancelled)['what_supporting_document_you_have_question_response_special_characters'] end Then(/^we should not see an error message due to the characters we entered$/) do on(DisputesPage).what_supporting_document_you_have_question_response_special_characters_edit_error.should == data_for(:dispute_page_cancelled_serivce_errors)['what_is_the_document_you_have_supporting_that_credit_is_due_error'] #on(DisputesPage).text.should_not include ("Please use only letters, numbers and any of the symbols -'.,&@:?!()$#/\ for the field labeled \"What is the document you have supporting that credit is due?\" Also, the &# combination is not allowed.") #on(DisputesPage).what_supporting_document_you_have_question_response_special_characters_edit_error.text on(DisputesPage).cancel_button_element.visible?.should be true on(DisputesPage).cancel_button_element.click on(TransactionsDetailsPage).wait_for_td_page_load on(TransactionsDetailsPage).transactions_details_title.should == 'Transactions & Details' end When(/^the customer paste special character that are allowed for the field "([^"]*)"$/) do |arg| on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).merchant_issued_credit_voucher_response_yes_selected?.should be true on(DisputesPage).select_does_document_have_date_on_it_response_yes on(DisputesPage).does_document_have_date_on_it_response_yes_selected?.should be true Clipboard.copy(arg) on(DisputesPage).what_supporting_document_you_have_question_response = Clipboard.paste end Then(/^we should not see an error message due to the characters we pasted$/) do on(DisputesPage).text.should_not include "Please use only letters, numbers and any of the symbols -'.,&@:?!()$#/\ for the field labeled \"What is the document you have supporting that credit is due?\" Also, the &# combination is not allowed." end When(/^the customer enters a special character other than "([^"]*)"$/) do on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).merchant_issued_credit_voucher_response_yes_selected?.should be true on(DisputesPage).select_does_document_have_date_on_it_response_yes on(DisputesPage).does_document_have_date_on_it_response_yes_selected?.should be true on(DisputesPage).what_supporting_document_you_have_question_response = data_for(:responses_for_i_am_still_being_charged_for_something_i_cancelled)['what_supporting_document_you_have_question_response_special_characters_allowed'] end Then(/^the page will display an error message\.$/) do on(DisputesPage).what_supporting_document_you_have_question_response_special_characters_edit_error.text.should == ("Please use only letters, numbers and any of the symbols -'.,&@:?!()$#/\ for the field labeled \"What is the document you have supporting that credit is due?\" Also, the &# combination is not allowed.") end When(/^the customer enters &\# in the field$/) do on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).merchant_issued_credit_voucher_response_yes_selected?.should be true on(DisputesPage).select_does_document_have_date_on_it_response_yes on(DisputesPage).does_document_have_date_on_it_response_yes_selected?.should be true on(DisputesPage).what_supporting_document_you_have_question_response = "&\#" end When(/^the customer enters a special character that is not allowed$/) do pending end When(/^the customer enters "([^"]*)" that are allowed for the field \-'\.,&@:\?!\(\)\$\#\/\\$/) do |arg| on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).merchant_issued_credit_voucher_response_yes_selected?.should be true on(DisputesPage).select_does_document_have_date_on_it_response_yes on(DisputesPage).does_document_have_date_on_it_response_yes_selected?.should be true on(DisputesPage).what_supporting_document_you_have_question_response = arg end When(/^the customer enters special characters that are allowed for the field"([^"]*)" and verifies to make sure no error is displayed$/) do |table| # table is a table.hashes.keys # => [:special_characters] table.hashes.each do |x| on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).merchant_issued_credit_voucher_response_yes_selected?.should be true on(DisputesPage).select_does_document_have_date_on_it_response_yes on(DisputesPage).does_document_have_date_on_it_response_yes_selected?.should be true puts x['special_characters'] on(DisputesPage).what_supporting_document_you_have_question_response = x['special_characters'] on(DisputesPage).what_supporting_document_you_have_question_element.focus on(DisputesPage).select_does_document_have_date_on_it_response_no on(DisputesPage).what_supporting_document_you_have_question_response_special_characters_edit_error.should == data_for(:dispute_page_cancelled_serivce_errors)['what_is_the_document_you_have_supporting_that_credit_is_due_error'] # if on(DisputesPage).what_supporting_document_you_have_question_response_special_characters_edit_error_element.present? # puts on(DisputesPage).what_supporting_document_you_have_question_response_special_characters_edit_error_element.text # end end end When(/^the customer enters a special character other than '\-'\.,&@:\?!\(\)\$\#\/\\' and verifies to see an error is displayed$/) do |table| # table is a table.hashes.keys # => [:special_characters] table.hashes.each do |x| on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).merchant_issued_credit_voucher_response_yes_selected?.should be true on(DisputesPage).select_does_document_have_date_on_it_response_yes on(DisputesPage).does_document_have_date_on_it_response_yes_selected?.should be true puts x['special_characters'] on(DisputesPage).what_supporting_document_you_have_question_response = x['special_characters'] on(DisputesPage).what_supporting_document_you_have_question_element.focus on(DisputesPage).what_supporting_document_you_have_question_element.click on(DisputesPage).what_supporting_document_you_have_question_response_special_characters_edit_error.should == data_for(:dispute_page_cancelled_serivce_errors)['what_is_the_document_you_have_supporting_that_credit_is_due_error'] on(DisputesPage).what_supporting_document_you_have_question_response = 'This is a happy path text to remove edit error' on(DisputesPage).what_supporting_document_you_have_question_element.focus on(DisputesPage).what_supporting_document_you_have_question_element.click end end When(/^the customer enters &\# in the field and verifies to see an error is displayed for the combination$/) do |table| table.hashes.each do |x| on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).merchant_issued_credit_voucher_response_yes_selected?.should be true on(DisputesPage).select_does_document_have_date_on_it_response_yes on(DisputesPage).does_document_have_date_on_it_response_yes_selected?.should be true puts x['special_characters'] on(DisputesPage).what_supporting_document_you_have_question_response = x['special_characters'] on(DisputesPage).what_supporting_document_you_have_question_element.focus on(DisputesPage).select_does_document_have_date_on_it_response_no on(DisputesPage).what_supporting_document_you_have_question_response_special_characters_edit_error.should == data_for(:dispute_page_cancelled_serivce_errors)['what_is_the_document_you_have_supporting_that_credit_is_due_error'] # on(DisputesPage).text.should include "Please use only letters, numbers and any of the symbols -'.,&@:?!()$#/\ for the field labeled \"What is the document you have supporting that credit is due?\" Also, the &# combination is not allowed." end end When(/^the customer enters \#& in the field and verifies to see an error is NOT displayed for the combination$/) do |table| # table is a table.hashes.keys # => [:special_characters] table.hashes.each do |x| on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).merchant_issued_credit_voucher_response_yes_selected?.should be true on(DisputesPage).select_does_document_have_date_on_it_response_yes on(DisputesPage).does_document_have_date_on_it_response_yes_selected?.should be true puts x['special_characters'] on(DisputesPage).what_supporting_document_you_have_question_response = x['special_characters'] on(DisputesPage).what_supporting_document_you_have_question_element.focus on(DisputesPage).select_does_document_have_date_on_it_response_no on(DisputesPage).text.should_not include "Please use only letters, numbers and any of the symbols -'.,&@:?!()$#/\ for the field labeled \"What is the document you have supporting that credit is due?\" Also, the &# combination is not allowed." end end When(/^a date is manually entered for "([^"]*)" that is the same as the transaction date, no error is thrown$/) do |arg| txn_date = on(DisputesPage).get_txn_details_from_disputes_page(3) on(DisputesPage).select_date_for_the_date_field_element(arg, txn_date) end When(/^the customer enters special characters that are allowed for the field '\-'\.,&@:\?!\(\)\$\#\/' and verifies to make sure no error is displayed$/) do |table| # table is a table.hashes.keys # => [:special_characters] table.hashes.each do |x| on(DisputesPage).select_merchant_issued_credit_voucher_response_yes on(DisputesPage).merchant_issued_credit_voucher_response_yes_selected?.should be true on(DisputesPage).select_does_document_have_date_on_it_response_yes on(DisputesPage).does_document_have_date_on_it_response_yes_selected?.should be true puts x['special_characters'] on(DisputesPage).what_supporting_document_you_have_question_response = x['special_characters'] on(DisputesPage).what_supporting_document_you_have_question_element.focus on(DisputesPage).select_does_document_have_date_on_it_response_no puts on(DisputesPage).text.should_not include "Please use only letters, numbers and any of the symbols -'.,&@:?!()$#/ for the field labeled \"What is the document you have supporting that credit is due?\" Also, the &# combination is not allowed." end end When(/^a date is manually entered for "([^"]*)" that is after the transaction date, no error is thrown$/) do |arg| txn_date = on(DisputesPage).get_txn_details_from_disputes_page(3) @return_date = on(DisputesPage).return_date_for_input_value(txn_date, '+', 360) puts @return_date on(DisputesPage).select_date_for_the_date_field_element(arg, @return_date) end When(/^a date is manually entered for "([^"]*)" that is before the transaction date, no error is thrown$/) do |arg| txn_date = on(DisputesPage).get_txn_details_from_disputes_page(3) @return_date = on(DisputesPage).return_date_for_input_value(txn_date, '-', 360) puts @return_date on(DisputesPage).select_date_for_the_date_field_element(arg, @return_date) end When(/^a date is manually entered for "([^"]*)" that is in the future, no error is thrown$/) do |arg| txn_date = on(DisputesPage).get_txn_details_from_disputes_page(3) @return_date = on(DisputesPage).return_date_for_input_value('systemdate', '-', 360) puts @return_date on(DisputesPage).select_date_for_the_date_field_element(arg, @return_date) end Then(/^the system will display an error message with the field label$/) do # on(DisputesPage).date_service_received_date_error.should == "Please double-check the field labeled * Date service was received. It could be blank or have invalid characters." on(DisputesPage).date_service_received_date_error.should == "Please enter a valid date using the MM/DD/YYYY format or, select a date from the calendar." #on(DisputesPage).date_service_received_date_error.should == data_for(:date_selection_errors)['date_of_service_date_format_error'] end When(/^a "([^"]*)" is manually entered for "([^"]*)" that is invalid$/) do |date, question| puts question txn_date = on(DisputesPage).get_txn_details_from_disputes_page(3) puts txn_date on(DisputesPage).select_date_for_the_date_field_element(question, date) end When(/^a date is manually entered for "([^"]*)" that is invalid an error message should be displayed$/) do |question, table| table.hashes.each do |x| puts x['date'] on(DisputesPage).select_date_for_the_date_field_element(question, x['date']) case question when question = 'Date service was received' on(DisputesPage).date_service_received_date_error.should? == data_for(:date_selection_errors)['date_of_service_date_format_error'] date_entered= on(DisputesPage).date_service_was_received_question_response date_of_cancellation_date_error date_entered.should == x['date'] on(DisputesPage).date_service_was_received_question_response_element.clear puts on(DisputesPage).date_service_was_received_question_response when question = 'Date of cancellation' on(DisputesPage).date_of_cancellation_date_error.should? == data_for(:date_selection_errors)['date_of_cancellation_date_format_error'] date_entered= on(DisputesPage).date_of_cancellation_question_response date_entered.should == x['date'] on(DisputesPage).date_of_cancellation_question_response_element.clear puts on(DisputesPage).date_of_cancellation_question_response when question = 'What is the date on the document?' on(DisputesPage).what_is_the_date_on_document_date_error.should? == data_for(:date_selection_errors)['what_is_the_date_on_the_document_date_format_error'] date_entered= on(DisputesPage).what_is_the_date_on_the_document_question_response date_entered.should == x['date'] on(DisputesPage).what_is_the_date_on_the_document_question_element.clear puts on(DisputesPage).what_is_the_date_on_the_document_question_response else Puts "No matching date field" end end end When(/^a date is manually entered for "([^"]*)" without the \/ included will display error$/) do |arg| txn_date = on(DisputesPage).get_txn_details_from_disputes_page(3) puts txn_date_without_slash = txn_date.delete("/") on(DisputesPage).select_date_for_the_date_field_element(arg, txn_date_without_slash) case arg when arg == 'Date service was received' on(DisputesPage).date_service_received_date_error.should? == data_for(:date_selection_errors)['date_of_service_date_format_error'] puts on(DisputesPage).date_service_was_received_question_response when arg == 'Date of cancellation' on(DisputesPage).date_of_cancellation_date_error.should? == data_for(:date_selection_errors)['date_of_cancellation_date_format_error'] puts on(DisputesPage).date_of_cancellation_question_response when arg == 'What is the date on the document?' on(DisputesPage).what_is_the_date_on_document_date_error.should? == data_for(:date_selection_errors)['what_is_the_date_on_the_document_date_format_error'] puts on(DisputesPage).what_is_the_date_on_the_document_question_response end end Given(/^I login to the application and dispute a charge with the reason 'I am still being charged for something I cancelled'$/) do visit(LoginPage) on(LoginPage) do |page| login_data = page.data_for(:dispute_single_disputable_ods) #dispute_single_DNR_charge, dispute_single_disputable_ods username = login_data['username'] password = login_data['password'] ssoid = login_data['ssoid'] page.login(username, password, ssoid) end @authenticated = on(DisputesPage).is_summary_shown? if @authenticated[0] == false fail("#{@authenticated[1]}" "--" "#{@authenticated[2]}") end visit(TransactionsDetailsPage) on(DisputesPage) do |page| page.search_for_valid_disputable_txn_iteratively @matching_transaction_id, @txn_details = page.click_disputes_link_when_present page.select_surcharge_radio_no_option page.surcharge_radio_no_option_selected?.should be true page.reason_option_selection = "I am still being charged for something I cancelled" end end When(/^all fields are filled in for 'I am still being charged for something i cancelled' reason$/) do #on(DisputesPage).dispute_reason_questions_date('cancelled_service_where_you_advised_of_cancellation_data_all_questions', []) on(DisputesPage).dispute_reason_questions_date('i_am_still_being_charged_for_something_i_cancelled_default_data_response_CAN', []) end Then(/^Dispute should be submitted to the backend$/) do @browser.h1(:class => 'page_title').when_present do page_text = @browser.h1(:class => 'page_title').text if page_text = 'Case Already Open'|| 'Dispute Request Confirmation' puts ("Disputes submitted successfully") else fail("Failure submitting dispute") end end end
class HN class Item attr_accessor :id attr_accessor :title, :url attr_accessor :user_id, :content def initialize(params) @id = params[:id] @title = params[:title] @url = params[:url] @user_id = params[:user_id] @content = params[:content] end def comments @comments ||= [] doc = TFHpple.alloc.initWithHTMLData item_url.nsurl.nsdata doc.searchWithXPathQuery("//table[@class='comment-tree']/tr[@class='athing comtr ']").map do |e| id = e[:id] user_id = e.peekAtSearchWithXPathQuery("//*[@class='comhead']/a[@class='hnuser']") user_id = user_id.text if user_id content = e.peekAtSearchWithXPathQuery("//*[@class='comment']/span[@class]") content = content.text if content Item.new id: id, user_id: user_id, content: content end end private def item_url 'https://news.ycombinator.com/item?id=%s' % @id end end class << self def shared_instance @instance ||= self.new end end attr_reader :items def initialize @items = [] @morepage = nil end def load_next_page doc = TFHpple.alloc.initWithHTMLData( ( @morepage.nil? ? baseurl.nsurl : @morepage.nsurl(baseurl) ).nsdata ) @morepage = doc.peekAtSearchWithXPathQuery("//a[@class='morelink']")[:href] @items = doc.searchWithXPathQuery("//tr[@class='athing']").map do |e| link = e.peekAtSearchWithXPathQuery("//a[@class='storylink']") Item.new id: e[:id], title: link.text, url: link[:href].nsurl(baseurl).absoluteString end self end private def baseurl "https://news.ycombinator.com/news".nsurl end end
class Donation < ApplicationRecord validates :cuenta, presence: true, uniqueness:true, length: {minimum: 6} validates :banco, presence: true, length: {maximum: 60} validates :detalle, presence: true end
class TranslationsController < ApplicationController before_filter :authenticate_user! def create @passage = Phrase.find(params[:phrase_id]) @new_translation = @passage.translations.build(trans_params) @new_translation.user = current_user if @new_translation.save flash[:notice] = "Translation saved!" redirect_to phrase_path(@passage) else flash[:alert] = "Error - translation not saved." surrounding_text(@passage) render 'phrases/show' end end def trans_params params.require(:translation).permit(:translation) end end
require '../spec_helper.rb' require './substrings.rb' describe "substrings" do it "creates a hash with number of times words in array are contained in string" do expect(substrings("below", ["below", "down", "go", "going", "horn", "how", "howdy", "it", "i", "low", "own", "part", "partner", "sit"])).to include( "below" => 1, "low" => 1 ) end end describe "substrings" do it "creates a hash with number of times words in array are contained in string" do expect(substrings("Howdy partner, sit down! How's it going?", ["below", "down", "go", "going", "horn", "how", "howdy", "it", "i", "low", "own", "part", "partner", "sit"])).to include( "down" => 1, "how" => 2, "howdy" => 1, "go" => 1, "going" => 1, "it" => 2, "i" => 3, "own" => 1, "part" => 1, "partner" => 1, "sit" => 1 ) end end
class Facility < ActiveRecord::Base has_many :institution_facilities has_many :institutions, through: :institution_facilities end
class UserStoriesController < ApplicationController skip_before_filter :verify_authenticity_token, :only => [:update_priority] def create @user_story = UserStory.new(user_story_params) if @user_story.save puts "*****WE SHOULDNT BE HERE ****" redirect_to :controller => "sprints", :action => "show", :id => @user_story.sprint_id else render 'new' end end def edit end def index @user_stories = UserStory.all end def new @user_story = UserStory.new end def show @user_story = UserStory.find(params[:id]) @tasks_ready = @user_story.tasks.select{ |task| task[:status] == TaskStatus::READY} @tasks_in_progress = @user_story.tasks.select{ |task| task[:status] == TaskStatus::IN_PROGRESS} @tasks_done = @user_story.tasks.select{ |task| task[:status] == TaskStatus::DONE} estimated_hours = @tasks_ready.to_a.sum(&:hours) estimated_hours = 0 unless estimated_hours @user_story.estimated_hours = estimated_hours @user_story.save end # Post method for updating user story priority. def update_priority data = params[:_json] # Itearate json object and update userStory priority. data.each do |set| userStory = UserStory.find(set['id'].to_i) userStory.update(:priority => set['priority'].to_s) end # Return json payload. payload = { data: "success", status: "success" } render :json => payload, :status => :ok end private def user_story_params params.require(:user_story).permit(:id, :title, :description, :criteria, :story_points, :priority, :estimated_hours, :sprint_id) end end
class ThemesController < ApplicationController before_action :set_theme, only: [:show, :destroy, :edit, :update] def index @theme = Theme.new @themes = Theme.includes(:user).order("created_at DESC") end def create Theme.create(theme_params) redirect_to root_path end def show @post = Post.new @posts = @theme.posts end def destroy @theme.destroy redirect_to root_path end def edit end def update @theme.update(theme_params) redirect_to root_path end private def theme_params params.require(:theme).permit(:title).merge(user_id: current_user.id) end def set_theme @theme = Theme.find(params[:id]) end end
require 'rails_helper' RSpec.describe 'ユーザ管理機能', type: :system do before do @normal = FactoryBot.create(:normal) @admin = FactoryBot.create(:admin) end describe 'ユーザ登録' do context 'ユーザを新規作成した場合' do it '作成したユーザの詳細ページが表示される' do visit new_user_path fill_in 'Name', with: 'test' fill_in 'Email', with: 'test@example.com' fill_in 'Password', with: 'password' fill_in 'Password confirmation', with: 'password' click_on '登録する' expect(page).to have_content 'ログインしました' expect(page).to have_content 'testのページ' expect(page).to have_content 'test@example.com' end end context 'ユーザがログインしないでタスク一覧画面に飛ぼうとした場合' do it 'ログイン画面に遷移する' do visit tasks_path expect(page).to have_content 'ログインしてください' expect(page).to have_content 'Email' expect(page).to have_content 'Password' end end end describe 'セッション機能' do before do visit new_session_path fill_in 'Email', with: 'normal@example.com' fill_in 'Password', with: 'password' click_on 'Log in' end context '正しいユーザ情報を入力した場合' do it 'ログインできる' do expect(page).to have_content 'ログインしました' expect(page).to have_content 'normalのページ' expect(page).to have_content 'normal@example.com' end it 'ログアウトできる' do click_on 'ログアウト' expect(page).to have_content 'ログアウトしました' expect(page).to have_content 'ログイン' expect(page).to have_content 'Email' expect(page).to have_content 'Password' end it 'マイページに飛べる' do click_on 'マイページ' expect(page).to have_content 'normalのページ' expect(page).to have_content 'normal@example.com' end end context '一般ユーザが他人の詳細画面に飛んだ場合' do it 'タスク一覧画面に遷移する' do visit user_path(id: @admin.id) expect(page).to have_content 'タスク一覧' expect(page).to have_content 'タスク名' expect(page).to have_content 'タスク詳細' expect(page).to have_content '終了期限' expect(page).to have_content '登録日時' expect(page).to have_content 'ステータス' expect(page).to have_content '優先順位' end end describe '管理機能' do context '正しいユーザ情報を入力した場合' do it '管理画面にアクセスできる' do visit new_session_path fill_in 'Email', with: 'admin@example.com' fill_in 'Password', with: 'password' click_on 'Log in' click_on '管理画面' expect(page).to have_content 'ユーザ一覧' expect(page).to have_content 'ユーザ名' expect(page).to have_content 'タスク数' expect(page).to have_content '管理者権限' end it 'ユーザの新規登録ができる' do visit new_session_path fill_in 'Email', with: 'admin@example.com' fill_in 'Password', with: 'password' click_on 'Log in' click_on '管理画面' click_on 'ユーザを登録する' fill_in 'Name', with: 'test' fill_in 'Email', with: 'test@example.com' fill_in 'Password', with: 'password' fill_in 'Password confirmation', with: 'password' click_on '登録する' expect(page).to have_content 'testのページ' expect(page).to have_content 'test@example.com' end it 'ユーザの詳細画面にアクセスできる' do visit new_session_path fill_in 'Email', with: 'admin@example.com' fill_in 'Password', with: 'password' click_on 'Log in' click_on '管理画面' click_on "詳細", match: :first expect(page).to have_content 'normalのページ' expect(page).to have_content 'normal@example.com' end it 'ユーザを編集できる' do visit new_session_path fill_in 'Email', with: 'admin@example.com' fill_in 'Password', with: 'password' click_on 'Log in' click_on '管理画面' click_on "編集", match: :first fill_in 'Name', with: 'changed_normal' fill_in 'Email', with: 'changed_normal@example.com' fill_in 'Password', with: 'password' fill_in 'Password confirmation', with: 'password' click_on '更新する' expect(page).to have_content 'changed_normalのページ' expect(page).to have_content 'changed_normal@example.com' end it 'ユーザを削除できる' do visit new_session_path fill_in 'Email', with: 'admin@example.com' fill_in 'Password', with: 'password' click_on 'Log in' click_on '管理画面' click_on "削除", match: :first page.driver.browser.switch_to.alert.accept expect(page).to have_content 'ユーザを削除しました' expect(page).to_not have_content 'changed_normal' end end context '正しくないユーザ情報を入力した場合' do it '管理画面にアクセスできない' do visit new_session_path fill_in 'Email', with: 'normal@example.com' fill_in 'Password', with: 'password' click_on 'Log in' visit admin_users_path expect(page).to have_content '管理者以外はアクセスできません' expect(page).to have_content 'タスク一覧' expect(page).to have_content 'タスク名' expect(page).to have_content 'タスク詳細' expect(page).to have_content '終了期限' expect(page).to have_content '登録日時' expect(page).to have_content 'ステータス' expect(page).to have_content '優先順位' end end end end end
# frozen_string_literal: true require "sentry/utils/exception_cause_chain" module Sentry class SingleExceptionInterface < Interface include CustomInspection SKIP_INSPECTION_ATTRIBUTES = [:@stacktrace] PROBLEMATIC_LOCAL_VALUE_REPLACEMENT = "[ignored due to error]".freeze OMISSION_MARK = "...".freeze MAX_LOCAL_BYTES = 1024 attr_reader :type, :module, :thread_id, :stacktrace attr_accessor :value def initialize(exception:, stacktrace: nil) @type = exception.class.to_s exception_message = if exception.respond_to?(:detailed_message) exception.detailed_message(highlight: false) else exception.message || "" end @value = exception_message.byteslice(0..Event::MAX_MESSAGE_SIZE_IN_BYTES) @module = exception.class.to_s.split('::')[0...-1].join('::') @thread_id = Thread.current.object_id @stacktrace = stacktrace end def to_hash data = super data[:stacktrace] = data[:stacktrace].to_hash if data[:stacktrace] data end # patch this method if you want to change an exception's stacktrace frames # also see `StacktraceBuilder.build`. def self.build_with_stacktrace(exception:, stacktrace_builder:) stacktrace = stacktrace_builder.build(backtrace: exception.backtrace) if locals = exception.instance_variable_get(:@sentry_locals) locals.each do |k, v| locals[k] = begin v = v.inspect unless v.is_a?(String) if v.length >= MAX_LOCAL_BYTES v = v.byteslice(0..MAX_LOCAL_BYTES - 1) + OMISSION_MARK end v rescue StandardError PROBLEMATIC_LOCAL_VALUE_REPLACEMENT end end stacktrace.frames.last.vars = locals end new(exception: exception, stacktrace: stacktrace) end end end
class PaperTrail::VersionPolicy < ApplicationPolicy def index? (user.is_admin? or user.is_volunteer?) if user end def show? (user.is_admin? or user.is_volunteer?) if user end end
class PaymentsController < ApplicationController rescue_from ActiveRecord::RecordNotFound, with: :render_not_found_response rescue_from ActiveRecord::RecordInvalid, with: :render_unprocessable_entity_response def index payments = Payment.all render json: payments end def create payment = Payment.create!(payment_params) render json: payment end private def payment_params params.require(:payment).permit(:user_id, :shopping_cart_id, :total, :subtotal, :tax, :shipping) end def render_not_found_response render json: {error: "Shopping cart not found"}, status: :not_found end def render_unprocessable_entity_response(invalid) render json: { errors: invalid.record.errors.full_messages}, status: :unprocessable_entity end end
require 'spec_helper' describe DashboardController do render_views let(:user) { User.make! } before(:each) do sign_in user end it "should render the dashboard" do deployment = Deployment.make!(:user => user, :name => 'Example deployment') cloud_provider = CloudProvider.make! Cloud.make!(:cloud_provider => cloud_provider) get :index response.code.should == "200" assigns(:recent_deployments).should == [deployment] assigns(:example_deployment).should == deployment assigns(:services).should_not be_nil assigns(:cloud_providers).should include(cloud_provider) assigns(:cloud_count).should > 1 response.should render_template("index") end it "should render the dashboard when there is no example deployment" do get :index response.code.should == "200" assigns(:recent_deployment).should be_nil assigns(:example_deployment).should be_nil response.should render_template("index") end end
class Admin::EuDecisionTypesController < Admin::StandardAuthorizationController def index index! do |format| format.json { render :json => EuDecisionType.dict.sort.to_json } end end def create create! do |failure| failure.js { render 'new' } end end protected def collection @eu_decision_types ||= end_of_association_chain.page(params[:page]). order('UPPER(name) ASC') end end
module Auth::Controllers::SignInOut def sign_in(scope, resource, options = {}) expire_data_after_sign_in! if options[:bypass] warden.session_serializer.store(resource, scope) elsif warden.user(scope) == resource # && !options.delete(:force) # Do nothing. User already signed in and we are not forcing it. true else warden.set_user(resource, scope: scope) # options.merge!(scope: scope)) end end def sign_out(scope) warden.logout(scope) end def sign_out_all_scopes(lock = true) users = Devise.mappings.each_value do |m| warden.user(scope: m.name, run_callbacks: false) end warden.logout expire_data_after_sign_out! warden.clear_strategies_cache! warden.lock! if lock users.any? end private def all_signed_out? users = Devise.mappings.each_value do |m| warden.user(scope: m.name, run_callbacks: false) end users.all?(&:blank?) end def expire_data_after_sign_in! # session.keys will return an empty array if the session is not yet loaded. # This is a bug in both Rack and Rails. # A call to #empty? forces the session to be loaded. session.empty? session.keys.grep(/^devise\./).each { |k| session.delete(k) } end alias expire_data_after_sign_out! expire_data_after_sign_in! # Helper for use in before_actions where no authentication is required. # # Example: # before_action :require_no_authentication, only: :new def require_no_authentication(scope) if warden.authenticated?(scope) && warden.user(scope) flash[:alert] = I18n.t("devise.failure.already_authenticated") redirect_to root_path end end # Check if there is no signed in user before doing the sign out. # # If there is no signed in user, it will set the flash message and redirect # to the after_sign_out path. def verify_signed_out_user if all_signed_out? flash[:notice] = I18n.t('devise.sessions.already_signed_out') redirect_to root_path end end end
class UtilService class << self def experiment(name) service_name = name.split('_').map(&:capitalize).join service = Object.const_get("#{service_name}Service") raise BadRequestError.new('Service Not Match') unless service < ExperimentService service end end end
Given(/^service on "(.+)"$/) do |url| @service = Infra['soap.client'].new(wsdl: url) end When(/^execute operation (\S+)$/) do |name| @response = @service.call(name.to_sym) end Then(/^response body is presented$/) do body = @response.body log body expect(body.empty?).to be false end
class CreateChats < ActiveRecord::Migration def change create_table :chats do |t| t.references :question_friend, index: true t.string :message t.boolean :is_from t.timestamps end end end
require 'rails_helper' RSpec.feature "Listing exercises" do before do @john=User.create(first_name:"alex",last_name:"shyaka",email:"shyakaster@gmail.com",password:"password") @sarah=User.create(first_name:"sarah",last_name:"shyaka",email:"sarah@gmail.com",password:"password") login_as @john @e1=@john.exercises.create(duration_in_min:20, workout:"Body building",workout_date:Date.today) @e2=@john.exercises.create(duration_in_min:14, workout:"Body building and boxing",workout_date:Date.today) @following=Friendship.create(user:@john,friend:@sarah) end scenario "shows users workout for the last seven days" do visit '/' click_link "My Lounge" expect(page).to have_content(@e1.duration_in_min) expect(page).to have_content(@e1.workout) expect(page).to have_content(@e1.workout_date) expect(page).to have_content(@e2.duration_in_min) expect(page).to have_content(@e2.workout) expect(page).to have_content(@e2.workout_date) end scenario"show a list of users friends"do visit "/" click_link "My Lounge" expect(page).to have_content("My friends") expect(page).to have_content(@sarah.full_name) expect(page).to have_link("Unfollow") end end
require 'json' require 'yaml' VAGRANT_DOTFILE_PATH = 'bin/.vagrant' if(ENV['VAGRANT_DOTFILE_PATH'].nil? && '.vagrant' != VAGRANT_DOTFILE_PATH) puts "\033[#1;#33;#40m " puts ' changing metadata directory to ' + VAGRANT_DOTFILE_PATH ENV['VAGRANT_DOTFILE_PATH'] = VAGRANT_DOTFILE_PATH puts ' removing default metadata directory ' + FileUtils.rm_r('.vagrant').join("\n") system 'vagrant ' + ARGV.join(' ') ENV['VAGRANT_DOTFILE_PATH'] = nil #for good measure abort 'Finished' puts "\033[0m" end VAGRANTFILE_API_VERSION = "2" confDir = $confDir ||= File.expand_path(".") homesteadYamlPath = confDir + "/bin/Homestead.yaml" afterScriptPath = confDir + "/bin/scripts/after.sh" aliasesPath = confDir + "/bin/aliases" require File.expand_path(File.dirname(__FILE__) + '/bin/scripts/homestead.rb') Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| if File.exists? aliasesPath then config.vm.provision "file", source: aliasesPath, destination: "~/.bash_aliases" end Homestead.configure(config, YAML::load(File.read(homesteadYamlPath))) if File.exists? afterScriptPath then config.vm.provision "shell", path: afterScriptPath end end
require 'rails_helper' RSpec.describe 'merchant discount destroy' do before :each do Merchant.destroy_all Discount.destroy_all @merchant1 = create(:merchant) @discount_1 = @merchant1.discounts.create!(name: "TENoffTEN", percentage_discount: 10, quantity_threshold: 10, merchant_id: @merchant1.id) visit merchant_discounts_path(@merchant1) end it 'As a merchant, I can delete a discount' do within("#discount-#{@discount_1.id}") do click_button "Delete" end expect(current_path).to eq(merchant_discounts_path(@merchant1)) expect(page).to_not have_content(@discount_1.name) end end
require "date" require "fixnum" class DateRangeFormatter def initialize(start_date, end_date, start_time = nil, end_time = nil) @start_date = Date.parse(start_date) @end_date = Date.parse(end_date) @start_time = start_time @end_time = end_time end ## # The code repeats itself many times. This repeating code is a good clue # that a logical order can be found. That will dry up the code. # # The special cases should be handled after that. # # Additionally, rather than creating many branches and building the whole # output in each of them it will be much easier for reading if the output # builds gradually. # # # If this problem was created artificially it had to be a real crazyness for # the one creating it :) # def to_s_old full_start_date = @start_date.strftime("#{@start_date.day.ordinalize} %B %Y") full_end_date = @end_date.strftime("#{@end_date.day.ordinalize} %B %Y") if @start_date == @end_date if @start_time && @end_time "#{full_start_date} at #{@start_time} to #{@end_time}" elsif @start_time "#{full_start_date} at #{@start_time}" elsif @end_time "#{full_start_date} until #{@end_time}" else full_start_date end elsif @start_date.month == @end_date.month if @start_time && @end_time "#{full_start_date} at #{@start_time} - #{full_end_date} at #{@end_time}" elsif @start_time "#{full_start_date} at #{@start_time} - #{full_end_date}" elsif @end_time "#{full_start_date} - #{full_end_date} at #{@end_time}" else @start_date.strftime("#{@start_date.day.ordinalize} - #{@end_date.day.ordinalize} %B %Y") end elsif @start_date.year == @end_date.year if @start_time && @end_time "#{full_start_date} at #{@start_time} - #{full_end_date} at #{@end_time}" elsif @start_time "#{full_start_date} at #{@start_time} - #{full_end_date}" elsif @end_time "#{full_start_date} - #{full_end_date} at #{@end_time}" else @start_date.strftime("#{@start_date.day.ordinalize} %B - ") + @end_date.strftime("#{@end_date.day.ordinalize} %B %Y") end else if @start_time && @end_time "#{full_start_date} at #{@start_time} - #{full_end_date} at #{@end_time}" elsif @start_time "#{full_start_date} at #{@start_time} - #{full_end_date}" elsif @end_time "#{full_start_date} - #{full_end_date} at #{@end_time}" else "#{full_start_date} - #{full_end_date}" end end end ## # This is the simplified code. It goes in only two lines of thought. And that is, # a) build date range with the same start and end day # b) build date range with different start and end day # def to_s return to_s_same_day_range if @end_date == @start_date # if no time is given then simplify the date by removing month/year parts include_year = true include_month = true if @start_time.nil? && @end_time.nil? if @start_date.year == @end_date.year include_year = false if @start_date.month == @end_date.month include_month = false end end end fmt = @start_date.day.ordinalize.to_s fmt << " %B" if include_month fmt << " %Y" if include_year start_date = @start_date.strftime fmt full_end_date = @end_date.strftime(@end_date.day.ordinalize.to_s + " %B %Y") result = start_date result << ' at ' << @start_time if @start_time result << ' - ' result << full_end_date result << ' at ' << @end_time if @end_time result end private def to_s_same_day_range result = @start_date.strftime(@start_date.day.ordinalize.to_s + " %B %Y") result << ' at ' << @start_time if @start_time result << (@start_time ? ' to ' : ' until ') << @end_time if @end_time result end end
require 'spec_helper' describe Tournament do let(:rock_player) { RockPlayer.new } let(:paper_player) { PaperPlayer.new } let(:scissors_player) { ScissorsPlayer.new } it 'should be a tournament' do expect(subject).to be_a(Tournament) end describe ".load_players" do it "loads the list of players" do expect{ subject.load_players }.to change(subject.players, :count).from(0).to(3) end end describe ".load_rounds" do let(:players) { double('Players', :shuffle => [rock_player, paper_player, scissors_player], :empty? => false) } it "loads the rounds randomly" do subject.stub(:players).and_return(players) subject.load_rounds expect(subject.rounds).to eq([[rock_player, paper_player], [scissors_player, nil]]) end end describe ".play" do let(:players) { double('Players', :shuffle => [rock_player, paper_player, scissors_player], :empty? => false) } it "determines a winner" do subject.stub(:players).and_return(players) expect(subject.play).to eq(scissors_player) end end end
# frozen_string_literal: true RSpec.describe NilRemoteAd do let(:ad) { described_class.new } %i[reference status description].each do |attr| describe "##{attr}" do subject { ad.send(attr) } it { is_expected.to eq 'Non Existent' } end end end
class Api::ReviewsController < ApplicationController before_action :set_item def index render json: @item.reviews end def create end def update end def destroy end private def set_item @item = Items.find(params[:item_id]) end end
require 'test_helper' class DemandasControllerTest < ActionController::TestCase setup do @demanda = demandas(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:demandas) end test "should get new" do get :new assert_response :success end test "should create demanda" do assert_difference('Demanda.count') do post :create, demanda: { cidade_id: @demanda.cidade_id, cidade_origem: @demanda.cidade_origem, correspondente: @demanda.correspondente, descricao: @demanda.descricao, status: @demanda.status, user_id: @demanda.user_id, validade: @demanda.validade } end assert_redirected_to demanda_path(assigns(:demanda)) end test "should show demanda" do get :show, id: @demanda assert_response :success end test "should get edit" do get :edit, id: @demanda assert_response :success end test "should update demanda" do patch :update, id: @demanda, demanda: { cidade_id: @demanda.cidade_id, cidade_origem: @demanda.cidade_origem, correspondente: @demanda.correspondente, descricao: @demanda.descricao, status: @demanda.status, user_id: @demanda.user_id, validade: @demanda.validade } assert_redirected_to demanda_path(assigns(:demanda)) end test "should destroy demanda" do assert_difference('Demanda.count', -1) do delete :destroy, id: @demanda end assert_redirected_to demandas_path end end
class Subject < ActiveRecord::Base has_many :feedbacks # has_and_belongs_to_many :courses has_many :course_subjects has_many :courses, through: :course_subjects validates :name, presence: true validates :description, presence: true end
#!/usr/bin/ruby require 'mongoid' require 'json' require_relative '../models/place' require 'pry' env = 'development' ARGV.each do |arg| arg_split = arg.split "=" if arg_split[0] == 'env' if arg_split[1] == 'development' || arg_split[1] == 'test' env = arg_split[1] elsif arg_split[1] == 'production' if ENV['MONGOHQ_URL'].nil? || ENV['MONGOHQ_URL'].empty? raise "MONGOHQ_URL not defined" end env = arg_split[1] end end end Mongoid.load! "mongoid.yml", env categories = [] Place.each do |p| categories.concat p.categories end categories.uniq! place = Place.where(:name => "Melt Bar & Grilled - Lakewood").first puts place.categories.index("Nightlife") categories.each do |c| category = {name: c} category[:count] = Place.where(:categories.in => [c]).count category[:subcategories] = [] Place.where(:categories.in => [c]).each do |place| category[:subcategories].push place.subcategories[place.categories.index(c)] subcategory = {name: sub} subcategory[:count] = Place.where(subcategory: sub).count category[:subcategories] << subcategory end categories << category end File.open("categories.json","w") do |f| f.write(categories.to_json) end
require 'rmagick' require 'fileutils' require_relative 'imgen/color_names' module Imgen class Image # main entry point def initialize(options) 1.upto(options[:quantity]) do img = Magick::Image.new(options[:width], options[:height]) #img.colorspace = Magick::RGBColorspace colors = {r: 0, g: 0, b: 0} options[:color_dominant] = colors.keys.to_a.sample make_image(img, options) end end # image processing def make_image(img, options) index_range = (-5..5) color_name_index = rand(0..COLOR_NAMES.length - 1) # iterate over each pixel (0..img.columns).each do |x| (0..img.rows).each do |y| case options[:method] when :solid pixel = make_new_pixel(COLOR_NAMES[color_name_index]) when :texture new_color_name_index = (color_name_index + rand(index_range)) # fix boundary of index if new_color_name_index < 0 color_name_index = 0 elsif new_color_name_index >= COLOR_NAMES.length color_name_index = COLOR_NAMES.length - 1 else color_name_index = new_color_name_index end pixel = make_new_pixel(COLOR_NAMES[color_name_index]) end # save pixel color img.pixel_color(x, y, pixel) end end write_image_to_file(img, options) display_image(img, options) end # create new Pixel from color name def make_new_pixel(new_name) return Magick::Pixel.from_color(new_name) end # write image to disk def write_image_to_file(img, options) img_dir = options[:directory] img_ext = options[:format] unless File.directory?(img_dir) FileUtils.mkdir_p(img_dir) end counter = 0 img_uniq = "_0" options[:filename_path] = "#{img_dir}/#{options[:width]}x#{options[:height]}#{img_uniq}.#{img_ext}" until !File.exists?(options[:filename_path]) counter += 1 img_uniq = "_" + counter.to_s options[:filename_path] = "#{img_dir}/#{options[:width]}x#{options[:height]}#{img_uniq}.#{img_ext}" end puts "writing #{options[:filename_path]} to disk" if options[:verbose] begin img.write(options[:filename_path]) rescue puts 'error writing image to disk' end end # optionally display image after creation def display_image(img, options) if options[:display_x11] begin img.display rescue puts "could not display #{options[:filename_path]}" end elsif options[:display_imgcat] begin system("imgcat #{options[:filename_path]}") rescue puts "could not display #{options[:filename_path]}" end end end end end
# # Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands. # # This file is part of New Women Writers. # # New Women Writers is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # New Women Writers is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with New Women Writers. If not, see <http://www.gnu.org/licenses/>. # require 'cases/helper' class MyReader < ActiveRecord::Base has_and_belongs_to_many :my_books end class MyBook < ActiveRecord::Base has_and_belongs_to_many :my_readers end class HabtmJoinTableTest < ActiveRecord::TestCase def setup ActiveRecord::Base.connection.create_table :my_books, :force => true do |t| t.string :name end assert ActiveRecord::Base.connection.table_exists?(:my_books) ActiveRecord::Base.connection.create_table :my_readers, :force => true do |t| t.string :name end assert ActiveRecord::Base.connection.table_exists?(:my_readers) ActiveRecord::Base.connection.create_table :my_books_my_readers, :force => true do |t| t.integer :my_book_id t.integer :my_reader_id end assert ActiveRecord::Base.connection.table_exists?(:my_books_my_readers) end def teardown ActiveRecord::Base.connection.drop_table :my_books ActiveRecord::Base.connection.drop_table :my_readers ActiveRecord::Base.connection.drop_table :my_books_my_readers end uses_transaction :test_should_raise_exception_when_join_table_has_a_primary_key def test_should_raise_exception_when_join_table_has_a_primary_key if ActiveRecord::Base.connection.supports_primary_key? assert_raise ActiveRecord::ConfigurationError do jaime = MyReader.create(:name=>"Jaime") jaime.my_books << MyBook.create(:name=>'Great Expectations') end end end uses_transaction :test_should_cache_result_of_primary_key_check def test_should_cache_result_of_primary_key_check if ActiveRecord::Base.connection.supports_primary_key? ActiveRecord::Base.connection.stubs(:primary_key).with('my_books_my_readers').returns(false).once weaz = MyReader.create(:name=>'Weaz') weaz.my_books << MyBook.create(:name=>'Great Expectations') weaz.my_books << MyBook.create(:name=>'Greater Expectations') end end end
module Mastermind class Result attr_accessor :line def initialize(line) @line = line end def <=>(other) score <=> other.score end def score [rounds, seconds] end def rounds @line[/\d+ rounds/].to_i end def seconds @line[/\d+ seconds/].to_i end end end
class Neighbor < ActiveRecord::Base belongs_to :neighbor, :class_name => 'Household' belongs_to :household before_create :set_default_read def set_default_read #self.read = "f" end def send_neighbor_request_email(neighbor) @users = User.find(:all, :conditions => {:household_id => neighbor.neighbor_id, :household_confirmed => true}) for user in @users UserMailer.deliver_neighbor_request_email(self, user) end end def send_neighbor_confirmation_email(neighbor) @users = User.find(:all, :conditions => {:household_id => neighbor.neighbor_id, :household_confirmed => true}) for user in @users UserMailer.deliver_neighbor_confirmation_email(self, user) end end def self.can_render?(neighbors) true if neighbors.count > 0 end end
module ScorchedEarth module Subscribers module NextPlayer def setup super event_runner.subscribe(Events::MouseReleased) do |_event| @players = players.rotate! end end end end end
# Control series where on player has a secret which the other guesses class SecretBased < Controller private def setup_round @series.new_game(@id_of_leader) @series.choose_secret(@id_of_leader ^ 1) end def play_round game_over ||= @series.take_turn(@id_of_leader) until game_over game_over == 'saved' || stop_playing? end def midgame?(midgame_data) @midgame = !midgame_data.empty? end end
class CreateTasks < ActiveRecord::Migration def change create_table :tasks do |t| t.string :name t.string :description t.datetime :time t.integer :duration t.string :regulars t.boolean :ready t.integer :user_id t.timestamps end add_index :tasks, :user_id add_index :tasks, :regulars add_index :tasks, :name end end
# frozen_string_literal: true class AddRelationToInvoice < ActiveRecord::Migration[4.2] def change add_column :registration_groups, :invoice_id, :integer add_foreign_key :registration_groups, :invoices end end
require 'application_system_test_case' class UserFlowsTest < ApplicationSystemTestCase setup :setup_omniauth, :setup_auth_hash test 'log in with facebook and subscribe to calendar' do visit root_path click_button I18n.t(:login) assert_selector '#subscribe-button' click_button I18n.t(:subscribe) end end
can_compile_extensions = false begin require 'mkmf' can_compile_extensions = true rescue Exception # This will appear only in verbose mode. $stderr.puts "Could not require 'mkmf'. Not fatal, the extensions are optional." end if can_compile_extensions && have_header('ruby.h') extension_name = 'ccurl' dir_config(extension_name) # The destination create_makefile(extension_name) # Create Makefile else # Create a dummy Makefile, to satisfy Gem::Installer#install mfile = open("Makefile", "wb") mfile.puts '.PHONY: install' mfile.puts 'install:' mfile.puts "\t" + '@echo "Extensions not installed, falling back to pure Ruby version."' mfile.close end
# Ask user for info # use gets chomp to store their response as the value in a certain key in the hash # have hash already set up with keys and empty values # puts user information out as list after all questions have been answered # ask user if they would like to modify answers # if yes then ask them to enter in the key whose value to modify # if no then skip # print final updated version of hash client_hash = { name: nil, age: nil, children: nil, decor_theme: nil, likes_yellow: nil } puts "Name:" client_hash[:name] = gets.chomp puts "Age:" client_hash[:age] = gets.chomp.to_i puts "Number of children:" client_hash[:children] = gets.chomp.to_i puts "Decor theme:" client_hash[:decor_theme] = gets.chomp puts "Do you like the color yellow? Please type 'yes' or 'no':" likes_yellow = gets.chomp if likes_yellow == "yes" client_hash[:likes_yellow] = TRUE elsif likes_yellow == "no" client_hash[:likes_yellow] = false else client_hash[:likes_yellow] = nil end puts client_hash puts "Please enter the key of a value you would like to update (or type 'none' if you are happy with your results)" update = gets.chomp if update == "none" puts client_hash else puts "Please enter your updated value:" updated_value = gets.chomp update = update.to_sym if update == :age client_hash[:age] = updated_value.to_i elsif update == :children client_hash[:children] = updated_value.to_i elsif update == :likes_yellow if updated_value == "yes" client_hash[:likes_yellow] = TRUE elsif updated_value == "no" client_hash[:likes_yellow] = false else client_hash[:likes_yellow] = nil end else client_hash[update] = updated_value end puts client_hash end
require 'sinatra/base' require 'erb' # use Erb templates require 'httparty' require 'nokogiri' require 'mongoid' require 'mongoid_token' require 'mongoid-pagination' require 'addressable/uri' Mongoid.load!('./mongoid.yml', (ENV['RACK_ENV'] || 'development')) class Takeover include Mongoid::Document include Mongoid::Timestamps include Mongoid::Token include Mongoid::Pagination field :html, type: String field :url, type: String token length: 4 end class PageParser def initialize(url, urtak_code, selector, selector_type, ad_rotation, cads) @url = Addressable::URI.parse url @urtak_code = urtak_code @selector = selector @selector_type = selector_type @ad_rotation = ['1', 'true', 'on'].include? ad_rotation.to_s @custom_ads = cads # Let's party! response = HTTParty.get @url # Nokogirize! (And handle edge case.) @doc = Nokogiri::HTML scrub_docwrite_scripts response.body end def fetch_clean_and_takeover! insert_urtak_script! make_links_absolute! hack_aol_ad_server! hack_pagespeed_lazy_src! if @ad_rotation insert_fugger_script! end add_urtak! end def html @doc.to_html end attr_reader :url private def scrub_docwrite_scripts(body) body.gsub %Q{+ "'></script"}, %Q{+ "'></" + "script"} end def add_urtak! if @selector =~ /[^[:space:]]/ ele = (@doc.css @selector).first if ele if @selector_type == 'append' ele.add_next_sibling "<div>#{@urtak_code}</div>" elsif @selector_type == 'replace' new_node = @doc.create_element 'div' new_node.inner_html = @urtak_code ele.replace new_node end end end end CLR = "https://d39v39m55yawr.cloudfront.net/assets/clr.js" FUGGER = "https://d39v39m55yawr.cloudfront.net/assets/fugger.js" # CLR = "http://urtak.dev/assets/clr.js" # FUGGER = "http://urtak.dev/assets/fugger.js" DEFAULT_ADS = %Q{ <img src="/img/ad-rotation/1.png"/> <img src="/img/ad-rotation/2.png"/> <img src="/img/ad-rotation/3.png"/> <img src="/img/ad-rotation/4.png"/> <img src="/img/ad-rotation/5.png"/> <img src="/img/ad-rotation/6.png"/> <img src="/img/ad-rotation/7.png"/> <img src="/img/ad-rotation/8.png"/> } # Insert Urtak script into head. def insert_urtak_script! head.add_child(%Q{ <script src="#{CLR}" type="text/javascript"></script> }) end def ad_tags ads = @custom_ads =~ /[^[:space:]]/ ? @custom_ads : DEFAULT_ADS %Q{ <div style="display:none;"> #{ads} </div> }.gsub('"', '\"').gsub("\n", '').gsub(/\s+/, ' ').strip end def insert_fugger_script! head.add_child(%Q{ <script src="#{FUGGER}" type="text/javascript"></script> }) head.add_child(%Q{ <script type="text/javascript"> window.Urtak2.createRotation("#{ad_tags}"); </script> }) head.add_child(%Q{ <script type="text/javascript"> if (!window.__urtak_hooks__) { window.__urtak_hooks__ = [] } window.__urtak_hooks__.push(function (opts) { if (opts.action === "response") { if (!window.__urtak_counter__) { window.__urtak_counter__ = 0; } r = window.Urtak2.$("[id^=urtak-rotation]"); r.css("z-index", 100000); r.find("img").hide(); r.find("img:eq(" + window.__urtak_counter__ + ")").show(); r.find("div").show(); window.__urtak_counter__ += 1; if (window.__urtak_counter__ === r.find("img").size()) { window.__urtak_counter__ = 0; } } }); </script> }) end def head @head ||= (@doc.css 'head').first end def make_links_absolute! (@doc.css '*[href]').each { |ele| process_ele_url!(ele, :href) } (@doc.css '*[src]').each { |ele| process_ele_url!(ele, :src) } end def process_ele_url!(ele, attribute) # If href does not start with "http" or "//"... unless full_url? ele[attribute] # For leading slashes we only need the domain. For relative urls we # need the path. if ele[attribute][0] == '/' ele[attribute] = "#{url_host}#{ele[attribute]}" else ele[attribute] = "#{url_with_path_and_slash}#{ele[attribute]}" end end end def full_url?(url) url =~ %r{^(https?:)?//} ? true : false end def url_host @url_host ||= "#{@url.scheme}://#{@url.host}" end def url_with_path_and_slash @url_with_path_and_slash ||= begin url = "#{url_host}#{@url.path}" url = "#{url}/" if url[-1] != '/' url end end def hack_aol_ad_server! s = (@doc.search 'script').detect { |node| node.content =~ /adSetAdURL/ } if s s.content = s.content.gsub( /adSetAdURL\("(.*?)"\)/, "adSetAdURL(\"#{@url_host}\\1\")" ) end end def hack_pagespeed_lazy_src! (@doc.css 'img[pagespeed_lazy_src]').each do |img| img['src'] = img['pagespeed_lazy_src'] end end end class App < Sinatra::Base configure :development do require 'ruby-debug' end helpers do def h(text) Rack::Utils.escape_html(text) end end get '/' do erb :index end get '/takeovers' do @takeovers = Takeover.paginate(page: params[:page]) erb :takeovers end get '/:token' do begin (Takeover.find_by_token params[:token]).html rescue Mongoid::Errors::DocumentNotFound pass end end post '/' do page_parser = PageParser.new params[:url], params[:urtak], params[:selector], params[:selector_type], params[:ad_rotation], params[:custom_ads] page_parser.fetch_clean_and_takeover! takeover = Takeover.create html: page_parser.html, url: page_parser.url redirect "/#{takeover.token}" end end
RSpec.describe Api::V1::AuthController, type: :controller do describe 'POST #create' do let!(:resource) { create(%i[client staff].sample, password: 'password') } context 'valid credentials' do let(:valid_params) { { email: resource.email, password: 'password', scope: resource.class.to_s } } it 'login by email and password' do post :create, params: valid_params body = JSON(response.body)['data'] expect(response).to have_http_status(:success) expect(body.keys).to eq(%w[access_token refresh_token expires_at]) end end context 'invalid credentials' do let(:invalid_password) { { email: resource.email, password: 'wrong_password', scope: resource.class.to_s } } let(:invalid_email) { { email: 'test@test.com', password: 'password', scope: resource.class.to_s } } it 'wrong email' do post :create, params: invalid_email body = JSON(response.body)['errors'] expect(response).to have_http_status(404) expect(body).to eq(['User not found']) end it 'wrong password' do post :create, params: invalid_password body = JSON(response.body)['errors'] expect(response).to have_http_status(401) expect(body).to eq(['Incorrect Email/Passoword']) end end end describe 'POST #refresh_token' do let(:refresh_token) { SecureRandom.uuid } let(:resource_refresh_tokens) { { refresh_token => Time.now.to_i + 100 } } context 'valid credentials' do let!(:resource) { create(%i[client staff].sample, refresh_tokens: resource_refresh_tokens) } let(:valid_params) { { refresh_token: refresh_token, scope: resource.class.to_s } } it 'get new tokens by refresh_token' do post :refresh_token, params: valid_params body = JSON(response.body)['data'] expect(response).to have_http_status(:success) expect(body.keys).to eq(%w[access_token expires_at]) end end context 'invalid credentials' do let!(:resource) { create(%i[client staff].sample, refresh_tokens: resource_refresh_tokens) } let(:invalid_token_params) { { refresh_token: SecureRandom.uuid, scope: resource.class.to_s } } let(:expired_refresh_token) { SecureRandom.uuid } let(:expired_token_resource) { create(%i[client staff].sample, refresh_tokens: { expired_refresh_token => Time.now.to_i - 100 }) } let(:expired_token_params) { { refresh_token: expired_refresh_token, scope: resource.class.to_s } } it 'wrong token' do post :refresh_token, params: invalid_token_params body = JSON(response.body)['errors'] expect(response).to have_http_status(401) expect(body).to eq(['Invalid refresh token']) end it 'expired token' do post :refresh_token, params: expired_token_params body = JSON(response.body)['errors'] expect(response).to have_http_status(401) expect(body).to eq(['Invalid refresh token']) end end end end
module WsdlMapper module Dom class Documentation attr_reader :default attr_accessor :app_info def initialize(text = nil) @default = text end def present? !@default.nil? end end end end
module Faker class Class < Base flexible :class class << self def name parse('class.name') end def prefix; fetch('class.prefix'); end def subject; fetch('class.subject'); end end end end
# Definition for a binary tree node. # class TreeNode # attr_accessor :val, :left, :right # def initialize(val) # @val = val # @left, @right = nil, nil # end # end # @param {TreeNode} root # @param {Integer} sum # @return {Boolean} def has_path_sum(root, sum) if root == nil false else dfs(root, sum) end end def dfs(root, sum) sum -= root.val if not (root.left || root.right) sum == 0 elsif root.left && root.right dfs(root.left, sum) || dfs(root.right, sum) elsif root.left dfs(root.left, sum) else dfs(root.right, sum) end end
require 'rspec' require 'hyperclient' require 'json' # silence rantly output ENV['RANTLY_VERBOSE'] = '0' HAL = 'application/hal+json' HAL_REGEX = Regexp.escape(HAL) HTTP_OK = 200 TEST_DEBUG = ENV['TEST_DEBUG'] def api_root ENV['API_ROOT_URL'] || (raise RuntimeError.new('API_ROOT_URL is not set')) end def root_resource(resource_name) api_client = Hyperclient.new(api_root) do |c| c.connection do |conn| conn.adapter Faraday.default_adapter conn.response :json, :content_type => 'application/hal+json' conn.response :logger if TEST_DEBUG end end api_client.headers['Content-Type'] = 'application/json' resource = api_client._links.item.find { |item| item._url =~ %r{/#{resource_name}$} } unless resource msg = "#{resource_name.to_s.capitalize} API _link cannot be found." raise RuntimeError.new(msg) end resource end def api_conn Faraday.new(:url => api_root) do |builder| builder.adapter Faraday.default_adapter builder.response :json, :content_type => 'application/hal+json' builder.response :logger if TEST_DEBUG end end def test_file(name) File.open( File.join( File.dirname(File.expand_path(__FILE__)), 'test_data', name ), :ext_enc => Encoding::UTF_8 ) end def post_and_get(content, url) data = case when content.respond_to?(:read) content.read when content.respond_to?(:each_pair) JSON.dump(content) else content.to_s end response = api_conn.post(url) { |req| req.headers['Content-Type'] = 'application/json; charset=utf-8' req.body = data } location = response['Location'] response = api_conn.get location if block_given? begin yield response ensure api_conn.delete location end else response end end
class User < ApplicationRecord rolify # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable #:confirmable #ROLES = %w[admin manager hr employee].freeze has_and_belongs_to_many :roles, :join_table => :users_roles mount_uploader :img_url, ImageUploader validates_processing_of :img_url validate :image_size_validation def admin? has_role?(:admin) end def manager? has_role?(:manager) end def hr? has_role?(:hr) end def employee? has_role?(:employee) end private def image_size_validation errors[:img_url] << "should be less than 500KB" if img_url.size > 0.5.megabytes end end
FactoryBot.define do factory :reservationc do name { "MyString" } start_time { "2020-12-14 13:55:12" } end end
class Book < ActiveRecord::Base has_and_belongs_to_many :authors # attr_accessible :title, :description validates :title, :presence => true # def self.search(search) # find(:all, :conditions => ['title LIKE ?', "#{search}"]) # end def self.search(search) if search where('title LIKE ?', "%#{search}%") else scoped end end end
# frozen_string_literal: true require 'spec_helper' require 'et_azure_insights/adapters/rack' require 'et_azure_insights' require 'rack/mock' RSpec.describe EtAzureInsights::Adapters::Rack do include_context 'fake client' let(:fake_app_response) { [200, {}, 'app-body'] } let(:fake_app) { spy('Rack app', call: fake_app_response) } let(:fake_request_env) { Rack::MockRequest.env_for('http://www.dummy.com/endpoint?test=1') } subject(:rack) { described_class.new(fake_app) } describe '#call' do it 'calls the app' do rack.call(fake_request_env, client: fake_client) expect(fake_app).to have_received(:call).with(fake_request_env) end it 'returns what the app returns' do result = rack.call(fake_request_env, client: fake_client) expect(result).to eq fake_app_response end it 'calls track_request on the telemetry client' do rack.call(fake_request_env, client: fake_client) expect(fake_client).to have_received(:track_request) end it 'calls track_request with the correct request id' do rack.call(fake_request_env, client: fake_client) expect(fake_client).to have_received(:track_request).with(match(/\A\|[0-9a-f]{32}\.[0-9a-f]{16}\.\z/), anything, anything, anything, anything, anything) end it 'calls track_request with the correct status' do rack.call(fake_request_env, client: fake_client) expect(fake_client).to have_received(:track_request).with(anything, anything, anything, '200', anything, anything) end context 'with string status code' do let(:fake_app_response) { ['200', {}, 'app-body'] } it 'calls track_request with the correct status' do rack.call(fake_request_env, client: fake_client) expect(fake_client).to have_received(:track_request).with(anything, anything, anything, '200', anything, anything) end end context 'with non numeric string status code' do let(:fake_app_response) { ['wrongvalue', {}, 'app-body'] } it 'calls track_request with zero status' do rack.call(fake_request_env, client: fake_client) expect(fake_client).to have_received(:track_request).with(anything, anything, anything, '0', anything, anything) end end it 'calls track_request with the correct operation id' do expect(fake_app).to receive(:call) do |env| expect(fake_client_operation).to have_received(:id=).with(match(/\A\|[0-9a-f]{32}\./)) fake_app_response end rack.call(fake_request_env, client: fake_client) end it 'calls track_request with the correct operation id supplied from ActionDispatch::RequestId middleware if in use in rails or similar environment' do expect(fake_app).to receive(:call) do |env| expect(fake_client_operation).to have_received(:id=).with('|c1b40e908df64ed1b27e4344c2557642.') fake_app_response end rack.call(fake_request_env.merge('action_dispatch.request_id' => 'c1b40e90-8df6-4ed1-b27e-4344c2557642'), client: fake_client) end it 'sets the operation parent id set to the request id' do expected_request_id = nil expect(fake_app).to receive(:call) do |env| expect(fake_client_operation).to have_received(:parent_id=) do |val| expected_request_id = val end fake_app_response end subject.call(fake_request_env, client: fake_client) expect(fake_client).to have_received(:track_request).with(expected_request_id, anything, anything, anything, anything, anything) end it 'calls track_request with the correct operation name' do expect(fake_app).to receive(:call) do |env| expect(fake_client_operation).to have_received(:name=).with('GET /endpoint') fake_app_response end rack.call(fake_request_env, client: fake_client) end context 'error handling when error is raised in app' do it 'calls track_exception on the telemetry client with the exception if the app raises an exception' do allow(fake_app).to receive(:call).and_raise(RuntimeError, 'Fake error message') begin rack.call(fake_request_env, client: fake_client) rescue StandardError RuntimeError end expect(fake_client).to have_received(:track_exception) .with(an_instance_of(RuntimeError).and(have_attributes(message: 'Fake error message')),) end it 'calls track_exception on the telemetry client with the correct context if the app raises an exception' do allow(fake_app).to receive(:call).and_raise(RuntimeError, 'Fake error message') begin rack.call(fake_request_env, client: fake_client) rescue StandardError RuntimeError end expect(fake_client_operation).to have_received(:id=).with(match(/\A\|[0-9a-f]{32}\./)).at_least(:once) expect(fake_client).to have_received(:track_exception) end it 'calls track_request on the telemetry client even after an exception but with success of false' do allow(fake_app).to receive(:call).and_raise(RuntimeError, 'Fake error message') begin rack.call(fake_request_env, client: fake_client) rescue StandardError RuntimeError end expect(fake_client).to have_received(:track_request).with(anything, anything, anything, '500', false, anything) end it 're raises the original exception' do allow(fake_app).to receive(:call).and_raise(RuntimeError, 'Fake error message') expect { rack.call(fake_request_env, client: fake_client) }.to raise_exception(RuntimeError, 'Fake error message') end it 'keeps the original current span from before the call' do allow(fake_app).to receive(:call).and_raise(RuntimeError, 'Fake error message') original_span = EtAzureInsights::Correlation::Span.current begin rack.call(fake_request_env, client: fake_client) rescue StandardError RuntimeError end expect(EtAzureInsights::Correlation::Span.current).to be original_span end end context 'error handling when error has been caught upstream so is not raised' do let(:fake_app_response) { [500, {}, 'Fake error message'] } it 'calls track_exception on the telemetry client with the exception if the app raises an exception' do rack.call(fake_request_env, client: fake_client) expect(fake_client).to have_received(:track_exception) .with(an_instance_of(RuntimeError).and(have_attributes(message: 'Fake error message'))) end it 'calls track_exception on the telemetry client with the correct context if the app raises an exception' do rack.call(fake_request_env, client: fake_client) expect(fake_client_operation).to have_received(:id=).with(match(/\A\|[0-9a-f]{32}\./)).at_least(:once) expect(fake_client).to have_received(:track_exception) end it 'calls track_request on the telemetry client even after an exception but with success of false' do rack.call(fake_request_env, client: fake_client) expect(fake_client).to have_received(:track_request).with(anything, anything, anything, '500', false, anything) end it 'keeps the original current span from before the call' do original_span = EtAzureInsights::Correlation::Span.current rack.call(fake_request_env, client: fake_client) expect(EtAzureInsights::Correlation::Span.current).to be original_span end end context 'with traceparent header set suggesting this has been called by something else' do # Some rules # The request id contains |<root>.<parent>.<this-request-id>. # The operation id is just |<root>| # The parent id for the operation is |<root>.<parent>. let(:fake_traceparent) { '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01' } let(:fake_request_env) { Rack::MockRequest.env_for('http://www.dummy.com/endpoint?test=1', 'HTTP_TRACEPARENT' => fake_traceparent) } it 'calls track_dependency with the current operation data set' do rack.call(fake_request_env, client: fake_client) expect(fake_client_operation).to have_received(:id=).with('|4bf92f3577b34da6a3ce929d0e0e4736.').at_least(:once) expect(fake_client_operation).to have_received(:parent_id=).with('|4bf92f3577b34da6a3ce929d0e0e4736.00f067aa0ba902b7.') expect(fake_client_operation).to have_received(:name=).with('GET /endpoint').at_least(:once) expect(fake_client).to have_received(:track_request) end it 'calls track_dependency with the request id in the correct format' do rack.call(fake_request_env, client: fake_client) expect(fake_client).to have_received(:track_request).with(match(/\A\|[0-9a-f]{32}\.[0-9a-f]{16}\.\z/), anything, anything, anything, anything, anything) end it 'calls track_dependency with the request id that does not end with the parent' do rack.call(fake_request_env, client: fake_client) expect(fake_client).to have_received(:track_request).with(satisfy {|s| !s.end_with?('00f067aa0ba902b7.')}, anything, anything, anything, anything, anything) end end end end
class AddLocationIdToSharePrizes < ActiveRecord::Migration def change # In the existing code, a Location can share a prize with a user # (see the 'add_prize_user' method in NotificationController). # This isn't ideal, but refactoring will be a substantial effort, # so the easiest solution is to add a location_id column to # track which locations are sharing which prizes. add_column :share_prizes, :location_id, :integer, index: true end end
# frozen_string_literal: true module CodebreakerVk class Game include Output SECRET_CODE_LENGTH = 4 RANGE_START = 1 RANGE_END = 6 NOT_YET = '-' GOT_IT = '+' DIFFICULTY_LEVEL = { easy: { attempts: 15, hints: 3 }, medium: { attempts: 10, hints: 2 }, hell: { attempts: 5, hints: 1 } }.freeze attr_accessor :attempts_total, :attempts, :difficulty, :hints_total, :hints, :name, :secret def initialize(name:, difficulty:) @name = name @difficulty = difficulty @attempts = DIFFICULTY_LEVEL[difficulty][:attempts] @hints = DIFFICULTY_LEVEL[difficulty][:hints] @secret = make_number @unused_hints = @secret.chars end def make_number(numbers = RANGE_END) (1..SECRET_CODE_LENGTH).map { rand(RANGE_START..numbers) }.join end def check(number) @attempts -= 1 @last_result = check_numbers(@secret.chars, number.chars) end def win? @last_result == GOT_IT * SECRET_CODE_LENGTH end def use_hint return I18n.t(:no_hints) unless @hints.positive? @hints -= 1 hint(@unused_hints) end private def check_numbers(secret, numbers) exact_matches, non_exact_matches = secret.zip(numbers).partition do |secret_number, input_number| secret_number == input_number end result = Array.new(exact_matches.count, GOT_IT) find_non_exact_matches(result, non_exact_matches) if non_exact_matches.any? result.join end def find_non_exact_matches(result, non_exact_matches) secret, numbers = non_exact_matches.transpose numbers.each do |number_element| next unless secret.include? number_element result.push(NOT_YET) && secret.delete_at(secret.index(number_element)) end end def hint(secret) secret.shuffle.pop end end end
class CreateExhibitionsTags < ActiveRecord::Migration def change create_table :exhibitions_tags, :id => false do |t| t.references :exhibition, index: true, foreign_key: true t.references :tag, index: true, foreign_key: true end end end
require 'formula' class Mdxmini < Formula homepage 'http://clogging.web.fc2.com/psp/' url 'https://github.com/BouKiCHi/mdxplayer/archive/9afbc01f60a12052817cb14a81a8c3c976953506.tar.gz' version '20130115' sha1 '8ca3b597f009ee7de697329e26b9f3c402dda173' option "lib-only", "Do not build commandline player" depends_on 'sdl' unless build.include? "lib-only" def install cd "jni/mdxmini" do # Specify Homebrew's cc inreplace "mak/general.mak", "gcc", ENV.cc if build.include? "lib-only" system "make -f Makefile.lib" else system "make" end # Makefile doesn't build a dylib system "#{ENV.cc} -dynamiclib -install_name #{lib}/libmdxmini.dylib -o libmdxmini.dylib -undefined dynamic_lookup obj/*.o" bin.install "mdxplay" unless build.include? "lib-only" lib.install "libmdxmini.a", "libmdxmini.dylib" (include+'libmdxmini').install Dir['src/*.h'] end end end
class AddIndexForMediaEventCaliperEventReference < ActiveRecord::Migration[5.0] disable_ddl_transaction! def change add_index :media_events, :caliper_event_id, algorithm: :concurrently end end
class PollsController < ApplicationController before_action :set_poll, only: [:show, :edit ,:update ,:destroy] def index @polls = Poll.where(user_id: params[:user_id]) if session[:flag]==0 redirect_to poll_index1_path(params[:user_id]) end end def index1 @polls = Poll.where(user_id: params[:user_id]) end def new @poll = Poll.new session[:flag]=0 end def edit @poll = Poll.find(params[:id]) print(@poll.topic) end def richi @poll = Poll.find(params[:id]) if @poll.update_attributes(poll_params) flash[:success] = 'Poll was updated!' redirect_to user_poll_path(params[:user_id],@poll.id) else render 'edit' end end def update @poll = Poll.find(params[:id]) if @poll.update_attributes(poll_params) flash[:success] = 'Poll was updated!' redirect_to signup_path else render 'edit' end end def destroy @poll = Poll.find(params[:id]) session[:flag]=0 if @poll.destroy flash[:success] = 'Poll was destroyed!' else flash[:warning] = 'Error destroying poll...' end redirect_to user_polls_path end def create @poll = Poll.new(poll_params) @poll.user_id=params[:user_id] if @poll.save! flash[:success] = 'Poll was created!' redirect_to user_polls_path else render 'new' end end def show @poll = Poll.includes(:vote_options).find_by_id(params[:id]) end private def set_poll @poll=Poll.find(params[:id]) end def poll_params params.require(:poll).permit(:topic, vote_options_attributes: [:id, :title, :_destroy]) end end
class CreateCoders < ActiveRecord::Migration[5.1] def change create_table :coders do |t| t.text :first_name t.text :last_name t.text :about t.text :looking_for t.text :img_url t.timestamps end end end
class SkillsController < ApplicationController before_action :authenticate_user! def index @skills = current_user.skills.order(:id) if current_user @skill = Skill.new end def new @skill = Skill.new(user: current_user) @small_target = Target.new() end def edit @skill = Skill.find(params[:id]) @small_target = Target.new() end def create @skill = Skill.new(skill_params) if @skill.save # Poprawić to na dole redirect_to edit_skill_path(@skill.id) else flash[:error] = 'Coś poszło nie tak, spróbuj ponownie.' render 'index' end end def destroy @skill = Skill.find(params[:id]) if @skill.delete redirect_to skills_path end end def update @skill = Skill.find(params[:id]) targets = params[:skill][:small_targets].split(" ").map(&:to_i) targets.each do |target_id| target = Target.find(target_id) @skill.small_targets << target end if @skill.update(skill_params) redirect_to skills_path else flash[:error] = 'Coś poszło nie tak, spróbuj ponownie.' render 'index' end end private def skill_params params.require(:skill).permit(:name, :user_id, :big_target) end end
# 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) Owner.destroy_all Car.destroy_all Garage.destroy_all 25.times do o = Fabricate :owner g = Fabricate :garage c = Fabricate(:car, owner_id: o.id, garage_id: g.id) end
class Task < ActiveRecord::Base attr_accessible :complete, :name, :id belongs_to :user end
# Operator Overloading class Animal attr_accessor:name,:trait def initialize(name, trait) @name = name @trait = trait end #Operator overloading def + (other_object) return Animal.new("#{self.name}#{other_object.name}", "#{self.trait}#{other_object.trait}") # we can access object a by using self keyword end end class Zebra < Animal end a = Zebra.new("shreks", "fun") b = Zebra.new("smart", "youtube") #puts (a + b).inspect #This is operator overloading, invokes the method def + (other_object). Operator overloading allow us to add two user defined data types like objects # Operator overloading part 2 # "<", ">", "=" Comparable operators class MyClass include Comparable # include statements are used to include Ruby files, here we include Comparable module which is pre-defined module attr_accessor:myname def initialize(name) @myname = name end def <=>(other) self.myname<=>other.myname end end #puts "Shreks"<=>"Singh" #When <=> is encountered then def <=> method is called, and we are comparing the two values in that method #puts 100 <=> 20 obj = MyClass.new("Apple") obj2 = MyClass.new("Banana") #puts obj > obj2 #puts obj < obj2 #puts obj == obj2 #puts obj != obj2 # Operator overloading part 3 # "+", "-", "*", "/", "%", "**" operators class Tester attr_accessor:num def initialize(num) @num = num end def +(other) return self.num + other.num end def *(other) return self.num * other.num end def /(other) return self.num / other.num end def %(other) return self.num % other.num end def **(other) return self.num ** other.num end end a = Tester.new(5) b = Tester.new(3) #puts a + b # when this statement is executed then it will call +(other) function, other gets the value of 3, other is acting as fix number or integer value #puts a * b #puts a / b #puts a % b #puts a ** b # 5^3, ** = ^ (Exponential) # Operator overloading part 4 # "[]", "[]=", "<<" Operators using Array class Tester attr_accessor:arr def initialize(*arr) @arr = arr end def [] (x) return @arr[x] end def []=(x, value) @arr[x] = value end def <<(x) @arr << x end end a = Tester.new(0,1,2,3) puts a[3] a << 97 puts a[4] a[5] = 101 puts a[5]
class H0200b attr_reader :options, :name, :field_type, :node def initialize @name = "Urinary Toileting Program: Response - What was the resident's response to the trial program? (H0200b)" @field_type = RADIO @node = "H0200B" @options = [] @options << FieldOption.new("^", "NA") @options << FieldOption.new("0", "No improvement") @options << FieldOption.new("1", "Completely dry (continent)") @options << FieldOption.new("9", "Unable to determine or trial in progress") end def set_values_for_type(klass) return "^" end end
class AddUserIdToKingbehemoth < ActiveRecord::Migration[5.2] def change add_column :kingbehemoths, :user_id, :string end end
FactoryGirl.define do factory :user do sequence(:email) {|n| "email#{n}@gmail.com" } username "cartman" first_name "jeez" last_name "shit" password "123456" end factory :question do title 'What is this?' body 'don doodie' user_id 1 end end
require 'spec_helper' describe Jobs::TransactionCancellationJob do before(:each) do resource_method_is_speced_in_resource_mixin_spec end def stub_perform stub_find(mock_cancellation) mock_cancellation.stub \ :cancelled? => true, :transaction => mock_transaction, :url => 'http://example.com/cancellations', :cancelled! => true mock_transaction.stub :uri => 'http://example.com/transaction/uri' mock_resource.stub :post => nil end def mock_resource @mock_resource ||= mock(RestClient::Resource) end subject { Jobs::TransactionCancellationJob.new(mock_cancellation.to_param)} def stub_perform_on_cancelled_transaction stub_perform mock_transaction.stub :stopped? => false end it "should be stopped!" do stub_perform_on_cancelled_transaction mock_cancellation.should_receive :cancelled! subject.perform end it "should post a cancellation request to localhost" do stub_perform_on_cancelled_transaction subject.should_receive(:resource).with(mock_cancellation).once subject.perform end it "should post a cancellation request with the transaction uri" do stub_perform_on_cancelled_transaction mock_resource.should_receive(:post).with(hash_including(:transaction_uri => mock_transaction.uri)).once subject.perform end def resource_method_is_speced_in_resource_mixin_spec subject.stub :resource => mock_resource end end
require 'spec_helper' describe ServiceManager do let(:service_name) { 'wordpress' } let(:image_name) { 'some_image' } let(:service_description) { 'A wordpress service' } let(:service_state) do { 'node' => { 'value' => '{"loadState":"loaded"}' } } end let(:fake_fleet_client) do double( :fake_fleet_client, submit: true, load: true, start: true, stop: true, destroy: true ) end let(:service) do Service.new( name: service_name, description: service_description, from: image_name ) end subject { described_class.new(service) } before do allow(Fleet).to receive(:new).and_return(fake_fleet_client) end describe '.load' do let(:dummy_manager) { double(:dummy_manager, load: true) } before do allow(described_class).to receive(:new).and_return(dummy_manager) end it 'news an instance of itself' do expect(described_class).to receive(:new).with(service).and_return(dummy_manager) described_class.load(service) end it 'invokes load on manager instance' do expect(dummy_manager).to receive(:load) described_class.load(service) end end describe '.start' do let(:dummy_manager) { double(:dummy_manager, start: true) } before do allow(described_class).to receive(:new).and_return(dummy_manager) end it 'news an instance of itself' do expect(described_class).to receive(:new).with(service).and_return(dummy_manager) described_class.start(service) end it 'invokes start on manager instance' do expect(dummy_manager).to receive(:start) described_class.start(service) end end describe '#submit' do let(:linked_to_service) { Service.new(name: 'linked_to_service') } let(:docker_run_string) { 'docker run some stuff' } before do service.links << ServiceLink.new( alias: 'DB', linked_to_service: linked_to_service ) allow(service).to receive(:docker_run_string).and_return(docker_run_string) end it 'submits a service definition to the fleet service' do expect(fake_fleet_client).to receive(:submit) do |name, service_def| expect(name).to eq service.unit_name expect(service_def).to eq( { 'Unit' => { 'Description' => service_description, 'After' => linked_to_service.unit_name, 'Requires' => linked_to_service.unit_name, }, 'Service' => { 'ExecStartPre' => "-/usr/bin/docker pull #{image_name}", 'ExecStart' => docker_run_string, 'ExecStop' => "-/usr/bin/docker stop #{service_name}", 'Restart' => 'always', 'RestartSec' => '10', 'TimeoutStartSec' => '5min' } } ) end subject.submit end it 'returns the result of the fleet call' do expect(subject.submit).to eql true end end describe '#load' do before do allow(fake_fleet_client).to receive(:get_unit_state) .and_return('systemdLoadState' => 'loaded') end it 'sends a destroy message to the fleet client' do expect(fake_fleet_client).to receive(:load).with(service.unit_name) subject.load end it 'polls the unit state' do expect(fake_fleet_client).to receive(:get_unit_state) .and_return('systemdLoadState' => 'loaded') subject.load end it 'returns the result of the fleet call' do expect(subject.load).to eql true end end [:start, :stop].each do |method| describe "##{method}" do it "sends a #{method} message to the fleet client" do expect(fake_fleet_client).to receive(method).with(service.unit_name) subject.send(method) end it 'returns the result of the fleet call' do expect(subject.send(method)).to eql true end end end describe '#destroy' do before do allow(fake_fleet_client).to receive(:get_unit_state) .and_raise(Fleet::NotFound, 'oops') end it 'sends a destroy message to the fleet client' do expect(fake_fleet_client).to receive(:destroy).with(service.unit_name) subject.destroy end it 'polls the unit state' do expect(fake_fleet_client).to receive(:get_unit_state) .and_raise(Fleet::NotFound, 'oops') subject.destroy end it 'returns the result of the fleet call' do expect(subject.destroy).to eql true end end describe '#get_state' do let(:fleet_state) do { 'systemdLoadState' => 'a', 'systemdActiveState' => 'b', 'systemdSubState' => 'c' } end before do allow(fake_fleet_client).to receive(:get_unit_state).and_return(fleet_state) end it 'retrieves service state from the fleet client' do expect(fake_fleet_client).to receive(:get_unit_state).with(service.unit_name) subject.get_state end it 'returns the states' do expect(subject.get_state).to eq(load_state: 'a', active_state: 'b', sub_state: 'c') end context 'when an error occurs while querying fleet' do before do allow(fake_fleet_client).to receive(:get_unit_state).and_raise('boom') end it 'returns an empty hash' do expect(subject.get_state).to eql({}) end end end end
require 'conways' describe Cell do context "#live?" do it "returns true when initialized as live" do cell = Cell.new(:state => :live) cell.live?.should be_true end it "returns false when initialized as dead" do cell = Cell.new(:state => :dead) cell.live?.should be_false end end context "when live with 0 live neighbours" do it "has a next state of dead" do cell = Cell.new(:state => :live, :neighbours => 0) cell.next_state.should == false end end context "when live with 2 neighbours" do it "has a next state of live" do cell = Cell.new(:state => :live, :neighbours => 2) cell.next_state.should == true end end end
class AddCommentedUserToNotification < ActiveRecord::Migration[5.0] def change add_column :notifications, :commented_user, :string end end
class Destination < ApplicationRecord has_many :reviews validates :city, :presence => true def self.search(x) where("city ILIKE ?", "%#{x}%") end # scope :search, ->(country) {( # where("country ilike ?", country ) # )} end
class AddReleaseYearInMovies < ActiveRecord::Migration[6.1] def change add_column :movies, :release_year, :integer end end
Rails.application.routes.draw do root to: "users#new" resources :users end