text stringlengths 10 2.61M |
|---|
require 'json'
require 'rack/app'
class MyApp < Rack::App
headers 'Access-Control-Allow-Origin' => '*',
'Access-Control-Expose-Headers' => 'X-My-Custom-Header, X-Another-Custom-Header'
serializer do |obj|
if obj.is_a?(String)
obj
else
JSON.dump(obj)
end
end
error StandardError, NoMethodError do |ex|
{ error: ex.message }
end
get '/bad/endpoint' do
no_method_error_here
end
desc 'hello word endpoint'
validate_params do
required 'words', class: Array, of: String,
desc: 'words that will be joined with space',
example: %w(dog cat)
required 'to', class: String,
desc: 'the subject of the conversation'
end
get '/validated' do
return "Hello #{validate_params['to']}: #{validate_params['words'].join(' ')}"
end
get '/' do
{ hello: 'word'}
end
mount MediaFileServer, to: "/assets"
mount Uploader, to: '/upload'
end
run MyApp
|
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
has_many :likes, as: :likeable
has_one :device_inf, dependent: :destroy
has_many :notifications, as: :notificable
end
|
Rails.application.routes.draw do
# Routes for the Product_at_store resource:
# CREATE
get '/product_at_stores/new', :controller => 'product_at_stores', :action => 'new', :as => 'new_product_at_store'
post '/product_at_stores', :controller => 'product_at_stores', :action => 'create', :as => 'product_at_stores'
# READ
get '/product_at_stores', :controller => 'product_at_stores', :action => 'index'
get '/product_at_stores/:id', :controller => 'product_at_stores', :action => 'show', :as => 'product_at_store'
# UPDATE
get '/product_at_stores/:id/edit', :controller => 'product_at_stores', :action => 'edit', :as => 'edit_product_at_store'
patch '/product_at_stores/:id', :controller => 'product_at_stores', :action => 'update'
# DELETE
delete '/product_at_stores/:id', :controller => 'product_at_stores', :action => 'destroy'
#------------------------------
# Routes for the Product_from_source resource:
# CREATE
get '/product_from_sources/new', :controller => 'product_from_sources', :action => 'new', :as => 'new_product_from_source'
post '/product_from_sources', :controller => 'product_from_sources', :action => 'create', :as => 'product_from_sources'
# READ
get '/product_from_sources', :controller => 'product_from_sources', :action => 'index'
get '/product_from_sources/:id', :controller => 'product_from_sources', :action => 'show', :as => 'product_from_source'
# UPDATE
get '/product_from_sources/:id/edit', :controller => 'product_from_sources', :action => 'edit', :as => 'edit_product_from_source'
patch '/product_from_sources/:id', :controller => 'product_from_sources', :action => 'update'
# DELETE
delete '/product_from_sources/:id', :controller => 'product_from_sources', :action => 'destroy'
#------------------------------
# Routes for the Product_at_store_from_source resource:
# CREATE
get '/product_at_store_from_sources/new', :controller => 'product_at_store_from_sources', :action => 'new', :as => 'new_product_at_store_from_source'
post '/product_at_store_from_sources', :controller => 'product_at_store_from_sources', :action => 'create', :as => 'product_at_store_from_sources'
# READ
get '/product_at_store_from_sources', :controller => 'product_at_store_from_sources', :action => 'index'
get '/product_at_store_from_sources/:id', :controller => 'product_at_store_from_sources', :action => 'show', :as => 'product_at_store_from_source'
# UPDATE
get '/product_at_store_from_sources/:id/edit', :controller => 'product_at_store_from_sources', :action => 'edit', :as => 'edit_product_at_store_from_source'
patch '/product_at_store_from_sources/:id', :controller => 'product_at_store_from_sources', :action => 'update'
# DELETE
delete '/product_at_store_from_sources/:id', :controller => 'product_at_store_from_sources', :action => 'destroy'
#------------------------------
# Routes for the Product_category resource:
# CREATE
get '/product_categories/new', :controller => 'product_categories', :action => 'new', :as => 'new_product_category'
post '/product_categories', :controller => 'product_categories', :action => 'create', :as => 'product_categories'
# READ
get '/product_categories', :controller => 'product_categories', :action => 'index'
get '/product_categories/:id', :controller => 'product_categories', :action => 'show', :as => 'product_category'
# UPDATE
get '/product_categories/:id/edit', :controller => 'product_categories', :action => 'edit', :as => 'edit_product_category'
patch '/product_categories/:id', :controller => 'product_categories', :action => 'update'
# DELETE
delete '/product_categories/:id', :controller => 'product_categories', :action => 'destroy'
#------------------------------
# Routes for the Favorite resource:
# CREATE
get '/favorites/new', :controller => 'favorites', :action => 'new', :as => 'new_favorite'
post '/favorites', :controller => 'favorites', :action => 'create', :as => 'favorites'
# READ
get '/favorites', :controller => 'favorites', :action => 'index'
get '/favorites/:id', :controller => 'favorites', :action => 'show', :as => 'favorite'
# UPDATE
get '/favorites/:id/edit', :controller => 'favorites', :action => 'edit', :as => 'edit_favorite'
patch '/favorites/:id', :controller => 'favorites', :action => 'update'
# DELETE
delete '/favorites/:id', :controller => 'favorites', :action => 'destroy'
#------------------------------
# Routes for the Source resource:
# CREATE
get '/sources/new', :controller => 'sources', :action => 'new', :as => 'new_source'
post '/sources', :controller => 'sources', :action => 'create', :as => 'sources'
# READ
get '/sources', :controller => 'sources', :action => 'index'
get '/sources/:id', :controller => 'sources', :action => 'show', :as => 'source'
# UPDATE
get '/sources/:id/edit', :controller => 'sources', :action => 'edit', :as => 'edit_source'
patch '/sources/:id', :controller => 'sources', :action => 'update'
# DELETE
delete '/sources/:id', :controller => 'sources', :action => 'destroy'
#------------------------------
# Routes for the Store resource:
# CREATE
get '/stores/new', :controller => 'stores', :action => 'new', :as => 'new_store'
post '/stores', :controller => 'stores', :action => 'create', :as => 'stores'
# READ
get '/stores', :controller => 'stores', :action => 'index'
get '/stores/:id', :controller => 'stores', :action => 'show', :as => 'store'
# UPDATE
get '/stores/:id/edit', :controller => 'stores', :action => 'edit', :as => 'edit_store'
patch '/stores/:id', :controller => 'stores', :action => 'update'
# DELETE
delete '/stores/:id', :controller => 'stores', :action => 'destroy'
#------------------------------
# Routes for the Product resource:
# CREATE
get '/products/new', :controller => 'products', :action => 'new', :as => 'new_product'
post '/products', :controller => 'products', :action => 'create', :as => 'products'
# READ
get '/products', :controller => 'products', :action => 'index'
get '/products/:id', :controller => 'products', :action => 'show', :as => 'product'
# UPDATE
get '/products/:id/edit', :controller => 'products', :action => 'edit', :as => 'edit_product'
patch '/products/:id', :controller => 'products', :action => 'update'
# DELETE
delete '/products/:id', :controller => 'products', :action => 'destroy'
#------------------------------
# Routes for the User resource:
# CREATE
# get '/users/new', :controller => 'users', :action => 'new', :as => 'new_user'
# post '/users', :controller => 'users', :action => 'create', :as => 'users'
# # READ
# get '/users', :controller => 'users', :action => 'index'
# get '/users/:id', :controller => 'users', :action => 'show', :as => 'user'
# # UPDATE
# get '/users/:id/edit', :controller => 'users', :action => 'edit', :as => 'edit_user'
# patch '/users/:id', :controller => 'users', :action => 'update'
# # DELETE
# delete '/users/:id', :controller => 'users', :action => 'destroy'
devise_for :users
devise_scope :user do
authenticated :user do
root :to => 'products#index', as: :authenticated_root
end
unauthenticated :user do
root :to => 'devise/registrations#new', as: :unauthenticated_root
end
end
#------------------------------
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
|
#clase padre
#Parent
class Appointment
attr_accessor :location, :purpose, :hour, :min
def initialize(location, purpose, hour, min)
@location = location
@purpose = purpose
@hour = hour
@min = min
end
end
#clases hijo
#child
class MonthlyAppointment < Appointment
attr_accessor :day
def initialize(location, purpose, hour, min, day)
super(location, purpose, hour, min, day)
@day = day
end
def occurs_on?(day)
@day == day
end
def to_s
"Reunión mensual en #{@location} sobre #{@purpose} el día #{@day} a las #{@hour}:#{@min}hrs"
end
end
#child
class DailyAppointment < Appointment
def occurs_on?(hour, min)
(hour == @hour) && (min == @min)
end
def to_s
"Reunión diaria en #{@location} sobre #{@purpose} a las #{@hour}:#{@min}hrs"
end
end
#child
class OneTimeAppointment < Appointment
attr_accessor :day, :month, :year
def initialize(location, purpose, hour, min, day, month, year)
super(location, purpose, hour, min, day, month, year)
@day = day
@month = month
@year = year
end
def occurs_on?(day, month, year)
(day == @day) && (month == @month) && (year == @year)
end
def to_s
"Reunión mensual en #{@location} sobre #{@purpose} el #{@day}/#{month}/#{year} a las #{@hour}:#{@min}hrs"
end
end
|
class CreatePatients < ActiveRecord::Migration
def change
create_table :patients do |t|
t.string :species
t.string :race
t.string :gender
t.string :bloodtype
t.string :sterilized
t.string :size
t.string :activity
t.float :weight
t.date :birthday
t.references :owner
t.timestamps
end
add_index :patients, :owner_id
end
end
|
class RoomController < ApplicationController
before_action :authenticate_user!
respond_to :json
protect_from_forgery unless: -> { request.format.json? }
def index
respond_to do |format|
format.json { render json: Room.where(hotel_id: params[:hotel_id]) }
format.html
end
end
def create
respond_with Room.create(room_params)
end
def destroy
respond_with Room.destroy(params[:id])
end
def show
respond_to do |format|
format.json { render json: Room.find(params[:id]) }
format.html
end
end
def available
respond_to do |format|
@rooms = Room.where(':capacity = 0 OR beds = :capacity',
capacity: params[:capacity]).collect { |x| { id: x.id, name: x.number, capacity: x.beds, status: x.status }
}
format.json { render json: @rooms }
format.html { render json: @rooms }
end
end
private
def room_params
params.require(:room)
end
end |
# This class is for managing user model
# class user
require 'digest'
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable
# and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :tasks, dependent: :destroy
has_one_attached :profile_image
validates :email, presence: true,
uniqueness: { case_sensitive: false }
validates :name, presence: true, length: { in: 2..50 }
validates :role, presence: true
validates :phone, presence: true,
numericality:{ message: ' must be of 10 digits number' }
end
|
require 'rubygems'
require 'active_support/inflector'
require 'need'
require 'yaml'
need{'sweet_generator'}
module TestSweet
class ConfigGenerator < SweetGenerator
def initialize(*args)
@site,@name = args
unless @site && @name
raise ArgumentError, 'please provide a site and config name'
end
end
def generate
file_dir = File.expand_path(File.dirname(__FILE__))
config_dir = File.join(file_dir,'..','..','config',Inflector.underscore(@site))
unless File.exist? config_dir
raise ArgumentError, "site #{@blah} does not exist"
end
config_file = File.join(config_dir,"#{Inflector.underscore(@name)}.yaml")
add_file config_file, YAML::dump({'sample_key' => 'sample value'})
end
end
end |
require 'spec_helper'
describe LitmusGem do
it 'has a version number' do
expect(LitmusGem::VERSION).not_to be nil
end
end
|
require "spec_helper"
require "patient"
describe Patient do
it "is not valid without a full name" do
p = Patient.new
p.should_not be_valid
p.should have(1).errors # TEMP: used to deprecate first/last validations
p.should have(1).error_on(:name_full)
end
end |
# frozen_string_literal: true
# Advent of Code 2020
#
# Robert Haines
#
# Public Domain
require 'test_helper'
require 'aoc2020/passport_processing'
class AOC2020::PassportProcessingTest < MiniTest::Test
PASSPORTS = <<~EOPASS
ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
byr:1937 iyr:2017 cid:147 hgt:183cm
iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884
hcl:#cfa07d byr:1929
hcl:#ae17e1 iyr:2013
eyr:2024
ecl:brn pid:760753108 byr:1931
hgt:179cm
hcl:#cfa07d eyr:2025 pid:166559648
iyr:2011 ecl:brn hgt:59in
EOPASS
INVALID = <<~EOINVALID
eyr:1972 cid:100
hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926
iyr:2019
hcl:#602927 eyr:1967 hgt:170cm
ecl:grn pid:012533040 byr:1946
hcl:dab227 iyr:2012
ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277
hgt:59cm ecl:zzz
eyr:2038 hcl:74454a iyr:2023
pid:3556412378 byr:2007
EOINVALID
VALID = <<~EOVALID
pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980
hcl:#623a2f
eyr:2029 ecl:blu cid:129 byr:1989
iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm
hcl:#888785
hgt:164cm byr:2001 iyr:2015 cid:88
pid:545766238 ecl:hzl
eyr:2022
iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719
EOVALID
def setup
@pp = AOC2020::PassportProcessing.new
end
def test_parse
passports = @pp.parse(PASSPORTS)
assert_equal(4, passports.length)
assert_equal(8, passports[0].length)
assert(passports[0].key?('cid'))
refute(passports[2].key?('cid'))
end
def test_valid?
passports = @pp.parse(PASSPORTS)
assert(@pp.valid?(passports[0]))
refute(@pp.valid?(passports[1]))
assert(@pp.valid?(passports[2]))
refute(@pp.valid?(passports[3]))
end
def test_validations
v = AOC2020::PassportProcessing::VALIDATIONS
assert(v['byr'].call('2002'))
refute(v['byr'].call('2003'))
assert(v['hgt'].call('60in'))
assert(v['hgt'].call('190cm'))
refute(v['hgt'].call('190in'))
refute(v['hgt'].call('190'))
assert(v['hcl'].call('#123abc'))
refute(v['hcl'].call('#123abz'))
refute(v['hcl'].call('123abc'))
refute(v['hcl'].call('#123abcd'))
assert(v['ecl'].call('brn'))
refute(v['ecl'].call('wat'))
assert(v['pid'].call('000000001'))
refute(v['pid'].call('0123456789'))
assert(v['cid'].call('000000001'))
assert(v['cid'].call(''))
end
def test_fully_valid?
@pp.parse(INVALID).each { |passport| refute(@pp.fully_valid?(passport)) }
@pp.parse(VALID).each { |passport| assert(@pp.fully_valid?(passport)) }
end
end
|
class UsersController < ApplicationController
before_action :authenticate_user!, except: [:new, :create]
def new
@user = User.new
end
def create
@user = User.new user_params
if @user.save
sign_in(@user)
redirect_to index_path, notice: "User successfully created"
else
render :new
end
end
def edit
@user = current_user
end
#update params to prevent password change
def update
@user = current_user
if @user.authenticate(params[:user][:password]) && @user.update(user_params)
redirect_to index_path, notice: "User information updated."
else
flash[:alert] = "Wrong password" if !@user.authenticate(@user.password)
render :edit
end
end
def change_password
@user = current_user
end
def update_password
@user = current_user
old_pw = params[:user][:old_password]
new_pw = params[:user][:new_password]
new_pw_conf = params[:user][:new_password_confirmation]
if !@user.authenticate(old_pw)
flash[:alert] = "Wrong password"
render :change_password
elsif new_pw != new_pw_conf
flash[:alert] = "New passwords do not match"
render :change_password
elsif new_pw == old_pw
flash[:alert] = "The new password must differ from the old one"
render :change_password
elsif new_pw.length < 4
flash[:alert] = "New password is too short"
render :change_password
else
@user.password = new_pw
if @user.save
redirect_to index_path, notice: "Password changed"
end
end
end
private
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation)
end
end
|
#!/usr/bin/env ruby
Autotest.add_hook :initialize do |autotest|
%w{.git .DS_Store Gemfile bin doc html}.each do |exception|
autotest.add_exception(exception)
end
autotest.clear_mappings
autotest.add_mapping(/^test.*\/.*_test\.rb$/) { |filename, _| filename }
autotest.add_mapping(/test_helper.rb/) { |f, _| autotest.files_matching(/test\/.*_test\.rb$/) }
autotest.add_mapping(/^lib\/vanity\/(.*)\.rb/) do |filename, _|
file = File.basename(filename, '.rb')
dir = File.split(File.dirname(filename)).last
autotest.files_matching %r%^test/(#{file}|#{dir})_test.rb$%
end
end
# Don't run entire test suite when going from red to green
class Autotest
def tainted
false
end
end
|
class Dude
DIRECTIONS = %w[N E S W].freeze
attr_reader :visited
def initialize
@visited = []
@facing = "N"
@x = 0
@y = 0
end
def turn(direction)
pos = DIRECTIONS.index(@facing)
pos += ((direction == "L") ? -1 : 1)
@facing = DIRECTIONS[pos % DIRECTIONS.length]
end
def move(blocks)
blocks.times do
case @facing
when "N" then @y += 1
when "E" then @x += 1
when "S" then @y -= 1
when "W" then @x -= 1
end
track_position
end
end
def distance
@x.abs + @y.abs
end
def track_position
@visited << [@x, @y]
end
end
dude = Dude.new
INPUT.split(", ").each do |instruction|
dude.turn(instruction[0])
dude.move(instruction[1..].to_i)
end
solve!("The distance to Easter Bunny HQ:", dude.distance)
position = dude.visited.detect { |pos| dude.visited.count(pos) > 1 }
solve!("The distance to the first place you visited twice is:", position.sum(&:abs))
|
require_relative '../../automated_init'
context "Output" do
context "Error Summary" do
context "Exit File" do
path = "some_test.rb"
result = Controls::Result.example
context "Per-File Error Counter is Non-Zero" do
file_error_counter = 11
output = Output.new
assert(output.errors_by_file.empty?)
output.file_error_counter = file_error_counter
output.exit_file(path, result)
test "File and error counter are recorded" do
assert(output.errors_by_file[path] == file_error_counter)
end
test "Per-File Error counter is reset" do
assert(output.file_error_counter.zero?)
end
end
context "Per-File Error Counter is Zero" do
file_error_counter = 0
output = Output.new
output.file_error_counter = file_error_counter
output.exit_file(path, result)
test "File and error counter are not recorded" do
assert(output.errors_by_file.empty?)
end
end
end
end
end
|
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
# attr_accessible :title, :body
has_many :notifications
# Keywords subscriptions
def subscribe!(keyword)
$redis.multi do
$redis.sadd(self.redis_key(:subscribing), keyword.id)
$redis.sadd(keyword.redis_key(:subscribers), self.id)
end
end
def unsubscribe!(keyword)
$redis.multi do
$redis.srem(self.redis_key(:subscribing), keyword.id)
$redis.srem(keyword.redis_key(:subscribers), self.id)
end
end
def subscribing
keyword_ids = $redis.smembers(self.redis_key(:subscribing))
Keyword.where(:id => keyword_ids)
end
# Channel follows
def follow!(channel)
$redis.multi do
$redis.sadd(self.redis_key(:following), channel.name.to_s)
$redis.sadd(channel.redis_key(:followers), self.id)
end
end
def unfollow!(channel)
$redis.multi do
$redis.srem(self.redis_key(:following), channel.name.to_s)
$redis.srem(channel.redis_key(:followers), self.id)
end
end
def following
channel_names = $redis.smembers(self.redis_key(:following))
end
def redis_key(str)
"user:#{self.id}:#{str}"
end
end
|
class ChangeSeatTypetoQuizzes < ActiveRecord::Migration[5.0]
def change
remove_column :quizzes, :seat_number
add_column :quizzes, :seat_number, :integer
end
end
|
module JobPacks
class JobPackItem < ::ActiveRecord::Base
belongs_to :job_pack
belongs_to :job, polymorphic: true
WAITING = 0
RUNNING = 1
ERROR = 2
DONE = 3
attr_accessor :old_status
scope :done, -> {
where(status: DONE)
}
scope :running, -> {
where(status: RUNNING)
}
scope :error, -> {
where(status: ERROR)
}
scope :waiting, -> {
where(status: WAITING)
}
attr_accessor :delayed_job
before_create :run_job_and_set_status
def refresh_job_status
self.old_status = self.status
self.status = if job
if !job.locked_at.nil?
RUNNING
elsif !job.last_error.nil?
ERROR
else
WAITING
end
else
DONE
end
save! if changed?
end
private
def run_job_and_set_status
self.job = Delayed::Job.enqueue delayed_job
self.status = WAITING
end
end
end
|
describe 'Storefront routing' do
before do
@storefront = mock_storefront!(:foo)
end
describe 'based on storefront parameter' do
before do
Backstage::Core::Engine.register_routes(:foo) do
resources :products
end
class Foo::ProductsController < ApplicationController
def index
render text: 'you a foo!'
end
end
Rails.application.reload_routes!
end
it 'should route to the correct namespaced controller' do
pending do
visit('/products?storefront=foo')
expect(page).to have_content('you a foo!')
end
end
end
end
|
module Rool
class Send < Basic
attr_accessor :method_name, :rule_type
def process(dataset, method_name, rule_type)
super
@key = dataset[@data_key].clone
@new_key = @key.public_send(method_name) if @key.respond_to? method_name
@new_data = { @data_key => @new_key }
rule_type.new(@data_key, @operand).process(@new_data)
end
end
end |
# == Schema Information
#
# Table name: organization_locations
#
# id :integer not null, primary key
# organization_id :integer
# location_id :integer
# location_type :string(255)
# created_at :datetime
# updated_at :datetime
#
class OrganizationLocation < ActiveRecord::Base
belongs_to :organization
belongs_to :location, polymorphic: true
has_many :org_profiles
def to_s
self.name
end
def name
location.name if location.name.present?
end
end
|
# Etat d'une case
# @attr_reader etat [String] etat entre BLANC, NOIR ou POINT
# @attr BLANC [String] chaine correspondant à l'état blanc
# @attr NOIR [String] chaine correspondant à l'état noir
# @attr POINT [String] chaine correspondant à l'état point
class Etat
attr_reader :etat
BLANC ||= 'b'
NOIR ||= 'n'
POINT ||= 'b+'
@etat
def initialize
@etat = BLANC
end
# Passe l'état à l'état suivant
# @return [void]
def suivant!
case(@etat)
when BLANC
@etat = NOIR
when NOIR
@etat = POINT
when POINT
@etat = BLANC
else
@etat = BLANC
end
end
# Passe l'état à l'état précédent
# @return [void]
def precedent!
case(etat)
when BLANC
@etat = POINT
when NOIR
@etat = BLANC
when POINT
@etat = NOIR
else
@etat = BLANC
end
end
end |
require 'spec_helper'
describe Twitch::Chat::Client do
let(:client) { Twitch::Chat::Client.new(password: 'password', nickname: 'enotpoloskun') }
describe '#on' do
context 'There is one message callback' do
before { client.on(:message) { 'callback1' } }
it { client.callbacks[:message].count.should eq 1 }
context "There is another message callback" do
before { client.on(:message) { 'callback2' } }
it { client.callbacks[:message].count.should eq 2 }
end
end
end
describe '#trigger' do
before { client.on(:message) { client.inspect } }
it { client.should_receive(:inspect) }
after { client.trigger(:message) }
end
end
|
require 'rails_helper'
describe "Themes to items relationship" do
before(:all) do
@avrail = FactoryGirl.create(:item, :title => 'Les Aventuriers du rail')
@wonders = FactoryGirl.create(:item, :title => '7 Wonders')
@dow = FactoryGirl.create(:theme, :name => 'Building')
end
it "should recognise when a theme has no items" do
expect(@dow.items.count).to eq 0
end
it "should handle a theme with an item" do
@dow.items << @avrail
expect(@dow.items.count).to eq 1
end
it "should automatically know an item's themes" do
@dow.items << @avrail
expect(@avrail.themes.last.name).to eq "Building"
end
end
|
class Store < ActiveRecord::Base
attr_accessible :name, :user_id, :visits
belongs_to :user
has_many :links
end
|
class AddGradeRefToBoulders < ActiveRecord::Migration
def change
add_reference :boulders, :grade, index: true
end
end
|
n = gets.strip.to_i
a = Array.new(n)
min_heap = []
max_heap = []
def balanced?(array1, array2)
(array1.length - array2.length).abs <= 1
end
def get_parent(index)
return nil if index == 0
(index - 1) / 2
end
def get_child(index, heap, &prc)
left = index * 2 + 1
return nil if left >= heap.length
right = index * 2 + 2
return left if right >= heap.length
prc.call(heap[left], heap[right]) <= 0 ? left : right
end
def insert(value, heap, &prc)
index = heap.length
heap << value
parent_index = get_parent(index)
return heap if parent_index.nil?
until prc.call(heap[parent_index], heap[index]) <= 0
heap[parent_index], heap[index] = heap[index], heap[parent_index]
index = parent_index
parent_index = get_parent(index)
return heap if parent_index.nil?
end
heap
end
def peek(heap)
heap[0]
end
def pop(heap, &prc)
return nil if heap.empty?
heap[0], heap[-1] = heap[-1], heap[0]
popped = heap.pop
index = 0
child_index = get_child(index, heap, &prc)
return popped if child_index.nil?
until prc.call(heap[index], heap[child_index]) <= 0
heap[index], heap[child_index] = heap[child_index], heap[index]
index = child_index
child_index = get_child(index, heap, &prc)
return popped if child_index.nil?
end
popped
end
for a_i in (0..n-1)
a[a_i] = gets.strip.to_i
end
min_proc = Proc.new { |x, y| x <=> y }
max_proc = Proc.new { |x, y| y <=> x }
count = 0
a.each do |num|
# cover first two cases
count += 1
if min_heap.empty? && max_heap.empty?
min_heap << num
else
if num > peek(min_heap)
insert(num, min_heap, &min_proc)
else
insert(num, max_heap, &max_proc)
end
unless balanced?(min_heap, max_heap)
if min_heap.length > max_heap.length
insert(pop(min_heap, &min_proc), max_heap, &max_proc)
else
insert(pop(max_heap, &max_proc), min_heap, &min_proc)
end
end
end
if count.odd?
puts min_heap.length > max_heap.length ? peek(min_heap).round(1) : peek(max_heap).round(1)
else
puts(((peek(max_heap) + peek(min_heap)) / 2.0).round(1))
end
end
|
require 'spec_helper'
RSpec.describe Ultron::Event::Receiver do
let(:serial) { double(RubySerial::Posix::Termios) }
let(:mqtt) { MQTT::Client.new(host: 'localhost', port: 1883) }
let(:instance) { described_class.new(serial, mqtt) }
describe '#parse_and_publish' do
let(:message) { '{"topic":"receiver/temperature","value":"30"}' }
let(:message_parsed) { JSON.parse(message) }
let(:topic) { message_parsed['topic'] }
let(:value) { message_parsed['value'] }
subject { instance.parse_and_publish(message) }
context 'when valid message' do
before do
expect(Ultron.logger).to receive(:info).and_return(true)
end
context 'when has mqtt' do
before do
expect(mqtt).to receive(:publish).with("receiver/#{topic}", value).and_return(true)
expect(Ultron.logger).to receive(:info).and_return(true)
end
it { is_expected.to be_truthy }
end
context 'when hasnt mqtt' do
let(:mqtt) { nil }
it { is_expected.to be_nil }
end
end
context 'when invalid message' do
let(:message) { 'topic: receiver/temperature, value: 30' }
before do
expect(Ultron.logger).to receive(:error).and_return(true)
end
it { is_expected.to be_truthy }
end
end
end
|
module Sinatra
module ContentFor2
VERSION = '0.3'.freeze
end
end
|
require "fluent_plugin_kinesis_firehose/version"
class Fluent::KinesisFirehoseOutput < Fluent::BufferedOutput
Fluent::Plugin.register_output('kinesis_firehose', self)
include Fluent::SetTimeKeyMixin
include Fluent::SetTagKeyMixin
USER_AGENT_SUFFIX = "fluent-plugin-kinesis-firehose/#{FluentPluginKinesisFirehose::VERSION}"
PUT_RECORDS_MAX_COUNT = 500
PUT_RECORDS_MAX_DATA_SIZE = 1024 * 1024 * 4
unless method_defined?(:log)
define_method('log') { $log }
end
config_param :profile, :string, :default => nil
config_param :credentials_path, :string, :default => nil
config_param :aws_key_id, :string, :default => nil, :secret => true
config_param :aws_sec_key, :string, :default => nil, :secret => true
config_param :region, :string, :default => nil
config_param :endpoint, :string, :default => nil
config_param :http_proxy, :string, :default => nil
config_param :delivery_stream_name, :string
config_param :data_key, :string, :default => nil
config_param :append_new_line, :bool, :default => true
config_param :retries_on_putrecordbatch, :integer, :default => 3
config_param :local_path_fallback, :string, :default => nil
def initialize
super
require 'aws-sdk'
require 'multi_json'
end
def configure(conf)
super
@sleep_duration = Array.new(@retries_on_putrecordbatch) {|n| ((2 ** n) * scaling_factor) }
end
def format(tag, time, record)
[tag, time, record].to_msgpack
end
def write(chunk)
chunk = chunk.to_enum(:msgpack_each)
chunk.select {|tag, time, record|
if not @data_key or record[@data_key]
true
else
log.warn("'#{@data_key}' key does not exist: #{[tag, time, record].inspect}")
false
end
}.map {|tag, time, record|
convert_record_to_data(record)
}.each_slice(PUT_RECORDS_MAX_COUNT) {|data_list|
put_records(data_list)
}
rescue => e
log.error e.message
log.error_backtrace e.backtrace
end
private
def convert_record_to_data(record)
if @data_key
data = record[@data_key].to_s
else
data = MultiJson.dump(record)
end
if @append_new_line
data + "\n"
else
data
end
end
def put_records(data_list)
state = 0
data_list.slice_before {|data|
data_size = data.size
state += data_size
if PUT_RECORDS_MAX_DATA_SIZE < state
state = data_size
true
else
false
end
}.each {|chunk|
put_record_batch_with_retry(chunk)
}
end
def put_record_batch_with_retry(data_list, retry_count=0)
records = data_list.map do |data|
{:data => data}
end
response = client.put_record_batch(
:delivery_stream_name => @delivery_stream_name,
:records => records
)
if response[:failed_put_count] && response[:failed_put_count] > 0
failed_records = collect_failed_records(data_list, response)
if retry_count < @retries_on_putrecordbatch
sleep @sleep_duration[retry_count]
retry_count += 1
log.warn 'Retrying to put records. Retry count: %d' % retry_count
put_record_batch_with_retry(failed_records.map{|record| record[:data] }, retry_count)
else
failed_records.each {|record|
log.error 'Could not put record, Error: %s/%s, Record: %s' % [
record[:error_code],
record[:error_message],
record[:data]
]
}
if not @local_path_fallback.nil?
File.open(@local_path_fallback, 'a') { |f|
failed_records.each { |record| f.write record[:data] }
}
end
end
end
end
def collect_failed_records(data_list, response)
failed_records = []
response[:request_responses].each_with_index do |record, index|
if record[:error_code]
failed_records.push(
data: data_list[index],
error_code: record[:error_code],
error_message: record[:error_message]
)
end
end
failed_records
end
def client
return @client if @client
options = {:user_agent_suffix => USER_AGENT_SUFFIX}
options[:region] = @region if @region
options[:endpoint] = @endpoint if @endpoint
options[:http_proxy] = @http_proxy if @http_proxy
if @aws_key_id and @aws_sec_key
options[:access_key_id] = @aws_key_id
options[:secret_access_key] = @aws_sec_key
elsif @profile
credentials_opts = {:profile_name => @profile}
credentials_opts[:path] = @credentials_path if @credentials_path
credentials = Aws::SharedCredentials.new(credentials_opts)
options[:credentials] = credentials
end
if @debug
options[:logger] = Logger.new(log.out)
options[:log_level] = :debug
#options[:http_wire_trace] = true
end
@client = Aws::Firehose::Client.new(options)
end
def scaling_factor
0.5 + rand * 0.1
end
end
|
include ActionDispatch::TestProcess
FactoryGirl.define do
factory :job do
title { Faker::Name.title }
employed_from { Faker::Business.credit_card_expiry_date }
employed_to { Faker::Business.credit_card_expiry_date }
# associations
user
restaurant
trait :with_reviews do
ignore do
review_count 1 # tells FG this is NOT an attribute
end
after(:create) do |job, evaluator|
FactoryGirl.create_list :review, evaluator.comment_count, job: job
end
end
factory :job_with_reviews, traits: [:with_reviews]
end
end
|
require_relative('../db/sql_runner.rb')
class Movie
attr_reader :id
attr_accessor :title, :genre
def initialize(options)
@title = options["title"]
@genre = options["genre"]
@id = options["id"].to_i if options["id"]
@budget = options["budget"].to_i
end
def save()
sql = "INSERT INTO movies(title,genre) VALUES ($1, $2) RETURNING id;"
values =[ @title, @genre]
results = SqlRunner.run(sql,values).first
@id = results['id'].to_i
end
def update
sql = " UPDATE movies SET (title, genre) = ($1,$2) WHERE id = $3"
values = [@title, @genre, @id]
SqlRunner.run(sql, values )
end
def all_stars
sql = "SELECT stars.* FROM stars
INNER JOIN castings
ON castings.star_id = stars.id
WHERE castings.movie_id = $1"
values = [@id]
stars = SqlRunner.run(sql, values)
result = stars.map{|star| Star.new(star)}
return result
end
def get_cast()
sql = "SELECT * FROM castings WHERE movie_id = $1"
values = [@id]
cast_data = SqlRunner.run(sql, values)
cast = cast_data.map { |casting| Casting.new casting }
return cast
end
def calculate_remaining_budget()
cast = self.get_cast()
fees = cast.map { |star| star.fee }
total_fees = fees.sum
remaining_budget = @budget - total_fees
end
def self.delete_all()
sql = "DELETE FROM movies;"
SqlRunner.run(sql)
end
def self.all()
sql = "SELECT * FROM movies"
results = SqlRunner.run(sql)
movies = results.map{|movie| Movie.new(movie)}
return movies
end
end
|
# Die Class 1: Numeric
# I worked on this challenge by myself
# I spent [] hours on this challenge.
# 0. Pseudocode
# make a new class called die
# sets number of sides based on user input
# if user input is less than one, error
# rolling the die returns random number between 1 and 6 (or whatever)
# Input: 6
# Output: random number between 1 and 6
# Steps: 3
# 1. Initial Solution
class Die
def initialize(sides)
# code goes here
raise ArgumentError if sides < 1
@sides = sides
end
def sides
# code goes here
@sides
end
def roll
# code goes here
rand(@sides) + 1
end
end
# 3. Refactored Solution = The initial way works
# 4. Reflection
=begin
What is an ArgumentError and why would you use one?
When the argument is wrong.
What new Ruby methods did you implement? What challenges and successes did you have in implementing them?
raise, which specifies that the number can't be less than one.
What is a Ruby class?
a blueprint from which objects are created, for example a bicycle.
Why would you use a Ruby class?
so you don't have to reinvent the bicycle every time! A bicycle comes with a bunch of working parts, as does a Ruby class.
What is the difference between a local variable and an instance variable?
an instance variable is within a class, a local variable is within an object.
Where can an instance variable be used?
Within the class that instance variable belongs to
=end |
module Goodreads
module Shelves
# Get books from a user's shelf
def shelf(user_id, shelf_name, options={})
options = options.merge(:shelf => shelf_name, :v =>2)
data = request("/review/list/#{user_id}.xml", options)
reviews = data['reviews']['review']
books = []
unless reviews.nil?
# one-book results come back as a single hash
reviews = [reviews] if !reviews.instance_of?(Array)
books = reviews.map {|e| Hashie::Mash.new(e)}
end
Hashie::Mash.new({
:start => data['reviews']['start'].to_i,
:end => data['reviews']['end'].to_i,
:total => data['reviews']['total'].to_i,
:books => books
})
end
# Get list of shelf names
def list_shelf_names(id)
list_shelves(id).names
end
# Get list of shelves
def list_shelves(id)
data = request('/shelf/list.xml', {:user_id => id})
shelf_list = data['shelves']['user_shelf']
shelves = []
shelves = shelf_list.map {|s| Hashie::Mash.new(s)}
names = []
names = shelves.map {|s| s.name}
Hashie::Mash.new({
:start => data['shelves']['start'].to_i,
:end => data['shelves']['end'].to_i,
:total => data['shelves']['total'].to_i,
:shelves => shelves,
:names => names
})
end
# Add book to shelf
def add_book_to_shelf(book_id, shelf)
data = oauth_update('/shelf/add_to_shelf.xml',
{:book_id => book_id, :name => shelf})
end
# Add books to multiple shelves
def add_books_to_shelves(book_ids, shelves)
data = oauth_update('/shelf/add_books_to_shelves.xml',
{:bookids => book_ids, :shelves => shelves})
end
# Remove book from shelf
def remove_book_from_shelf(book_id, shelf)
data = oauth_update('/shelf/add_to_shelf.xml',
{:book_id => book_id, :name => shelf, :a => 'remove'})
end
end
end
|
#==============================================================================
# [VXACE] Advance Text Reader EX by Estriole
#-------------------------------------------------------------------------
# EST - Advance Text Reader
# Version: 1.2
# Released on: 26/07/2012
# Author : Estriole (yin_estriole@yahoo.com)
# also credits : Woratana for VX version
#
#
=begin
################################################################################
# Version History:
# v 1.00 - 2012.07.22 > First relase
# v 1.01 - 2012.07.23 > replace the old decorate text with escape code usage
# v 1.02 - 2012.07.26 > make switch togle between old decorate text and new
# escape code version
###############################################################################
==================================
+[Features in Version 1.2]+
** Start Read Text File by call script:
SceneManager.callplus(Text_Reader,"filename with file type")
* For example, you want to read file "test.txt", call script:
SceneManager.callplus(Text_Reader,"test.txt")
* ability to use almost all msg system escape codes
such as \c[4], \n[3]. default or custom message system
(known so far yanfly, victor, modern algebra ats)
* Advanced syntax to call is like this
SceneManager.callplus(Text_Reader,filename,[actorid],[type],[infocontent])
[actorid] & [type] & [infocontent] is optional
[infocontent] will print inside info window when some type chosen max [41char].
list of [type]: (what the content of info window)
"default" - just draw face window (if there is no actorid) without info window then draw text reader window
"simple_status" - info window containing simple actor status
"text_title" - info window containing titles for the text centered and yellow color
still building more [type]
example of some variation to call advanced syntax:
SceneManager.callplus(Text_Reader,"test.txt",11,"simple_status")
means it will draw actor 11 face and actor 11 simple status then below
is test.txt content.
or
SceneManager.callplus(Text_Reader,"test.txt",nil,"text_title","Stupid Tutorial")
which translate to : only info window containing text "Stupid Tutorial" with larger
font and yellow color centered (vertical and horizontal). and below it is the
test.txt content. (no actor face window because you put nil)
or
SceneManager.callplus(Text_Reader,"test.txt",12)
translate to : test.txt content with actor face window (small square at top left
of the test.txt (means it will block any text that below it. but its not a problem
if you center the text (manualy or using decorate text if you didn't need icons, color, etc)
** Custom Folder for Text File
You can change Text File's folder at line:
TEXT_FOLDER = "folder you want"
"" << for no folder, text file should be in your game's folder.
"Files/" << for folder "Your Game Folder > Files"
"Data/Files/" << for folder "Your Game Folder > Data > Files"
==================================
decorate text feature below can be used by editing :
TR_old_mode_switch = 0
change to switch you want.
if the switch turn on you can use decorate text feature below but lost ability
to use all the escape code (such as \c[5] \n[3] etc)
so basicly you can switch between using decorate text and using escape codes.
+[Decorate Text]+ [if you still want to use this feature instead nice icon and pics]
You can decorate your text by following features:
[b] << Bold Text
[/b] << Not Bold Text
[i] << Italic Text
[/i] << Not Italic Text
[s] << Text with Shadow
[/s] << Text without Shadow
[cen] << Show Text in Center
[left] << Show Text in Left side
[right] << Show Text in Right side
* Note: Don't put features that have opposite effects in same line...
For example, [b] that make text bold, and [/b] that make text not bold
* Note2: The decoration effect will be use in the next lines,
Until you use opposite effect features... For example,
[b]text1
text2
[/b]text3
text1 and text2 will be bold text, and text3 will be thin text.
==================================
+[Configuration]+
OPEN_SPEED = Speed when Reader Window is Opening/Closing
SCROLL_SPEED = Speed when player Scroll Reader Window up/down
TEXT_FOLDER = Folder for Text Files
e.g. "Data/Texts/" for Folder "Your Project Folder > Data > Texts"
================================================================================
compatibility list
================================================================================
message system
- yanfly ace msg system
- victor msg system
- modern algebra ats msg system
and i'm using loooottss of script and no conflict but i won't list them there
because it's not necessary (the one who can conflict only the one who alter
window_base or scene_base heavily like overwriting the method without mercy lol)
================================================================================
=end
# editable region
module ESTRIOLE
TR_old_mode_switch = 12 # switch if on use old decorate text mode change to 0
# you dont want to use the decorate text mode at all
TEXT_FOLDER = "Texts/" # Folder for Text Files -> this means at your project folder/text
OPEN_SPEED = 30 # Open/Close Speed of Reader Window (Higher = Faster)
SCROLL_SPEED = 30 # Scroll Up/Down Speed
end
#===========================================================================
# do not edit below this line except you know what you're doing
#===========================================================================
module SceneManager
def self.callplus(scene_class,filename,actor = nil,type="default",infocontent="")
@stack.push(@scene)
@scene = scene_class.new(filename,actor,type,infocontent)
end
end
class Text_Reader < Scene_MenuBase
OPEN_SPEED = ESTRIOLE::OPEN_SPEED
SCROLL_SPEED = ESTRIOLE::SCROLL_SPEED
TEXT_FOLDER = ESTRIOLE::TEXT_FOLDER
def initialize(file_name,actor = nil,type="default",infocontent="",mode = 0)
@filename = file_name
@infocontent = infocontent
if actor == nil
@actorx = nil
else
@actorx = $game_actors[actor]
end
@mode = mode
@type = type
end
def start
super
file = File.open(TEXT_FOLDER + @filename)
@text = []
for i in file.readlines
@text.push i.sub(/\n/) {}
end
if @mode == 1
@text[0] = @text[0].sub(/^./m) {}
end
@window = Window_Reader.new(@text,@actorx,@type)
@window.visible = true
if @actorx == nil
else
@actor_face_window = Window_Top_Reader_Face.new(@actorx)
end
case @type
when "default"
else;
@info_window = Window_Top_Reader_Info.new(@actorx,@type,@infocontent)
end
end
def update
super
@window.update
process_exit if Input.trigger?(:B)/> or Input.trigger?(:C)
process_down if Input.repeat?(:DOWN)
process_up if Input.repeat?(:UP)
end
def process_exit
Sound.play_cancel
SceneManager.call(Scene_Map)
end
def process_down
Sound.play_cursor if (@window.oy + 272) < @window.contents.height
@window.oy += SCROLL_SPEED if (@window.oy + 272) < @window.contents.height
end
def process_up
Sound.play_cursor if (@window.oy + 272) < @window.contents.height
@window.oy -= SCROLL_SPEED if @window.oy > 0
end
def scene_changing?
SceneManager.scene != self
end
end
class Window_Top_Reader_Face < Window_Base
def initialize(actor)
super(0,0,116,116)
draw_actor_face(actor,0,0,true)
end
end
class Window_Top_Reader_Info < Window_Base
def initialize(actor,type,infocontent)
if actor == nil
super(0,0,544,116)
@infowidth = 544
else
super(116,0,428,116)
@infowidth = 428
end
case type
when "simple_status"
draw_actor_simple_status(actor, 20, 20) if actor != nil
when "text_title"
make_font_bigger
make_font_bigger if actor == nil
change_color(text_color(6))
draw_text(0, 28, @infowidth - 40, 40, infocontent, 1) if actor == nil
draw_text(0, 32, @infowidth - 40, 32, infocontent, 1) if actor != nil
else;
end
end
end
class Window_Reader < Window_Base
attr_accessor :firstline, :nowline
def initialize(text,actorx,type)
if actorx == nil
case type
when "default"
super(0,0,544,416)
else;
super(0,116,544,300)
end
else
case type
when "default"
super(0,0,544,416)
else;
super(0,116,544,300)
end
end
#
@firstline = @nowline = 0
@text = text
@align = 0
@extra_lines = 0
@line_index = 0
draw_text_reader
end
def update
if self.openness < 255
self.openness += Text_Reader::OPEN_SPEED
end
end
def draw_text_reader
self.contents = Bitmap.new(width - 32, @text.size * 24 + 32)
@line_index = 0
for i in 0..@text.size
if @text[i] == nil
else
text = decorate_text(@text[i])
if $game_switches[ESTRIOLE::TR_old_mode_switch] == true
self.contents.draw_text(0, @line_index * 24, width - 32, 24, text, @align)
else
self.draw_text_ex_mod(0, @line_index * 24, text)
end
end
@line_index += 1
end
end
def draw_text_ex_mod(x, y, text)
#reset_font_settings
text = convert_escape_characters(text)
@pos = {:x => x, :y => y, :new_x => x, :height => calc_line_height(text)}
process_character_mod(text.slice!(0, 1), text, @pos) until text.empty?
end
def process_character_mod(c, text, pos)
if pos[:x] >500
process_new_line(text, pos)
@line_index += 1
@extra_lines += 1
end
case c
when "\n"
process_new_line(text, pos)
when "\f"
process_new_page(text, pos)
when "\e"
process_escape_character(obtain_escape_code(text), text, pos)
else
process_normal_character(c, pos)
end
end
def decorate_text(text)
a = text.scan(/(\[\/b\])/)
if $1.to_s != ""
self.contents.font.bold = false
text.sub!(/\[\/b\]/) {}
end
a = text.scan(/(\[b\])/)
if $1.to_s != ""
self.contents.font.bold = true
text.sub!(/\[b\]/) {}
end
a = text.scan(/(\[\/i\])/)
if $1.to_s != ""
self.contents.font.italic = false
text.sub!(/\[\/i\]/) {}
end
a = text.scan(/(\[i\])/)
if $1.to_s != ""
self.contents.font.italic = true
text.sub!(/\[i\]/) {}
end
a = text.scan(/(\[\/s\])/)
if $1.to_s != ""
self.contents.font.shadow = false
text.sub!(/\[\/s\]/) {}
end
a = text.scan(/(\[s\])/)
if $1.to_s != ""
self.contents.font.shadow = true
text.sub!(/\[s\]/) {}
end
a = text.scan(/(\[cen\])/)
if $1.to_s != ""
@align = 1
text.sub!(/\[cen\]/) {}
end
a = text.scan(/(\[left\])/)
if $1.to_s != ""
@align = 0
text.sub!(/\[left\]/) {}
end
a = text.scan(/(\[right\])/)
if $1.to_s != ""
@align = 2
text.sub!(/\[right\]/) {}
end
return text
end
end |
# encoding : utf-8
require "minitest/unit"
require_relative "../ondl"
MiniTest::Unit.autorun
class TestOndl < MiniTest::Unit::TestCase
def setup
@ondl=Ondl.new
end
#def test_translate
# assert_equal "オンドゥルルラギッタンディスカ",@ondl.translate("本当に裏切ったんですか")
#end
def test_word
assert_equal "ジャ",@ondl.translate_word("りゃ")
assert_equal "ベ",@ondl.translate_word("め")
assert_nil @ondl.translate_word("めだか")
end
def test_with_rest
assert_equal ["ベ","だか"],@ondl.translate_with_rest("めだか")
assert_equal ["オンドゥル",""],@ondl.translate_with_rest("ほんとうに")
assert_equal ["!","あ"],@ondl.translate_with_rest("!あ")
assert_equal ["x","あ"],@ondl.translate_with_rest("xあ")
end
def test_translate_kana
assert_equal "オンドゥルルラギッタンディスカ",@ondl.translate_kana("ほんとうにうらぎったんですか")
end
end
|
# frozen_string_literal: true
module EasyMonitor
module Util
module Connectors
class ActiverecordConnector
attr_accessor :base
def initialize(base = ActiveRecord::Base)
self.base = base
end
def database_alive?
raise StandardError unless EasyMonitor::Engine.use_active_record
base.connection.active?
end
end
end
end
end
|
require 'test_helper'
class PasswordBlurTest < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers
setup do
Settings.pw.enable_blur = true
end
teardown do
Settings.pw.enable_blur = true
end
def test_blur_enabled
post passwords_path, params: { password: { payload: 'testpw' } }
assert_response :redirect
# Preview page
follow_redirect!
assert_response :success
assert_select 'h2', 'Your push has been created.'
# File Push page
get request.url.sub('/preview', '')
assert_response :success
# Validate that blur is enabled
tags = assert_select '#push_payload'
assert tags.first.attr("class").include?("spoiler")
end
def test_blur_when_disabled
Settings.pw.enable_blur = false
post passwords_path, params: { password: { payload: 'testpw' } }
assert_response :redirect
# Preview page
follow_redirect!
assert_response :success
assert_select 'h2', 'Your push has been created.'
# File Push page
get request.url.sub('/preview', '')
assert_response :success
# Validate that blur is enabled
tags = assert_select '#push_payload'
assert !tags.first.attr("class").include?("spoiler")
end
end |
# frozen_string_literal: true
require 'base64'
module V0
class SessionsController < ApplicationController
include Accountable
skip_before_action :authenticate, only: %i[new logout saml_callback saml_logout_callback]
REDIRECT_URLS = %w[mhv dslogon idme mfa verify slo].freeze
STATSD_SSO_CALLBACK_KEY = 'api.auth.saml_callback'
STATSD_SSO_CALLBACK_TOTAL_KEY = 'api.auth.login_callback.total'
STATSD_SSO_CALLBACK_FAILED_KEY = 'api.auth.login_callback.failed'
STATSD_LOGIN_NEW_USER_KEY = 'api.auth.new_user'
STATSD_CONTEXT_MAP = {
LOA::MAPPING.invert[1] => 'idme',
'dslogon' => 'dslogon',
'myhealthevet' => 'myhealthevet',
LOA::MAPPING.invert[3] => 'idproof',
'multifactor' => 'multifactor',
'dslogon_multifactor' => 'dslogon_multifactor',
'myhealthevet_multifactor' => 'myhealthevet_multifactor'
}.freeze
# Collection Action: auth is required for certain types of requests
# @type is set automatically by the routes in config/routes.rb
# For more details see SAML::SettingsService and SAML::URLService
# rubocop:disable Metrics/CyclomaticComplexity
def new
url = case params[:type]
when 'mhv'
SAML::SettingsService.mhv_url(success_relay: params[:success_relay])
when 'dslogon'
SAML::SettingsService.dslogon_url(success_relay: params[:success_relay])
when 'idme'
query = params[:signup] ? '&op=signup' : ''
SAML::SettingsService.idme_loa1_url(success_relay: params[:success_relay]) + query
when 'mfa'
authenticate
SAML::SettingsService.mfa_url(current_user, success_relay: params[:success_relay])
when 'verify'
authenticate
SAML::SettingsService.idme_loa3_url(current_user, success_relay: params[:success_relay])
when 'slo'
authenticate
SAML::SettingsService.logout_url(session)
end
render json: { url: url }
end
# rubocop:enable Metrics/CyclomaticComplexity
def logout
session = Session.find(Base64.urlsafe_decode64(params[:session]))
raise Common::Exceptions::Forbidden, detail: 'Invalid request' if session.nil?
destroy_user_session!(User.find(session.uuid), session)
redirect_to SAML::SettingsService.slo_url(session)
end
def saml_logout_callback
logout_response = OneLogin::RubySaml::Logoutresponse.new(params[:SAMLResponse], saml_settings,
raw_get_params: params)
logout_request = SingleLogoutRequest.find(logout_response&.in_response_to)
errors = build_logout_errors(logout_response, logout_request)
if errors.size.positive?
extra_context = { in_response_to: logout_response&.in_response_to }
log_message_to_sentry("SAML Logout failed!\n " + errors.join("\n "), :error, extra_context)
end
# in the future the FE shouldnt count on ?success=true
ensure
logout_request&.destroy
redirect_to Settings.saml.logout_relay + '?success=true'
end
def saml_callback
saml_response = OneLogin::RubySaml::Response.new(params[:SAMLResponse], settings: saml_settings)
@sso_service = SSOService.new(saml_response)
if @sso_service.persist_authentication!
@current_user = @sso_service.new_user
@session = @sso_service.new_session
after_login_actions
redirect_to saml_login_relay_url + '?token=' + @session.token
log_persisted_session_and_warnings
StatsD.increment(STATSD_LOGIN_NEW_USER_KEY) if @sso_service.new_login?
StatsD.increment(STATSD_SSO_CALLBACK_KEY, tags: ['status:success', "context:#{context_key}"])
else
redirect_to saml_login_relay_url + "?auth=fail&code=#{@sso_service.auth_error_code}"
StatsD.increment(STATSD_SSO_CALLBACK_KEY, tags: ['status:failure', "context:#{context_key}"])
StatsD.increment(STATSD_SSO_CALLBACK_FAILED_KEY, tags: [@sso_service.failure_instrumentation_tag])
end
rescue NoMethodError
Raven.extra_context(base64_params_saml_response: Base64.encode64(params[:SAMLResponse].to_s))
raise
ensure
StatsD.increment(STATSD_SSO_CALLBACK_TOTAL_KEY)
end
private
def after_login_actions
set_sso_cookie!
async_create_evss_account
create_user_account
end
def log_persisted_session_and_warnings
obscure_token = Session.obscure_token(session.token)
Rails.logger.info("Logged in user with id #{session.uuid}, token #{obscure_token}")
# We want to log when SSNs do not match between MVI and SAML Identity. And might take future
# action if this appears to be happening frquently.
if current_user.ssn_mismatch?
additional_context = StringHelpers.heuristics(current_user.identity.ssn, current_user.va_profile.ssn)
log_message_to_sentry('SSNS DO NOT MATCH!!', :warn, identity_compared_with_mvi: additional_context)
end
end
def async_create_evss_account
return unless @current_user.authorize :evss, :access?
auth_headers = EVSS::AuthHeaders.new(@current_user).to_h
EVSS::CreateUserAccountJob.perform_async(auth_headers)
end
def destroy_user_session!(user, session)
# shouldn't return an error, but we'll put everything else in an ensure block just in case.
MHVLoggingService.logout(user) if user
ensure
destroy_sso_cookie!
session&.destroy
user&.destroy
end
def build_logout_errors(logout_response, logout_request)
errors = []
errors.concat(logout_response.errors) unless logout_response.validate(true)
errors << 'inResponseTo attribute is nil!' if logout_response&.in_response_to.nil?
errors << 'Logout Request not found!' if logout_request.nil?
errors
end
def default_relay_url
Settings.saml.relays.vetsgov
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/AbcSize
def saml_login_relay_url
return default_relay_url if current_user.nil?
# TODO: this validation should happen when we create the user, not here
if current_user.loa.key?(:highest) == false || current_user.loa[:highest].nil?
log_message_to_sentry('ID.me did not provide LOA.highest!', :error)
return default_relay_url
end
if current_user.loa[:current] < current_user.loa[:highest] && valid_relay_state?
SAML::SettingsService.idme_loa3_url(current_user, success_relay_url: params['RelayState'])
elsif current_user.loa[:current] < current_user.loa[:highest]
SAML::SettingsService.idme_loa3_url(current_user, success_relay: params['RelayState'])
elsif valid_relay_state?
params['RelayState']
else
default_relay_url
end
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/AbcSize
def valid_relay_state?
params['RelayState'].present? && Settings.saml.relays&.to_h&.values&.include?(params['RelayState'])
end
def benchmark_tags(*tags)
tags << "context:#{context_key}"
tags << "loa:#{current_user&.identity ? current_user.loa[:current] : 'none'}"
tags << "multifactor:#{current_user&.identity ? current_user.multifactor : 'none'}"
tags
end
def context_key
STATSD_CONTEXT_MAP[@sso_service.real_authn_context] || 'unknown'
rescue StandardError
'unknown'
end
end
end
|
# Problem 155: Counting Capacitor Circuits.
# http://projecteuler.net/problem=155
# An electric circuit uses exclusively identical capacitors of the same value C.
#
# The capacitors can be connected in series or in parallel to form sub-units, which can then be connected in series or in parallel with other capacitors or other sub-units to form larger sub-units, and so on up to a final circuit.
# Using this simple procedure and up to n identical capacitors, we can make circuits having a range of different total capacitances. For example, using up to n=3 capacitors of 60 http://projecteuler.net/project/images/p_155_capsmu.gifF each, we can obtain the following 7 distinct total capacitance values:
# http://projecteuler.net/project/images/p_155_capacitors1.gif
# If we denote by D(n) the number of distinct total capacitance values we can obtain when using up to n equal-valued capacitors and the simple procedure described above, we have: D(1)=1, D(2)=3, D(3)=7 ...
# Find D(18).
# Reminder : When connecting capacitors C1, C2 etc in parallel, the total capacitance is CT = C1 + C2 +...,
#
# whereas when connecting them in series, the overall capacitance is given by:
# http://projecteuler.net/project/images/p_155_capsform.gif
|
ActiveAdmin.register Product do
# See permitted parameters documentation:
# https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
#
# permit_params :list, :of, :attributes, :on, :model
#
# or
#
# permit_params do
# permitted = [:permitted, :attributes]
# permitted << :other if params[:action] == 'create' && current_user.admin?
# permitted
# end
permit_params :sku,
:name,
:description,
:quantity,
:active,
:category_id,
:price,
:width,
:diameter,
:height,
:length,
:weight,
:volume,
:size,
:resistance,
:colour,
:material,
:max_weight,
:finish,
:image,
:new,
:sale,
:sale_price
end
|
class Gutenberg < Formula
desc "A template and scaffolding utility."
homepage "https://github.com/sourcefoundryus/gutenberg"
url "https://github.com/sourcefoundryus/gutenberg/releases/download/1.0.0/gutenberg-1.0.0.zip"
sha256 "db6941effc6e83bea2be18283fa7758fdbcfdd36348747c6e628f344bc98668e"
version "1.0.0"
bottle :unneeded
def install
lib.install "gutenberg-1.0.0.jar"
bin.install "gutenberg"
end
end |
# == Schema Information
#
# Table name: invoice_lines
#
# id :integer not null, primary key
# quantity :integer
# unit_price :float
# created_at :datetime
# updated_at :datetime
# invoice_id :integer
# track_id :integer
#
class InvoiceLine < ApplicationRecord
belongs_to :invoice,
foreign_key: :invoice_id,
class_name: :Invoice
belongs_to :track,
foreign_key: :track_id,
class_name: :Track
end
|
require 'spec_helper.rb'
require 'helper.rb'
require 'service/lookup_service'
require 'service/authorized_service'
require 'service/returned_service'
RSpec.configure do |c|
c.include Helper
end
describe "Returned Service" do
before(:all) do
variable_init
end
it "should allow an item to be returned" do
# An order needs to be completed before an item can be returned
lookup_service = TaxCloud::LookupService.new(@client)
lookup_response = lookup_service.lookup(@api_id, @api_key, @customer_id, @cart_id, @origin, @destination, @cart_items)
# Here we are letting the service create a cart ID for us
@cart_id = lookup_response.cart_id
authorized_service = TaxCloud::AuthorizedService.new(@client)
authorized_response = authorized_service.authorized_with_capture(@api_id, @api_key, @customer_id, @cart_id, @order_id, @date_authorized, @date_captured)
# And now for the actual test
returned_service = TaxCloud::ReturnedService.new(@client)
returned_response = returned_service.returned(@api_id, @api_key, @order_id, @cart_items, @returned_date)
returned_response.response_type.to_s.should eql 'OK'
end
end |
require 'rspec/core/rake_task'
require 'rake'
# RSpec::Core::RakeTask.new('spec')
# task :default => :spec
namespace :pulumi do
desc "setup pulumi"
task :setup do
sh 'virtualenv -p python3 venv'
sh 'source venv/bin/activate'
sh 'pip3 install -r requirements.txt'
end
end
namespace :lint do
desc "Check pulumi preview"
task :pulumi do
sh 'inspec exec tests/preview_spec.rb'
end
end
namespace :build do
desc "Build resources"
task :pulumi do
sh 'pulumi up --yes'
end
end
namespace :test do
namespace :unit do
desc "Run awspec tests"
namespace :awspec do
RSpec::Core::RakeTask.new('spec')
task :default => :spec
end
namespace :inspec do
desc "Check pulumi stack"
task :stack do
sh 'inspec exec tests/stack_spec.rb'
end
# desc "Run first ansible Inspec tests"
# task :first do
# sh 'inspec exec spec/ansible_build_spec.rb'
# end
# desc "Run second ansible Inspec tests"
# task :second do
# sh 'inspec exec spec/ansible_second_build_spec.rb'
# end
end
namespace :python do
desc "unittest for ecr"
task :ecr do
sh 'python3 test_ecr.py'
end
end
end
namespace :integration do
desc "ecs test"
task :ecs do
sh 'inspec exec tests/ecs_spec.rb'
end
end
end
namespace :destroy do
desc "Destroy resources"
task :pulumi do
sh 'pulumi destroy --yes'
end
end
namespace :ci do
desc "Run CI test"
task :default do
Rake::Task["lint:pulumi"].invoke()
Rake::Task["build:pulumi"].invoke()
Rake::Task["test:unit:awspec:spec"].invoke()
Rake::Task["test:unit:inspec:stack"].invoke()
Rake::Task["spec:localhost"].invoke()
Rake::Task["destroy:pulumi"].invoke()
end
end
namespace :spec do
targets = []
Dir.glob('./serverspec/*').each do |dir|
next unless File.directory?(dir)
target = File.basename(dir)
target = "_#{target}" if target == "default"
targets << target
end
task :all => targets
task :default => :all
targets.each do |target|
original_target = target == "_default" ? target[1..-1] : target
desc "Run serverspec tests to #{original_target}"
RSpec::Core::RakeTask.new(target.to_sym) do |t|
ENV['TARGET_HOST'] = original_target
t.pattern = "serverspec/#{original_target}/*_spec.rb"
end
end
end
|
require "byebug"
class Player
attr_reader :name
attr_accessor :hand, :points
def initialize(name, deck)
@name = name
@hand = Hand.deal_from(deck)
@points = 0
end
def play_hand(board)
until won? || hand.next_move?(board) == false
self.hand.play(board)
board.render
end
if !won?
self.hand.hit(board.deck)
end
end
def won?
if hand.cards.empty?
return true
end
false
end
def return_cards(deck)
hand.return_cards(deck)
hand = nil
end
def update_points
self.hand.cards.each do |card|
case card.rank
when 13
@points -= 10
else
@points -= 1
end
end
points
end
def display_points
puts "#{self.name} has #{self.points} points"
end
end
|
class AddingUserRefToMemberships < ActiveRecord::Migration
def change
add_column :memberships, :user_id, :integer
add_index :memberships, :user_id
add_column :memberships, :project_id, :integer
add_index :memberships, :project_id
end
end
|
When(/^node "(.*?)" finds enough blocks for her park rate vote to become the median park rate$/) do |arg1|
step "node \"#{arg1}\" finds 3 blocks received by all nodes"
end
When(/^node "(.*?)" finds enough blocks for the voted park rate to become effective$/) do |arg1|
node = @nodes[arg1]
protocol = node.info["protocolversion"]
if protocol >= PROTOCOL_V2_0
step "node \"#{arg1}\" finds 12 blocks received by all nodes"
end
end
Then(/^the expected premium on node "(.*?)" for "(.*?)" NuBits parked for (\d+) blocks should be "(.*?)"$/) do |arg1, arg2, arg3, arg4|
node = @nodes[arg1]
amount = parse_number(arg2)
blocks = arg3.to_i
expected_premium = parse_number(arg4)
actual_premium = parse_number(node.unit_rpc('B', 'getpremium', amount, blocks))
expect(actual_premium).to eq(expected_premium)
end
|
module PUBG
class Telemetry
class LogPlayerAttack
require "pubg/telemetry/shared/attacker"
require "pubg/telemetry/shared/weapon"
require "pubg/telemetry/shared/vehicle"
attr_reader :data, :attackid, :attacker, :attacktype, :weapon, :vehicle, :_V, :_D, :_T
def initialize(args)
@data = args
@attackid = args["AttackId"]
@attacker = Attacker.new(args["Attacker"])
@attacktype = args["AttackType"]
@weapon = Weapon.new(args["Weapon"])
@vehicle = Vehicle.new(args["Vehicle"])
@_V = args["_V"]
@_D = args["_D"]
@_T = args["_T"]
end
end
end
end |
class Location < ActiveRecord::Base
validates :lat, :lng, presence: true
validates :address1, :presence => { :message => "STREET ADDRESS is required" }
validates :city, :presence => { :message => "CITY is required" }
validates :state, :presence => { :message => "STATE is required" }
validates :country, :presence => { :message => "COUNTRY is required" }
has_many :places
belongs_to :zip_code
geocoded_by :full_address, :latitude => :lat, :longitude => :lng
def self.nearby_places(area_text, distance = 50)
res = []
Location.near(area_text, distance).includes(:places => {:place_categories => :parent}).each do |l|
l.places.each do |p|
next unless p.name.present?
base_cat = p.get_parent_categories.first ? p.get_parent_categories.first.name : 'other'
res << {name: p.name, base_category: base_cat, place_url: '/places/' + p.id.to_s, lat: p.location.lat, lng: p.location.lng}
end
end
res
end
def full_address
[address1, city, state, country].compact.join(', ')
end
after_validation :geocode
# reverse_geocoded_by :lat, :lng
# after_validation :reverse_geocode
end
|
require 'omniauth-oauth2'
module OmniAuth
module Strategies
class PeentarID < OmniAuth::Strategies::OAuth2
option :name, 'peentar_id'
option :client_options, {
site: ::PeentarID.auth_site,
authorize_url: ::PeentarID.auth_url,
token_url: ::PeentarID.token_url,
redirect_uri: ::PeentarID.redirect_uri,
auth_scheme: :basic_auth,
}
def raw_info
return @raw_info unless @raw_info.nil?
user_info = ::PeentarID.user_info_url
@raw_info = access_token.get(user_info).parsed
@raw_info
end
uid do
raw_info['sub']
end
info do
{
name: raw_info['name'],
email: raw_info['email'],
sub: raw_info['sub'],
uid: raw_info['uid'],
email_verified: raw_info['email_verified'],
phone_number: raw_info['phone_number'],
phone_number_verified: raw_info['phone_number_verified'],
address: raw_info['address']
}
end
end
end
end
OmniAuth.config.add_camelization "peentar_id", "PeentarID"
|
require File.join(File.dirname(__FILE__), "test_helper")
require 'ctime_classifier'
class TestCTimeClassifier < Test::Unit::TestCase
def setup
@target_dir = 'test_target'
end
context "when the target directory is found" do
setup do
FileUtils.mkdir_p @target_dir
end
should "be able to instantiation with scanning the target directory" do
ctcl = CTimeClassifier.scan(@target_dir)
assert ctcl.kind_of?(CTimeClassifier)
end
context "when there are no files and directories in the target directory" do
setup do
@ctcl = CTimeClassifier.scan(@target_dir)
end
should "have no associations" do
assert_equal 0, @ctcl.length
end
end
teardown do
FileUtils.rm_rf @target_dir
end
end
context "when the target directory is not found" do
should "raise the RuntimeError if it is instantiated by the scan class method" do
#
end
end
def teardown
end
end
|
require 'rails_helper'
require 'web_helpers'
feature 'jobs' do
context 'no jobs have been added' do
scenario 'should display a prompt to add a job' do
visit '/jobs'
expect(page).to have_content 'No jobs yet'
expect(page).to have_link 'Add a job'
end
end
context 'creating jobs' do
scenario 'user signed in' do
sign_up
create_job
expect(page).to have_text 'Awesome tech job'
end
end
context 'viewing jobs' do
let!(:job){ Job.create(title:'job name') }
scenario 'lets anyone view a job' do
visit '/jobs'
click_link 'job name'
expect(page).to have_content 'job name'
expect(current_path).to eq "/jobs/#{job.id}"
end
end
context 'editing restaurants' do
before { Job.create title: 'junior dev', description: 'We teach you everything' }
scenario 'let a user edit a job spec' do
sign_up
edit_job
expect(page).to have_content 'Senior dev'
expect(page).to have_content 'We decided we want you to know everything already'
expect(current_path).to eq '/jobs'
end
end
context 'deleting Job specs' do
before { Job.create title: 'web developer', description: 'make me things' }
scenario 'removes a job when a user clicks a delete link' do
sign_up
visit '/jobs'
click_link 'Delete'
expect(page).not_to have_content 'web developer'
expect(page).to have_content 'Job spec deleted successfully'
end
end
end
|
class Status < ActiveHash::Base
self.data = [
{ id: 1, name: '-----' },
{ id: 2, name: 'その他補正なし' },
{ id: 3, name: '×2.0 (おいかぜ)' },
{ id: 4, name: '×0.5 (まひ状態)' }
]
include ActiveHash::Associations
has_many :calculations
end |
require 'rails_helper'
RSpec.describe Fact, type: :model do
let!(:fact) { create(:fact) }
describe "#set_defaults" do
context "when creating a new fact" do
it "returns the expected default fact score value of 0" do
expect(fact.score).to eq 0
end
end
end
describe "#supporting_evidence" do
context "when adding supporting evidence to fact" do
it "returns the created supporting evidence" do
evidence = create(:supporting_evidence, fact_id: fact.id)
expect(fact.supporting_evidence.first).to eq evidence
end
end
end
describe "#refuting_evidence" do
context "when adding refuting evidence to fact" do
it "returns the created refuting evidence" do
evidence = create(:refuting_evidence, fact_id: fact.id)
expect(fact.refuting_evidence[0]).to eq evidence
end
end
end
describe "#total_votes" do
context "when there are votes on a facts evidence" do
it "returns total votes on a facts evidence" do
evidence_1 = create(:evidence, support: true, fact_id: fact.id)
evidence_2 = create(:evidence, support: false, fact_id: fact.id)
vote_1 = create_list(:vote, 5, upvote: true, evidence_id: evidence_1.id)
vote_2 = create_list(:vote, 5, upvote: false, evidence_id: evidence_2.id)
fact.reload
expect(fact.total_votes).to eq 10
end
end
end
describe "#update_score" do
context "when there are equal upvotes for supporting and refuting evidence" do
it "returns a fact score of 50" do
evidence_1 = create(:evidence, support: true, fact_id: fact.id)
evidence_2 = create(:evidence, support: false, fact_id: fact.id)
vote_1 = create(:vote, upvote: true, evidence_id: evidence_1.id)
vote_2 = create(:vote, upvote: true, evidence_id: evidence_2.id)
fact.reload # This is necessary to make the test pass. Why exactly?
# Because the fact was created before the test, and doesn't know
# about the evidences and votes created in this test
fact.update_score
expect(fact.score).to eq 50
end
end
context "when there is only supporting evidence and there are equal upvotes and downvotes" do
it "returns a fact score of 50" do
evidence_1 = create(:evidence, support: true, fact_id: fact.id)
evidence_2 = create(:evidence, support: true, fact_id: fact.id)
vote_1 = create(:vote, upvote: true, evidence_id: evidence_1.id)
vote_2 = create(:vote, upvote: false, evidence_id: evidence_2.id)
fact.reload
fact.update_score
expect(fact.score).to eq 50
end
end
context "when there is only refuting evidence and only upvotes" do
it "returns a fact score of 0" do
evidence_1 = create(:evidence, support: false, fact_id: fact.id)
evidence_2 = create(:evidence, support: false, fact_id: fact.id)
vote_1 = create(:vote, upvote: true, evidence_id: evidence_1.id)
vote_2 = create(:vote, upvote: true, evidence_id: evidence_2.id)
fact.reload
fact.update_score
expect(fact.score).to eq 0
end
end
context "when there is only refuting evidence and only downvotes" do
it "returns a fact score of 0" do
evidence_1 = create(:evidence, support: false, fact_id: fact.id)
evidence_2 = create(:evidence, support: false, fact_id: fact.id)
vote_1 = create(:vote, upvote: true, evidence_id: evidence_1.id)
vote_2 = create(:vote, upvote: true, evidence_id: evidence_2.id)
fact.reload
fact.update_score
expect(fact.score).to eq 0
end
end
end
end
|
#! /usr/bin/ruby
$LOAD_PATH << File.dirname(__FILE__)
module AnalyzeSchedule
def self.team_name(schedule, tnum)
if schedule.has_key?(:team_names)
return schedule[:team_names][tnum - 1]
end
return tnum.to_s
end
def self.analyze_schedule(schedule, html)
all_games_for_each_team = Hash.new { |hsh, key| hsh[key] = [] }
schedule[:weeks].each do |week|
bye_t = week[:bye]
if bye_t != nil
all_games_for_each_team[bye_t].push({
:bye => true,
:skipped => false,
:date => week[:date],
:opponent => nil,
:home => false,
:start_time => nil,
:timeslot_id => nil,
:rink_id => nil,
})
end
# A skipped game happens when a league plays on two nights.
# The primary night of the league has games scheduled, but the
# secondary night has a holiday so there are no games. We
# record the teams that should have played on the overflow
# day as a skipped game.
if week.has_key?(:skipped) && week[:skipped].size() == 2
week[:skipped].each do |t|
all_games_for_each_team[t].push({
:bye => false,
:skipped => true,
:date => week[:date],
:opponent => nil,
:home => false,
:start_time => nil,
:timeslot_id => nil,
:rink_id => nil,
})
end
end
week[:games].each do |game|
#puts "<br>#{team_name(schedule, game[:home])} v. #{team_name(schedule, game[:away])}"
t = game[:home]
all_games_for_each_team[t].push({
:bye => false,
:skipped => false,
:date => game[:datetime].to_date,
:opponent => game[:away],
:home => true,
:start_time => game[:start_time],
:timeslot_id => game[:timeslot_id],
:rink_id => game[:rink_id],
})
t = game[:away]
all_games_for_each_team[t].push({
:bye => false,
:skipped => false,
:date => game[:datetime].to_date,
:opponent => game[:home],
:home => false,
:start_time => game[:start_time],
:timeslot_id => game[:timeslot_id],
:rink_id => game[:rink_id],
})
end
end
teams_seen = all_games_for_each_team.keys.map {|t| team_name(schedule, t) }.sort
puts "#{teams_seen.size()} teams seen in this calendar: "
puts "<pre>" if html
puts " #{teams_seen.join(', ')}"
puts "</pre>" if html
puts ""
team_number_of_games = Hash.new(0)
team_late_games = Hash.new(0)
team_early_games = Hash.new(0)
team_bye_games = Hash.new(0)
team_overflow_games = Hash.new(0)
team_skipped_games = Hash.new(0)
team_num_games_at_each_rink = Hash.new {|hsh, key| hsh[key] = Hash.new(0) }
all_games_for_each_team.keys.each do |tnum|
team_name = team_name(schedule, tnum)
all_games_for_each_team[tnum].each do |g|
tid = g[:timeslot_id]
if tid != nil
if schedule[:timeslots][tid][:late_game]
team_late_games[team_name] += 1
end
if schedule[:timeslots][tid][:late_game]
team_early_games[team_name] += 1
end
if schedule[:timeslots][tid][:overflow_day]
team_overflow_games[team_name] += 1
end
if schedule[:timeslots][tid][:overflow_day]
team_overflow_games[team_name] += 1
end
if g[:bye]
team_bye_games[team_name] += 1
end
if g[:skipped]
team_skipped_games[team_name] += 1
end
if g[:bye] == false && g[:skipped] == false
team_number_of_games[team_name] += 1
end
rink_name = schedule[:rinks][g[:rink_id]][:short_name]
team_num_games_at_each_rink[team_name][rink_name] += 1
end
end
end
# this one would only be interesting if the schedule was having serious problems...
#
# print "<h4>" if html
# print "Total # of games each team has in this schedule:"
# print "</h4>" if html
# puts ""
# puts "<pre>" if html
# team_number_of_games.keys.sort {|x,y| team_number_of_games[y] <=> team_number_of_games[x]}.each do |tname|
# puts " #{team_number_of_games[tname]} games: #{tname}"
# end
# puts "</pre>" if html
# puts ""
if team_late_games.size() > 0
print "<h4>" if html
print "# of late games each team has in this schedule:"
print "</h4>" if html
puts ""
puts "<pre>" if html
team_late_games.keys.sort {|x,y| team_late_games[y] <=> team_late_games[x]}.each do |tname|
puts " #{team_late_games[tname]} games: #{tname}"
end
puts "</pre>" if html
puts ""
end
# if team_early_games.size() > 0
# print "<h4>" if html
# print "# of early games each team has in this schedule:"
# print "</h4>" if html
# puts ""
# puts "<pre>" if html
# team_early_games.keys.sort {|x,y| team_early_games[y] <=> team_early_games[x]}.each do |tname|
# puts " #{team_early_games[tname]} games: #{tname}"
# end
# puts "</pre>" if html
# puts ""
# end
if team_bye_games.size() > 0
print "<h4>" if html
print "# of bye games each team has in this schedule:"
print "</h4>" if html
puts ""
puts "<pre>" if html
team_bye_games.keys.sort {|x,y| team_bye_games[y] <=> team_bye_games[x]}.each do |tname|
puts " #{team_bye_games[tname]} games: #{tname}"
end
puts "</pre>" if html
puts ""
end
if team_skipped_games.size() > 0
print "<h4>" if html
print "# of skipped games each team has in this schedule:"
print "</h4>" if html
puts ""
puts "<pre>" if html
team_skipped_games.keys.sort {|x,y| team_skipped_games[y] <=> team_skipped_games[x]}.each do |tname|
puts " #{team_skipped_games[tname]} games: #{tname}"
end
puts "</pre>" if html
puts ""
end
# only print the rink summaries if there is more than one rink
if team_num_games_at_each_rink.values.map {|v| v.keys}.flatten.sort.uniq.size() > 1
rinks_seen = team_num_games_at_each_rink.values.map {|v| v.keys}.flatten.sort.uniq.sort()
rinks_seen.each do |rinkname|
team_num_games_at_each_rink.keys.each do |tname|
if !team_num_games_at_each_rink[tname].has_key?(rinkname)
team_num_games_at_each_rink[tname][rinkname] = 0
end
end
print "<h4>" if html
print "# of games each team has at #{rinkname} in this schedule:"
print "</h4>" if html
puts ""
puts "<pre>" if html
team_num_games_at_each_rink.keys.sort {|x,y| team_num_games_at_each_rink[y][rinkname] <=> team_num_games_at_each_rink[x][rinkname]}.each do |tname|
puts " #{team_num_games_at_each_rink[tname][rinkname]} games: #{tname}"
end
puts "</pre>" if html
puts ""
end
end
all_games_for_each_team.keys.sort {|x,y| team_name(schedule, x) <=> team_name(schedule, y)}.each do |tnum|
team_name = team_name(schedule, tnum)
if html
puts "<h3>#{team_name}</h3>"
else
puts team_name
end
puts "<blockquote>" if html
gamecount = all_games_for_each_team[tnum].select {|g| g[:bye] == false && g[:skipped] == false}.size()
puts "Number of games: #{gamecount}"
home_game_count = all_games_for_each_team[tnum].select {|g| g[:home] == true }.size()
away_game_count = all_games_for_each_team[tnum].select {|g| g[:home] == false && g[:bye] == false && g[:skipped] == false}.size()
bye_game_count = all_games_for_each_team[tnum].select {|g| g[:bye] == true }.size()
skipped_game_count = all_games_for_each_team[tnum].select {|g| g[:skipped] == true }.size()
puts "<br />" if html
printf("Number of home games: #{home_game_count} (%d%%)\n", 100.0 * home_game_count / gamecount)
puts "<br />" if html
printf("Number of away games: #{away_game_count} (%d%%)\n", 100.0 * away_game_count / gamecount)
if bye_game_count > 0
puts "<br />" if html
printf("Number of byes: #{bye_game_count} (%d%%)\n", 100.0 * bye_game_count / gamecount)
end
if skipped_game_count > 0
puts "<br />" if html
printf("Number of skipped games: #{skipped_game_count} (%d%%)\n", 100.0 * skipped_game_count / gamecount)
end
game_time_strs = Array.new
opponent_name_strs = Array.new
rink_name_strs = Array.new
all_games_for_each_team[tnum].each do |g|
if g[:bye] != false
if html
game_time_strs.push("<b>bye</b>")
opponent_name_strs.push("<b>bye</b>")
rink_name_strs.push("<b>bye</b>")
else
game_time_strs.push("BYE")
opponent_name_strs.push("BYE")
rink_name_strs.push("BYE")
end
next
end
if g[:skipped] == true
if html
game_time_strs.push("<b>skipped</b>")
opponent_name_strs.push("<b>skipped</b>")
rink_name_strs.push("<b>skipped</b>")
else
game_time_strs.push("SKIPPED")
opponent_name_strs.push("SKIPPED")
rink_name_strs.push("SKIPPED")
end
next
end
game_time_desc = schedule[:timeslots][g[:timeslot_id]][:description]
if schedule[:timeslots][g[:timeslot_id]][:overflow_day]
if html
game_time_desc = "<b>ALT</b> #{game_time_desc}"
else
game_time_desc = "ALT #{game_time_desc}"
end
end
game_time_strs.push(game_time_desc)
opponent_name_strs.push(team_name(schedule, g[:opponent]))
rink_name_strs.push(schedule[:rinks][g[:rink_id]][:short_name])
end
puts "<p />" if html
print "<b>" if html
print "Game times"
print "</b>" if html
print ": "
puts game_time_strs.join(', ')
puts "<p />" if html
print "<b>" if html
print "Opponents"
print "</b>" if html
print ": "
puts opponent_name_strs.join(', ')
if schedule[:rinkcount] > 1
puts "<p />" if html
print "<b>" if html
print "Rinks"
print "</b>" if html
print ": "
puts rink_name_strs.join(', ')
end
game_times = Hash.new(0)
opponents = Hash.new(0)
rinks = Hash.new(0)
all_games_for_each_team[tnum].each do |g|
next if g[:bye] != false
next if g[:skipped] == true
opponents[team_name(schedule, g[:opponent])] += 1
hr = schedule[:timeslots][g[:timeslot_id]][:hour]
min = schedule[:timeslots][g[:timeslot_id]][:minute]
time = "%02d:%02d" % [hr, min]
game_times[time] += 1
rinks[schedule[:rinks][g[:rink_id]][:short_name]] += 1
end
puts "<p />" if html
print "Number of "
print "<b>" if html
print "games at each timeslot"
print "</b>" if html
puts ":"
puts "<tt>" if html
game_times.keys.sort {|x,y| x <=> y}.each do |t|
puts "<br />" if html
printf " #{t} - #{game_times[t]} games (%d%%)\n", 100.0 * game_times[t] / gamecount
end
puts "</tt>" if html
timeslot_attribs = all_games_for_each_team[tnum].map do |g|
tid = g[:timeslot_id]
schedule[:timeslots][tid]
end
if timeslot_attribs.count {|ts| ts[:late_game] == true || ts[:early_game] == true || ts[:overflow_day] == true} > 0
puts "<p />" if html
print "Number of "
print "<b>" if html
print "games at undesirable timeslots"
print "</b>" if html
puts ":"
puts "<tt>" if html
late_games = timeslot_attribs.select {|ts| ts[:late_game]}
early_games = timeslot_attribs.select {|ts| ts[:early_game]}
overflow_day_games = timeslot_attribs.select {|ts| ts[:overflow_day]}
if early_games.size() > 0
games = early_games.size()
puts "<br />" if html
printf " #{games} - early games (%d%%)\n", 100.0 * games / gamecount
end
if late_games.size() > 0
games = late_games.size()
puts "<br />" if html
printf " #{games} - late games (%d%%)\n", 100.0 * games / gamecount
end
if overflow_day_games.size() > 0
games = overflow_day_games.size()
puts "<br />" if html
printf " #{games} - overflow day games (%d%%)\n", 100.0 * games / gamecount
end
puts "</tt>" if html
end
puts "<p />" if html
print "Number of "
print "<b>" if html
print "times playing against opposing teams"
print "</b>" if html
puts ":"
puts "<tt>" if html
opponents.keys.sort {|x,y| opponents[y] <=> opponents[x]}.each do |o|
puts "<br />" if html
printf " #{opponents[o]} games: #{o} (%d%%)\n", 100.0 * opponents[o] / gamecount
end
puts "</tt>" if html
if schedule[:rinkcount] > 1
puts "<p />" if html
print "Number of "
print "<b>" if html
print "times playing at each rink"
print "</b>" if html
puts ":"
puts "<tt>" if html
rinks.keys.sort {|x,y| rinks[y] <=> rinks[x]}.each do |r|
puts "<br />" if html
printf " #{rinks[r]} games: #{r} (%d%%)\n", 100.0 * rinks[r] / gamecount
end
puts "</tt>" if html
end
opponent_list = all_games_for_each_team[tnum].select {|g| g[:bye] == false && g[:skipped] == false}.map {|g| team_name(schedule, g[:opponent])}
times_list = all_games_for_each_team[tnum].select {|g| g[:bye] == false && g[:skipped] == false}.map {|g| g[:timeslot_id]}
rink_list = all_games_for_each_team[tnum].select {|g| g[:bye] == false && g[:skipped] == false}.map {|g| g[:rink_id]}
opponent_streaks = opponent_list.chunk{|y| y}.map{|y, ys| [y, ys.length]}.select{|v| v[1] > 1}
time_streaks = times_list.chunk{|y| y}.map{|y, ys| [y, ys.length]}.select{|v| v[1] > 1}.
select do |v|
tid = v[0]
ts = schedule[:timeslots][tid]
ts[:late_game] == true || ts[:early_game] == true || ts[:overflow_day] == true
end.
map {|v| [schedule[:timeslots][v[0]][:description], v[1]]}
rink_streaks = rink_list.chunk{|y| y}.map{|y, ys| [y, ys.length]}.select{|v| v[1] > 1}.
map {|v| [schedule[:rinks][v[0]][:long_name], v[1]]}
puts "<p />" if html
print "Back-to-back "
print "<b>" if html
print "games against the same opponent"
print "</b>" if html
puts ":"
if opponent_streaks.size() > 0
puts "<br /><tt>" if html
opponent_streaks.sort {|x,y| y[1] <=> x[1]}.each do |v|
opponent = v[0]
count = v[1]
puts " #{count} games in a row against #{opponent}"
puts "<br />" if html
end
puts "</tt>" if html
end
puts "<p />" if html
print "Back-to-back "
print "<b>" if html
print "games in the same timeslot"
print "</b>" if html
puts ":"
if time_streaks.size() > 0
puts "<br /><tt>" if html
time_streaks.sort {|x,y| y[1] <=> x[1]}.each do |v|
timeslot = v[0]
count = v[1]
puts " #{count} games in a row at #{timeslot}"
puts "<br />" if html
end
puts "</tt>" if html
end
if rink_streaks.size() > 0 && schedule[:rinkcount] > 1
puts "<p />" if html
print "Back-to-back "
print "<b>" if html
print "games at the same rink"
print "</b>" if html
puts ":"
puts "<br /><tt>" if html
rink_streaks.sort {|x,y| y[1] <=> x[1]}.each do |v|
rink = v[0]
count = v[1]
puts " #{count} games in a row at rink #{rink}"
puts "<br />" if html
end
puts "</tt>" if html
end
if html
puts "</blockquote>"
puts "<p />"
else
puts ""
end
end
end
end
if __FILE__ == $0
require 'parse-ics'
ics_text = %x[./test-ics.rb]
schedule = ParseICS.ics_to_schedule(ics_text)
AnalyzeSchedule.analyze_schedule(schedule, false)
end
|
class Song
attr_accessor :name,:artist,:genre
@@all=[]
def initialize(name,artist,genre)
@name = name
@artist=artist
@genre=genre
@@all << self
end
def self.all
@@all
end
end
|
require 'rails_helper'
RSpec.describe Product, type: :model do
context 'fields' do
it { is_expected.to have_field(:title).of_type(String) }
it { is_expected.to have_field(:description).of_type(String) }
it { is_expected.to have_field(:image_url).of_type(String) }
it { is_expected.to have_field(:date).of_type(String) }
it { is_expected.to have_field(:price).of_type(Float) }
end
context 'validations' do
it { is_expected.to validate_presence_of(:title) }
it { is_expected.to validate_presence_of(:description) }
it { is_expected.to validate_presence_of(:image_url) }
it { is_expected.to validate_presence_of(:date) }
it { is_expected.to validate_numericality_of(:price) }
it { is_expected.to validate_length_of(:description).with_minimum(20) }
end
context 'associations' do
it { is_expected.to have_many :line_items }
it { is_expected.to have_many(:comments).with_dependent(:destroy) }
end
=begin
context 'callbacks' do
subject(:product) { FactoryGirl.build(:product) }
end
context 'scopes' do
subject(:product) { FactoryGirl.build(:product) }
end
=end
end
|
# Preview all emails at http://localhost:3000/rails/mailers/marketing_mailer
class MarketingMailerPreview < ActionMailer::Preview
# Preview this email at http://localhost:3000/rails/mailers/marketing_mailer/promotion
def promotion
MarketingMailer.with(
user: User.first,
message: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede.",
subject: "Limited time offer!"
).promotion
end
end |
require 'spec_helper'
describe "StaticPages" do
describe "Home page" do
it "should have the h1 'Sample App'" do
visit '/static_pages/home'
page.should have_selector('h1', :text => 'Test App')
end
it "should have the title 'Test App'" do
visit '/static_pages/home'
page.should have_selector('title', :text => "Bindraw | Home")
end
it "should have a test canvas" do
visit '/static_pages/home'
page.should have_selector('canvas', :id => "test")
end
end
end
|
# == Schema Information
#
# Table name: avatars
#
# id :integer not null, primary key
# user_id :integer
# image_file_name :string(255)
# image_content_type :string(255)
# image_file_size :integer
# image_updated_at :datetime
# title :string(255)
# created_at :datetime
# updated_at :datetime
# description :text default("")
#
class Avatar < ActiveRecord::Base
validates :image, presence: true
belongs_to :user
default_scope -> { order(:id => :asc) }
has_attached_file :image, styles: {
big: "250x250#",
small: "50x50#"
}
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end
|
# == Schema Information
#
# Table name: bills
#
# id :integer not null, primary key
# name :string(255)
# total :float
# finished :boolean
# created_at :datetime
# updated_at :datetime
# user_id :text
#
class Bill < ActiveRecord::Base
has_and_belongs_to_many :user
has_many :item
serialize :user_id, Array
validates :name, presence: true
end
|
class CellGenerator
attr_reader :width, :height, :living_cell_locations, :number_random_living_cells
def initialize(args = {})
@width = args[:width]
@height = args[:height]
@number_random_living_cells = args.fetch(:number_random_living_cells, default_random_living_cells)
@living_cell_locations = args.fetch(:living_cell_locations, generate_living_cell_locations(@number_random_living_cells))
end
def default_random_living_cells
0
end
def generate_cells
new_cells = []
width.times do |x|
height.times do |y|
state = alive?(x, y) ? Cell::States::ALIVE : Cell::States::DEAD
new_cells << Cell.new(x: x, y: y, state: state)
end
end
new_cells
end
def generate_living_cell_locations(num)
matrix = num.times.map do |i|
x = rand(0..(width - 1))
y = rand(0..(height - 1))
[x, y]
end
end
def alive?(x, y)
living_cell_locations.include?([x, y])
end
end |
require_relative 'test_helper'
class RequestValidatorTest < Minitest::Test
def setup
@app = lambda { |env| [200, {}, []] }
@validator = Superintendent::Request::Validator.new(
@app,
monitored_content_types: ['application/json', 'application/vnd.api+json'],
forms_path: File.expand_path('../forms', __FILE__)
)
end
def mock_env(path, method, opts={})
Rack::MockRequest.env_for(
path,
{
'CONTENT_TYPE' => 'application/json',
method: method,
}.merge(opts)
)
end
def test_default_env
env = Rack::MockRequest.env_for('/', { 'method': 'GET' })
status, _headers, _body = @validator.call(env)
assert_equal 200, status
end
def test_monitored_content
env = mock_env('/', 'GET')
status, _headers, _body = @validator.call(env)
assert_equal 200, status
end
def test_monitored_content_create
params = {
_jsonapi: {
data: {
attributes: {
first_name: 'Test User'
},
type: 'users'
}
}
}
env = mock_env(
'/users',
'POST',
input: JSON.generate(params),
'CONTENT_TYPE' => 'application/vnd.api+json'
)
status, _headers, _body = @validator.call(env)
assert_equal 200, status
end
def test_monitored_accept_update
params = {
_jsonapi: {
data: {
attributes: {
first_name: 'Test User'
},
id: 'US5d251f5d477f42039170ea968975011b',
type: 'users'
}
}
}
%w[PUT PATCH].each do |method|
env = mock_env(
'/users/US5d251f5d477f42039170ea968975011b',
method,
input: JSON.generate(params),
'CONTENT_TYPE' => 'application/vnd.api+json'
)
status, _headers, _body = @validator.call(env)
assert_equal 200, status
end
end
def test_single_resource
params = {
_json: {
data: {
attributes: {
first_name: 'Test User'
},
id: 'US5d251f5d477f42039170ea968975011b',
type: 'users'
}
}
}
env = mock_env('/users/US5d251f5d477f42039170ea968975011b', 'PUT', input: JSON.generate(params))
status, _headers, _body = @validator.call(env)
assert_equal 200, status
end
def test_single_resource_json_api
params = {
_jsonapi: {
data: {
attributes: {
first_name: 'Test User'
},
id: 'US5d251f5d477f42039170ea968975011b',
type: 'users'
}
}
}
env = mock_env('/users/US5d251f5d477f42039170ea968975011b', 'PUT',
input: JSON.generate(params), 'CONTENT_TYPE' => 'application/vnd.api+json')
status, _headers, _body = @validator.call(env)
assert_equal 200, status
end
def test_optional_attributes_not_supplied
params = {
_jsonapi: {
data: {
meta: {},
type: 'no_attributes'
}
}
}
env = mock_env('/no_attributes_supplied/NA1111111111111111111111111111111', 'POST',
input: JSON.generate(params), 'CONTENT_TYPE' => 'application/vnd.api+json')
status, _headers, _body = @validator.call(env)
assert_equal 200, status
end
def test_relationships
params = {
_jsonapi: {
data: {
id: 'US5d251f5d477f42039170ea968975011b',
type: 'mothers'
}
}
}
env = mock_env('/users/US5d251f5d477f42039170ea968975011b/relationships/mother', 'PUT',
input: JSON.generate(params), 'CONTENT_TYPE' => 'application/vnd.api+json')
status, _headers, _body = @validator.call(env)
assert_equal 200, status
end
def test_relationships_400
params = {
_jsonapi: {
data: {
id: 'US5d251f5d477f42039170ea968975011b',
type: 'fathers'
}
}
}
env = mock_env('/users/US5d251f5d477f42039170ea968975011b/relationships/mother', 'PUT',
input: JSON.generate(params), 'CONTENT_TYPE' => 'application/vnd.api+json')
status, _headers, body = @validator.call(env)
assert_equal 400, status
expected = {"status"=>400, "code"=>"enum", "title"=>"Enum", "detail"=>"The property 'data/type' value \"fathers\" did not match one of the following values: mothers"}
validate_error(expected, body)
end
def test_relationships_no_form_404
params = {
data: {
id: 'US5d251f5d477f42039170ea968975011b',
type: 'father'
}
}
env = mock_env('/users/US5d251f5d477f42039170ea968975011b/relationships/father', 'PUT',
input: JSON.generate(params), 'CONTENT_TYPE' => 'application/vnd.api+json')
status, _headers, _body = @validator.call(env)
assert_equal 404, status
end
def test_relationships_delete_200
params = {
_jsonapi: {
data: {
id: 'US5d251f5d477f42039170ea968975011b',
type: 'mothers'
}
}
}
env = mock_env('/users/US5d251f5d477f42039170ea968975011b/relationships/mother', 'DELETE',
input: JSON.generate(params), 'CONTENT_TYPE' => 'application/vnd.api+json')
status, _headers, _body = @validator.call(env)
assert_equal 200, status
end
def test_relationships_delete_400_bad_request
params = {
data: {
id: 'US5d251f5d477f42039170ea968975011b'
}
}
env = mock_env('/users/US5d251f5d477f42039170ea968975011b/relationships/mother', 'DELETE',
input: JSON.generate(params), 'CONTENT_TYPE' => 'application/vnd.api+json')
status, _headers, body = @validator.call(env)
assert_equal 400, status
expected = { "code"=>"type-v4", "title"=>"TypeV4", "detail"=>"The property '' of type null did not match the following type: object" }
validate_error(expected, body)
end
def test_relationships_delete_400_no_body
env = mock_env('/users/US5d251f5d477f42039170ea968975011b/relationships/mother', 'DELETE',
'CONTENT_TYPE' => 'application/vnd.api+json')
status, _headers, body = @validator.call(env)
assert_equal 400, status
expected = {"code"=>"required", "title"=>"Required", "detail"=>"The request did not contain a required property of 'data'"}
validate_error(expected, body)
end
def test_relationships_delete_404_no_form_method
params = {
_jsonapi: {
data: {
id: 'US5d251f5d477f42039170ea968975011b',
type: 'users'
}
}
}
env = mock_env('/users/US5d251f5d477f42039170ea968975011b', 'DELETE',
input: JSON.generate(params), 'CONTENT_TYPE' => 'application/vnd.api+json')
status, _headers, _body = @validator.call(env)
assert_equal 404, status
end
def test_delete_200_no_body_no_form_method
env = mock_env('/users/US5d251f5d477f42039170ea968975011b', 'DELETE',
'CONTENT_TYPE' => 'application/vnd.api+json')
status, _headers, _body = @validator.call(env)
assert_equal 200, status
end
def test_no_form_method
['POST', 'PATCH', 'PUT'].each do |verb|
env = mock_env('/no_methods/NM5d251f5d477f42039170ea968975011b', verb,
'CONTENT_TYPE' => 'application/vnd.api+json')
status, _headers, _body = @validator.call(env)
assert_equal 404, status
end
end
def test_plural_relationships_use_singular_form
params = {
_jsonapi: { data: [] }
}
env = mock_env('/users/US5d251f5d477f42039170ea968975011b/relationships/things', 'PUT',
input: JSON.generate(params), 'CONTENT_TYPE' => 'application/vnd.api+json')
status, _headers, _body = @validator.call(env)
assert_equal 200, status
end
def test_no_form_404
env = mock_env('/things', 'POST')
status, _headers, _body = @validator.call(env)
assert_equal 404, status
end
def test_nested_resource_no_form_404
env = mock_env('/users/US5d251f5d477f42039170ea968975011b/things', 'POST')
status, _headers, _body = @validator.call(env)
assert_equal 404, status
end
def test_schema_conflict
params = {
attributes: {
first_name: 123
},
type: 'users'
}
env = mock_env('/users', 'POST', input: JSON.generate(params))
status, _headers, body = @validator.call(env)
assert_equal 400, status
expected = {
"code" => "type-v4",
"title" => "TypeV4",
"detail" => "The property '' of type null did not match the following type: object"
}
validate_error(expected, body)
end
def test_schema_conflict_with_alternate_error_class
validator = Superintendent::Request::Validator.new(
@app,
monitored_content_types: ['application/json'],
error_class: MyError,
forms_path: File.expand_path('../forms', __FILE__)
)
params = {
attributes: {
first_name: 123
},
type: 'users'
}
env = mock_env('/users', 'POST', input: JSON.generate(params))
status, _headers, body = validator.call(env)
assert_equal 400, status
expected = {
"id" => nil,
"status" => 400,
"code" => "type-v4",
"title" => "TypeV4",
"detail" => "The property '' of type null did not match the following type: object",
"type" => "errors"
}
errors = JSON.parse(body.first)['errors']
assert_equal expected, errors.first
end
def test_400_missing_required_attribute
params = {
attributes: {
last_name: 'Jones'
},
type: 'users'
}
env = mock_env('/users', 'POST', input: JSON.generate(params))
status, _headers, body = @validator.call(env)
assert_equal 400, status
# TODO: this seems like the wrong error
expected = {
"code" => "type-v4",
"title" => "TypeV4",
"detail" => "The property '' of type null did not match the following type: object"
}
validate_error(expected, body)
end
def test_drop_extra_params
params = {
_json: {
data: {
attributes: {
first_name: 'Bob',
last_name: 'Jones',
extra: 'value'
},
type: 'users'
}
}
}
env = mock_env(
'/users',
'POST',
input: JSON.generate(params)
)
status, _headers, _body = @validator.call(env)
attributes = env.dig(
'action_dispatch.request.request_parameters',
'_json',
'data',
'attributes'
)
refute attributes.has_key? 'extra'
assert_equal 200, status
end
end
|
require 'test_helper'
class ArticleTest < ActiveSupport::TestCase
test "should create article" do
article = Article.new
article.user = users(:eugene)
article.title = "Test article"
article.body = "Test body"
assert article.save
end
test "should find article" do
article_id = articles(:welcome_to_rails).id
assert_nothing_raised { Article.find(article_id) }
end
test "should update article" do
article = articles(:welcome_to_rails)
assert article.update_attributes(title: "New title")
end
test "should destroy article" do
article = articles(:welcome_to_rails)
article.destroy
assert_raise(ActiveRecord::RecordNotFound) { Article.find(article.id) }
end
test "should not create an article without title nor body" do
article = Article.new
assert !article.valid?
assert article.errors[:title].any?
assert article.errors[:body].any?
assert_equal ["can't be blank"], article.errors[:title]
assert_equal ["can't be blank"], article.errors[:body]
assert !article.save
end
end
|
class AddTsToDiscussion < ActiveRecord::Migration
def self.up
add_column :discussions, :ts, :string
end
def self.down
remove_column :discussions, :ts
end
end
|
class UserSerializer < ActiveModel::Serializer
attributes :username, :email, :id
has_many :comments
end
|
module SuccessionDatesValidation
def self.included(base)
base.extend(ClassMethods)
end
def update_from_json(json, extra_values = {}, apply_nested_records = true)
obj = super
obj.validate_succession_date!
obj
end
def validate_succession_date!
my_relationships('series_system_agent_relationships').each_with_index do |relationship, idx|
next unless relationship[:jsonmodel_type] == 'series_system_agent_agent_succession_relationship'
relator = BackendEnumSource.value_for_id('series_system_succession_relator', relationship[:relator_id])
date_to_check = nil
if relator == 'supercedes' && relationship[:relationship_target_id] != self.id
next if self.date.empty?
next if self.date.first.begin.nil?
date_to_check = self.date.first.begin
else
target_obj = relationship.other_referent_than(self)
next if target_obj.nil?
next if target_obj.date.empty?
next if target_obj.date.first.begin.nil?
date_to_check = target_obj.date.first.begin
end
unless valid_succession_date?(relationship[:start_date], date_to_check)
self.errors.add(:"series_system_agent_relationships/#{idx}/start_date", "Succession Date must be after the successor existence date")
raise Sequel::ValidationFailed.new(self)
end
end
end
def valid_succession_date?(succession_date, successor_date)
# raise ["valid_succession_date?", succession_date, successor_date].inspect
begin
JSONModel::Validations.parse_sloppy_date(succession_date)
JSONModel::Validations.parse_sloppy_date(successor_date)
rescue ArgumentError => e
# let the other validations catch this
return true
end
shorty = [succession_date.length, successor_date.length].min
succession_date[0,shorty] >= successor_date[0,shorty]
end
module ClassMethods
def create_from_json(json, extra_values = {})
obj = super
obj.validate_succession_date!
obj
end
end
end |
class RemoveReportsTable < ActiveRecord::Migration
def change
drop_table :reports if ActiveRecord::Base.connection.table_exists? 'reports'
end
end |
class DataParent < ApplicationRecord
has_many :children, -> { order 'id ASC' }, class_name: 'DataChild', foreign_key: 'data_parent_id'
accepts_nested_attributes_for :children
end
|
class Contest::TaskSerializer < ActiveModel::Serializer
root false
cached
attributes :id, :title, :body, :quest, :kind
attributes :skip, :timespan
has_many :choices, serializer: Contest::ChoiceSerializer
def kind
"single"
end
def skip
0
end
def timespan
0
end
end
|
class Image < ApplicationRecord
belongs_to :user
mount_uploader :picture, PictureUploader
validate :picture_size
private
def picture_size
if picture.size > 5.megabytes
errors.add(:picture, "should be less than 5MB")
end
end
end
|
FactoryGirl.define do
factory :library_category do
name {Faker::Name.name}
end
end
|
class Certificate < ActiveRecord::Base
include AASM
extend FriendlyId
friendly_id :code
CODE_LENGTH = 8
belongs_to :merchant
belongs_to :customer
belongs_to :charity
belongs_to :deal
before_validation :create_code, :on => :create
validates :merchant_id, :charity_id, :presence => true
validates :customer, :presence => true, :associated => true
validates :code, :presence => true, :uniqueness => true
after_create :create_customer_newsletter_subscriptions!
include CommonAttributes::OfferCapCents
include CommonAttributes::AmountCents
include CommonAttributes::DiscountRate
attr_accessor :communicate_with_merchant, :communicate_with_charity
#--- state machine
aasm_initial_state :unredeemed
aasm :column => "status" do
state :unredeemed
state :redeemed
state :canceled
event :redeem do
transitions :from => :unredeemed, :to => :redeemed
end
event :unredeem do
transitions :from => :redeemed, :to => :unredeemed
end
event :cancel do
transitions :from => [:redeemed, :unredeemed], :to => :canceled
end
end
scope :unredeemed, where(:status => "unredeemed")
scope :redeemed, where(:status => "redeemed")
scope :canceled, where(:status => "canceled")
scope :donatable, where("status IN (?)", ["redeemed", "unredeemed"])
scope :current_month, where("created_at >= ? AND created_at <= ?", Time.zone.now.beginning_of_month, Time.zone.now.end_of_month)
def title
"#{amount.format} gift certificate redeemable at #{merchant.name}"
end
def communicate_with_charity?
!!communicate_with_charity.to_s.match(/^true|1/)
end
def communicate_with_merchant?
!!communicate_with_merchant.to_s.match(/^true|1/)
end
private
def create_code
self.code ||= rand(36 ** CODE_LENGTH).to_s(36).upcase
end
def create_customer_newsletter_subscriptions!
customer.newsletter_subscriptions.create! :merchant => merchant if customer && communicate_with_merchant?
customer.newsletter_subscriptions.create! :charity => charity if customer && communicate_with_charity?
end
end
|
# frozen_string_literal: true
require 'rails_helper'
describe UserMailer do
describe '#basic' do
subject(:mailer) do
described_class.basic(user.username, user.email, user.instance_variable_get('@generated_password'))
end
let(:user) { create(:user) }
its(:body) do
is_expected.to eq("Username: #{user.username} \n Password: #{user.instance_variable_get('@generated_password')}")
end
its(:subject) { is_expected.to eq 'Account details' }
its(:to) { is_expected.to eq [user.email] }
end
end
|
require 'test_helper'
class Sims::SimsResearchesControllerTest < ActionDispatch::IntegrationTest
setup do
@postgresql_view_person = postgresql_view_people(:one)
end
test "should get index" do
get postgresql_view_people_url
assert_response :success
end
test "should get new" do
get new_postgresql_view_person_url
assert_response :success
end
test "should create postgresql_view_person" do
assert_difference('PostgresqlViewPerson.count') do
post postgresql_view_people_url, params: { postgresql_view_person: { } }
end
assert_redirected_to postgresql_view_person_url(PostgresqlViewPerson.last)
end
test "should show postgresql_view_person" do
get postgresql_view_person_url(@postgresql_view_person)
assert_response :success
end
test "should get edit" do
get edit_postgresql_view_person_url(@postgresql_view_person)
assert_response :success
end
test "should update postgresql_view_person" do
patch postgresql_view_person_url(@postgresql_view_person), params: { postgresql_view_person: { } }
assert_redirected_to postgresql_view_person_url(@postgresql_view_person)
end
test "should destroy postgresql_view_person" do
assert_difference('PostgresqlViewPerson.count', -1) do
delete postgresql_view_person_url(@postgresql_view_person)
end
assert_redirected_to postgresql_view_people_url
end
end
|
class Location < ActiveRecord::Base
validates_uniqueness_of :name, :normalized_name
validates_presence_of :name, :normalized_name
before_validation :set_normalized_name, on: :create
has_many :script_lines
def self.find_or_create_by_name(name)
normalized_name = TextNormalizer.remove_apostrophes_and_normalize(name)
find_by_normalized_name(normalized_name) ||
create { |c| c.name = name }
end
def set_normalized_name
self.normalized_name = TextNormalizer.remove_apostrophes_and_normalize(name)
end
end
|
class MembersController < ApplicationController
def new
@company = Company.find(params[:company_id])
@member= Member.new
end
def create
@company = Company.find(params[:company_id])
@member= Member.new(member_params)
if @member.save
redirect_to company_path(@company.id)
else
render :new
end
end
def destroy
@company = Company.find(params[:company_id])
@member = Member.find(params[:id])
@member.destroy
end
private
def member_params
params.require(:member).permit(:member_name).merge(company_id: @company.id)
end
end
|
class Tag < ApplicationModel
has_many :post_tags, :dependent => :destroy
has_many :user_tags, :dependent => :destroy
has_many :store_tags, :dependent => :destroy
validates_presence_of :tag
validates_uniqueness_of :tag
def self.generate(arg = {:tags => nil, :user_id => nil, :post_id => nil})
tags = arg[:tags].split(",").map {|tag| tag.strip}
user_id = arg[:user_id]
post_id = arg[:post_id]
for tag in tags
t = find_by_tag(tag)
if t.nil?
t = new(:tag => tag)
return false unless t.save
end
UserTag.generate(:user_id => user_id, :tag_id => t.id)
PostTag.generate(:post_id => post_id, :tag_id => t.id)
post = Post.find(post_id)
unless post.store_id.nil?
StoreTag.genertae(:store_id => post.store_id, :tag_id => t.id)
end
end
return true
end
end
|
class Iteration < ActiveRecord::Base
belongs_to :engagement
validates_presence_of :engagement_id
validates_associated :engagement
validates_presence_of :end_date
default_scope { order('end_date ASC') }
def customer_feedback_to_hash
JSON.parse customer_feedback rescue Hash.new
end
def customer_rating
Hash[
customer_feedback_with_rating
.to_a
.map{|k,v| [k, Iteration.rating_to_score(v)]}
]
end
def customer_feedback_with_rating
customer_feedback_to_hash.select do |key, _value|
Iteration.customer_rating_keys.include? key
end
end
def self.create_base_rating_hash
Hash[self.customer_rating_keys.map {|key| [key, 0]}]
end
def self.customer_rating_keys
%w(demeanor engaged communication understanding effectiveness satisfied)
end
def self.customer_text_keys
%w(demeanor_text engaged_text communication_text understanding_text effectiveness_text satisfied_text)
end
def self.ratings
{
"Strongly agree" => 5,
"Mostly agree" => 4,
"Neither agree nor disagree" => 3,
"Mostly disagree" => 2,
"Strongly disagree" => 1
}
end
def self.rating_to_score(rating)
self.ratings[rating]
end
def self.rating_options
[
'Strongly agree',
'Mostly agree',
'Neither agree nor disagree',
'Mostly disagree',
'Strongly disagree'
]
end
def self.duration_options
[
'15 min',
'30 min',
'45 min',
'1 hour',
'1 hour 15 min',
'1 hour 30 min',
'Longer than 1 hour 30 min']
end
end
|
class Tag
PROPERTIES = [:timestamp, :id, :name]
attr_accessor *PROPERTIES
def initialize(hash = {})
hash.each do |key, value|
if PROPERTIES.member? key.to_sym
self.send("#{key}=", value)
end
end
end
end
|
# include_recipe 'build-essential::default'
python_runtime '2'
python_virtualenv "#{node[:project_dir]}venv"
python_package 'uwsgi'
python_package 'pypiserver'
python_package 'passlib'
template "/etc/init.d/pypid" do
source 'pypid.erb'
variables(
:app_dir => node[:project_dir]
)
end
file "/etc/init.d/pypid" do
mode '0755'
end
directory "#{node[:project_dir]}packages" do
owner owner
group group
recursive true
action :create
end
file "#{node[:project_dir]}packages/.htaccess" do
content 'jenkins:$apr1$XqmmxIyK$yB4.4Pp46xOR6bouKk5yN1'
end
template "home/vagrant/.pypirc" do
source 'pypirc.erb'
end
execute 'start-pypi' do
command '/etc/init.d/pypid start'
action :run
end |
class Booking < ApplicationRecord
belongs_to :client, class_name: 'User', foreign_key: 'user_id'
belongs_to :bathroom
has_one :owner, through: :bathroom
validates :date, presence: true
validates :duration, presence: true, inclusion: { in: [15, 20, 25, 30, 35, 40, 45] }
validates :bathroom, presence: true
has_many :photos, through: :bathroom
has_one :review, dependent: :destroy
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'application#home'
namespace :api do
resources :jobs, only: [:index] do
resources :tasks, only: [:update]
end
end
end
|
require 'check_item_status'
require 'add_categories'
class MembersController < ApplicationController
include ::CheckItemStatus
include ::AddCategories
before_filter :authenticate, :only => [:edit, :update, :show, :destroy, :index]
before_filter :correct_user, :only => [:edit, :update, :show]
def index
@members = Member.paginate(:page => params[:page])
@title = "All registered members"
end
def new
@member = Member.new
@title = "Sign Up"
end
def create
@member = Member.new(params[:member])
if @member.save
#create categories if there are none
@categories = Category.all
if (@categories.empty?)
create_categories
end
sign_in @member
flash[:success] = "Welcome to the Tartan MarketPlace!"
redirect_to @member
else
@title = "Sign up"
render 'new'
end
end
def destroy
@member = Member.find(params[:id])
@member.destroy
Item.destroy_all(["seller_id=? OR buyer_id=?",@member.id,@member.id])
if (current_member.admin?)
flash[:success] = "Member destroyed."
redirect_to members_path
else
redirect_to root_path
end
end
def show
@member = Member.find(params[:id])
@items_sold = Item.find(:all, :conditions=>["seller_id=? AND buyer_id<> -1",@member.id])
@items1 = @items_sold
check_availability
@items_for_auction = Item.find(:all, :conditions=>["seller_id=? AND buyer_id= -1",@member.id])
@items_bought = Item.find(:all, :conditions=>["buyer_id=?",@member.id])
@items_bid = BidderPeriodItem.find(:all, :conditions=>["member_id=?",@member.id])
end
def edit
@title = "Edit member details"
end
def update
@member = Member.find(params[:id])
if @member.update_attributes(params[:member])
flash[:success] = "Profile updated."
redirect_to @member
else
@title = "Edit member details"
render 'edit'
end
end
private
def correct_user
@member = Member.find(params[:id])
redirect_to(root_path) unless current_user?(@member)
end
end |
namespace :fedena_inventory do
desc "Install Fedena Inventory Module"
task :install do
system "rsync --exclude=.svn -ruv vendor/plugins/fedena_inventory/public ."
end
end
|
require 'minitest/autorun'
require "#{Dir.pwd}/app/app"
class TestSinatraHelpers < MiniTest::Unit::TestCase
include Sinatra::Helpers
def test_shorter_track_should_cut
longy = open("#{Dir.pwd}/tmp/input.mp3")
shorty = shorter_track longy
assert_equal "#{Dir.pwd}/tmp/output.mp3", shorty.path
shorty.close
longy.close
end
def test_tmp_folder_should_be_created_and_deleted
tmp_folder('test test') do |folder_name|
assert_equal "#{Dir.pwd}/tmp/test_test", folder_name
assert File.exists?("#{Dir.pwd}/tmp/test_test"), "dir has not been created"
end
refute File.exists?("#{Dir.pwd}/tmp/test"), "dir has not been deleted"
end
def test_raplace_long_replaces
tmp_folder('test') do |path|
file = File.open("#{Dir.pwd}/tmp/input.mp3")
hash = {tempfile: file}
replace_long_audio hash, path
assert_equal "#{Dir.pwd}/tmp/test/output.mp3", hash[:tempfile].path
hash[:tempfile].close
end
end
end
|
require 'rails_helper'
RSpec.describe 'Visits API', type: :request do
let!(:visits) { create_list(:visit, 10) }
let(:visit) { visits.first }
let(:visit_id) { visit.id }
describe 'GET /visits' do
before { get '/visits' }
it 'returns active visits' do
expect(json).not_to be_empty
expect(json.size).to eq(10)
end
it 'returns status code 200' do
expect(response).to have_http_status(200)
end
end
describe 'GET /visits/:id' do
before { get "/visits/#{visit_id}" }
context 'when the record exists' do
it 'returns the visit' do
expect(json).not_to be_empty
expect(json['id']).to eq(visit_id)
end
it 'returns status code 200' do
expect(response).to have_http_status(200)
end
end
context 'when the record does not exist' do
let(:visit_id) { 200 }
it 'returns status code 404' do
expect(response).to have_http_status(404)
end
it 'returns a not found message' do
expect(response.body).to match(/Couldn't find Visit/)
end
end
end
describe 'POST /visits' do
let(:user_id) { create(:user).id }
let(:event_id) { create(:event).id }
let(:valid_attributes) { { user_id: user_id, event_id: event_id } }
context 'when the request is valid' do
before { post '/visits', params: valid_attributes }
it 'creates a visit' do
expect(json['user_id']).to eq(user_id)
expect(json['event_id']).to eq(event_id)
end
it 'returns status code 201' do
expect(response).to have_http_status(201)
end
end
context 'when the request is invalid' do
before { post '/visits', params: { user_id: user_id } }
it 'returns status code 422' do
expect(response).to have_http_status(422)
end
it 'returns a validation failure message' do
expect(json['message'])
.to eq("Validation failed: Event must exist, Event can't be blank")
end
end
end
end
|
class Pub
attr_reader :name, :till
def initialize(name, drinks = {})
@name = name
@till = 0
@drinks = drinks
end
def sell_drink(drink, customer)
if customer.age >= 18 && customer.drunk_level <= 5
@till += drink.price
elsif customer.age < 18 || customer.drunk_level > 5
return "Get out!"
end
end
def check_age_of_customer(customer)
return customer.age()
end
end |
# frozen_string_literal: true
# @param {String} j
# @param {String} s
# @return {Integer}
def num_jewels_in_stones(j, s)
count = 0
j.split('').each do |jewel|
s.split('').each do |stone|
jewel == stone ? count += 1 : count
end
end
count
end
|
class AddResultToApnMessage < ActiveRecord::Migration
def self.up
add_column :apn_messages, :result, :string
end
def self.down
end
end
|
module Fog
module Parsers
module Vcloud
module Terremark
module Vcloud
class GetVdc < Fog::Parsers::Vcloud::Base
def reset
@target = nil
@response = Struct::TmrkVcloudVdc.new([],[],[])
end
def start_element(name, attributes)
@value = ''
case name
when 'Link'
@response.links << generate_link(attributes)
when 'Network'
@response.networks << generate_link(attributes)
when 'ResourceEntity'
@response.resource_entities << generate_link(attributes)
when 'Vdc'
handle_root(attributes)
end
end
end
end
end
end
end
end
|
class Credit < ActiveRecord::Base
validates :amount_cents, :member, :presence => true
belongs_to :member, :inverse_of => :credits
belongs_to :transaction
scope :active, where(:active => true)
def as_json(options={})
[self.member.id, self.amount_cents]
end
end
|
class PhotoPostsController < ApplicationController
def index
end
def create
c = Tumblr::Client.new
post = PhotoPost.new(photo_post_params)
c.photo('doomy.tumblr.com', {data: post.data, caption: post.caption})
redirect_to root_path
end
private
def photo_post_params
params.require(:photo_post).permit(:data, :caption)
end
end
|
require "rails_helper"
describe "Session test" do
before(:each) do
visit root_path
@user = create(:user)
@user = User.load_from_activation_token(@user.activation_token)
@user.activate!
end
it "opens login page" do
click_link "Войти"
expect(page).to have_content "Вход"
end
it "activate user" do
expect(@user.activation_state).to eq("active")
end
it "login user" do
login("mama@mail.ru", "123456789")
expect(page).to have_content "Вы вошли!"
end
it "logout user" do
login("mama@mail.ru", "123456789")
click_link "Выйти"
expect(page).to have_content "До встречи"
end
it "registration" do
registration
expect(page).to have_content "Вам на почту были высланы инструкции, для активации аккаунта"
end
end
|
class Space
attr_reader :description, :exits, :related_rooms, :items, :actions, :necessary_item
def initialize(description, exits, items, actions, necessary_item)
@description = description
@exits = exits
@related_rooms = {}
@items = items
@actions = actions
@necessary_item = necessary_item
end
def add_related_rooms(related_rooms)
directions = related_rooms.keys
directions.each do |direction|
if @exits.include?(direction)
@related_rooms[direction] = related_rooms[direction]
end
end
end
def add_item(item)
@items << item
end
end |
module ShoesHelper
def paid_for_checkbox(f, shoe)
if payment_options_disabled?(shoe)
f.check_box :paid_for, disabled: "disabled"
else
f.check_box :paid_for
end
end
def payment_options_button(f, shoe, payment_type)
if payment_options_disabled?(shoe)
f.radio_button :type_of_payment, payment_type, disabled: "disabled"
else
f.radio_button :type_of_payment, payment_type
end
end
def cost_input_field(f, shoe)
if payment_options_disabled?(shoe)
f.number_field :cost, disabled: "disabled"
else
f.number_field :cost, min: 0, step: ".01"
end
end
def search_results
setup_shoes_search
date_received_search(search_params)
date_due_search(search_params)
type_of_payment_search(search_params)
paid_for_search(search_params)
delivered_search(search_params)
id_search(search_params)
phone_search(search_params)
name_search(search_params)
void_search(search_params)
@shoes_search
end
private
def setup_shoes_search
@shoes_search = Shoe.where(organization_id: current_user.organization.id).order(created_at: :desc)
end
def search_params
params[:search_options]
end
def date_received_search(search_params)
if param_to_boolean(search_params[:date_received])
date_received_from = extract_date_from_params(search_params, "date_received_from")
date_received_to = extract_date_from_params(search_params, "date_received_to")
@shoes_search = @shoes_search.where(date_received: date_received_from..date_received_to)
end
@shoes_search
end
def date_due_search(search_params)
if param_to_boolean(search_params[:date_due])
date_due_from = extract_date_from_params(search_params, "date_due_from")
date_due_to = extract_date_from_params(search_params, "date_due_to")
@shoes_search = @shoes_search.where(updated_date_due: date_due_from..date_due_to)
end
@shoes_search
end
def type_of_payment_search(search_params)
if search_params[:type_of_payment]
@shoes_search = @shoes_search.where(type_of_payment: search_params[:type_of_payment])
end
@shoes_search
end
def paid_for_search(search_params)
if search_params[:paid_for]
paid_for = param_to_boolean(search_params[:paid_for])
@shoes_search = @shoes_search.where(paid_for: paid_for)
end
@shoes_search
end
def delivered_search(search_params)
if search_params[:delivered]
delivered = param_to_boolean(search_params[:delivered])
@shoes_search = @shoes_search.where(delivered: delivered).order(created_at: :desc)
end
@shoes_search
end
def id_search(search_params)
if !search_params[:id].blank?
id_within_organization = search_params[:id].to_i
@shoes_search = @shoes_search.where(id_within_organization: id_within_organization)
end
@shoes_search
end
def phone_search(search_params)
if !search_params[:phone_number].blank?
phone = search_params[:phone_number].to_i
@shoes_search = @shoes_search.where(phone: phone)
end
@shoes_search
end
def name_search(search_params)
if !search_params[:name].blank?
search_name = search_params[:name]
shoes_table = Shoe.arel_table
@shoes_search = @shoes_search.where(shoes_table[:owner].matches("%#{search_name}%"))
end
@shoes_search
end
def void_search(search_params)
if search_params[:void]
void = param_to_boolean(search_params[:void])
@shoes_search = @shoes_search.where(void: void)
end
@shoes_search
end
def extract_date_from_params(search_params, param)
date_values = ["1", "2", "3"].map do |j|
search_params["#{param}(#{j}i)"].to_i
end
Date.new(*date_values)
end
def param_to_boolean(param)
ActiveRecord::Type::Boolean.new.deserialize(param)
end
def payment_options_disabled?(shoe)
Shoe.exists?(shoe.id) && shoe.paid_for? && !shoe.paid_for_changed?
end
end
|
{
:schema => {
"$schema" => "http://www.archivesspace.org/archivesspace.json",
"version" => 1,
"type" => "object",
"parent" => "abstract_archival_object",
"uri" => "/repositories/:repo_id/resources",
"properties" => {
"id_0" => {"type" => "string", "ifmissing" => "error", "maxLength" => 255},
#Added warning for missing Resource Number Part 2
"id_1" => {"type" => "string", "ifmissing" => "warn","maxLength" => 255},
"id_2" => {"type" => "string", "maxLength" => 255},
"id_3" => {"type" => "string", "maxLength" => 255},
"level" => {"type" => "string", "ifmissing" => "error", "dynamic_enum" => "archival_record_level"},
"other_level" => {"type" => "string", "maxLength" => 255},
"language" => {"ifmissing" => "warn"},
"resource_type" => {"type" => "string", "dynamic_enum" => "resource_resource_type"},
"tree" => {
"type" => "object",
"subtype" => "ref",
"properties" => {
"ref" => {
"type" => "JSONModel(:resource_tree) uri",
"ifmissing" => "error"
},
"_resolved" => {
"type" => "object",
"readonly" => "true"
}
}
},
"restrictions" => {"type" => "boolean", "default" => false},
"repository_processing_note" => {"type" => "string", "maxLength" => 65000},
"ead_id" => {"type" => "string", "maxLength" => 255},
"ead_location" => {"type" => "string", "maxLength" => 255},
# Finding aid
"finding_aid_title" => {"type" => "string", "maxLength" => 65000},
"finding_aid_subtitle" => {"type" => "string", "maxLength" => 65000},
"finding_aid_filing_title" => {"type" => "string", "maxLength" => 65000},
"finding_aid_date" => {"type" => "string", "maxLength" => 255},
"finding_aid_author" => {"type" => "string", "maxLength" => 65000},
"finding_aid_description_rules" => {"type" => "string", "dynamic_enum" => "resource_finding_aid_description_rules"},
"finding_aid_language" => {"type" => "string", "maxLength" => 255},
"finding_aid_sponsor" => {"type" => "string", "maxLength" => 65000},
"finding_aid_edition_statement" => {"type" => "string", "maxLength" => 65000},
"finding_aid_series_statement" => {"type" => "string", "maxLength" => 65000},
"finding_aid_status" => {"type" => "string", "dynamic_enum" => "resource_finding_aid_status"},
"finding_aid_note" => {"type" => "string", "maxLength" => 65000},
# Extents (overrides abstract schema)
"extents" => {"type" => "array", "ifmissing" => "error", "minItems" => 1, "items" => {"type" => "JSONModel(:extent) object"}},
"revision_statements" => {"type" => "array", "items" => {"type" => "JSONModel(:revision_statement) object"}},
# Dates (overrides abstract schema)
"dates" => {"type" => "array", "ifmissing" => "error", "minItems" => 1, "items" => {"type" => "JSONModel(:date) object"}},
"instances" => {"type" => "array", "items" => {"type" => "JSONModel(:instance) object"}},
"deaccessions" => {"type" => "array", "items" => {"type" => "JSONModel(:deaccession) object"}},
"collection_management" => {"type" => "JSONModel(:collection_management) object"},
"user_defined" => {"type" => "JSONModel(:user_defined) object"},
"related_accessions" => {
"type" => "array",
"items" => {
"type" => "object",
"subtype" => "ref",
"properties" => {
"ref" => {"type" => [{"type" => "JSONModel(:accession) uri"}],
"ifmissing" => "error"},
"_resolved" => {
"type" => "object",
"readonly" => "true"
}
}
}
},
"classifications" => {
"type" => "array",
"items" => {
"type" => "object",
"subtype" => "ref",
"properties" => {
"ref" => {
"type" => [ { "type" => "JSONModel(:classification) uri"},
{ "type" => "JSONModel(:classification_term) uri" }],
"ifmissing" => "error"
},
"_resolved" => {
"type" => "object",
"readonly" => "true"
}
}
}
},
"notes" => {
"type" => "array",
"items" => {"type" => [{"type" => "JSONModel(:note_bibliography) object"},
{"type" => "JSONModel(:note_index) object"},
{"type" => "JSONModel(:note_multipart) object"},
{"type" => "JSONModel(:note_singlepart) object"}]},
},
"representative_image" => {
"type" => "JSONModel(:file_version) object",
"readonly" => true
}
},
},
}
|
require 'spec_helper'
describe Task do
let(:user) { FactoryGirl.create(:user) }
before do
@list = user.lists.build( name: "test" )
@task = @list.tasks.build( name: "test_task" )
end
subject { @task }
it { should be_valid }
its(:finished) { should be_false }
end
|
class Board
attr_accessor :cells
def initialize
reset!
end
def reset!
@cells = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
end
def display
puts " #{@cells[0]} | #{@cells[1]} | #{@cells[2]} "
puts "-----------"
puts " #{@cells[3]} | #{@cells[4]} | #{@cells[5]} "
puts "-----------"
puts " #{@cells[6]} | #{@cells[7]} | #{@cells[8]} "
end
def position(value)
return @cells[value.to_i - 1]
end
def full?
if @cells.include?(" ") || @cells.include?("") || @cells.include?(nil)
false
else
true
end
end
def turn_count
i = 1
count = 0
9.times do
if taken?(i) == true
count = count + 1
end
i = i + 1
end
count
end
def taken?(value)
value = value.to_i - 1
if @cells[value] == "X" || @cells[value] == "O"
return true
else
return false
end
end
def valid_move?(index)
new_index = index.to_i - 1
if (taken?(index) == false && new_index.between?(0, 8))
true
else
false
end
end
def position_taken?(index)
!(@cells[index.to_i].nil? || @cells[index.to_i] == " ")
end
def update(space, player)
@cells[space.to_i - 1] = player.token
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.