text stringlengths 10 2.61M |
|---|
class Adoption < ApplicationRecord
belongs_to :owner
belongs_to :dog
has_and_belongs_to_many :comments
validates_uniqueness_of :owner, :dog
end
|
require 'fileutils'
require 'securerandom'
class LetterAvatar
# CHANGE these values to support more pixel ratios
FULLSIZE = 120 * 3
class << self
def generate(letter, size, r, g, b, version = 1)
File.read(generate_path(letter, size, r, g, b, version))
end
def generate_path(letter, size, r, g, b, version = 1, char_type)
size = FULLSIZE if size > FULLSIZE
fullsize_path = temp_path("/#{letter}/#{r}/#{g}_#{b}/full_v#{version}.png")
resized_path = temp_path("/#{letter}/#{r}/#{g}_#{b}/#{size}_v#{version}.png")
return resized_path if File.exist?(resized_path)
temp_file_path = temp_path("/" << SecureRandom.hex << ".png")
temp_file_dir = File.dirname(temp_file_path)
FileUtils.mkdir_p(temp_file_dir) unless Dir.exists?(temp_file_dir)
if File.exist?(fullsize_path)
FileUtils.cp(fullsize_path, temp_file_path)
else
`#{fullsize_command(temp_file_path, letter, r, g, b, version, char_type)} 2>/dev/null`
FileUtils.cp(temp_file_path, temp_file_path + "1")
FileUtils.mkdir_p(File.dirname(fullsize_path))
FileUtils.mv(temp_file_path + "1", fullsize_path)
end
`#{resize_command(temp_file_path, size)} 2>/dev/null`
`pngquant #{temp_file_path} -o #{temp_file_path} --force 2>/dev/null`
FileUtils.mv(temp_file_path, resized_path)
resized_path
end
def temp_path(path)
"#{ENV["TEMP_FILE_PATH"] || "/tmp"}#{path}"
end
def v1
@v1 ||= ["Helvetica", Hash.new('-0+26')]
end
def v2
@v2 ||= begin
offsets = Hash.new('-0+0')
offsets['0'] = '+0+6'
offsets['1'] = '-4+6'
offsets['2'] = '+0+5'
offsets['3'] = '-3+4'
offsets['4'] = '-3+5'
offsets['5'] = '-7+5'
offsets['6'] = '-3+4'
offsets['7'] = '+4+6'
offsets['8'] = '+0+4'
offsets['9'] = '-1+7'
offsets['A'] = '+0+5'
offsets['B'] = '+3+6'
offsets['C'] = '+2+4'
offsets['D'] = '+4+6'
offsets['E'] = '-6+6'
offsets['F'] = '-4+6'
offsets['G'] = '+3+7'
offsets['H'] = '+1+7'
offsets['I'] = '+2+6'
offsets['J'] = '+6+5'
offsets['K'] = '-1+5'
offsets['L'] = '-1+6'
offsets['M'] = '+1+6'
offsets['N'] = '+1+6'
offsets['O'] = '+2+5'
offsets['P'] = '+3+5'
offsets['Q'] = '+2+6'
offsets['R'] = '+3+5'
offsets['S'] = '-4+6'
offsets['T'] = '+1+6'
offsets['U'] = '+2+5'
offsets['V'] = '+1+6'
offsets['W'] = '+0+6'
offsets['X'] = '+0+6'
offsets['Y'] = '+2+5'
offsets['Z'] = '+4+6'
["Roboto-Medium", offsets]
end
end
def v4
@v4 ||= begin
offsets = Hash.new('+0-8')
["NotoSansMono-Medium", offsets]
end
end
def fullsize_command(path, letter, r, g, b, version, char_type)
versions = {1 => v1, 2 => v2, 3 => v2, 4 => v4}
font, offsets = versions[version]
pointsize = 280
if version > 3
pointsize = 220
font = case char_type
when 'display'
'NotoSansDisplay-Medium.ttf'
when 'mono'
'NotoSansMono-Medium.ttf'
when 'cjk'
'NotoSansMonoCJKsc-Regular.otf'
when 'arabic'
'NotoSansArabic-Medium.ttf'
when 'devaganari'
'NotoSansDevanagari-Medium.ttf'
when 'bengali'
'NotoSansBengali-Medium.ttf'
when 'javanese'
'NotoSansJavanese-Regular.ttf'
when 'telugu'
'NotoSansTelugu-Regular.ttf'
when 'thai'
'NotoSansThai-Medium.ttf'
when 'hebrew'
'NotoSansHebrew-Medium.ttf'
when 'armenian'
'NotoSansArmenian-Medium.ttf'
end
end
# NOTE: to debug alignment issues, add these lines before the path
# -fill '#00F'
# -draw "line 0,#{FULLSIZE/2 + FULLSIZE/4} #{FULLSIZE},#{FULLSIZE/2 + FULLSIZE/4}"
# -draw "line 0,#{FULLSIZE/2} #{FULLSIZE},#{FULLSIZE/2}"
# -draw "line 0,#{FULLSIZE/4} #{FULLSIZE},#{FULLSIZE/4}"
# -draw "line #{FULLSIZE/2 + FULLSIZE/4},0 #{FULLSIZE/2 + FULLSIZE/4},#{FULLSIZE}"
# -draw "line #{FULLSIZE/2},0 #{FULLSIZE/2},#{FULLSIZE}"
# -draw "line #{FULLSIZE/4},0 #{FULLSIZE/4},#{FULLSIZE}"
%W{
convert
-depth 8
-dither None
-colors 128
-size #{FULLSIZE}x#{FULLSIZE}
xc:'rgb(#{r},#{g},#{b})'
-pointsize #{pointsize}
-fill '#FFFFFFCC'
-font '#{font}'
-gravity Center
-annotate #{offsets[letter]} '#{letter}'
'#{path}'
}.join(' ')
end
def resize_command(path, size)
%W{
convert
'#{path}'
-gravity center
-background transparent
-thumbnail #{size}x#{size}
-extent #{size}x#{size}
-interpolate Catrom
-unsharp 2x0.5+0.7+0
-quality 98
-dither None
-colors 128
'#{path}'
}.join(' ')
end
end
end
|
class PollsController < ApplicationController
before_action :redirect_to_root, :if => :not_signed_in?, only: [:edit, :destroy, :new, :edit]
before_action :require_admins, only: [:crete, :new, :edit, :update, :destroy]
def index
@polls = Poll.all
end
def new
@poll = Poll.new
end
def show
@poll = Poll.includes(:vote_options).find_by_id(params[:id])
end
def create
@poll = Poll.new(poll_params)
if @poll.save
flash[:success] = t('forms.messages.success')
redirect_to polls_path
else
render 'new'
end
end
def edit
@poll = Poll.find_by_id(params[:id])
end
def update
@poll = Poll.find_by_id(params[:id])
if @poll.update_attributes(poll_params)
flash[:success] = t('forms.messages.success')
redirect_to polls_path
else
render 'edit'
end
end
def destroy
@poll = Poll.find_by_id(params[:id])
if @poll.destroy
flash[:success] = t('forms.messages.success')
else
flash[:warning] = t('forms.messages.error')
end
redirect_to polls_path
end
private
def poll_params
params.require(:poll).permit(:topic, vote_options_attributes: [:id, :title, :_destroy])
end
end |
module Helpstation
module Fetchers
NotFoundError = Class.new(StandardError)
class ByKeyFetcher < Processor
def self.build(input_key, output_key, &block)
Class.new(self) do
define_method :input_key do
input_key
end
define_method :output_key do
output_key
end
define_method :fetch do |input_value|
block.call input_value, env
end
end
end
def call
if input_value = input[input_key]
success(input.merge(output_key => fetch(input_value)))
else
error("#{input_key} must be present")
end
rescue NotFoundError
error("#{Inflecto.humanize(output_key)} ##{input_value} not found")
end
end
class ActiveRecordFetcher < ByKeyFetcher
def call
super
rescue ActiveRecord::RecordNotFound
error("#{Inflecto.humanize(output_key)} ##{input[input_key]} not found")
end
end
end
end
|
class Doc8 < Formula
include Language::Python::Virtualenv
desc "Style checker for Sphinx documentation"
homepage "https://github.com/PyCQA/doc8"
url "https://files.pythonhosted.org/packages/bb/fd/a39b9b8ce02f38777a24ce06d886b1dd23cea46f14b0f0c0418a03e5254d/doc8-0.9.1.tar.gz"
sha256 "0e967db31ea10699667dd07790f98cf9d612ee6864df162c64e4954a8e30f90d"
license "Apache-2.0"
revision 1
head "https://github.com/PyCQA/doc8.git", branch: "main"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "ef9dd2c5a52fffc7d9daf8a5308bc48eb87b21b350bc4508e62d7785955b3b66"
sha256 cellar: :any_skip_relocation, big_sur: "ea5c82933dfaec4a02061ab64bb164cfe83f31deaccdadbb3d0462923e980cea"
sha256 cellar: :any_skip_relocation, catalina: "ea5c82933dfaec4a02061ab64bb164cfe83f31deaccdadbb3d0462923e980cea"
sha256 cellar: :any_skip_relocation, mojave: "ea5c82933dfaec4a02061ab64bb164cfe83f31deaccdadbb3d0462923e980cea"
end
depends_on "python@3.10"
resource "docutils" do
url "https://files.pythonhosted.org/packages/4c/17/559b4d020f4b46e0287a2eddf2d8ebf76318fd3bd495f1625414b052fdc9/docutils-0.17.1.tar.gz"
sha256 "686577d2e4c32380bb50cbb22f575ed742d58168cee37e99117a854bcd88f125"
end
resource "pbr" do
url "https://files.pythonhosted.org/packages/35/8c/69ed04ae31ad498c9bdea55766ed4c0c72de596e75ac0d70b58aa25e0acf/pbr-5.6.0.tar.gz"
sha256 "42df03e7797b796625b1029c0400279c7c34fd7df24a7d7818a1abb5b38710dd"
end
resource "Pygments" do
url "https://files.pythonhosted.org/packages/b7/b3/5cba26637fe43500d4568d0ee7b7362de1fb29c0e158d50b4b69e9a40422/Pygments-2.10.0.tar.gz"
sha256 "f398865f7eb6874156579fdf36bc840a03cab64d1cde9e93d68f46a425ec52c6"
end
resource "restructuredtext-lint" do
url "https://files.pythonhosted.org/packages/45/69/5e43d0e8c2ca903aaa2def7f755b97a3aedc5793630abbd004f2afc3b295/restructuredtext_lint-1.3.2.tar.gz"
sha256 "d3b10a1fe2ecac537e51ae6d151b223b78de9fafdd50e5eb6b08c243df173c80"
end
resource "stevedore" do
url "https://files.pythonhosted.org/packages/f9/57/328653fd8a631d81b2d71261e471a102d5b64a95c1b1dda1a55b053bf0db/stevedore-3.4.0.tar.gz"
sha256 "59b58edb7f57b11897f150475e7bc0c39c5381f0b8e3fa9f5c20ce6c89ec4aa1"
end
def install
virtualenv_install_with_resources
end
test do
(testpath/"broken.rst").write <<~EOS
Heading
------
EOS
output = pipe_output("#{bin}/doc8 broken.rst 2>&1")
assert_match "D000 Title underline too short.", output
end
end
|
class WentsController < ApplicationController
before_action :set_went, only: [:show, :edit, :update, :destroy]
# GET /wents
# GET /wents.json
def index
@wents = Went.all
if params[:shop_id].present?
went = Went.find_by(user_id: current_user.id, shop_id: params[:shop_id])
render json: {status: 'success', went: went, counts: Went.where(shop_id: params[:shop_id]).count, wented: went.present?}
end
end
# GET /wents/1
# GET /wents/1.json
def show
end
# GET /wents/new
def new
@went = Went.new
end
# GET /wents/1/edit
def edit
end
# POST /wents
# POST /wents.json
def create
@went = Went.new(user_id: current_user.id, shop_id: params[:shop_id])
respond_to do |format|
if @went.save
format.html { redirect_to :back, notice: 'Went was successfully created.' }
format.json { render json: {status: 'success', went: @went, counts: Went.where(shop_id: @went.shop_id).count, wented: true} }
else
format.html { render :new }
format.json { render json: @went.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /wents/1
# PATCH/PUT /wents/1.json
def update
respond_to do |format|
if @went.update(went_params)
format.html { redirect_to @went, notice: 'Went was successfully updated.' }
format.json { render :show, status: :ok, location: @went }
else
format.html { render :edit }
format.json { render json: @went.errors, status: :unprocessable_entity }
end
end
end
# DELETE /wents/1
# DELETE /wents/1.json
def destroy
@went = Went.find_by(user_id: current_user.id, shop_id: params[:shop_id])
@went.destroy
respond_to do |format|
format.html { redirect_to wents_url, notice: 'Went was successfully destroyed.' }
format.json { render json: {status: 'success', went: @went, counts: Went.where(shop_id: params[:shop_id]).count}, wented: false }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_went
end
# Never trust parameters from the scary internet, only allow the white list through.
def went_params
params.require(:went).permit(:user_id, :shop_id)
end
end
|
class ProductsController < ApplicationController
include AdminHelper
layout "admin"
before_filter :validate_admin
before_filter :set_tab_index
before_filter :load_categories, only: [:index, :new, :edit]
before_filter :save_image, only: [:create, :update]
before_filter :prepare_config
before_filter :make_custom_fields, only: [:create, :update]
before_filter :make_tags, only: [:create, :update]
def set_tab_index
@tab = 0
end
def load_categories
@categories = Category.all.to_a
end
def save_image
params[:product][:images] = []
params.keys.each do |k|
if /^_image_\d+$/.match k
data = params[k]
end
if data && data.is_a?(ActionDispatch::Http::UploadedFile)
filename = SecureRandom.hex
File.open(Rails.root.join('public', 'uploads', filename), 'wb') do |file|
file.write(data.read)
end
params[:product][:images] << "/uploads/#{filename}"
elsif data && data.is_a?(String)
data.strip!
if Product.is_remote_image?(data) || Product.is_local_image?(data)
params[:product][:images] << data
end
end
end
end
def make_custom_fields
custom_fields = {}
params.keys.each do |k|
if /^_custom_field_name_\d+$/.match(k)
id = k.scan(/.*(\d+)/).first.first
name = params[k].to_sym
options = params["_custom_field_options_#{id}".to_sym].split(",")
options.each {|o| o.strip! }
custom_fields[name] = options
end
end
params[:product][:custom_fields] = custom_fields
end
def make_tags
tags = []
params.keys.each do |k|
if /^_tag_\d+$/.match(k)
t = params[k].strip
tags << t if t && t.length > 0
end
end
params[:product][:tags] = tags
end
def index
@keyword = params[:keyword]
if @keyword && @keyword.length > 0
criteria = Product.general_search @keyword
else
criteria = Product.all
end
criteria = criteria.order_by([[:updated_at, :desc]])
@products = criteria.page(params[:page]).per(10)
@title = I18n.t "admin.product_list"
render "admin/product/index"
end
def new
@title = I18n.t "admin.create_product"
@product = Product.new
render "admin/product/new"
end
def create
Product.create params[:product]
redirect_to products_path
end
def edit
@product = Product.where(id: params[:id]).first
if !@product
redirect_to products_path
else
@title = I18n.t "admin.edit_product"
render "admin/product/edit"
end
end
def update
@product = Product.where(id: params[:id]).first
if @product
if @product.has_image?
removed = []
@product.images.each do |i|
if Product.is_local_image?(i) && !params[:product][:images].find_index(i)
Product.delete_image i
end
end
end
@product.update_attributes params[:product]
end
redirect_to products_path
end
def destroy
product = Product.where(id: params[:id]).first
if product
product.delete
end
redirect_to products_path
end
end |
class Import < ActiveRecord::Base
belongs_to :workspace
belongs_to :source_dataset, :class_name => 'Dataset'
belongs_to :user
belongs_to :import_schedule
def self.run(import_id)
Import.find(import_id).run
end
def run
import_attributes = attributes.symbolize_keys
import_attributes.slice!(:workspace_id, :to_table, :new_table, :sample_count, :truncate, :dataset_import_created_event_id)
if workspace.sandbox.database != source_dataset.schema.database
Gppipe.run_import(source_dataset.id, user.id, import_attributes)
else
GpTableCopier.run_import(source_dataset.id, user.id, import_attributes)
end
import_schedule.update_attribute(:new_table, false) if new_table? && import_schedule
end
def target_dataset_id
if dataset_import_created_event_id
event = Events::DatasetImportCreated.find(dataset_import_created_event_id)
event.target2_id if event
end
end
end |
require 'rails_helper'
require 'spec_helper'
RSpec.describe LocationController do
let(:json) { JSON.parse(response.body) }
let!(:location_attributes) { attributes_for(:location) }
context '#create' do
context 'when given all attributes' do
before do
post :create, params: location_attributes
end
it { is_expected.to respond_with(201) }
end
context 'when' do
let!(:location_params) { location_attributes }
context 'street value is missing' do
before do
location_params['street'] = nil
post :create, params: location_params
end
it { is_expected.to respond_with(422) }
it 'returns street can\'t be blank' do
expect(json['errors']['street']).to include('street can\'t be blank')
end
end
context 'street and city values are missing' do
before do
location_params['street'] = nil
location_params['city'] = nil
post :create, params: location_params
end
it { is_expected.to respond_with(422) }
it 'returns street can\'t be blank' do
puts json.inspect
expect(json['errors']['street']).to include('street can\'t be blank')
end
it 'returns city can\'t be blank' do
expect(json['errors']['city']).to include('city can\'t be blank')
end
end
end
end
end |
require 'spec_helper'
describe Boxzooka::ProductListRequest do
let(:instance) {
described_class.new(
customer_access: Boxzooka::CustomerAccess.new(customer_id: 123, customer_key: 'abc')
)
}
describe 'XML serialization' do
let(:xml) { Boxzooka::Xml.serialize(instance) }
it { puts Ox.dump(Ox.parse(xml)) }
end
end
|
module Util
class Options
private_class_method :new
DEBUG_1 = 1 # everything
DEBUG_2 = 2 # interpreter only
DEBUG_3 = 3 # debug command only (default level if switch is present)
DEBUG_OFF = 9 # no debug (default)
LANG_EN = 'en'.freeze # en-CA (default)
LANG_JA = 'ja'.freeze # ja-JP
INPUT_FILE = 1
INPUT_INTERACTIVE = 2
class << self
# rubocop:disable Metrics/CyclomaticComplexity
def parse_arguments
print_usage if ARGV.empty?
options = { debug: DEBUG_OFF, lang: LANG_EN, input: INPUT_FILE, argv: [] }
until ARGV.empty? do
arg = ARGV.shift
case arg
when /^(-d|--debug)\d?$/ then set_debug_level arg, options
when '-h', '--help' then print_usage
when '-i', '--interactive' then options[:input] = INPUT_INTERACTIVE
when /^(-l|--lang)=\w{2}$/ then set_lang arg, options
when '-t', '--tokens' then options[:tokens] = true
when '-v', '--version' then options[:version] = true
when '--' then options[:argv] += ARGV.slice! 0..-1
when /^-/ then print_invalid_option arg
else
options[:argv] << arg
end
end
options[:filename] = options[:argv].first
validate_options options
options
end
# rubocop:enable Metrics/CyclomaticComplexity
private
def print_usage
puts %(\
Usage: #{$PROGRAM_NAME} [options] sourcefile
Options:
-d[level], --debug[level] Print various debugging information to stdout
level: 1 = verbose
2 = execution only
3 = debug messages only (default)
-h, --help Show this usage message
-i, --interactive Enter interactive mode
-l=<code>, --lang=<code> Set error message language
code: en = English (en-CA) (default)
ja = 日本語 (ja-JP)
-t, --tokens Print tokens and exit
-v, --version Print version and exit
-- Separate following arguments from preceding
options
)
exit
end
def print_invalid_option(arg)
abort "#{$PROGRAM_NAME}: Invalid option #{arg} (use -h for usage details)"
end
def set_debug_level(arg, options)
level = (arg.match(/(\d)$/)&.captures&.first || DEBUG_3).to_i
print_invalid_option arg unless [DEBUG_1, DEBUG_2, DEBUG_3].include? level
options[:debug] = level
end
def set_lang(arg, options)
lang = arg.match(/(\w{2})$/).captures.first
print_invalid_option arg unless [LANG_EN, LANG_JA].include? lang
options[:lang] = lang
end
def validate_options(options)
if options[:input] == INPUT_INTERACTIVE && options[:tokens]
abort "Options '-i' and '-t' cannot be used together"
end
return if options[:version] || options[:input] == INPUT_INTERACTIVE || File.exist?(options[:filename].to_s)
abort "Input file (#{options[:filename]}) not found"
end
end
end
end
|
class DepartmentsController < ApplicationController
before_action :set_department, :only => [:edit, :destroy, :update]
def index
@departments=Department.all
end
def new
@department=Department.new
end
def edit
end
def update
respond_to do |format|
if @department.update(department_params)
format.html{
redirect_to department_url(@department)
}
format.js
else
format.html{render :edit}
format.js
end
end
end
def destroy
@department.destroy
redirect_to departments_path
end
def create
@department=Department.new(department_params)
respond_to do |format|
if @department.save
format.html{
redirect_to departments_path
}
format.js
else
format.html{render :new}
format.js
end
end
end
# Department.where('name like ?', '%小白%')
def search
@departments = Department.where('name like ?', "%#{params[:keywords]}%")
render :index
end
private
def department_params
params.require(:department).permit(:name)
end
def set_department
@department=Department.find(params[:id])
end
end
|
class ProgrammingTestCase < ActiveRecord::Base
attr_accessible :stdin, :stdout
validates :stdin, presence: true
validates :stdout, presence: true
belongs_to :programming_task, inverse_of: :programming_test_cases
end
|
class Deposito < ApplicationRecord
belongs_to :account
before_save :validar_operacao
validates_presence_of :valor, :account_id
def validar_operacao
account = Account.find_by_id(self.account_id)
deposita_conta(account)
end
end
|
class Laser
SPEED = 5
def initialize (x, y, angle)
@x = x
@y = y
@angle = angle
@img = Gosu::Image.new("media/starfighter.bmp")
end
def update
@x += Gosu::offset_x(@angle, SPEED)
@y += Gosu::offset_y(@angle, SPEED)
end
def draw
@img.draw_rot(@x,@y, ZOrder::PLAYER, @angle)
end
end |
QuoteManager::Application.routes.draw do
authenticated :user do
root 'dashboard#index', as: :subdomain_root
end
root 'welcome#index'
namespace :admin do
get '/', action: :index
post '/deactive/:account_id', action: :deactive, as: :deactive
post '/active/:account_id', action: :active, as: :active
end
resources :forms
get '/form-inline/:id' => 'forms#form_inline'
resources :requests do
get '/download/:field_id', action: :download, as: :download
patch '/update-note', action: :update_note, as: :update_note
end
get '/offer/:id' => 'quotes#public', as: :public_quote
resources :quotes do
get '/email-tracking', action: :track_email , as: :email_tracking
get '/analytics', action: :analytics, as: :analytics
patch '/update-note', action: :update_note, as: :update_note
post '/send-quote', action: :send_quote, as: :send
post '/accept', action: :accept
post '/decline', action: :decline
end
resources :contacts do
patch '/update-note', action: :update_note, as: :update_note
get '/send-email', action: :send_email
post '/send-email', action: :send_email_to_contact, as: :send_email_to_contact
collection do
post :import
end
end
devise_for :users, :controllers => { omniauth_callbacks: 'omniauth_callbacks' }
resources :users do
collection do
post :create_user
end
end
resources :templates
resources :payments do
collection do
get :new
post :create
get :edit
put :update
patch :update
post :hook
end
end
resources :notifications, only: [:show, :index] do
collection do
get :unread
end
end
resources :accounts, except: [:show] do
collection do
post :login
end
end
end
|
class Abcl < Formula
homepage "http://abcl.org"
url "http://abcl.org/releases/1.3.1/abcl-bin-1.3.1.tar.gz"
sha1 "7abb22130acfbca9d01c413da9c98a6aa078c78b"
depends_on :java => "1.5+"
depends_on "rlwrap"
def install
libexec.install "abcl.jar", "abcl-contrib.jar"
(bin+"abcl").write <<-EOS.undent
#!/bin/sh
rlwrap java -jar "#{libexec}/abcl.jar" "$@"
EOS
end
test do
assert_match "42", pipe_output("#{bin}/abcl", "(+ 1 1 40)")
end
end
|
class Authors < Netzke::Basepack::Grid
def configure(c)
super
c.model = "Author"
end
end
|
class Reservation < ApplicationRecord
after_create_commit { notify }
belongs_to :user
belongs_to :place
#belongs_to :reservation_status
def time_diff(start_time, end_time)
seconds_diff = (start_time - end_time).to_i.abs
hours = seconds_diff / 3600
seconds_diff -= hours * 3600
minutes = seconds_diff / 60
seconds_diff -= minutes * 60
seconds = seconds_diff
"#{hours.to_s.rjust(2, '0')}:#{minutes.to_s.rjust(2, '0')}:#{seconds.to_s.rjust(2, '0')}"
end
def check_big_bag (total_reservations)
total = 0
total_reservations.each do |b|
total = total + b.big_bags_for_thistime
end
end
private
def notify
Notification.create(event: "你有一筆新訂單")
end
end
|
#!/usr/bin/ruby
#
# Create a platform with 3 networks (asia, europe, us) connected together
# via a 'global' network.
# Inspired from the tutorial's example
# To use with: platform_setup_globalinternet.rb <SUBNET>
# e.g.: platform_setup_globalinternet.rb 10.144.0.0/22
require 'distem'
require 'ipaddress'
$cl = Distem::NetAPI::Client.new
# The path to the compressed filesystem image
# We can point to local file since our homedir is available from NFS
FSIMG="file:///home/dmalikireddy/public/node-1-fsimage.tar.gz"
# Getting the physical nodes list which is set in the
# environment variable 'DISTEM_NODES' by distem-bootstrap
#pnodes=ENV['DISTEM_NODES'].split("\n")
=begin
def create_vnodes
# Read SSH keys
private_key = IO.readlines('/root/.ssh/id_rsa').join
public_key = IO.readlines('/root/.ssh/id_rsa.pub').join
sshkeys = {
'private' => private_key,
'public' => public_key
}
pnodes=ENV['DISTEM_NODES'].split("\n")
#FSIMG="file:///home/ejeanvoine/public/distem/distem-fs-wheezy.tar.gz"
$cl.vnode_create('r-us', { 'host' => pnodes[0] }, sshkeys)
$cl.vfilesystem_create('r-us', { 'image' => FSIMG })
$cl.vnode_create('r-europe', { 'host' => pnodes[1] }, sshkeys)
$cl.vfilesystem_create('r-europe', { 'image' => FSIMG })
$cl.vnode_create('r-asia', { 'host' => pnodes[2] }, sshkeys)
$cl.vfilesystem_create('r-asia', { 'image' => FSIMG })
$cl.vnode_create('us1', { 'host' => pnodes[0] }, sshkeys)
$cl.vfilesystem_create('us1', { 'image' => FSIMG })
$cl.vnode_create('us2', { 'host' => pnodes[0] }, sshkeys)
$cl.vfilesystem_create('us2', { 'image' => FSIMG })
$cl.vnode_create('europe1', { 'host' => pnodes[1] }, sshkeys)
$cl.vfilesystem_create('europe1', { 'image' => FSIMG })
$cl.vnode_create('europe2', { 'host' => pnodes[1] }, sshkeys)
$cl.vfilesystem_create('europe2', { 'image' => FSIMG })
$cl.vnode_create('asia1', { 'host' => pnodes[2] }, sshkeys)
$cl.vfilesystem_create('asia1', { 'image' => FSIMG })
$cl.vnode_create('asia2', { 'host' => pnodes[2] }, sshkeys)
$cl.vfilesystem_create('asia2', { 'image' => FSIMG })
end
def create_vifaces
# routers on global network
$cl.viface_create('r-us', 'if0', { 'vnetwork' => 'global', "output"=>{ "latency"=> {"delay" => "20ms"} }, "input"=>{ "latency"=> { "delay" => "20ms" } }})
$cl.viface_create('r-europe', 'if0', { 'vnetwork' => 'global', "output"=>{ "latency"=> {"delay" => "30ms" } }, "input"=>{ "latency"=>{ "delay" => "30ms" } } })
$cl.viface_create('r-asia', 'if0', { 'vnetwork' => 'global', "output"=>{ "latency"=> { "delay" => "40ms" } }, "input"=>{ "latency"=> { "delay" => "40ms" } } })
# routers on their respective local networks
$cl.viface_create('r-us', 'if1', { 'vnetwork' => 'us' })
$cl.viface_create('r-europe', 'if1', { 'vnetwork' => 'europe' })
$cl.viface_create('r-asia', 'if1', { 'vnetwork' => 'asia' })
# nodes on local networks
$cl.viface_create('us1', 'if1', { 'vnetwork' => 'us' })
$cl.viface_create('us2', 'if1', { 'vnetwork' => 'us' })
$cl.viface_create('europe1', 'if1', { 'vnetwork' => 'europe' })
$cl.viface_create('europe2', 'if1', { 'vnetwork' => 'europe' })
$cl.viface_create('asia1', 'if1', { 'vnetwork' => 'asia' })
$cl.viface_create('asia2', 'if1', { 'vnetwork' => 'asia' })
end
=end
def create_subnets
res_subnet = IPAddress(ARGV[-1])
$no = (ARGV.length - 1)/4
subnets = res_subnet.split($no+1)
$cl.vnetwork_create('global', subnets[0].to_string)
$no.times do |index|
$cl.vnetwork_create(ARGV[4*index], subnets[index+1].to_string)
end
pp $cl.vnetworks_info
end
def create_vnodes
# Read SSH keys
private_key = IO.readlines('/root/.ssh/id_rsa').join
public_key = IO.readlines('/root/.ssh/id_rsa.pub').join
sshkeys = {
'private' => private_key,
'public' => public_key
}
pnodes=ENV['DISTEM_NODES'].split("\n")
#FSIMG="file:///home/ejeanvoine/public/distem/distem-fs-wheezy.tar.gz"
if pnodes.length < $nodelist.length
$flag = -1
$nodelist.length.times do |index|
if $nodelist[index].start_with?('r_') == true
$flag += 1
end
$cl.vnode_create($nodelist[index], { 'host' => pnodes[$flag] }, sshkeys)
$cl.vfilesystem_create($nodelist[index], { 'image' => FSIMG })
end
else
$nodelist.length.times do |index|
$cl.vnode_create($nodelist[index], { 'host' => pnodes[index] }, sshkeys)
$cl.vfilesystem_create($nodelist[index], { 'image' => FSIMG })
end
end
end
def create_vifaces
# routers on global network
$no = (ARGV.length - 1)/4
$no.times do |index|
$cl.viface_create("r_"+ARGV[4*index], 'if0', { 'vnetwork' => 'global', "output"=>{ "latency"=> {"delay"=> ARGV[4*index+1].to_s+"ms"} }, "input"=>{ "latency"=> {"delay"=> ARGV[4*index+1].to_s+"ms"} }})
end
# routers on their respective local networks
$no.times do |index|
$cl.viface_create("r_"+ARGV[4*index], 'if1', { 'vnetwork' => ARGV[4*index] })
end
# nodes on local networks
$nodelist.length.times do |index|
if $nodelist[index].start_with?('r_') == false
$node = $nodelist[index].gsub(/[SC0-9_]/,'')
$cl.viface_create($nodelist[index], 'if1', { 'vnetwork' => $node })
puts $node
end
end
end
def create_vroutes
puts 'Completing virtual routes'
$cl.vroute_complete
puts 'Virtual route creation completed'
end
#puts ARGV.length
$nodelist = Array.new
$i=0
while $i < ARGV.length - 1
$nodelist.push("r_"+ARGV[$i])
ARGV[$i+2].to_i.times do |index|
$nodelist.push(ARGV[$i]+"_S"+index.to_s)
end
ARGV[$i+2].to_i.times do |index|
$nodelist.push(ARGV[$i]+"_C"+index.to_s)
end
$i += 4
end
$nodelist.each do |element|
puts element
end
puts 'Creating sub-networks'
create_subnets
puts 'Sub-network creation done'
puts 'Creating virtual nodes'
create_vnodes
puts 'Virtual nodes creation done'
puts 'Creating virtual interfaces'
create_vifaces
puts 'Virtual interfaces creation done'
create_vroutes
puts 'Starting virtual nodes'
# start all vnodes
$cl.vnodes_start($cl.vnodes_info.map { |vn| vn['name'] })
puts "Setting global /etc/hosts"
$cl.set_global_etchosts()
puts "Setting global ARP tables"
$cl.set_global_arptable()
puts 'Network setup complete'
pp $cl.vnodes_info
exit(0)
|
require 'rails_helper'
RSpec.describe VoteOpinion, type: :model do
context 'validations' do
let(:vote_opinion) { FactoryBot.build(:vote_opinion) }
subject { vote_opinion }
it { should belong_to(:poll) }
it { should belong_to(:answer) }
it { should belong_to(:user) }
it { should validate_presence_of :user }
it { should validate_presence_of :answer }
it { should validate_presence_of :poll }
end
context 'Persistance (opinion)' do
let!(:symfields) { %i[vote_label] }
let!(:valid_attributes_opinion) { build(:vote_opinion).attributes }
let!(:vote_op) { create(:vote_opinion, valid_attributes_opinion) }
it 'when done through factory should be ok' do
symfields.each do |s_field|
expect(
vote_op.send(s_field)
).to be == valid_attributes_opinion[s_field.to_s]
end
end
end
context 'with invalid attributes' do
let(:valid_attributes_opinion) { build(:vote_opinion).attributes }
let(:invalid_poll_attribute) do
FactoryBot.build(:vote_opinion, poll_id: nil).attributes
end
let(:invalid_user_attribute) do
FactoryBot.build(:vote_opinion, user_id: nil).attributes
end
it 'tolerates empty fields but the poll_id' do
vote = build(:vote_opinion, invalid_poll_attribute)
expect(vote).not_to be_valid
end
it 'tolerates empty fields but the user_id' do
vote = build(:vote_opinion, invalid_user_attribute)
expect(vote).not_to be_valid
end
end
describe '#clean_votes' do
let(:vote_opinion) { create(:vote_opinion) }
let(:vote_opinion2) do
build(
:vote_opinion,
poll_id: vote_opinion.poll_id,
user_id: vote_opinion.user_id
)
end
let(:vote_date) do
create(
:vote_date,
poll_id: vote_opinion.poll_id,
user_id: vote_opinion.user_id
)
end
it 'shall delete vote_opinion only' do
expect { vote_opinion2.clean_votes }.to change(VoteOpinion, :count).by(1)
end
end
end
|
class TagValidator < ActiveRecord::EachValidator
TAGS_ALLOWED = ["sports","news","social media"]
def validate_each(record, attribute_name, value)
unless TAGS_ALLOWED.include?(value)
record.errors[attribute_name] << (options[:message] || "Tag not allowed")
end
end
end
class TagTopic < ActiveRecord::Base
has_many :short_urls
attr_accessible :tag, :short_url_id, :created_at, :updated_at
validates :tag, :presence => true, :tag => true
validates :short_url_id, :presence => true
validates_uniqueness_of :tag, :scope => :short_url_id
end |
class Category < ActiveRecord::Base
belongs_to :user
has_many :sub_categories
validates :name, presence: true, uniqueness: true
end
|
require 'rails_helper'
describe 'users/notifications/index' do
before do
@notifications = []
@notifications << build_stubbed(:user_notification, read: false)
@notifications << build_stubbed(:user_notification, read: true)
end
it 'displays' do
assign(:notifications, @notifications)
render
end
end
|
class Tetherer < ActiveRecord::Base
attr_accessible :data_available, :mac_address
has_many :users
end
|
require 'test_helper'
class ScholarshipStudyFieldsControllerTest < ActionDispatch::IntegrationTest
setup do
@scholarship_study_field = scholarship_study_fields(:one)
end
test "should get index" do
get scholarship_study_fields_url
assert_response :success
end
test "should get new" do
get new_scholarship_study_field_url
assert_response :success
end
test "should create scholarship_study_field" do
assert_difference('ScholarshipStudyField.count') do
post scholarship_study_fields_url, params: { scholarship_study_field: { scholarship_id: @scholarship_study_field.scholarship_id, status: @scholarship_study_field.status, study_field_id: @scholarship_study_field.study_field_id, user_id: @scholarship_study_field.user_id } }
end
assert_redirected_to scholarship_study_field_url(ScholarshipStudyField.last)
end
test "should show scholarship_study_field" do
get scholarship_study_field_url(@scholarship_study_field)
assert_response :success
end
test "should get edit" do
get edit_scholarship_study_field_url(@scholarship_study_field)
assert_response :success
end
test "should update scholarship_study_field" do
patch scholarship_study_field_url(@scholarship_study_field), params: { scholarship_study_field: { scholarship_id: @scholarship_study_field.scholarship_id, status: @scholarship_study_field.status, study_field_id: @scholarship_study_field.study_field_id, user_id: @scholarship_study_field.user_id } }
assert_redirected_to scholarship_study_field_url(@scholarship_study_field)
end
test "should destroy scholarship_study_field" do
assert_difference('ScholarshipStudyField.count', -1) do
delete scholarship_study_field_url(@scholarship_study_field)
end
assert_redirected_to scholarship_study_fields_url
end
end
|
require "java"
require 'carrot/util/timeout'
require 'uri'
require 'net/http'
require 'rack'
import java.lang.Runtime
import java.lang.Runnable
import java.io.InputStreamReader
import java.io.BufferedReader
module Carrot
class ExtendServer
attr_accessor :server_process, :shutdown_process
class ShutdownHook
include Runnable
def initialize( &block)
super()
@block=block
end
def run
@block[]
end
end
def self.at_exit( &block)
hook = ShutdownHook.new( &block)
Runtime.getRuntime().addShutdownHook(java.lang.Thread.new( hook ))
end
def run()
Thread.new do
command = ["/bin/bash","-c", "cd #{Carrot.project_path} ; #{Carrot.rails_command}"].to_java(java.lang.String)
begin
@server_process = Runtime.getRuntime().exec(command)
if Carrot.server_debug
buf = BufferedReader.new(InputStreamReader.new(@server_process.get_input_stream))
while line = buf.readLine()
puts line
end
end
ExtendServer.at_exit{ Carrot.shutdown }
@server_process.wait_for
rescue Exception => e
puts e
end
end
Carrot.timeout(60) { if responsive? then true else sleep(0.5) and false end }
end
def shutdown
Thread.new do
command = ["/bin/bash","-c", "cd #{Carrot.project_path} ; kill `cat #{Carrot.project_path}/tmp/pids/server.pid`"].to_java(java.lang.String)
begin
@shutdown_process = Runtime.getRuntime().exec(command)
@shutdown_process.wait_for
@shutdown_process.destroy
rescue Exception => e
puts e
end
end
end
def responsive?
host = "127.0.0.1"
res = Net::HTTP.start(host, Carrot.server_port) { |http| http.get('/__identify__') }
unless res.nil?
return true
end
rescue Errno::ECONNREFUSED, Errno::EBADF
return false
end
end
end
|
class FeathersController < ApplicationController
if FeatherCms::Config.authentication.kind_of?(Hash)
http_basic_authenticate_with FeatherCms::Config.authentication.merge(except: :published)
else
before_filter FeatherCms::Config.authentication.to_sym, except: :published
end
before_filter :find_page, only: [:page, :preivew]
layout 'feather_layout', except: [:preivew, :published]
def index
@pages = FeatherPage.all
end
def page
if request.put? or request.post?
@feather_page.attributes = params[:feather_page]
@feather_page.name = params[:type]
@feather_page.save
end
render action: @feather_page.name
end
def preivew
render inline: @feather_page.content, type: @feather_page.template_type, layout: @feather_page.layout
end
def published
@feather_page = FeatherPage.where(name: params[:type], status: 'published').first
render inline: @feather_page.content, type: @feather_page.template_type, layout: @feather_page.layout
end
def find_page
status = params[:feather_page] ? params[:feather_page][:status] : (params[:status] || 'draft')
@feather_page = FeatherPage.where(name: params[:type], status: status)
@feather_page = @feather_page.first || @feather_page.new
end
end
|
module Nagios
class Plugin
VERSION = '3.0.2'
EXIT_CODE =
{ unknown: 3,
critical: 2,
warning: 1,
ok: 0 }
def self.run!(*args)
plugin = new(*args)
plugin.check if plugin.respond_to?(:check)
puts plugin.output
exit EXIT_CODE[plugin.status]
rescue => e
puts "PLUGIN UNKNOWN: #{e.message}\n\n" << e.backtrace.join("\n")
exit EXIT_CODE[:unknown]
end
def output
s = "#{name.upcase} #{status.upcase}"
s << ": #{message}" if ( respond_to?(:message) && !message.to_s.empty? )
s
end
def status
return :critical if critical?
return :warning if warning?
return :ok if ok?
:unknown
end
def name
self.class.name.split('::').last.upcase
end
def to_s
output
end
end
end
|
require 'tb'
require 'test/unit'
require_relative 'util_tbtest'
class TestTbCSV < Test::Unit::TestCase
def parse_csv(csv)
Tb::HeaderCSVReader.new(StringIO.new(csv)).to_a
end
def generate_csv(ary)
writer = Tb::HeaderCSVWriter.new(out = '')
ary.each {|h| writer.put_hash h }
writer.finish
out
end
def test_parse
t = parse_csv(<<-'End'.gsub(/^\s+/, ''))
a,b
1,2
3,4
End
assert_equal(
[{"a"=>"1", "b"=>"2"},
{"a"=>"3", "b"=>"4"}],
t)
end
def test_parse_empty_line_before_header
empty_line = "\n"
t = parse_csv(empty_line + <<-'End'.gsub(/^\s+/, ''))
a,b
1,2
3,4
End
assert_equal(
[{"a"=>"1", "b"=>"2"},
{"a"=>"3", "b"=>"4"}],
t)
end
def test_parse_empty_value
t = parse_csv(<<-'End'.gsub(/^\s+/, ''))
a,b,c
1,,2
3,"",4
End
assert_equal(
[{"a"=>"1", "b"=>nil, "c"=>"2"},
{"a"=>"3", "b"=>"", "c"=>"4"}],
t)
end
def test_parse_newline
t = parse_csv("\n")
assert_equal([], t)
end
def test_generate
t = [{'a' => 1, 'b' => 2},
{'a' => 3, 'b' => 4}]
assert_equal(<<-'End'.gsub(/^\s+/, ''), generate_csv(t))
a,b
1,2
3,4
End
end
def test_generate_empty
t = [{'a' => 1, 'b' => nil, 'c' => 2},
{'a' => 3, 'b' => '', 'c' => 4}]
assert_equal(<<-'End'.gsub(/^\s+/, ''), generate_csv(t))
a,b,c
1,,2
3,"",4
End
end
def test_parse_ambiguous_header
t = nil
stderr = capture_stderr {
t = parse_csv(<<-'End'.gsub(/^\s+/, ''))
a,b,a,b,c
0,1,2,3,4
5,6,7,8,9
End
}
assert_equal(
[{"a"=>"0", "b"=>"1", "c"=>"4"},
{"a"=>"5", "b"=>"6", "c"=>"9"}],
t)
assert_match(/Ambiguous header field/, stderr)
end
def test_parse_empty_header_field
t = nil
stderr = capture_stderr {
t = parse_csv(<<-'End'.gsub(/^\s+/, ''))
a,,c
0,1,2
5,6,7
End
}
assert_equal(
[{"a"=>"0", "c"=>"2"},
{"a"=>"5", "c"=>"7"}],
t)
assert_match(/Empty header field/, stderr)
end
end
|
# Shortest String
# I worked on this challenge by myself.
# shortest_string is a method that takes an array of strings as its input
# and returns the shortest string
#
# +list_of_words+ is an array of strings
# shortest_string(array) should return the shortest string in the +list_of_words+
#
# If +list_of_words+ is empty the method should return nil
#Your Solution Below
=begin
def shortest_string(list_of_words)
if list_of_words == []
return nil
else
list_of_words.each do |word|
if word.length
list_of_words.sort_by {|word| word.length}
return list_of_words[0]
end
end
end
end
puts shortest_string(['cat', 'zzzzzzz', 'apples,', 'a'])
=end
#Refactored Solution:
def shortest_string(list_of_words)
list_of_words.min { |a, b| a.length <=> b.length }
end |
class ProjectEstimationForm
include ActiveModel::Model
attr_accessor :projects, :estimated_proxy_size, :base, :time
validate :number_of_data_items
validate :number_of_historical_data_items
def self.model_name
ActiveModel::Name.new(self, nil, "Estimation")
end
def submit(params)
@projects = params[:projects].select {|p| p if p.present?}
@estimated_proxy_size = params[:estimated_proxy_size].to_i
@base = params[:base].to_i
@time = params[:time].to_i
validate ? true : false
end
def estimation
@estimation ||= ::Estimation.new(total_size: estimated_total_size, projected_size: projected_size, total_time: estimated_time)
end
def projected_size
@projected_size ||= probe_estimation.perform[1][:beta0] + probe_estimation.perform[1][:beta1] * @estimated_proxy_size if probe_estimation.perform
end
def probe_estimation
@probe_estmation ||= ProbeEstimationService.new(estimated_proxy_data: estimated_proxy_data,
planned_size_data: planned_size_data,
actual_size_data: actual_size_data,
planned_time: planned_time,
actual_time: actual_time)
end
def estimated_time
@estimated_time = probe_estimation.regression_for_time[:beta0] + probe_estimation.regression_for_time[:beta1] * @time if probe_estimation.perform
end
def planned_time
@planned_time = historical_data.map(&:estimated_hours).compact
end
def actual_time
@actual_time = historical_data.map(&:actual_hours).compact
end
def estimated_total_size
@estimated_total_size ||= projected_size + base
end
def historical_data
@historical_data ||= HistoricalDatum.find(@projects)
end
def estimated_proxy_data
@estimated_proxy_data ||= historical_data.map {|hd| hd.estimated_proxy_size }.compact
end
def planned_size_data
@planned_size_data ||= historical_data.map {|hd| hd.planned_size }.compact
end
def actual_size_data
@actual_size_data ||= historical_data.map {|hd| hd.actual_size }.compact
end
def number_of_data_items
if actual_size_data.size < 6
errors[:projects] << "Need more data (at least 6 items)"
end
end
def number_of_historical_data_items
if planned_size_data.size < 6 && estimated_proxy_data.size < 6
errors[:projects] << "Need more historical data"
end
end
end |
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Brcobranca::Remessa::Cnab240::Sicoob do
let(:pagamento) do
Brcobranca::Remessa::Pagamento.new(
valor: 50.0,
data_vencimento: Date.current,
nosso_numero: '429715',
documento: 6969,
documento_sacado: '82136760505',
nome_sacado: 'PABLO DIEGO JOSÉ FRANCISCO,!^.?\/@ DE PAULA JUAN NEPOMUCENO MARÍA DE LOS REMEDIOS CIPRIANO DE LA SANTÍSSIMA TRINIDAD RUIZ Y PICASSO',
endereco_sacado: 'RUA RIO GRANDE DO SUL,!^.?\/@ São paulo Minas caçapa da silva junior',
bairro_sacado: 'São josé dos quatro apostolos magros',
cep_sacado: '12345678',
cidade_sacado: 'Santa rita de cássia maria da silva',
uf_sacado: 'RJ',
tipo_mora: '0',
codigo_protesto: '1'
)
end
let(:params) do
{
empresa_mae: 'SOCIEDADE BRASILEIRA DE ZOOLOGIA LTDA',
agencia: '4327',
conta_corrente: '03666',
documento_cedente: '74576177000177',
modalidade_carteira: '01',
convenio: '512231',
pagamentos: [pagamento]
}
end
let(:sicoob) { subject.class.new(params) }
context 'validacoes' do
context '@modalidade_carteira' do
it 'deve ser invalido se nao possuir a modalidade da carteira' do
objeto = subject.class.new(params.merge(modalidade_carteira: nil))
expect(objeto.invalid?).to be true
expect(objeto.errors.full_messages).to include('Modalidade carteira não pode estar em branco.')
end
end
context '@tipo_formulario' do
it 'deve ser invalido se nao possuir o tipo de formulario' do
objeto = subject.class.new(params.merge(tipo_formulario: nil))
expect(objeto.invalid?).to be true
expect(objeto.errors.full_messages).to include('Tipo formulario não pode estar em branco.')
end
end
context '@parcela' do
it 'deve ser invalido se nao possuir a parcela' do
objeto = subject.class.new(params.merge(parcela: nil))
expect(objeto.invalid?).to be true
expect(objeto.errors.full_messages).to include('Parcela não pode estar em branco.')
end
end
context '@agencia' do
it 'deve ser invalido se a agencia tiver mais de 4 digitos' do
sicoob.agencia = '12345'
expect(sicoob.invalid?).to be true
expect(sicoob.errors.full_messages).to include('Agencia deve ter 4 dígitos.')
end
end
context '@convenio' do
it 'deve ser invalido se nao possuir o convenio' do
sicoob.convenio = nil
expect(sicoob.invalid?).to be true
expect(sicoob.errors.full_messages).to include('Convenio não pode estar em branco.')
end
end
context '@conta_corrente' do
it 'deve ser invalido se a conta corrente tiver mais de 8 digitos' do
sicoob.conta_corrente = '123456789'
expect(sicoob.invalid?).to be true
expect(sicoob.errors.full_messages).to include('Conta corrente deve ter 8 dígitos.')
end
end
end
context 'formatacoes' do
it 'codigo do banco deve ser 756' do
expect(sicoob.cod_banco).to eq '756'
end
it 'nome do banco deve ser Sicoob com 30 posicoes' do
nome_banco = sicoob.nome_banco
expect(nome_banco.size).to eq 30
expect(nome_banco[0..19]).to eq 'SICOOB '
end
it 'versao do layout do arquivo deve ser 081' do
expect(sicoob.versao_layout_arquivo).to eq '081'
end
it 'versao do layout do lote deve ser 040' do
expect(sicoob.versao_layout_lote).to eq '040'
end
it 'deve calcular o digito da agencia' do
# digito calculado a partir do modulo 11 com base 9
#
# agencia = 1 2 3 4
#
# 4 3 2 1
# x 9 8 7 6
# = 36 24 14 6 = 80
# 80 / 11 = 7 com resto 3
expected_digito_agencia_list = [
{ agencia: '3214', dv: '0' },
{ agencia: '2006', dv: '0' },
{ agencia: '5651', dv: '0' },
{ agencia: '5691', dv: '0' },
{ agencia: '5741', dv: '0' },
{ agencia: '1008', dv: '1' },
{ agencia: '5681', dv: '2' },
{ agencia: '5731', dv: '2' },
{ agencia: '4327', dv: '3' },
{ agencia: '1001', dv: '4' },
{ agencia: '5761', dv: '4' },
{ agencia: '3032', dv: '5' },
{ agencia: '5671', dv: '5' },
{ agencia: '5631', dv: '6' },
{ agencia: '1005', dv: '7' },
{ agencia: '5661', dv: '8' },
{ agencia: '0001', dv: '9' },
{ agencia: '5621', dv: '9' }
]
expected_digito_agencia_list.each do |expected_dv_agencia|
remessa_params = params.merge!(agencia: expected_dv_agencia[:agencia])
remessa = subject.class.new(remessa_params)
expect(remessa.digito_agencia).to eq expected_dv_agencia[:dv]
end
end
it 'deve calcular digito da conta' do
# digito calculado a partir do modulo 11 com base 9
#
# conta = 1 2 3 4 5
#
# 5 4 3 2 1
# x 9 8 7 6 5
# = 45 32 21 12 5 = 116
# 116 / 11 = 10 com resto 5
expect(sicoob.digito_conta).to eq '8'
end
it 'cod. convenio deve retornar as informacoes nas posicoes corretas' do
cod_convenio = sicoob.codigo_convenio
expect(cod_convenio[0..19]).to eq ' '
end
it 'info conta deve retornar as informacoes nas posicoes corretas' do
info_conta = sicoob.info_conta
expect(info_conta[0..4]).to eq '04327'
expect(info_conta[5]).to eq '3'
expect(info_conta[6..17]).to eq '000000003666'
expect(info_conta[18]).to eq '8'
end
it 'complemento header deve retornar espacos em branco' do
expect(sicoob.complemento_header).to eq ''.rjust(29, ' ')
end
it 'complemento trailer deve retornar espacos em branco com a totalização das cobranças' do
total_cobranca_simples = '00000100000000000005000'
total_cobranca_vinculada = ''.rjust(23, '0')
total_cobranca_caucionada = ''.rjust(23, '0')
total_cobranca_descontada = ''.rjust(23, '0')
expect(sicoob.complemento_trailer).to eq "#{total_cobranca_simples}#{total_cobranca_vinculada}"\
"#{total_cobranca_caucionada}#{total_cobranca_descontada}".ljust(217, ' ')
end
it 'formata o nosso numero' do
nosso_numero = sicoob.formata_nosso_numero 1
expect(nosso_numero).to eq '000000000101014 '
end
end
context 'geracao remessa' do
it_behaves_like 'cnab240'
context 'arquivo' do
before { Timecop.freeze(Time.local(2015, 7, 14, 16, 15, 15)) }
after { Timecop.return }
it { expect(sicoob.gera_arquivo).to eq(read_remessa('remessa-bancoob-cnab240.rem', sicoob.gera_arquivo)) }
end
end
end
|
class RepackagingOrder
FLAT_MARKUP_PERCENTAGE = 0.05
EMPLOYEE_MARKUP_PERCENTAGE = 0.012
FOOD_MARKUP_PERCENTAGE = 0.13
DRUGS_MARKUP_PERCENTAGE = 0.075
ELECTRONICS_MARKUP_PERCENTAGE = 0.02
attr_accessor :base_price, :type, :required_employees_quantity
def initialize(base_price, type, required_employees_quantity = 1)
# Data types validation
raise "Must have a numeric base_price value greater than 0" if base_price <= 0
raise "Must have a type parameter given as a string" unless type.is_a?(String)
raise "Must have an integer required_employees_quantity value equal or greater than 1" if !required_employees_quantity.is_a?(Integer) || required_employees_quantity < 1
#Instance variables
@base_price = base_price
@type = type.downcase
@required_employees_quantity = required_employees_quantity
end
def increase_required_employees_quantity
modify_required_employees_quantity(required_employees_quantity+1)
end
def decrease_required_employees_quantity
modify_required_employees_quantity(required_employees_quantity-1)
end
def modify_required_employees_quantity(new_required_employees_quantity)
raise "New required_employees_quantity has to be an integer value equal or greater than 1" if !new_required_employees_quantity.is_a?(Integer) || new_required_employees_quantity < 1
self.required_employees_quantity = new_required_employees_quantity
end
def final_cost_estimate
total_extra_markup_percentage = EMPLOYEE_MARKUP_PERCENTAGE * required_employees_quantity
case type
when "food"
total_extra_markup_percentage += FOOD_MARKUP_PERCENTAGE
when "drugs"
total_extra_markup_percentage += DRUGS_MARKUP_PERCENTAGE
when "electronics"
total_extra_markup_percentage += ELECTRONICS_MARKUP_PERCENTAGE
end
return calculate_cost_including_markup(flat_markup, total_extra_markup_percentage)
end
private
def flat_markup
return calculate_cost_including_markup(base_price, FLAT_MARKUP_PERCENTAGE)
end
def calculate_cost_including_markup(base_price, markup_percentage)
(base_price*(1+markup_percentage)).round(2)
end
end |
require 'test_helper'
class ArtyscisControllerTest < ActionController::TestCase
setup do
@artysci = artyscis(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:artyscis)
end
test "should get new" do
get :new
assert_response :success
end
test "should create artysci" do
assert_difference('Artysci.count') do
post :create, artysci: { nazwa: @artysci.nazwa }
end
assert_redirected_to artysci_path(assigns(:artysci))
end
test "should show artysci" do
get :show, id: @artysci
assert_response :success
end
test "should get edit" do
get :edit, id: @artysci
assert_response :success
end
test "should update artysci" do
patch :update, id: @artysci, artysci: { nazwa: @artysci.nazwa }
assert_redirected_to artysci_path(assigns(:artysci))
end
test "should destroy artysci" do
assert_difference('Artysci.count', -1) do
delete :destroy, id: @artysci
end
assert_redirected_to artyscis_path
end
end
|
class Relationthemeship < ActiveRecord::Base
belongs_to :theme
belongs_to :reltheme, :class_name => "Theme"
end
|
class AddAdditionalInformationToServiceItems < ActiveRecord::Migration[5.2]
def change
add_column :service_items, :additional_information, :text
end
end
|
# == Schema Information
#
# Table name: interests
#
# id :integer not null, primary key
# category :string(255)
# category_desc :string(255)
# active :boolean
# created_at :datetime not null
# updated_at :datetime not null
# reserved :boolean default(FALSE)
#
class Interest < ActiveRecord::Base
audited
attr_accessible :active, :category, :category_desc, :reserved
has_many :radiusposts
validates :category, presence: true
validates :category_desc, presence: true
def self.is_reserved(current_user)
true_false = "true,false"
if current_user.admin? || current_user.business?
where("reserved IN (#{true_false})")
else
where(reserved: false)
end
end
def self.search(search)
if search
find(:all, :conditions => ['category LIKE ?', "%#{search}%"])
else
find(:all)
end
end
end
|
require 'spec_helper'
require 'world'
describe "Address" do
include World
describe "normally" do
let(:address) { FactoryGirl.build( :address ) }
it { address.address.should == '1 Main Street' }
it { address.zip.should == '90000' }
it { address.isactive.should be_true}
end
end
|
require 'spec_helper'
require_relative '../lesson3/station'
RSpec.describe Station do
subject {described_class.new('A')}
let(:trains) {build_list(:train, 2, type: :freight)}
describe '#return_trains_on_type' do
before { subject.add_train(trains.first); station1.add_train(trains.last)}
it 'Return sorted list' do
expect(subject.return_trains_on_type(type: :freight)).to eq(trains.first)
expect(subject.return_trains_on_type(type: :passenger)).to eq(trains.last)
end
end
describe 'train_leave' do
before{ subject.train_leave}
it 'Remove first train from list' do
expect(subject.trains_list).to eq(trains.last)
end
end
end |
class PrcolorsController < ApplicationController
before_filter :admin_required
# GET /prcolors
# GET /prcolors.xml
def index
@prcolors = Prsize.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @prcolors }
end
end
# GET /prcolors/1
# GET /prcolors/1.xml
def show
@prcolor = Prcolor.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @prcolor }
end
end
# GET /prcolors/new
# GET /prcolors/new.xml
def new
@prcolor = Prcolor.new
if params[:product_id]
@prcolor.product = Product.find(params[:product_id])
end
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @prcolor }
end
end
# GET /prcolors/1/edit
def edit
@prcolor = Prcolor.find(params[:id])
end
# POST /prcolors
# POST /prcolors.xml
def create
@prcolor = Prcolor.new(params[:prcolor])
respond_to do |format|
if @prcolor.save
flash[:notice] = 'Цвет успешно создана.'
format.html { redirect_to(@prcolor.product) }
format.xml { render :xml => @prcolor, :status => :created, :location => @prcolor }
else
format.html { render :action => "new" }
format.xml { render :xml => @prcolor.errors, :status => :unprocessable_entity }
end
end
end
# PUT /prcolors/1
# PUT /prcolors/1.xml
def update
@prcolor = Prcolor.find(params[:id])
respond_to do |format|
if @prcolor.update_attributes(params[:prcolor])
flash[:notice] = 'Цвет успешно обновлена.'
format.html { redirect_to(@prcolor.product) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @prcolor.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /prsizes/1
# DELETE /prsizes/1.xml
def destroy
@prcolor = Prcolor.find(params[:id])
@prcolor.destroy
respond_to do |format|
format.html { redirect_to(@prcolor.product) }
format.xml { head :ok }
end
end
end
|
class HomeController < ApplicationController
before_filter :setup_session_user
before_filter :setup_mygov_client
before_filter :setup_mygov_access_token
def oauth_callback
auth = request.env["omniauth.auth"]
session[:user] = auth.extra.raw_info.to_hash
session[:token] = auth.credentials.token
redirect_to session[:return_to] || root_url
end
def index
end
def logout
session[:user] = nil # :before_filter sets to empty hash
redirect_to root_url
end
private
def setup_session_user
session[:user] = {} if session[:user].nil?
end
def setup_mygov_client
@mygov_client = OAuth2::Client.new(ENV['MYGOV_CLIENT_ID'], ENV['MYGOV_SECRET_ID'], {:site => ENV['MYGOV_HOME'], :token_url => "/oauth/authorize"})
end
def setup_mygov_access_token
@mygov_access_token = OAuth2::AccessToken.new(@mygov_client, session[:token]) if session
end
end |
require 'fs/xfs/superblock'
module XFSProbe
def self.probe(dobj)
unless dobj.kind_of?(MiqDisk)
$log&.debug("XFSProbe << FALSE because Disk Object class is not MiqDisk, but is '#{dobj.class}'")
return false
end
# The first Allocation Group's Superblock is at block zero.
dobj.seek(0, IO::SEEK_SET)
XFS::Superblock.new(dobj)
# If initializing the superblock does not throw any errors, then this is XFS
$log&.debug("XFSProbe << TRUE")
return true
rescue => err
$log&.debug("XFSProbe << FALSE because #{err.message}")
return false
ensure
dobj.seek(0, IO::SEEK_SET)
end
end
|
module ESearchy
module SocialEngines
class LinkedIn < ESearchy::BasePlugin
include ESearchy::Helpers::Search
include ESearchy::Parsers::People
ESearchy::PLUGINS[self.name.split("::")[-1].downcase] = self
def initialize(options={}, &block)
@info = {
#This name should be the class name
:name => "LinkedIn",
:desc => "Parses LinkedIn using Google Searches that match.",
# URL/page,data of engine or site to parse
:engine => "www.google.com",
:help => "",
:author => "Matias P. Brutti <FreedomCoder>",
# Port for request
:port => 80,
# Max number of searches per query.
# This is usually the max entries for most search engines.
:num => 100,
#TYPE 1 searches emails / TYPE 2 Searches people / TYPE 3 Profiling and Operations with data.
:type => 2
}
super options
end
def run
if @options[:company] != ""
@options[:query] = "site%3Awww.linkedin.com/pub+in+%22at+" + CGI.escape(@options[:company])
Display.msg "[ '+' => New, '<' => Updated, '=' => Existing ]"
search_engine do
parse google
end
else
Display.error "Needo to provide a company name."
end
end
def parse( results )
ts = []
results.each do |result|
ts << Thread.new {
begin
name_last = result[:title].scan(/[\w\s]* \|/)[0]
if name_last != nil && name_last != " |"
name_last = name_last.gsub(/profile[s]*/i,"").gsub("|","").strip.split(" ")
name = name_last.first
last = name_last.last
if (name.strip != "" || last.strip != "") && (name != nil || last != nil)
if result[:url].match(/http[s]*:\/\/www.linkedin.com\/pub\//) != nil
info = linkedin(result[:url])
if info[:company] == @options[:company]
new_empl = @project.persons.where(:name => name, :last => last)
if new_empl.size == 0
employee = Person.new
employee.name = name
employee.last = last
employee.created_at = Time.now
employee.found_by = @info[:name]
employee.found_at = result[:url]
employee.networks << Network.new({:name => "LinkedIn", :url => result[:url], :nickname => name+last, :info => info, :found_by => @info[:name]})
@project.persons << employee
@project.save
Display.msg "[LinkedIn] + " + name + " " + last
else
employee = new_empl.first
if networks_exist?(employee.networks, "LinkedIn")
Display.msg "[LinkedIn] < " + name + " " + last
employee.networks << Network.new({:name => "LinkedIn", :url => result[:url], :nickname => name+last, :info => info, :found_by => @info[:name]})
employee.found_by << @info[:name]
employee.save!
@project.save
else
Display.msg "[LinkedIn] = " + name + " " + last
end
end
end
end
end
end
rescue Exception => e
Display.debug "Something went wrong." + e
end
}
ts.each {|t| t.join }
end
end
end
end
end |
class User < ApplicationRecord
has_secure_password
validates_presence_of :email
validates_uniqueness_of :email
end
|
# ==========================================================================
# Project: Lebowski Framework - The SproutCore Test Automation Framework
# License: Licensed under MIT license (see License.txt)
# ==========================================================================
module Lebowski
module Foundation
module Views
#
# Represents a proxy to a SproutCore select field view (SC.SelectFieldView)
#
class SelectFieldView < Lebowski::Foundation::Views::View
# include Lebowski::Foundation
representing_sc_class 'SC.SelectFieldView'
EMPTY_VALUE = '***'
def selected?()
val = self['value']
return false if val.nil?
return false if (val.kind_of?(String) and (val.empty? or val == EMPTY_VALUE))
return true
end
#
# Use to check if this view has an empty item
#
def has_empty_option?()
empty = self['emptyName']
return (not (empty.nil? or empty.empty?))
end
def selected_with_name?(value)
objs = self['objects']
val = self['value']
objs.each do |obj|
name = get_object_name(obj)
return (val == get_object_value(obj)) if (not (name =~ /^#{value}$/i).nil?)
end
return false
end
def selected_with_value?(value)
objs = self['objects']
val = self['value']
objs.each do |obj|
if value.kind_of? String
return true if (not (val =~ /^#{get_object_value(obj)}$/i).nil?)
else
return true if (value == val)
end
end
return false
end
def selected_with_index?(index)
# TODO
end
def select(val)
return if val.nil?
if val.kind_of? Integer
select_with_index(val)
elsif val == :empty
select_empty
else
select_with_name(val.to_s)
end
end
#
# Used to select an item via its index
#
# @see #select
#
def select_with_index(val)
option_locator = "index=#{val}"
@driver.sc_select(:view, option_locator, self.abs_path)
stall :select
end
#
# Used to select an item via its label
#
# @see #select
#
def select_with_name(val)
option_locator = "label=regexi:^#{val}$"
@driver.sc_select(:view, option_locator, self.abs_path)
stall :select
end
#
# Used to select an item via its value
#
# @see #select
#
def select_with_value(val)
guid = @driver.get_sc_guid(val)
option_locator = "value=regexi:^#{guid}$"
@driver.sc_select(:view, option_locator, self.abs_path)
stall :select
end
#
# Used to select the empty item, if there is one
#
# @see #select
#
def select_empty()
option_locator = "value=#{EMPTY_VALUE}"
@driver.sc_select(:view, option_locator, self.abs_path)
stall :select
end
private
def get_object_name(obj)
if obj.kind_of?(ProxyObject)
@nameKey = self["nameKey"] if @nameKey.nil?
return obj[@nameKey]
end
return obj
end
def get_object_value(obj)
if obj.kind_of?(ProxyObject)
@valueKey = self["valueKey"] if @valueKey.nil?
return obj[@valueKey]
end
return obj
end
end
end
end
end |
require "spec_helper"
describe JwtRest::AuthHeader do
jwt_token_boilerplate
basic_token_boilerplate
let(:basic_header) { described_class.new("basic #{basic_token}") }
let(:jwt_header) { described_class.new("bearer #{jwt_token}") }
let(:ugly_header) { described_class.new("8923ihwefbmndsfnbdg") }
before :each do
allow(JwtRest::Secrets).to receive(:rsa_private_key).and_return private_key
end
describe "#is_basic?" do
it "is able to identify a basic token headers" do
expect(basic_header.is_basic?).to be_truthy
expect(ugly_header.is_basic?).to be_falsy
end
end
describe "#is_token?" do
it "is able to identify a baerer token headers" do
expect(jwt_header.is_token?).to be_truthy
expect(ugly_header.is_token?).to be_falsy
end
end
describe "#token" do
it "parses the basic token" do
expect(basic_header.token.username).to eq(username)
end
it "parses the JWT token" do
expect(jwt_header.token.payload.dig("name")).to eq("Mario")
end
it "return nil on ugly token" do
expect(ugly_header.token).to be_nil
end
it "does not raises exception on nil param for constructor" do
expect { described_class.new(nil) }.not_to raise_error
end
end
end
|
class ProjectsController < ApplicationController
def index
@time_sheets = TimeSheet.includes(:project).all
end
def new
@project = Project.new
@projects = Project.all.pluck(:name, :id)
end
def create
time_sheet = Project.new(time_sheet_params)
time_sheet.save
end
private
def time_sheet_params
params.require(:project).permit(time_sheets_attributes: [:id, :project_id, :description, :_destroy])
end
end
|
require 'test_helper'
class PostTest < ActiveSupport::TestCase
test "last_commenter" do
post = Post.create! :name => "testpost"
post.comments.create! :commenter => "the commenter"
assert_equal "the commenter", post.reload.last_commenter
end
end
|
class Player < ActiveRecord::Base
has_many :participations
has_many :games, through: :participations
end
|
module TheCityAdmin
# This class is the base class for all TheCity objects and is meant to be inherited.
#
class ApiList
attr_reader :total_entries, :total_pages, :per_page, :current_page
def self.load(options = {})
self.new(options)
end
# Checks if there is a next page.
#
# @return true for yes, false for no.
def next_page?
@current_page < @total_pages
end
# Gets the next page of results.
#
# @return [UserList] or nil if there are no more pages.
def next_page
return nil unless next_page?
self.class.new( @options.merge({:page => @options[:page]+1}) )
end
# Loads the next page of results and replaces self with the results.
#
# @return true on success or otherwise false.
def next_page!
return false unless next_page?
@options[:page] += 1
@options[:reader] = @options[:reader].class.new(@options)
@json_data = @options[:reader].load_feed
@total_entries = @json_data['total_entries']
@total_pages = @json_data['total_pages']
@per_page = @json_data['per_page']
@current_page = @json_data['current_page']
return true
end
end
end
|
require 'rails_helper'
describe 'user can see all tags' do
describe 'they visit /tags' do
it 'should show a list of all tags' do
article = Article.create!(title: "New Title", body: "New Body")
article.tags.create(name: "ruby")
article.tags.create(name: "programming")
visit tags_path
expect(page).to have_content("ruby")
expect(page).to have_content("programming")
end
end
end
|
Rails.application.routes.draw do
get '/' => 'sites#home'
post '/' => 'sites#index'
resources :concerts do
resources :comments
end
get '/popular_concerts' => 'concerts#show_most_popular'
end
|
module Frivol
# == Frivol::Config
# Sets the Frivol configuration (currently only the Redis config), allows access to the configured Redis instance,
# and has a helper method to include Frivol in a class with an optional storage expiry parameter
module Config
# Set the Backend.
#
# Expects one of Frivol::Backend::Redis, Frivol::Backend::RedisDistributed,
# Frivol::Backend::Riak or Frivol::Backend::Multi
def self.backend=(new_backend)
@@backend = new_backend
end
# Get the Backend.
def self.backend
@@backend
end
def self.allow_json_create
@@allow_json_create ||= []
end
# A convenience method to include Frivol in a class, with an optional storage expiry parameter.
#
# For example, you might have the following in environment.rb:
# Frivol::Config.redis_config = REDIS_CONFIG
# Frivol::Config.include_in ActiveRecord::Base, 600
# Which would include Frivol in ActiveRecord::Base and set the default storage expiry to 10 minutes
def self.include_in(host_class, storage_expires_in = nil)
host_class.send(:include, Frivol)
host_class.storage_expires_in storage_expires_in if storage_expires_in
end
end
end
|
require "task"
RSpec.describe Task do
describe "#project" do
it "detects ::shop" do
task = Task.new("Get milk ::shop")
expect(task.project).to eq("shop")
end
it "detects :shop" do
task = Task.new("Get milk :shop")
expect(task.project).to eq("shop")
end
it "detects :shop in the middle" do
task = Task.new("Get :shop milk")
expect(task.project).to eq("shop")
end
it "detects :shop at the start" do
task = Task.new(":shop Get milk")
expect(task.project).to eq("shop")
end
it "doesn't match on the wrong side" do
task = Task.new("Listen: Music")
expect(task.project).to eq(nil)
end
end
describe "#project=" do
it "appends at the end" do
task = Task.new("Get milk")
task.project = "shop"
expect(task.project).to eq("shop")
expect(task.to_s).to eq("Get milk ::shop")
end
it "replaces existing project" do
task = Task.new("Get milk :supermarket")
task.project = "shop"
expect(task.project).to eq("shop")
expect(task.to_s).to eq("Get milk ::shop")
end
it "removes spaces from task string" do
task = Task.new("Get milk :shop")
task.project = "Hello World!"
expect(task.to_s).to eq("Get milk ::HelloWorld!")
end
it "saves as changed" do
task = Task.new("Get milk")
task.project = "shop"
expect(task.project_changed?).to be_truthy
expect(task.context_changed?).to be_falsy
end
end
describe "#context=" do
it "appends at the end" do
task = Task.new("Get milk")
task.context = "shop"
expect(task.context).to eq("shop")
expect(task.to_s).to eq("Get milk @shop")
end
it "saves as changed" do
task = Task.new("Get milk")
task.context = "shop"
expect(task.context_changed?).to be_truthy
expect(task.project_changed?).to be_falsy
end
end
describe "#likely_editing" do
it "detects context with both" do
task = Task.new("Get milk ::groceries @shop")
expect(task.likely_editing?(:context)).to be_truthy
expect(task.likely_editing?(:project)).to be_falsy
end
it "detects project with both" do
task = Task.new("Get milk @shop ::groceries")
expect(task.likely_editing?(:project)).to be_truthy
expect(task.likely_editing?(:context)).to be_falsy
end
it "detects context alone" do
task = Task.new("Get milk @shop")
expect(task.likely_editing?(:context)).to be_truthy
expect(task.likely_editing?(:project)).to be_falsy
end
it "detects project alone" do
task = Task.new("Get milk ::groceries")
expect(task.likely_editing?(:project)).to be_truthy
expect(task.likely_editing?(:context)).to be_falsy
end
it "detects none" do
task = Task.new("Get milk")
expect(task.likely_editing?(:project)).to be_falsy
expect(task.likely_editing?(:context)).to be_falsy
end
end
describe "examples" do
it "passes tasks without project or contexts straight through" do
task = Task.new("Get milk #tonight")
expect(task.to_s).to eq("Get milk #tonight")
end
end
end
|
require "application_system_test_case"
class FileSentsTest < ApplicationSystemTestCase
setup do
@file_sent = file_sents(:one)
end
test "visiting the index" do
visit file_sents_url
assert_selector "h1", text: "File Sents"
end
test "creating a File sent" do
visit file_sents_url
click_on "New File Sent"
fill_in "Content", with: @file_sent.content
fill_in "Structure", with: @file_sent.structure_id
fill_in "User", with: @file_sent.user_id
click_on "Create File sent"
assert_text "File sent was successfully created"
click_on "Back"
end
test "updating a File sent" do
visit file_sents_url
click_on "Edit", match: :first
fill_in "Content", with: @file_sent.content
fill_in "Structure", with: @file_sent.structure_id
fill_in "User", with: @file_sent.user_id
click_on "Update File sent"
assert_text "File sent was successfully updated"
click_on "Back"
end
test "destroying a File sent" do
visit file_sents_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "File sent was successfully destroyed"
end
end
|
class JobsController < ApplicationController
before_action :authenticate_user!, only: [:new, :create]
before_action :authenticate_worker!, only: [:update]
def index
@jobs = Job.all
end
def show
@job = Job.find(params[:id])
end
def new
@job = Job.new
render :new
end
def create
@job = Job.new(job_params)
if @job.save
flash[:notice] = "You added a job"
redirect_to jobs_path
else
flash[:alert] = @job.errors.full_messages.each {|m| m.to_s}.join
render :new
end
end
def edit
@job = Job.find(params[:id])
render :edit
end
def update
@job = Job.find(params[:id])
@job.update(job_params)
respond_to do |format|
format.js
format.html { redirect_to worker_path(current_worker) }
end
end
private
def job_params
params.require(:job).permit(:title, :description, :user_id, :worker_id, :pending, :completed, :in_progress)
end
end
|
require 'helper'
describe Esendex::Users do
let(:credentials) { Esendex::Credentials.new('user', 'pass', 'ref') }
subject { Esendex::Users.new(credentials) }
end
|
require 'rails_helper'
describe 'forums/topics/edit' do
let(:topic) { create(:forums_topic) }
it 'displays' do
assign(:topic, topic)
render
end
end
|
require 'rails_helper'
describe Types::CommentType do
types = GraphQL::Define::TypeDefiner.instance
it 'defines a field id of type ID!' do
expect(subject).to have_field(:id).that_returns(!types.ID)
end
it 'defines a field provider of type String!' do
expect(subject).to have_field(:body).that_returns(!types.String)
end
it 'defines a field updated_at of type String!' do
expect(subject).to have_field(:updated_at).that_returns(!types.String)
end
it 'defines a field user of type Types::UserType!' do
expect(subject).to have_field(:user).that_returns(!Types::UserType)
end
it 'defines a field post of type Types::PostType!' do
expect(subject).to have_field(:post).that_returns(!Types::PostType)
end
end
|
class Article < ApplicationRecord
include Voteable
belongs_to :user
has_many :comments, dependent: :destroy
has_many :reports, as: :reportable, dependent: :destroy
validates :user, :title, presence: true
validates :uid, uniqueness: true
validates :url, uniqueness: true, allow_blank: true
validates :url, url: true
validate :url_and_or_description
before_create :set_uid, :set_slug
def presenter
ArticlePresenter.new(self)
end
private
def set_slug
self.slug = title.gsub(/[^0-9a-z ]/i, '')
.gsub(/\W/, '_')
.downcase
end
def set_uid
hex = SecureRandom.hex(3)
self.uid = hex.to_s
end
def url_and_or_description
return unless url.empty? && description.empty?
errors.add(:base, 'Url and Description cannot both be empty')
end
end
|
FactoryGirl.define do
factory :category do
sequence :name do |i|
"Category #{i}"
end
end
end
|
require 'factory_bot'
require 'faker'
namespace :check_list_engine do
desc 'Seed data for an audit'
task seed_audit_data: :environment do
def create_available_component_types
available_component_types = [
{title: 'Title', has_photo: false},
{title: 'Choices', has_photo: false},
{title: 'Section', has_photo: false},
{title: 'Photo', has_photo: true},
{title: 'Date', has_photo: false},
{title: 'Address', has_photo: false},
{title: 'Text', has_photo: false},
{title: 'Signature', has_photo: true},
{title: 'Yes/No', has_photo: false}
]
available_component_types.each do |component|
CheckListEngine::AvailableComponentType.new(component).save!
end
end
def get_component_id(title)
CheckListEngine::AvailableComponentType.find_by_title(title).id
end
def create_pest_audit
audit_type = CheckListEngine::AuditType.new title: "Pest control audit"
audit_type.save!
pest_audit_components = [
{ title: 'Title', position: 1, available_component_type_id: get_component_id('Title'), audit_type_id: audit_type.id, is_mandatory: false },
{ title: 'Customers Address', position: 2, available_component_type_id: get_component_id('Address'), audit_type_id: audit_type.id, is_mandatory: false },
{ title: 'Date of visit', position: 3, available_component_type_id: get_component_id('Date'), audit_type_id: audit_type.id, is_mandatory: false},
{ title: 'Kind of pest', position: 7, available_component_type_id: get_component_id('Text'), audit_type_id: audit_type.id, choices: 'Rat, Mouse, Squirrel, Flea', is_mandatory: false},
{ title: 'Description of the problem', position: 4, available_component_type_id: get_component_id('Text'), audit_type_id: audit_type.id, is_mandatory: false },
{ title: 'Customer signature', position: 5, available_component_type_id: get_component_id('Signature'), audit_type_id: audit_type.id, is_mandatory: false},
{ title: 'Work carried out', position: 6, available_component_type_id: get_component_id('Text'), audit_type_id: audit_type.id, is_mandatory: false},
{ title: 'Photo', position: 7, available_component_type_id: get_component_id('Photo'), audit_type_id: audit_type.id, is_mandatory: false}
]
pest_audit_components.each do |component|
CheckListEngine::AuditTypeComponent.new(component).save!
end
end
def create_rental_house_audit
audit_type = CheckListEngine::AuditType.new title: 'Inspection of a rented house by a landlord'
audit_type.save!
rental_house_audit_components = [
{ title: 'Property Address', position: 1, available_component_type_id: get_component_id('Address'), audit_type_id: audit_type.id, is_mandatory: false },
{ title: 'Date of visit', position: 2, available_component_type_id: get_component_id('Date'), audit_type_id: audit_type.id, is_mandatory: false},
{ title: 'General impression', position: 3, available_component_type_id: get_component_id('Title'), audit_type_id: audit_type.id, is_mandatory: false },
{ title: 'Boiler serviced ?', position: 5, available_component_type_id: get_component_id('Yes/No'), audit_type_id: audit_type.id, is_mandatory: false},
{ title: 'Buildings insurance in place ?', position: 6, available_component_type_id: get_component_id('Yes/No'), audit_type_id: audit_type.id, is_mandatory: false},
{ title: 'Photo', position: 7, available_component_type_id: get_component_id('Photo'), audit_type_id: audit_type.id, is_mandatory: false},
{ title: 'Maintainance work needed', position: 8, available_component_type_id: get_component_id('Title'), audit_type_id: audit_type.id, is_mandatory: false },
{ title: 'Inspecting agents signature', position: 9, available_component_type_id: get_component_id('Signature'), audit_type_id: audit_type.id, is_mandatory: false},
]
rental_house_audit_components.each do |component|
CheckListEngine::AuditTypeComponent.new(component).save!
end
end
def create_burglar_alarm_inspection
audit_type = CheckListEngine::AuditType.new title: 'Burglar alarm service'
audit_type.save!
burglar_alarm_service_audit_components = [
{ title: 'Customer name', position: 3, available_component_type_id: get_component_id('Title'), audit_type_id: audit_type.id, is_mandatory: true },
{ title: 'Property Address', position: 1, available_component_type_id: get_component_id('Address'), audit_type_id: audit_type.id, is_mandatory: true },
{ title: 'Type of installation', position: 2, available_component_type_id: get_component_id('Choices'), audit_type_id: audit_type.id, is_mandatory: true, choices: 'External Audible Only, Remote Signalling'},
{ title: 'Check carrried out', position: 3, available_component_type_id: get_component_id('Section'), audit_type_id: audit_type.id, is_mandatory: true },
{ title: 'That the installed system is fitted as per the documentation ', position: 5, available_component_type_id: get_component_id('Yes/No'), audit_type_id: audit_type.id, is_mandatory: true},
{ title: 'Tamper detection', position: 6, available_component_type_id: get_component_id('Yes/No'), audit_type_id: audit_type.id, is_mandatory: true},
{ title: 'Setting and unsetting', position: 7, available_component_type_id: get_component_id('Yes/No'), audit_type_id: audit_type.id, is_mandatory: true},
{ title: 'Entry and exit procedures', position: 8, available_component_type_id: get_component_id('Yes/No'), audit_type_id: audit_type.id, is_mandatory: true},
{ title: 'Power supplies, including any APS', position: 9, available_component_type_id: get_component_id('Yes/No'), audit_type_id: audit_type.id, is_mandatory: true},
{ title: 'Functioning of detectors and HDs', position: 6, available_component_type_id: get_component_id('Yes/No'), audit_type_id: audit_type.id, is_mandatory: true},
{ title: 'Visual inspection of potential problems (electrial and physical)', position: 10, available_component_type_id: get_component_id('Yes/No'), audit_type_id: audit_type.id, is_mandatory: true},
{ title: 'What work was done ?', position: 11, available_component_type_id: get_component_id('Text'), audit_type_id: audit_type.id, is_mandatory: true},
{ title: 'Materials used', position: 12, available_component_type_id: get_component_id('Text'), audit_type_id: audit_type.id, is_mandatory: true},
{ title: 'Site specific risk assessment', position: 13, available_component_type_id: get_component_id('Section'), audit_type_id: audit_type.id, is_mandatory: true },
{ title: 'EC01 Working at height', position: 14, available_component_type_id: get_component_id('Yes/No'), audit_type_id: audit_type.id, is_mandatory: false},
{ title: 'EC04 Use of ladders', position: 15, available_component_type_id: get_component_id('Yes/No'), audit_type_id: audit_type.id, is_mandatory: false},
{ title: 'EC18 use of hand tools', position: 16, available_component_type_id: get_component_id('Yes/No'), audit_type_id: audit_type.id, is_mandatory: false},
{ title: 'EC26 electrical work up to 415v', position: 17, available_component_type_id: get_component_id('Yes/No'), audit_type_id: audit_type.id, is_mandatory: false},
{ title: 'EC29 Electrical Testing and Commisioning ', position: 18, available_component_type_id: get_component_id('Yes/No'), audit_type_id: audit_type.id, is_mandatory: false},
{ title: 'EC33 Displosal of waste materials', position: 19, available_component_type_id: get_component_id('Yes/No'), audit_type_id: audit_type.id, is_mandatory: false},
{ title: 'Additional hazards identified in this job', position: 20, available_component_type_id: get_component_id('Text'), audit_type_id: audit_type.id, is_mandatory: true},
{ title: 'Overall risk rating', position: 21, available_component_type_id: get_component_id('Choices'), audit_type_id: audit_type.id, is_mandatory: true, choices: 'Hich, Low, Medium'},
{ title: 'Have these controls brought the level of risk down as low as is practical ?', position: 22, available_component_type_id: get_component_id('Yes/No'), audit_type_id: audit_type.id, is_mandatory: true},
{ title: 'I have read and understood the control measures identified above and agree to implement all the requirements', position: 23, available_component_type_id: get_component_id('Yes/No'), audit_type_id: audit_type.id, is_mandatory: true},
{ title: 'Time arrived', position: 24, available_component_type_id: get_component_id('Text'), audit_type_id: audit_type.id, is_mandatory: true},
{ title: 'Time departed', position: 24, available_component_type_id: get_component_id('Text'), audit_type_id: audit_type.id, is_mandatory: true},
{ title: 'Engineers signature', position: 25, available_component_type_id: get_component_id('Signature'), audit_type_id: audit_type.id, is_mandatory: false},
{ title: 'Customers signature', position: 26, available_component_type_id: get_component_id('Signature'), audit_type_id: audit_type.id, is_mandatory: false},
]
burglar_alarm_service_audit_components.each do |component|
CheckListEngine::AuditTypeComponent.new(component).save!
end
end
def dump_audits
CheckListEngine::AuditType.all.each do |audit|
puts "----------- Audit: #{audit.title} -------------"
audit.audit_type_components.order(:position).each do |c|
puts " #{c.title} (a #{c.available_component_type.title})"
end
end
end
CheckListEngine::AuditTypeComponent.delete_all
CheckListEngine::AuditType.delete_all
CheckListEngine::AvailableComponentType.delete_all
create_available_component_types
create_pest_audit
create_rental_house_audit
dump_audits
end
end
|
@counter = 0
@account_number = 0
private
def pin
@pin = 1234
end
class Account
attr_reader :name, :balance, :number
def initialize(name, balance=100)
@name = name
@balance = balance
end
def display_balance()
puts "Balance: $#{@balance}."
end
def withdraw(amount)
if balance < amount
puts "Overdraw, transaction denied"
else
@balance -= amount
puts "Withdrew $#{amount}. New balance: $#{@balance}."
end
end
def deposit(amount)
@balance += amount
puts "Deposited $#{amount}. New balance: $#{@balance}."
end
def transfer(amount)
if balance < amount
puts "Overdraw, transaction denied "
exit
end
end
end
#Outside the class
@checking_account = Account.new("Checking", 9_000_000)
@savings_account = Account.new("Savings", 1000)
def menu
puts "What would you like to do?"
puts " "
puts "-- Type 'Balance' to check balance."
puts "-- Type 'Withdraw' to withdraw funds."
puts "-- Type 'Deposit' to deposit funds."
puts "-- Type 'Transfer' to transfer funds."
puts " "
choice = gets.chomp.upcase
case choice
when 'BALANCE'
@current_account.display_balance()
puts " "
menu
when 'WITHDRAW'
puts "Enter How Much to Withdraw"
amount = gets.chomp.to_i
@current_account.withdraw(amount)
puts " "
menu
when 'DEPOSIT'
puts "Enter How Much to Deposit"
amount = gets.chomp.to_i
@current_account.deposit(amount)
puts " "
menu
when 'TRANSFER'
puts "Enter How Much to Transfer"
amount = gets.chomp.to_i
puts "To Which Account?"
gets.chomp
@secondary_account = @savings_account
@secondary_account.deposit(amount)
@current_account.transfer(amount)
@current_account.withdraw(amount)
puts "Succesfully transfered $#{amount}"
puts " "
menu
when 'CHANGE'
account_choice
when 'ADD'
@account_number += 1
if @account_number <= 1
puts "What Would You like to name this account?"
name = gets.chomp.upcase
@extra_account = Account.new(name, 0)
puts "Created new #{@extra_account.name} Account"
@extra_account.display_balance
account_choice
else puts "Cannot create more accounts"
account_choice
end
when 'EXIT'
exit
else
puts "Not a Valid Command"
puts "Try Again"
menu
# I added the "choice" case to the menu method.
end
end
def account_choice
if @account_number == 0
puts "Which Account To Access?"
puts "#{@savings_account.name.upcase}"
puts "#{@checking_account.name.upcase}"
selection = gets.chomp.upcase
else
puts "Which Account To Access?"
puts "#{@savings_account.name.upcase}"
puts "#{@checking_account.name.upcase}"
puts "#{@extra_account.name}"
selection = gets.chomp.upcase
end
case selection
when 'SAVINGS'
@current_account = @savings_account
@secondary_account = @checking_account
puts "Currently in #{@savings_account.name} Account"
menu
when 'CHECKING'
@current_account = @checking_account
puts "Currently in #{@checking_account.name} Account"
menu
when "#{@extra_account.name}"
@current_account = @extra_account
puts "Currently in #{@extra_account.name} Account"
menu
else
puts "Not a Correct Selection"
account_choice
# I added the "selection" case to the account_choice method.
end
end
def pin_error
@counter += 1
if @counter < 3
puts "Access Denied: Incorrect PIN."
login
else
puts "Too Many Pin Attempts. Now Exiting."
exit
end
end
def login
puts "Enter PIN"
if
gets.to_i == pin
account_choice
else
pin_error
end
end
#This is where I stop defining methods, and call stuff
login
|
class Subscription < ActiveRecord::Base
belongs_to :channel, counter_cache: true
belongs_to :user, counter_cache: true
validates :channel_id, presence: true, uniqueness: { scope: :user_id }
validates :user_id, presence: true
def to_h
SubscriptionSerializer.new(self).attributes
end
end
|
require 'spec_helper'
describe ::ServiceBinding::ConjurV5AppBinding do
let(:service_id) { "service_id" }
let(:binding_id) { "binding_id" }
let(:org_guid) { nil }
let(:space_guid) { nil }
let(:service_binding) do
::ServiceBinding::ConjurV5AppBinding.new(
service_id,
binding_id,
org_guid,
space_guid
)
end
describe "#create" do
let(:host) { double("host") }
let(:policy_load_response) { double("response") }
let(:create_result) { service_binding.create }
before do
# Assume V5 by default
allow(ENV).to receive(:[]).and_call_original
allow(ENV).to receive(:[]).with('CONJUR_VERSION').and_return('5')
allow(host).to receive(:exists?).and_return(false)
allow_any_instance_of(Conjur::API).to receive(:role).and_return(host)
allow_any_instance_of(ConjurClient).to receive(:platform).and_return(nil)
policy_load_response.stub_chain(:created_roles, :values, :first, :[]).and_return("api_key")
end
context "when space context is not present" do
it "generates all hosts in the foundation policy" do
expected_policy = <<~YAML
- !host
id: binding_id
YAML
expect_any_instance_of(Conjur::API)
.to receive(:load_policy)
.with("root", expected_policy, method: :post)
.and_return(policy_load_response)
expect(create_result[:authn_login]).to eq("host/binding_id")
end
context "when the platform is present" do
before do
allow(ConjurClient).to receive(:platform).and_return("platform")
end
it "generates policy that includes the platform annotation" do
expected_policy = <<~YAML
- !host
id: binding_id
annotations:
platform: true
YAML
expect_any_instance_of(Conjur::API)
.to receive(:load_policy)
.with("root", expected_policy, method: :post)
.and_return(policy_load_response)
expect(create_result[:authn_login]).to eq("host/binding_id")
end
end
end
context "when space context is present" do
let(:org_guid) { "org_guid" }
let(:space_guid) { "space_guid" }
it "generates hosts within the org/space hierarchy" do
expected_policy = <<~YAML
- !host
id: binding_id
- !grant
role: !layer
member: !host binding_id
YAML
expect_any_instance_of(Conjur::API)
.to receive(:load_policy)
.with("org_guid/space_guid", expected_policy, method: :post)
.and_return(policy_load_response)
expect(create_result[:authn_login]).to eq("host/org_guid/space_guid/binding_id")
end
end
end
describe "#delete" do
let(:host) { double("host") }
let(:service_binding) do
::ServiceBinding::ConjurV5AppBinding.new(
service_id,
binding_id,
nil,
nil
)
end
before do
allow(host).to receive(:exists?).and_return(true)
allow(host).to receive(:rotate_api_key)
allow_any_instance_of(Conjur::API).to receive(:role).and_return(host)
end
context "when space context is not present" do
it "uses the Conjur API to load policy to delete the host" do
expected_policy = <<~YAML
- !delete
record: !host binding_id
YAML
expect_any_instance_of(Conjur::API)
.to receive(:load_policy)
.with("root", expected_policy, method: :patch)
expect(host).to receive(:rotate_api_key)
service_binding.delete
end
end
end
end
|
# Execute Choria Playbook Tasks
#
# Any task supported by Choria Playbooks is supported and
# can be used from within a plan, though there is probably
# not much sense in using the Bolt task type as you can just
# use `run_task` or `run_command` directly in the plan.
#
# The options to Playbook tasks like `pre_book`, `on_success`,
# `on_fail` and `post_book` does not make sense within the
# Puppet Plan DSL.
#
# @example disables puppet and wait for all nodes to idle
#
# choria::task("mcollective",
# "action" => "puppet.disable",
# "nodes" => $all_nodes,
# "properties" => {
# "message" => "disabled during plan execution ${name}"
# }
# )
#
# $result = choria::task("mcollective",
# "action" => "puppet.status",
# "nodes" => $all_nodes,
# "assert" => "idling=true",
# "tries" => 10,
# "try_sleep" => 30
# )
#
# if $result.ok {
# choria::task("slack",
# "token" => $slack_token,
# "channel" = "#ops",
# "text" => "All nodes have been disabled and are idling"
# )
# }
Puppet::Functions.create_function(:"choria::task", Puppet::Functions::InternalFunction) do
dispatch :run_task do
scope_param
param "String", :type
param "Hash", :properties
return_type "Choria::TaskResults"
end
dispatch :run_mcollective_task do
scope_param
param "Hash", :properties
return_type "Choria::TaskResults"
end
def run_mcollective_task(scope, properties)
run_task(scope, "mcollective", properties)
end
def run_task(scope, type, properties)
require_relative "../../_load_choria"
MCollective::Util::BoltSupport.init_choria.run_task(scope, type, properties)
end
end
|
class Product < ApplicationRecord
has_and_belongs_to_many :categories
belongs_to :merchant
has_many :order_items
has_many :reviews
validates :name, presence: true, uniqueness: true
validates :price, presence: true, numericality: {greater_than: 0}
def average_rating
return self.reviews.average(:rating)
end
def already_in_cart(cart)
status = cart.nil? ? nil : cart.order_items.find_by(product_id: self.id)
return status ? status.id : status
end
def self.search(search)
return Product.where("name iLIKE ?", "%#{search}%")
end
def self.top_rated(products)
top_rated = products.sort_by { |product| product.average_rating.to_i }.reverse
return top_rated[0..4]
end
def self.newest(products)
return products.last
end
end
|
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by(:email => params[:login][:email].downcase)
if user && user.authenticate(params[:login][:password])
session[:user_id] = user.id
render :json => { success: true }
else
render :json => { success: false }
end
end
def destroy
session.delete(:user_id)
render :json => { success: true }
end
def _login_params
params.require(:login).permit(:email, :password)
end
end
|
#
# Cookbook:: asf
# Recipe:: service
#
# Copyright:: 2017, Tyler Wong, All Rights Reserved.
poise_service_user 'asf' do
action :create
end
%W(#{node['asf']['install']['path']} #{node['asf']['config']['path']}).each do |dir|
directory dir do
owner 'asf'
group 'asf'
mode '0755'
recursive true
action :create
end
end
remote_file "#{node['asf']['install']['path']}/ASF.exe" do
source File.join(node['asf']['source'], node['asf']['version'], 'ASF.exe')
checksum node['asf']['checksum']
owner 'asf'
group 'asf'
mode '0755'
notifies :restart, 'poise_service[asf]', :delayed
action :create
end
template "#{node['asf']['config']['path']}/ASF.json" do
source 'ASF.erb'
owner 'asf'
group 'asf'
mode '0755'
notifies :restart, 'poise_service[asf]', :delayed
action :create
end
node['asf']['bots'].keys.each do |bot_name|
template "#{node['asf']['config']['path']}/#{bot_name}.json" do
source 'bot.erb'
owner 'asf'
group 'asf'
mode '0550'
variables(bot_name: bot_name)
notifies :restart, 'poise_service[asf]', :delayed
action :create
end
end
poise_service 'asf' do
command "/usr/bin/mono #{node['asf']['install']['path']}/ASF.exe --path=#{node['asf']['install']['path']} --server"
user 'asf'
directory node['asf']['install']['path']
restart_on_update true
action :enable
end
|
require 'spec_helper'
describe FraudModel do
let(:user) { FactoryGirl.create(:merchant) }
let!(:good_transaction) { FactoryGirl.create(:good_transaction, user: user, amount: 50) }
let!(:bad_transaction) { FactoryGirl.create(:bad_transaction, user: user, amount: 200) }
let!(:extreme_transaction) { FactoryGirl.create(:bad_transaction, user: user, amount: 1000000) }
let!(:tiny_transaction) { FactoryGirl.create(:good_transaction, user: user, amount: 5) }
let(:model) { user.fraud_model }
describe "#reliability_score" do
it "should return a number between 0 and 100" do
score = model.reliability_score(good_transaction)
score.should be >= 0
score.should be <= 100
end
it "should give a higher score to a bad transaction than a good transaction" do
model.reliability_score(bad_transaction).should > model.reliability_score(good_transaction)
#TODO: rename; it's a fraud score, not a reliability score
end
end
describe "#explain_factor" do
it "should return a string describing how much this factor affected the score" do
explanation = model.explain_factor(model.reliability_score(good_transaction), :amount)
explanation.should match /The amount factor accounted for [0-9]*% of the score\./
explanation.should match /This transaction's amount was worse than [0-9]*% of transactions in the sample\./
explanation.should match /the amount of the transaction/
explanation.should include "50"
end
end
describe "#explain" do
it "should return a string " do
explanation = model.explain(model.reliability_score(good_transaction))
explanation.should be_kind_of(String)
explanation.should be_present
end
it "should not raise an error for an extreme transaction" do
expect {
score = model.reliability_score(extreme_transaction)
explanation = model.explain(score)
}.not_to raise_error
end
it "should not raise an error for a perfect transaction" do
expect {
score = model.reliability_score(tiny_transaction)
explanation = model.explain(score)
}.not_to raise_error
end
end
describe "#factor_details" do
let(:proportion_value) { 0.1 }
let(:quantile_value) { 0.2 }
let(:value) { 0.3 }
let(:factor) { :amount }
before do
@score = mock
@score.stub(:proportion_of_score).and_return(factor => proportion_value)
@score.stub(:quantile_of_feature).and_return(factor => quantile_value)
@score.stub(:value_of_feature).and_return(factor => value)
end
it "should return details of each factor" do
description = ExplanatoryVariable.lookup(factor).description.titleize
model.factor_details(@score, factor).should ==
{:value => value, :proportion => (proportion_value*100).floor,
:quantile => (quantile_value*100).floor, :description => description }
end
end
describe "#extracted_factors" do
before do
@score = double("Score")
end
it "shouldn't return unaffected factors and should order by the importance of factors" do
@score.stub(:proportion_of_score).and_return({:factor1 => 1, :factor2 => 2, :factor3 => 0})
model.extracted_factors(@score).should == [:factor2, :factor1]
end
it "should return top 5 factors" do
@score.stub(:proportion_of_score).and_return({:factor1 => 10, :factor2 => 9, :factor3 => 8,
:factor4 => 7, :factor5 => 6, :factor6 => 5})
model.extracted_factors(@score).should == [:factor1, :factor2, :factor3, :factor4, :factor5]
end
end
describe "initialize" do
it "should create a sane model if class is a just a string" do
merchant = FactoryGirl.create(:merchant)
f = FraudModel.new(merchant_id: merchant.id, class: "Scorer::OutlierOrder" )
end
it "should create a sane model if terms is just a string" do
merchant = FactoryGirl.create(:merchant)
f = FraudModel.new(merchant_id: merchant.id, model_params_string: Scorer::OutlierOrder.default_model_params.to_json )
end
it "should raise an error if unknown arguments are given" do
merchant = FactoryGirl.create(:merchant)
expect {
f = FraudModel.new(merchant_id: merchant.id, crazy_key: 15 )
}.to raise_error
end
end
end
|
require 'rails_helper'
RSpec.describe "Users::Sessions", type: :request do
describe "GET /users/auth/:provide" do
let(:auth_info) {
OmniAuth::AuthHash.new({
provider: 'github',
info: {
email: 'github@rubyconf.tw'
}
})
}
it "copy data from provider session" do
visit new_user_session_url
expect(page).to have_content("Sign in with Github")
OmniAuth.config.mock_auth[:github] = auth_info
click_link "Sign in with Github"
expect(page).to have_content("You are already signed in.")
end
end
end
|
class Project < ActiveRecord::Base
has_many :project_users, dependent: :destroy
has_many :users, through: :project_users
has_one :work_branch_collection
accepts_nested_attributes_for :work_branch_collection, allow_destroy: true
serialize :actions, Array
def github_access_token
authenticating_user.github_access_token
end
def authenticating_user
users.first
end
def repo_full_name
"#{owner}/#{name}"
end
end
|
# frozen_string_literal: true
RSpec.describe ErrorHandler do
describe '.error_json' do
context 'when error' do
it 'should return an error status' do
error_message = 'some arbitrary app error'
error = StandardError.new error_message
code, content_type, status = described_class.new(app).error_json error
status = JSON.parse status[0]
expect(content_type['Content-Type']).to match 'application/json'
expect(code).to be_between(400, 500)
expect(status['status']).to match 'error'
expect(status['message']).to match error_message
end
end
end
end
|
require 'rails_helper'
RSpec.describe ContentsController, type: :controller do
describe 'GET #index' do
let(:contents) { create_list(:content, 2) }
before { get :index }
it 'array all contents' do
expect(assigns(:contents)).to match_array(contents)
end
it 'render index view' do
expect(response).to render_template :index
end
end
describe 'GET #edit' do
let(:content) { create(:content) }
before { get :edit, params: { id: content } }
it 'assigns content to @content' do
expect(assigns(:content)).to eq content
end
it 'render show view' do
expect(response).to render_template :edit
end
end
end
|
require 'spec_helper'
describe AdventurersHelper do
let(:user) { FactoryGirl.create(:user) }
let(:story) { FactoryGirl.create(:story) }
let(:chapter) { FactoryGirl.create(:chapter, story: story) }
let(:item) { FactoryGirl.create(:item) }
let(:modifier_shop) { FactoryGirl.create(:modifier_shop, chapter: chapter, item: item, quantity: 4) }
let(:adventurer) { FactoryGirl.create(:adventurer, user: user) }
describe '#return_real_quantity' do
context "shop is related to adventurer" do
let(:adventurer_shop) { FactoryGirl.create(:adventurer_shop, adventurer: adventurer, modifier_shop: modifier_shop, quantity: 3) }
it "returns adventurer_modifier_shop" do
adventurer_shop
@adventurer = adventurer
expect(helper.return_real_quantity(modifier_shop)).to eql(3)
end
end
context "shop is not related to adventurer" do
it "returns modifier_shop quantity" do
@adventurer = adventurer
expect(helper.return_real_quantity(modifier_shop)).to eql(4)
end
end
end
describe '#current_weapon_damage' do
let(:sword) { FactoryGirl.create(:weapon, name: 'Espada', damage: 4) }
let(:lance) { FactoryGirl.create(:weapon, name: 'Lança', damage: 3) }
context 'there is a selected weapon' do
before do
adventurer.items << lance
adventurer.items << sword
adventurer_item = adventurer.adventurers_items.last
adventurer_item.update(selected: true)
end
it 'returns damage of selected weapon' do
expect(helper.current_weapon_damage(adventurer)).to eql(4)
end
end
context 'there is not a selected weapon' do
before do
adventurer.items << lance
adventurer.items << sword
end
it 'returns default number' do
expect(helper.current_weapon_damage(adventurer)).to eql(2)
end
end
end
end |
class Evil::Client::Operation
class UnexpectedResponseError < RuntimeError
attr_reader :status, :data
private
def initialize(schema, status, data)
@status = status
@data = data
message = "Response to operation '#{schema[:key]}'" \
" with http status #{status} and body #{data}" \
" cannot be processed."
message << " See #{schema[:doc]} for details." if schema[:doc]
super message
end
end
end
|
class Feed < ActiveRecord::Base
attr_accessible :name, :url, :user_id
#has_many :readlater
before_save do |record|
unless self.unique then
raise "Feed name or url already exists."
end
unless self.user_feed_quota(record.user_id) then
raise "You cannot agregate more than 40 feeds."
end
return true
end
after_create do |record|
#UserLog.add_action('add_feed')
return true
end
def self.get_user_feeds(user_id, full=true)
if full then
return Feed.where("user_id = ?", user_id).order("id ASC")
else
return Feed.select("id").where("user_id = ?", user_id).order("id ASC").map {|x| x.id}
end
end
def unique
user_feeds = Feed.where("user_id = ? and (name = ? or url = ?)", self.user_id, self.name, self.url).count
if user_feeds > 0
return false
end
return true
end
def user_feed_quota(user_id)
user_feeds = Feed.where("user_id = ?", user_id).count
if user_feeds > 40
return false
end
return true
end
end
|
Rails.application.routes.draw do
get 'thanks' => 'pages#thanks'
resources :signups, only: [:new, :create]
get 'signups' => 'signups#new'
post 'signups' => 'signups#create'
root 'pages#home'
get 'about' => 'pages#about'
end
|
# -*- encoding : utf-8 -*-
class Cms::FeedbacksController < Cms::BaseController
def index
@feedbacks = Feedback.latest.page(params[:page])
end
def show
@feedback = Feedback.find(params[:id])
end
def new
@feedback = Feedback.new
end
def edit
@feedback = Feedback.find(params[:id])
end
def create
@feedback = Feedback.new(feedback_params)
if @feedback.save
redirect_to [:cms, @feedback], notice: '创建成功!'
else
render action: 'new'
end
end
def update
@feedback = Feedback.find(params[:id])
if @feedback.update_attributes(feedback_params)
redirect_to [:cms, @feedback], notice: '更新成功!'
else
render action: 'edit'
end
end
def destroy
@feedback = Feedback.find(params[:id])
@feedback.trash
redirect_to cms_feedbacks_path, notice: '删除成功!'
end
protected
def feedback_params
params.require(:feedback).permit!
end
end
|
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.references :post_category, index: true, null:false
t.string :name, null:false
t.string :title
t.string :heading
t.text :keywords
t.text :description
t.text :content
t.timestamps
end
end
end
|
require "./lib/node.rb"
class LinkedList
attr_reader :head
def initialize
@head = nil
end
def append(data)
if @head.nil?
@head = Node.new(data)
else
current_node = @head
until current_node.next_node == nil
current_node = current_node.next_node
end
current_node.next_node = Node.new(data)
# require "pry"; binding.pry
end
data
end
def prepend(data)
old_nodes = @head
@head = Node.new(data)
@head.next_node = old_nodes
data
end
def insert(position, data)
current_node = @head
counter = 1
while counter != position
current_node = current_node.next_node
counter += 1
end
new_node = Node.new(data)
remaining_nodes = current_node.next_node
current_node.next_node = new_node
new_node.next_node = remaining_nodes
end
def count
current_node = @head
if head.nil?
counter = 0
else
counter = 1
until current_node.next_node == nil
current_node = current_node.next_node
counter += 1
end
end
counter
end
def to_string
current_node = @head
bag_of_strings = []
bag_of_strings << @head.data
until current_node.next_node.nil?
current_node = current_node.next_node
bag_of_strings << current_node.data
end
bag_of_strings.join(" ")
end
def find(position, return_amount)
current_node = @head
counter = 0
sounds = ""
until position == counter
current_node = current_node.next_node
counter += 1
end
return_amount.times do
sounds << current_node.data + " "
counter += 1
current_node = current_node.next_node
end
sounds.chop
end
def includes?(data)
current_node = @head
until current_node.next_node == nil
if current_node.data == data
return true
end
current_node = current_node.next_node
end
if current_node.data != data
return false
end
end
def pop
current_node = @head
until current_node.next_node.next_node == nil
current_node = current_node.next_node
end
node = current_node.next_node.data
current_node.next_node = nil
node
end
end
|
class Event < ActiveRecord::Base
BASE_ROLE_NAME = 'participant'
validates :name, :start_date, :end_date, :owner_id, presence: true
validates :capacity, presence: true, numericality: { only_integer: true, greater_than: 0 }
belongs_to :owner, class_name: 'User'
has_many :days
has_many :participants
has_many :services
has_many :event_prices
has_many :pricing_periods
has_many :roles
has_many :service_groups
before_create :generate_random_id
after_create :create_base_role
def to_param
unique_id
end
def registration_status
participant_count >= capacity ? 'closed' : 'open'
end
def default_role
roles.try(:find_by_name, BASE_ROLE_NAME)
end
private
def create_base_role
return if roles.find_by_name(BASE_ROLE_NAME)
roles.create!(name: BASE_ROLE_NAME)
end
def generate_random_id
begin
self.unique_id = SecureRandom.random_number(999_999_9)
end while self.class.exists?(unique_id: unique_id.to_s)
end
def participant_count
self.participants.where.not(status: 5).count
end
end
|
require "rails_helper"
describe DirectionService do
context "#direction" do
it "returns directions to the closest chipotle" do
VCR.use_cassette("directions") do
lat = 39.7511873
lng = -105.0031571
destination = PlaceService.new.get_chipotle(lat, lng, 500)
directions = DirectionService.new.get_directions(lat, lng, destination)
expect(directions.class).to eq Array
expect(directions.first.class).to eq String
expect(directions.first).to eq "Head <b>northeast</b> on <b>Wewatta St</b> toward <b>15th St</b>"
end
end
end
end
|
################################################################################
# Model Test For Album
################################################################################
require 'spec_helper'
require 'rails_helper'
describe Song, :type => :model do
include_context 'song_setup'
let(:album_search_term) {'Revolver'}
# CREATE A LIST OF Songs ------------------------------------------------
let(:find_a_song) {
create_songs
}
# SETUP FOR EACH TEST ------------------------------------------------
before(:each) {
find_a_song
}
after(:each) {
Song.destroy_all
}
## SEARCH TESTS ---------------------------------------------------
describe "Search tests" do
it "Should return Zero Album Entry" do
album_test = FactoryGirl.create(:album)
album_test.save
expect(Album.album_search(nil).count).to eq(0)
end
it "Should return a Non-Zero Album Entry" do
album_test = FactoryGirl.create(:album)
album_test.save
expect(Album.album_search(album_search_term).count).not_to eq(0)
end
end
end
|
module Jekyll
module Tags
class PermalinkTag < Liquid::Tag
def initialize(tag_name, markup, tokens)
super
@post_permalink = "#{markup.strip}/"
end
def render(context)
possible_posts = context['site']['posts'].select do |post|
post.permalink == @post_permalink
end
if possible_posts.empty?
abort "No posts with permalink '#{@post_permalink}'"
elsif possible_posts.length > 1
# You'd think Jekyll would detect conflicting permalinks, but it does
# not.
post_titles = possible_posts.map { |post| "'#{post.title}'" }.join(', ')
abort "Multiple posts with permalink '#{@post_permalink}': #{post_titles}"
end
"#{context['site']['baseurl']}/#{@post_permalink}"
end
end
end
end
Liquid::Template.register_tag('permalink', Jekyll::Tags::PermalinkTag)
|
class ContactGathering < ActiveRecord::Base
belongs_to :gathering
belongs_to :contact
end
|
class CreateItemTmplViews < ActiveRecord::Migration
def change
create_table :item_tmpl_views do |t|
t.integer :item_tmpl_id
t.string :name
t.text :tmpl
t.string :tmpl_type
t.timestamps
end
end
end
|
class CreateStudents < ActiveRecord::Migration
def change
create_table :students do |t|
t.column :student_id, :string, :primary_key => true
t.string :student_name
t.string :major
t.string :minor
t.text :other_information
t.integer :class_year_st
t.integer :hours_st
t.string :qr_st
t.timestamps
end
end
end
|
class Index::History < ApplicationRecord
belongs_to :user,
class_name: 'Index::User',
foreign_key: :user_id,
optional: true
belongs_to :product, -> { with_del },
class_name: 'Index::Product',
foreign_key: :p_id
default_scope { order('index_histories.updated_at DESC') }
# 浏览记录
# 一天新建一个浏览记录
# 同一个用户或者IP每6小时可以重新计算一次浏览记录
def self.add prod, ip, user
h = self.find_or_initialize_by(p_id: prod.id, remote_ip: ip)
if h.id
if (Time.now - h.updated_at > (Time.now - Time.now.midnight))
h = self.new(p_id: prod.id, remote_ip: ip)
end
end
prod.update readtimes: (prod.readtimes + 1)
h.product_name = prod.name
h.user = user if user
h.times += 1
h.save!
end
private
def self.create_ip_his ip, p
end
end
|
class ToolsController < ApplicationController
before_action :find_tool, only: [:show, :edit, :update]
def index
@tools = Tool.all
end
def show
# find_tool
end
def new
@users = User.all
@tool = Tool.new
end
def create
@tool = Tool.new(tool_params)
if @tool.save
redirect_to tools_path
else
@errors = @tool.errors.full_messages
render :new
end
end
def edit
@users = User.all
# find_tool
end
def update
# @tool has been set by our before action
@tool.assign_attributes(tool_params)
if @tool.save
redirect_to tool_path(@tool)
else
@errors = @tool.errors.full_messages
render :edit
end
end
private
def find_tool
@tool = Tool.find_by(id: params[:id])
end
def tool_params
params.require(:tool).permit(:name, :condition, :user_id)
end
end
|
require 'test_helper'
class ChromeLoggerTest < Minitest::Test
def test_env_name_is_configurable
assert_respond_to \
ChromeLogger,
:env_name=
end
def test_env_name_has_default
assert_equal \
ChromeLogger::DEFAULT_ENV_NAME,
ChromeLogger.env_name
end
def test_accepts_an_app_on_initialize
assert_raises ArgumentError do
ChromeLogger.new
end
app = Class.new.new
assert_equal \
app,
ChromeLogger.new( app ).app
end
end
|
class AddServicioIdToComponents < ActiveRecord::Migration[5.0]
def change
add_column :components, :servicio_id, :integer
end
end
|
#!/usr/bin/env ruby
#
# csv_to_vhdl.rb
#
# Quick script to convert Logic Analyzer output to a VHDL testbench.
# Should also support oscilloscope output in the future.
#
require 'csv'
require 'trollop'
#
# Read in options fro the command line.
#
options = Trollop::options do
version "CSV to VHDL (c) 2013 Kyle J. Temkin"
banner <<-EOS
CSV to VHDL converts logic analyzer (or oscilloscope) output into VHDL testbench waveforms.
This easily allows one to run simulations against captures of real sensor input.
Usage:
test [options] <csv_filename>
where [options] are:
EOS
opt :time_column, "The name of the column in the CSV which encodes sample times.", :default => 'Time[s]'
opt :entity, "If provided, a full VHDL template will be generated using the given entity name.", :type => :string
opt :signal_type, "For use with --entity. Specfies the data type to be used for the captured signals.", :default => 'std_ulogic'
end
time_column = options[:time_column]
#
# Parse each of the samples in the CSV.
#
samples = {}
times = []
last_sample_time = 0
least_sample_difference = Float::INFINITY
least_runtime_duration = 0
CSV.foreach(ARGV.first, :headers => true) do |row|
#Ensure that we never have an negative duration.
#This easily fixes
last_sample_time = [last_sample_time, row[time_column].to_f].min
#Determine the duration for which this sample will be presented;
sample_difference = row[time_column].to_f - last_sample_time
times << "#{sample_difference} sec"
#Keep track of the current sample time, and the least difference
#between sample times.
last_sample_time = row[time_column].to_f
least_sample_difference = [least_sample_difference, sample_difference].min if sample_difference > 0
least_runtime_duration += sample_difference
#And add each of the other samples to an appropriately named array.
row.each do |name, value|
value.strip!
#If this is our time column, replace the time with a duration.
next if name == time_column
#And append the sample to the appropriate array.
samples[name] ||= []
samples[name] << "'#{value}'"
end
end
#
# Generate the relevant code.
#
if options[:entity]
#Start the entity and architecture.
puts <<-EOS
----------------------------------------------------------------------------------
-- Testbench file: #{options[:entity]}
--
-- Generated automatically from Logic Analyzer / Oscilloscope output
-- by csv_to_vhdl; a tool by Kyle Temkin <ktemkin@binghamton.edu>.
--
-- Minimum recommended simulation duration: #{"%.3e" % least_runtime_duration} sec
-- Minimum recommended simulation precision: #{"%.3e" % least_sample_difference} sec
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
entity #{options[:entity]} is
end entity;
architecture captured_waveforms of #{options[:entity]} is
--Signals automatically generated from CSV file:
EOS
#Add each of the signals...
samples.each { |name, _| puts " signal #{name} : #{options[:signal_type]};" }
end
#Output standard types for simulation.
puts
puts " --Delays between the samples captured from the instrument."
puts " --These are used to re-create the captured waveforms."
puts " type sample_delay_times is array(natural range <>) of time;"
puts " constant duration_of_previous_sample : sample_delay_times := (#{times.join(",")});"
puts
puts " --The actual samples captured by the instrument."
puts " --These are used to re-create the captured waveforms."
puts " type std_ulogic_samples is array(natural range <>) of std_ulogic;"
#Output an array for each of the values to include.
samples.each do |name, values|
puts " constant #{name}_samples : std_ulogic_samples := (#{values.join(", ")});"
end
puts "\nbegin" if options[:entity]
#Create the stimulus process.
puts
puts
puts " --Main stimulus process. This process applies the captured waveforms."
puts " process"
puts " begin"
puts " --Loop through all of the captured samples."
puts " for i in 0 to #{times.count - 1} loop"
puts " wait for duration_of_previous_sample(i);"
samples.each { |name, _| puts " #{name} <= #{name}_samples(i);" }
puts " end loop;"
puts " end process;"
puts "\nend captured_waveforms;" if options[:entity]
|
class User < ApplicationRecord
has_many :send_messages, foreign_key: "sender_id", class_name: "Message"
has_many :receive_messages, foreign_key: "receiver_id", class_name: "Message"
def self.is_authenticated(email,password)
user = User.find_by_email(email)
if ( user.present? )
return user.password === password
else
return false;
end
end
end
|
class CreateKptEntries < ActiveRecord::Migration
def change
create_table :kpt_entries do |t|
t.integer :kpt_board_id
t.integer :user_id
t.integer :kind, :null => false, :default => 0
t.string :description, :null => false, :default => "", :limit => 150
t.datetime :created_at
end
add_index :kpt_entries, :kpt_board_id
add_index :kpt_entries, :user_id
add_index :kpt_entries, :kind
add_index :kpt_entries, :created_at
end
end
|
require_relative './11.skills'
require_relative './13.diets'
class Animal
# Con el método include podemos agregar los
# módulos como si fueran método de instancia.
# Si tenemos varios módulos dentro de un módulo
# podemos acceder a ellos con el operador de alcance '::' (scope opertor)
include Skills::Walk
attr_reader :name
def initialize(name)
@name = name
end
end
class Bird < Animal
end
class Mammal < Animal
end
class Penguin < Bird
include Skills::Swim
end
class SevenColor < Bird
include Skills::Fly
end
class Eagle < Bird
include Skills::Fly
include Diet::Carnivorous
end
class Jilguero < Bird
include Skills::Fly
include Diet::Herbivore
end |
module ReportsHelper
def list_id(list)
"list_#{list['id']}"
end
def list_member_id(list)
"listMember_#{list['id']}"
end
def report_params(additional_params = {})
new_params = {}
[:from, :to, :period, :time_group, :campaign].each do |param|
new_params[param] = params[param] if params[param]
new_params[param] = additional_params[param] if additional_params[param]
end
new_params.delete_if {|k, v| [:from, :to].include?(k) } if new_params[:period]
new_params
end
# Navigation link to a specfic report. Translate the report type a the label,
# apply any additional parameters
def report_link(report_type, additional_params = {})
link_to t("reports.name.#{report_type}", :time_period => nil).strip, report_path(resource, report_type, report_params(additional_params))
end
def video_report(name, additional_params = {})
link_to t("reports.name.video_item", :name => name), report_path(resource, "video", report_params(additional_params))
end
def add_dimension(report_type, additional_params = {})
link_to dimension_label(additional_params), report_path(resource, report_type, report_params(additional_params))
end
def report_path(resource, report_type, additional_params)
if resource.is_a?(Account)
path = send("account_report_path", report_type, additional_params)
else
path = send("#{resource.class.name.downcase}_report_path", resource, report_type, additional_params)
end
end
# Summarise an AR collection by collapsing all records that are
# less than a given percentage of the total down to an "other"
# row that is added to the collection
def collapse_data(data, label_column, value_column, options = {})
default_options = {:min_percent => 0.05}
options = default_options.merge(options)
other = 0; new_data = []
total_data = data.inject(0) {|sum, row| sum += row[value_column].to_f}
data.sort! {|a, b| a[value_column] <=> b[value_column]}.reverse!
data.each do |i|
if (i[value_column].to_f / total_data) >= options[:min_percent]
new_data << i
else
other = other + i[value_column].to_f
end
end
new_track = Track.new
new_track[label_column] = I18n.t("reports.other_#{label_column.to_s}", :default => "Other")
new_track[value_column] = other
new_data << new_track
end
def report_cache_key(prefix)
"#{prefix}/#{current_account['id']}/#{current_user['id']}/#{Trackster::Theme.current_theme}-#{I18n.locale}-#{params[:period] || 'p'}-#{params[:time_group] || 't'}"
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
def login_required
if session[:client_id]
@current_client = Client.find(session[:client_id])
Time.zone = @current_client.time_zone
return true
end
flash[:warning]='Please login to continue.'
session[:return_to] = request.path
redirect_to :controller => "client", :action => "login"
return false
end
def redirect_to_stored
if return_to = session[:return_to]
session[:return_to]=nil
redirect_to(return_to)
else
redirect_to :controller=>'client', :action=>'home'
end
end
def initialize_client_session(client_id)
session[:client_id] = client_id
session[:return_to] = nil
end
def verify_date(string)
begin
return Time.zone.parse(string) ? true : false
rescue
return false
end
end
end
|
class Role < Sequel::Model
many_to_many :users, left_key: :role_id, right_key: :user_id, join_table: :users_roles
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.