text stringlengths 10 2.61M |
|---|
module DamperRepairReport
class TabularBreakdownPage
include Report::RepairDataPageWritable
def initialize(records, damper_type, building_section, tech)
@records = records
@damper_type = damper_type
@building_section = building_section
@tech = tech
end
def write(pdf)
return if @records.empty?
super
pdf.font_size 10
pdf.text("<b>#{title}</b>", :inline_format => true)
attributes = summary_table_attributes
draw_summary_table(pdf, summary_table_data(attributes), attributes)
end
def owner
@job ||= @records.first
end
def building
@building ||= @building_section
end
def title
DamperInspectionReporting.translate(@damper_type)
end
def summary_table_attributes
attributes = []
attributes += [[:date, nil],
[:damper_number, nil],
[:floor, nil],
[:damper_location, 85],
[:status, 60],
[:corrective_action, 100]]
attributes
end
def summary_table_data(attributes)
[attributes.map do |column, _|
DamperRepairReporting.column_heading(column)
end] +
@records.map do |record|
if record.u_dr_passed_post_repair == "Pass"
@post_status = "Passed Post Repair"
else
@post_status = "Failed Post Repair"
end
if record.u_repair_action_performed == "Damper Repaired"
data = {
:date => record.u_inspected_on.localtime.strftime(I18n.t('time.formats.mdY')),
:damper_number => record.u_tag,
:floor => record.u_floor.to_i,
:damper_location => record.u_location_desc,
:status => @post_status,
:corrective_action => record.u_dr_description
}
attributes.map { |column, | data[column] }
else
data = {
:date => record.u_inspected_on.localtime.strftime(I18n.t('time.formats.mdY')),
:damper_number => record.u_tag,
:floor => record.u_floor.to_i,
:damper_location => record.u_location_desc,
:status => @post_status,
:corrective_action => record.u_repair_action_performed
}
attributes.map { |column, | data[column] }
end
end
end
def draw_summary_table(pdf, data, attributes)
pdf.table(data, :header => true, :cell_style => { :size => 8, :padding => 4, :align => :center }) do |table|
last = table.row_length - 1
table.row_colors = %w(ffffff eaeaea)
table.row(0).style :border_color => '888888',
:background_color => '444444',
:text_color => 'ffffff'
table.rows(1..last).style :border_color => 'cccccc'
attributes.each_with_index do |pair, index|
table.column(index).style :width => pair.last unless pair.last.nil?
end
result_index = attributes.find_index do |pair|
pair.first == :inspection_result
end
result_index && table.column(result_index).rows(1..last).each do |cell|
cell.text_color = case cell.content
when DamperInspectionReporting.translate(:fail)
'c1171d'
when DamperInspectionReporting.translate(:na)
'f39d27'
else
'202020'
end
end
end
end
end
end |
class AddUserRefToPost < ActiveRecord::Migration[5.0]
def change
add_column :posts, :user, :refernces
end
end
|
class ArrowFiredNotifier < Struct.new(:from_user_id,:to_user_id)
def perform
from_user = User.find(from_user_id)
to_user = User.find(to_user_id)
Notifications::arrow_fired(from_user,to_user).deliver
end
end
|
class ShiftListsController < ApplicationController
before_action :set_q2, only: [:index, :search]
def index
@staff = Staff.where(user_id: current_user.id)
end
def search
@results = @q.result.where(user_id: current_user.id)
end
private
def set_q2
@q = Shift.ransack(params[:q])
end
end
|
require 'rails_helper'
RSpec.describe ChildrenController, type: :controller do
describe "children#new action" do
before :each do
@user = FactoryGirl.create(:user)
@school = FactoryGirl.create(:school)
@family = FactoryGirl.create(:family)
end
it "should successfully show the new form" do
sign_in @user
get :new, school_id: @school, family_id: @family
expect(response).to have_http_status(:success)
end
it "should require users to be logged in" do
get :new, school_id: @school, family_id: @family
expect(response).to redirect_to new_user_session_path
end
end
describe "children#create action" do
before :each do
@user = FactoryGirl.create(:user)
@school = FactoryGirl.create(:school)
@family = FactoryGirl.create(:family)
@child = FactoryGirl.attributes_for(:child)
end
it "should successfully create a child in our database" do
sign_in @user
qty_children = @family.children.count
expect{post :create, child: @child, school_id: @school, family_id: @family}.to change(Child ,:count).by(1)
expect(response).to redirect_to school_family_path(@school, @family)
expect(@family.children.count).to eq(qty_children + 1)
end
it "should require users to be logged in" do
post :create, child: @child, school_id: @school, family_id: @family
expect(response).to redirect_to new_user_session_path
end
end
describe "children#edit action" do
before :each do
@user = FactoryGirl.create(:user)
@school = FactoryGirl.create(:school)
@family = FactoryGirl.create(:family)
@child = FactoryGirl.create(:child)
end
it "should successfully show the edit form if the child is found" do
sign_in @user
get :edit, id: @child, school_id: @school, family_id: @family
expect(response).to have_http_status(:success)
end
it "should return a 404 error message if the child is not found" do
sign_in @user
get :edit, id: 'BLABLABLA', school_id: @school, family_id: @family
expect(response).to have_http_status(:not_found)
end
it "should require users to be logged in" do
get :edit, id: @child, school_id: @school, family_id: @family
expect(response).to redirect_to new_user_session_path
end
end
describe "children#update action" do
before :each do
@user = FactoryGirl.create(:user)
@school = FactoryGirl.create(:school)
@family = FactoryGirl.create(:family)
@child = FactoryGirl.create(:child)
end
it "should allow users to successfully update a child" do
sign_in @user
patch :update, id: @child, child: FactoryGirl.attributes_for(:child, nombre: "Daniel", tipo_servicio: Child::GRADOS['6to Grado']), school_id: @school, family_id: @family
expect(response).to redirect_to school_family_path(@school, @family)
@child.reload
expect(@child.nombre).to eq "Daniel"
expect(@child.tipo_servicio).to eq Child::GRADOS['6to Grado']
end
it "should have HTTP 404 error message if the child cannot be found" do
sign_in @user
patch :update, id: 'BLABLABLA', child: FactoryGirl.attributes_for(:child, nombre: "Daniel", tipo_servicio: Child::GRADOS['6to Grado']), school_id: @school, family_id: @family
expect(response).to have_http_status(:not_found)
end
it "should render the edit form with an http status of unprocessable_entity" do
sign_in @user
old_name = @child[:nombre]
patch :update, id: @child, child: FactoryGirl.attributes_for(:child, nombre: ""), school_id: @school, family_id: @family
expect(response).to have_http_status(:unprocessable_entity)
@child.reload
expect(@child.nombre).to eq old_name
end
it "should require users to be logged in" do
patch :update, id: @child, child: FactoryGirl.attributes_for(:child, nombre: "Daniel", tipo_servicio: Child::GRADOS['6to Grado']), school_id: @school, family_id: @family
expect(response).to redirect_to new_user_session_path
end
end
describe "children#destroy action" do
before :each do
@user = FactoryGirl.create(:user)
@school = FactoryGirl.create(:school)
@family = FactoryGirl.create(:family)
@child = FactoryGirl.create(:child)
end
it "should successfully delete a child if found" do
sign_in @user
expect{delete :destroy, id: @child, school_id: @school, family_id: @family}.to change(Child, :count).by(-1)
expect(response).to redirect_to school_family_path(@school, @family)
ch = Child.find_by_id(@child)
expect(ch).to eq nil
end
it "should return a 404 error message if the child is not found" do
sign_in @user
expect{delete :destroy, id: 'BLABLABLA', school_id: @school, family_id: @family}.not_to change(Child, :count)
expect(response).to have_http_status(:not_found)
end
it "should require users to be logged in" do
post :destroy, id: @child, school_id: @school, family_id: @family
expect(response).to redirect_to new_user_session_path
end
end
end |
#!/usr/bin/env ruby
# encoding: utf-8
require "bunny"
require_relative "../config/rabbitmq"
conn = Bunny.new(Config::RabbitMQ::CONF)
conn.start
ch = conn.create_channel
class FibonacciServer
def initialize(ch)
@ch = ch
end
def start(queue_name)
@q = @ch.queue(queue_name)
@x = @ch.default_exchange
@q.subscribe(block: true) do |delivery_info, properties, payload|
n = payload.to_i
r = self.class.fib(n)
@x.publish(r.to_s,
routing_key: properties.reply_to,
correlation_id: properties.correlation_id)
end
end
def self.fib(n)
case n
when 0 then 0
when 1 then 1
else
fib(n - 1) + fib(n - 2)
end
end
end
begin
server = FibonacciServer.new(ch)
puts " [x] Awaiting RPC requests"
server.start("rpc_queue")
rescue Interrupt => _
ch.close
conn.close
end
|
class ApplicantsController < ApplicationController
before_action :require_login, only: [:edit, :background_check, :background_check_confirm]
before_action :require_background_check_confirmed, only: [:background_check, :background_check_confirm]
def new
@applicant = Applicant.new
end
def create
@applicant = Applicant.new(applicant_params)
@applicant.set_init_info
if @applicant.save
log_in @applicant
flash[:notice] = "#{@applicant.first_name}, application submitted successfully."
redirect_to background_check_info_path
else
render 'new'
end
end
def edit
@applicant = current_applicant
end
def update
@applicant = current_applicant
if @applicant.update_attributes(applicant_params)
flash[:notice] = "Profile updated"
redirect_to root_path
else
render 'edit'
end
end
def background_check_info
end
def background_check_confirm
current_applicant.confirm_backgraound_check
if current_applicant.save
redirect_to background_check_finish_path
else
flash[:notice] = "Confirm failed."
redirect_to background_check_info_path
end
end
def background_check_finish
end
private
def applicant_params
params.require(:applicant).permit(:first_name, :last_name, :email,
:phone, :phone_type, :region)
end
def require_background_check_confirmed
if current_applicant.background_check
redirect_to background_check_finish_path
end
end
end
|
require "net/http"
require "json"
require "pry"
require "dotenv"
class OnConnect
def initialize(zip_code, date = Date.today)
@zip_code = zip_code
@date = date
@data = api_call(@zip_code, @date)
end
def showtimes
all_movies = []
@data.each do |movie|
movie_info = movie['title']
movie['showtimes'].each do |showtime|
show_info = "#{movie_info} @ #{showtime['theatre']['name']} "
time_string = Time.parse(showtime['dateTime']).to_s
time_parse = time_string.match(/(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})/)
show_info += "#{time_parse}"
all_movies << show_info
end
end
all_movies
end
private
def api_call(zip_code, date)
key = ENV['ONCONNECT_API_KEY']
uri = URI("http://data.tmsapi.com/v1.1/movies/showings?startDate=#{date}&zip=#{zip_code}&api_key=#{key}")
response = Net::HTTP.get_response(uri)
JSON.parse(response.body)
end
end
|
FactoryBot.define do
factory :user, aliases: [:owner] do
provider { 'github' }
sequence(:uid) { |i| i }
sequence(:name) { |i| "ユーザー#{format('%03d', i)}" }
sequence(:image_url) { |i| "http://example.com/image_#{i}.jpg" }
end
end
|
class CreateBuchungOnline < ActiveRecord::Migration
def self.up
create_table(:BuchungOnline, :primary_key => :id) do |t|
#ID PS
t.integer :id, :uniqueness => true, :limit => 10, :null => false
#Mnr FS
t.integer :mnr, :uniqueness => true, :limit => 10, :null => false
#Überweisungsdatum
t.date :ueberwdatum, :null => false
#Soll Kontonummer
t.integer :sollktonr, :limit => 5, :default => 0, :null => false
#Haben Kontonummer
t.integer :habenktonr, :limit => 5, :default => 0, :null => false
#Punkte
t.integer :punkte, :null => false, :limit => 10
#Tan
t.integer :tan, :null => false, :limit => 5
#BlockNr
t.integer :blocknr, :null => false, :limit => 2
end
end
def self.down
drop_table :BuchungOnline
end
end
|
require "./lib/victory_checker"
describe 'VictoryChecker' do
let(:victory_checker) { VictoryChecker.new }
let(:board) { Board.new }
context "Computer player makes winning move" do
it "should determine that the Computer Player has won" do
board.grid = {1 => 'O', 2 => 'O', 3 => 'X',
4 => ' ', 5 => 'X', 6 => ' ',
7 => 'X', 8 => ' ', 9 => ' '}
winner = victory_checker.victory_or_continue_play(board)
winner.should == "X"
end
it "should determine that the Computer Player has won" do
board.grid = {1 => 'O', 2 => 'O', 3 => 'X',
4 => ' ', 5 => ' ', 6 => 'X',
7 => ' ', 8 => ' ', 9 => 'X'}
winner = victory_checker.victory_or_continue_play(board)
winner.should == "X"
end
it "should determine that the Computer Player has won" do
board.grid = {1 => 'O', 2 => 'O', 3 => ' ',
4 => ' ', 5 => ' ', 6 => ' ',
7 => 'X', 8 => 'X', 9 => 'X'}
winner = victory_checker.victory_or_continue_play(board)
winner.should == "X"
end
end
context "Human Player makes winning move" do
it "should determine that the Human Player has won" do
board.grid = {1 => 'O', 2 => ' ', 3 => 'X',
4 => 'O', 5 => 'X', 6 => ' ',
7 => 'O', 8 => ' ', 9 => ' '}
winner = victory_checker.victory_or_continue_play(board)
winner.should == "O"
end
it "should determine that the Human Player has won" do
board.grid = {1 => 'X', 2 => ' ', 3 => 'O',
4 => 'X', 5 => 'O', 6 => ' ',
7 => 'O', 8 => ' ', 9 => ' '}
winner = victory_checker.victory_or_continue_play(board)
winner.should == "O"
end
it "should determine that the Human Player has won" do
board.grid = {1 => 'X', 2 => ' ', 3 => ' ',
4 => 'X', 5 => 'X', 6 => ' ',
7 => 'O', 8 => 'O', 9 => 'O'}
winner = victory_checker.victory_or_continue_play(board)
winner.should == "O"
end
end
context "When there is a stalemate" do
it "should determine the game is a draw" do
board.grid = {1 => 'X', 2 => 'X', 3 => 'O',
4 => 'O', 5 => 'O', 6 => 'X',
7 => 'X', 8 => 'X', 9 => 'O'}
result = victory_checker.victory_or_continue_play(board)
result.should == "It's a Draw!!!"
end
end
context "When there is no win and play can continue" do
it "should determine the game is a draw" do
board.grid = {1 => 'X', 2 => 'X', 3 => 'O',
4 => 'O', 5 => 'O', 6 => 'X',
7 => 'X', 8 => ' ', 9 => ' '}
result = victory_checker.victory_or_continue_play(board)
result.should == "continue play"
end
end
end |
RSpec.describe Zenform::FileCache do
let(:project_path) { File.expand_path "../fixtures/", File.dirname(__FILE__) }
let(:cache_path) { File.expand_path file_name, project_path }
let(:file_name) { Zenform::FileCache::FILENAME % { content_name: content_name } }
let(:content_name) { "test" }
after do
File.delete cache_path if File.exists? cache_path
end
describe ".read" do
subject { Zenform::FileCache.read project_path, content_name }
context "no cache file" do
it { is_expected.to be_nil }
end
context "cache file" do
let(:data) { { "timestamp" => Time.now.to_i, "ticket_fields" => [] } }
before do
File.open(cache_path, "w") { |f| f.puts data.to_json }
end
it { is_expected.to eq data }
end
end
describe ".write" do
subject { Zenform::FileCache.write project_path, content_name, data }
let(:data) { { "timestamp" => Time.now.to_i, "ticket_fields" => [] } }
it "makes file" do
expect { subject }.to change { File.exists? cache_path }.to(true)
end
it "write json data" do
subject
expect(Zenform::FileCache.read(project_path, content_name)).to eq data
end
end
end
|
class Cohort < ApplicationRecord
# belongs_to :lead, class_name: "User"
has_many :students, foreign_key: "cohort_id", class_name: "User"
has_many :projects, through: :students
end
|
class CatRentalRequest < ActiveRecord::Base
validates :status, inclusion: { in: %w(PENDING APPROVED DENIED),
message: "%{ value } is not a valid status"}
# validate :overlapping_approved_requests
belongs_to :cat
def overlapping_approved_requests
binds = { start_date: self.start_date, end_date: self.end_date }
results = CatRentalRequest.find_by_sql([<<-SQL, binds])
SELECT
id
FROM
cat_rental_requests
WHERE
start_date BETWEEN :start_date AND :end_date OR end_date BETWEEN :start_date AND :end_date AND status = 'APPROVED'
SQL
unless results.empty?
errors[:start_date] << "is in between a approved date"
end
end
def overlapping_pending_requests
binds = { start_date: self.start_date, end_date: self.end_date }
results = CatRentalRequest.find_by_sql([<<-SQL, binds])
SELECT
id
FROM
cat_rental_requests
WHERE
start_date BETWEEN :start_date AND :end_date OR end_date BETWEEN :start_date and :end_date AND status = 'PENDING'
SQL
end
def approve!
self.transaction do
self.status = "APPROVED"
self.save
overlapping_pending_requests.each do |request|
request.deny! unless self.id == request.id
end
end
end
def deny!
self.status = "DENIED"
self.save
end
def pending?
self.status == "PENDING"
end
# def overlapping_approved_requests
# overlapping_requests.where(status: "approved")
# unless overlapping_requests.empty?
# errors[:start_date] << "is in between a approved date"
# end
# end
end
|
require ('Message')
require ('pry')
require ('rspec')
describe('#Message') do
before(:each) do
Board.clear()
Message.clear()
@board = Board.new({:name => "music", :id => nil})
@board.save()
end
describe('.clear') do
it('clears all messages') do
message = Message.new({:text => "music", :board_id => @board.id, :id => nil})
message.save()
message2 = Message.new({:text => "music", :board_id => @board.id, :id => nil})
message2.save()
Message.clear()
expect(Message.all).to(eq([]))
end
end
describe('#==') do
it("is the same message if it has the same attributes as another message") do
message = Message.new({:text => "music", :board_id => @board.id, :id => nil})
message1 = Message.new({:text => "music", :board_id => @board.id, :id => nil})
expect(message).to(eq(message1))
end
end
end |
a = "bob"
case a
when /b$/
puts "it ends with b"
when /^b/
puts "it starts with b"
when "bob"
puts "its the word bob"
else
puts "it doesnt match any of these terms"
end
|
require 'spec_helper'
describe ProjectsController do
before do
@user = mock_current_user
controller.stub(:current_user).and_return(@user)
end
describe '#index' do
it "lists user's projects" do
@user.should_receive(:projects).and_return([mock_model(Project)])
get :index
response.should be_success
end
end
describe '#show' do
it "renders" do
@user.stub_chain(:projects, :find).and_return(mock_model(Project))
get :show
response.should be_success
end
end
describe '#new' do
it "renders" do
get :new
response.should be_success
end
end
describe '#create' do
it "creates a project and redirects" do
mock_project = mock_model(Project)
mock_project.should_receive(:save).and_return(true)
@user.stub_chain(:projects, :build).and_return(mock_project)
post :create, :project => {
:name => '100 test cake',
:description => 'Wheres my cake',
:start => '0',
:target => '100'
}
response.should redirect_to(projects_path)
end
end
describe '#edit' do
it "renders" do
@user.stub_chain(:projects, :find).and_return(mock_model(Project))
get :edit, :id => '1'
response.should be_success
end
end
describe '#update' do
it "updates a project and redirects" do
mock_project = mock_model(Project)
mock_project.should_receive(:update_attributes).and_return(true)
@user.stub_chain(:projects, :find).and_return(mock_project)
put :update, :id => '1', :project => {
:name => '100 test cake',
:description => 'Wheres my cake',
:start => '0',
:target => '100'
}
response.should redirect_to(projects_path)
end
end
end
|
class ProjectComment < ApplicationRecord
belongs_to :user
belongs_to :project
has_paper_trail
validates :content, presence: true
end
|
# frozen_string_literal: true
require "renalware"
require "dotenv-rails"
module Renalware
module Diaverum
def self.table_name_prefix
"renalware_diaverum."
end
class Engine < ::Rails::Engine
isolate_namespace Renalware::Diaverum
initializer :append_migrations do |app|
# Prevent duplicate migrations if we are db:migrating at the engine level (eg when
# running tests) rather than the host app
running_in_dummy_app = Dir.pwd.ends_with?("dummy")
running_outside_of_engine = app.root.to_s.match(root.to_s + File::SEPARATOR).nil?
if running_in_dummy_app || running_outside_of_engine
engine_migration_paths = config.paths["db/migrate"]
app_migration_paths = app.config.paths["db/migrate"]
engine_migration_paths.expanded.each do |expanded_path|
app_migration_paths << expanded_path
end
end
end
end
end
end
|
RSpec.describe Overrider do
RSpec::Matchers.define :ensure_trace_point_disable do
match do |klass|
klass.instance_variable_get("@__overrider_trace_point").nil? &&
klass.instance_variable_get("@__overrider_singleton_trace_point").nil?
end
failure_message do
"trace_point cleared"
end
failure_message_when_negated do
"trace_point remained"
end
end
context "Unless `override` method has super method" do
it "does not raise", aggregate_failures: true do
class A1
def foo
end
end
class A2 < A1
extend Overrider
override def foo
end
end
expect {
c = Class.new(A1) do
extend Overrider
override def foo
end
end
expect(c).to ensure_trace_point_disable
}.not_to raise_error
end
end
context "Unless `override` method has no super method" do
it "raise Overrider::NoSuperMethodError", aggregate_failures: true do
ex = nil
begin
class B1
end
class B2 < B1
extend Overrider
override def foo
end
end
rescue Overrider::NoSuperMethodError => e
ex = e
end
expect(B2).to ensure_trace_point_disable
expect(ex).to be_a(Overrider::NoSuperMethodError)
expect(ex.override_class).to eq(B2)
expect(ex.unbound_method.name).to eq(:foo)
begin
c = Class.new do
extend Overrider
override def bar
end
end
expect(c).to ensure_trace_point_disable
rescue Overrider::NoSuperMethodError => e
ex = e
end
expect(ex).to be_a(Overrider::NoSuperMethodError)
expect(ex.override_class).to be_a(Class)
expect(ex.unbound_method.name).to eq(:bar)
end
end
context "Unless `override` method has no super method but include after" do
it "does not raise" do
expect {
module C1
def foo
end
def bar
end
end
class C2
extend Overrider
override def foo
end
include C1
end
Class.new do
extend Overrider
override def foo
end
pr = proc {}
pr.call
include C1
end
ex = nil
begin
class C3
extend Overrider
override def foo
end
raise "err"
include C1
end
rescue RuntimeError => e
ex = e
end
expect(ex).to be_a(RuntimeError)
}.not_to raise_error
end
end
context "Unless `override` singleton method has no super method but extend after" do
it "raise NoSuperMethodError", aggregate_failures: true do
ex = nil
begin
class D1
end
class D2 < D1
extend Overrider
class << self
def foo
end
end
override_singleton_method :foo
end
rescue Overrider::NoSuperMethodError => e
ex = e
end
expect(D2).to ensure_trace_point_disable
expect(ex).to be_a(Overrider::NoSuperMethodError)
expect(ex.override_class).to eq(D2)
expect(ex.unbound_method.name).to eq(:foo)
begin
c = Class.new do
extend Overrider
class << self
def bar
end
end
override_singleton_method :bar
end
expect(c).to ensure_trace_point_disable
rescue Overrider::NoSuperMethodError => e
ex = e
end
expect(ex).to be_a(Overrider::NoSuperMethodError)
expect(ex.override_class).to be_a(Class)
expect(ex.unbound_method.name).to eq(:bar)
class D2_1
def self.foo
end
end
class D2_2 < D2_1
extend Overrider
class << self
def foo
end
end
override_singleton_method :foo
end
expect(D2_2).to ensure_trace_point_disable
end
end
context "`override` singleton method has no super method but extend after" do
it do
expect {
module E1
def foo
end
def bar
end
end
class E2
extend Overrider
class << self
def foo
end
def bar
end
end
override_singleton_method :foo
override_singleton_method :bar
extend E1
end
expect(E2).to ensure_trace_point_disable
Class.new do
extend Overrider
class << self
def foo
end
end
override_singleton_method :foo
pr = proc {}
pr.call
extend E1
end
}.not_to raise_error
end
end
context "`override` singleton_method has super method" do
it "does not raise" do
expect {
class F1
class << self
def foo
end
end
end
class F2 < F1
extend Overrider
override_singleton_method def self.foo
end
end
expect(F2).to ensure_trace_point_disable
}.not_to raise_error
end
end
it "can support `class << self` and `override`. but singleton_class requires `extend` Overrider" do
expect {
class G1
class << self
def foo
end
end
end
class G2 < G1
class << self
extend Overrider
override def foo
end
end
end
}.not_to raise_error
end
it "cannot support `class << self` and `override` and after extend module" do
ex = nil
begin
module H1
def foo
end
end
class H2
class << self
extend Overrider
override def foo
end
end
extend H1
end
rescue Overrider::NoSuperMethodError => e
ex = e
end
expect(ex).to be_a(Overrider::NoSuperMethodError)
end
it "can support `class << self` and `override` and before extend module" do
expect {
module I1
def foo
end
end
class I2
extend I1
class << self
extend Overrider
override def foo
end
end
end
}.not_to raise_error
end
it "cannot support `override` and open class at other place" do
ex = nil
begin
module J1
def foo
end
end
class J2
extend Overrider
override def foo
end
end
class J2
include J1
end
rescue Overrider::NoSuperMethodError => e
ex = e
end
expect(ex).to be_a(Overrider::NoSuperMethodError)
end
context "Overrider.disable = true" do
around do |ex|
Overrider.disable = true
ex.call
Overrider.disable = false
end
it "does not raise" do
expect {
class K1
end
class K2 < K1
extend Overrider
override def foo
end
end
}.not_to raise_error
end
end
it "supports to call `override` outer class definition" do
class L1
def bar
end
end
class L2 < L1
extend Overrider
def foo
end
end
ex = nil
begin
L2.send(:override, :foo)
rescue Overrider::NoSuperMethodError => e
ex = e
end
expect(ex).to be_a(Overrider::NoSuperMethodError)
class L3 < L1
extend Overrider
def bar
end
end
L3.send(:override, :bar)
end
it "supports to call `override_singleton_method` outer class definition" do
class M1
def self.bar
end
end
class M2 < M1
extend Overrider
def self.foo
end
end
ex = nil
begin
M2.send(:override_singleton_method, :foo)
rescue Overrider::NoSuperMethodError => e
ex = e
end
expect(ex).to be_a(Overrider::NoSuperMethodError)
class M3 < M1
extend Overrider
def self.bar
end
end
M3.send(:override_singleton_method, :bar)
end
end
|
# frozen_string_literal: true
# rubocop:todo all
require 'spec_helper'
describe Mongo::Error::Parser do
let(:parser) do
described_class.new(document)
end
describe '#message' do
context 'when the document contains no error message' do
let(:document) do
{ 'ok' => 1 }
end
it 'returns an empty string' do
expect(parser.message).to be_empty
end
end
context 'when the document contains an errmsg' do
let(:document) do
{ 'errmsg' => 'no such command: notacommand', 'code' => 59 }
end
it 'returns the message' do
expect(parser.message).to eq('[59]: no such command: notacommand')
end
end
context 'when the document contains an errmsg and code name' do
let(:document) do
{ 'errmsg' => 'no such command: notacommand', 'code' => 59, 'codeName' => 'foo' }
end
it 'returns the message' do
expect(parser.message).to eq('[59:foo]: no such command: notacommand')
end
end
=begin
context 'when the document contains writeErrors' do
context 'when only a single error exists' do
let(:document) do
{ 'writeErrors' => [{ 'code' => 9, 'errmsg' => 'Unknown modifier: $st' }]}
end
it 'returns the message' do
expect(parser.message).to eq('[9]: Unknown modifier: $st')
end
end
context 'when multiple errors exist' do
let(:document) do
{
'writeErrors' => [
{ 'code' => 9, 'errmsg' => 'Unknown modifier: $st' },
{ 'code' => 9, 'errmsg' => 'Unknown modifier: $bl' }
]
}
end
it 'returns the messages concatenated' do
expect(parser.message).to eq(
'Multiple errors: 9: Unknown modifier: $st; 9: Unknown modifier: $bl'
)
end
end
context 'when multiple errors with code names exist' do
let(:document) do
{
'writeErrors' => [
{ 'code' => 9, 'codeName' => 'foo', 'errmsg' => 'Unknown modifier: $st' },
{ 'code' => 9, 'codeName' => 'foo', 'errmsg' => 'Unknown modifier: $bl' },
]
}
end
it 'returns the messages concatenated' do
expect(parser.message).to eq(
'Multiple errors: [9:foo]: Unknown modifier: $st; [9:foo]: Unknown modifier: $bl'
)
end
end
end
=end
context 'when the document contains $err' do
let(:document) do
{ '$err' => 'not authorized for query', 'code' => 13 }
end
it 'returns the message' do
expect(parser.message).to eq('[13]: not authorized for query')
end
end
context 'when the document contains err' do
let(:document) do
{ 'err' => 'not authorized for query', 'code' => 13 }
end
it 'returns the message' do
expect(parser.message).to eq('[13]: not authorized for query')
end
end
context 'when the document contains a writeConcernError' do
let(:document) do
{ 'writeConcernError' => { 'code' => 100, 'errmsg' => 'Not enough data-bearing nodes' } }
end
it 'returns the message' do
expect(parser.message).to eq('[100]: Not enough data-bearing nodes')
end
end
end
describe '#code' do
context 'when document contains code and ok: 1' do
let(:document) do
{ 'ok' => 1, 'errmsg' => 'not master', 'code' => 10107, 'codeName' => 'NotMaster' }
end
it 'returns nil' do
expect(parser.code).to be nil
end
end
context 'when document contains code and ok: 1.0' do
let(:document) do
{ 'ok' => 1.0, 'errmsg' => 'not master', 'code' => 10107, 'codeName' => 'NotMaster' }
end
it 'returns nil' do
expect(parser.code).to be nil
end
end
context 'when document contains code' do
let(:document) do
{ 'ok' => 0, 'errmsg' => 'not master', 'code' => 10107, 'codeName' => 'NotMaster' }
end
it 'returns the code' do
expect(parser.code).to eq(10107)
end
context 'with legacy option' do
let(:parser) do
described_class.new(document, nil, legacy: true)
end
it 'returns nil' do
expect(parser.code).to be nil
end
end
end
context 'when document does not contain code' do
let(:document) do
{ 'ok' => 0, 'errmsg' => 'not master' }
end
it 'returns nil' do
expect(parser.code).to eq(nil)
end
end
context 'when the document contains a writeConcernError with a code' do
let(:document) do
{ 'writeConcernError' => { 'code' => 100, 'errmsg' => 'Not enough data-bearing nodes' } }
end
it 'returns the code' do
expect(parser.code).to eq(100)
end
end
context 'when the document contains a writeConcernError without a code' do
let(:document) do
{ 'writeConcernError' => { 'errmsg' => 'Not enough data-bearing nodes' } }
end
it 'returns nil' do
expect(parser.code).to be nil
end
end
context 'when both top level code and write concern code are present' do
let(:document) do
{ 'ok' => 0,
'errmsg' => 'not master', 'code' => 10107, 'codeName' => 'NotMaster',
'writeConcernError' => {
'code' => 100, 'errmsg' => 'Not enough data-bearing nodes' } }
end
it 'returns top level code' do
expect(parser.code).to eq(10107)
end
end
end
describe '#code_name' do
context 'when document contains code name and ok: 1' do
let(:document) do
{ 'ok' => 1, 'errmsg' => 'not master', 'code' => 10107, 'codeName' => 'NotMaster' }
end
it 'returns nil' do
expect(parser.code_name).to be nil
end
end
context 'when document contains code name and ok: 1.0' do
let(:document) do
{ 'ok' => 1.0, 'errmsg' => 'not master', 'code' => 10107, 'codeName' => 'NotMaster' }
end
it 'returns nil' do
expect(parser.code_name).to be nil
end
end
context 'when document contains code name' do
let(:document) do
{ 'ok' => 0, 'errmsg' => 'not master', 'code' => 10107, 'codeName' => 'NotMaster' }
end
it 'returns the code name' do
expect(parser.code_name).to eq('NotMaster')
end
context 'with legacy option' do
let(:parser) do
described_class.new(document, nil, legacy: true)
end
it 'returns nil' do
expect(parser.code_name).to be nil
end
end
end
context 'when document does not contain code name' do
let(:document) do
{ 'ok' => 0, 'errmsg' => 'not master' }
end
it 'returns nil' do
expect(parser.code_name).to eq(nil)
end
end
context 'when the document contains a writeConcernError with a code' do
let(:document) do
{ 'writeConcernError' => { 'code' => 100, 'codeName' => 'CannotSatisfyWriteConcern',
'errmsg' => 'Not enough data-bearing nodes' } }
end
it 'returns the code name' do
expect(parser.code_name).to eq('CannotSatisfyWriteConcern')
end
end
context 'when the document contains a writeConcernError without a code' do
let(:document) do
{ 'writeConcernError' => { 'code' => 100, 'errmsg' => 'Not enough data-bearing nodes' } }
end
it 'returns nil' do
expect(parser.code_name).to be nil
end
end
context 'when both top level code and write concern code are present' do
let(:document) do
{ 'ok' => 0,
'errmsg' => 'not master', 'code' => 10107, 'codeName' => 'NotMaster',
'writeConcernError' => {
'code' => 100, 'errmsg' => 'Not enough data-bearing nodes' } }
end
it 'returns top level code' do
expect(parser.code_name).to eq('NotMaster')
end
end
end
describe '#write_concern_error?' do
context 'there is a write concern error' do
let(:document) do
{ 'ok' => 1,
'writeConcernError' => {
'code' => 100, 'errmsg' => 'Not enough data-bearing nodes' } }
end
it 'is true' do
expect(parser.write_concern_error?).to be true
end
end
context 'there is no write concern error' do
let(:document) do
{ 'ok' => 0,
'errmsg' => 'not master', 'code' => 10107, 'codeName' => 'NotMaster',
}
end
it 'is false' do
expect(parser.write_concern_error?).to be false
end
end
context 'there is a top level error and write concern error' do
let(:document) do
{ 'ok' => 0,
'errmsg' => 'not master', 'code' => 10107, 'codeName' => 'NotMaster',
'writeConcernError' => {
'code' => 100, 'errmsg' => 'Not enough data-bearing nodes' } }
end
it 'is true' do
expect(parser.write_concern_error?).to be true
end
end
end
describe '#write_concern_error_code' do
context 'there is a write concern error' do
let(:document) do
{ 'ok' => 1,
'writeConcernError' => {
'code' => 100, 'errmsg' => 'Not enough data-bearing nodes' } }
end
it 'is true' do
expect(parser.write_concern_error_code).to eq(100)
end
end
context 'there is no write concern error' do
let(:document) do
{ 'ok' => 0,
'errmsg' => 'not master', 'code' => 10107, 'codeName' => 'NotMaster',
}
end
it 'is nil' do
expect(parser.write_concern_error_code).to be nil
end
end
context 'there is a top level error and write concern error' do
let(:document) do
{ 'ok' => 0,
'errmsg' => 'not master', 'code' => 10107, 'codeName' => 'NotMaster',
'writeConcernError' => {
'code' => 100, 'errmsg' => 'Not enough data-bearing nodes' } }
end
it 'is true' do
expect(parser.write_concern_error_code).to eq(100)
end
end
end
describe '#write_concern_error_code_name' do
context 'there is a write concern error' do
let(:document) do
{ 'ok' => 1,
'writeConcernError' => {
'code' => 100, 'codeName' => 'SomeCodeName',
'errmsg' => 'Not enough data-bearing nodes' } }
end
it 'is the code name' do
expect(parser.write_concern_error_code_name).to eq('SomeCodeName')
end
end
context 'there is no write concern error' do
let(:document) do
{ 'ok' => 0,
'errmsg' => 'not master', 'code' => 10107, 'codeName' => 'NotMaster',
}
end
it 'is nil' do
expect(parser.write_concern_error_code_name).to be nil
end
end
context 'there is a top level error and write concern error' do
let(:document) do
{ 'ok' => 0,
'errmsg' => 'not master', 'code' => 10107, 'codeName' => 'NotMaster',
'writeConcernError' => {
'code' => 100, 'codeName' => 'SomeCodeName',
'errmsg' => 'Not enough data-bearing nodes' } }
end
it 'is the code name' do
expect(parser.write_concern_error_code_name).to eq('SomeCodeName')
end
end
end
describe '#document' do
let(:document) do
{ 'ok' => 0, 'errmsg' => 'not master', 'code' => 10107, 'codeName' => 'NotMaster' }
end
it 'returns the document' do
expect(parser.document).to eq(document)
end
end
describe '#replies' do
context 'when there are no replies' do
let(:document) do
{ 'ok' => 0, 'errmsg' => 'not master', 'code' => 10107, 'codeName' => 'NotMaster' }
end
it 'returns nil' do
expect(parser.replies).to eq(nil)
end
end
end
describe '#labels' do
let(:document) do
{
'code' => 251,
'codeName' => 'NoSuchTransaction',
'errorLabels' => labels,
}
end
context 'when there are no labels' do
let(:labels) do
[]
end
it 'has the correct labels' do
expect(parser.labels).to eq(labels)
end
end
context 'when there are labels' do
let(:labels) do
%w(TransientTransactionError)
end
it 'has the correct labels' do
expect(parser.labels).to eq(labels)
end
end
end
describe '#wtimeout' do
context 'when document contains wtimeout' do
let(:document) do
{ 'ok' => 1, 'writeConcernError' => {
'errmsg' => 'replication timed out', 'code' => 64,
'errInfo' => {'wtimeout' => true}} }
end
it 'returns true' do
expect(parser.wtimeout).to be true
end
end
context 'when document does not contain wtimeout' do
let(:document) do
{ 'ok' => 1, 'writeConcernError' => {
'errmsg' => 'replication did not time out', 'code' => 55 }}
end
it 'returns nil' do
expect(parser.wtimeout).to be nil
end
end
end
end
|
class AddToAuthentications < ActiveRecord::Migration[5.0]
def change
add_column :authentications, :lti_user_id, :string
add_index :authentications, :lti_user_id
end
end
|
class PdfsController < ApplicationController
def show
@pdf = Pdf.find_by_slug(params[:id]);
redirect_to @pdf.file.url
end
end
|
class Lead < ApplicationRecord
belongs_to :user, optional: true
validates :name, presence: true
validates :email, presence: true, format: { with: /\A.*@.*\.\S*\z/ }
validates :user, presence: true
validates :phone, presence: true
validates :source, presence: true
validates :html, presence: true
validates :status, inclusion: { in: ["pending","accepted","settled","lost"], allow_nil: false }
def self.to_csv
attributes = %w{name email received_at accepted_at user status source response_time created_at updated_at phone }
CSV.generate(headers: true) do |csv|
csv << attributes
all.each do |lead|
hash = lead.attributes
hash["user"] = lead.user.name
csv << hash.values_at(*attributes)
end
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
#管理ユーザー
user1 = User.create!(name: "arthur",
email: "arthur5138@gmail.com",
password: "1234567",
password_confirmation: "1234567",
admin: true)
user1.skip_confirmation! #Deviseのactivation(メール承認)をスキップしてる。
user1.save!
#4人のサンプルユーザー
4.times do |n|
name = Faker::Name.name
email = "example-#{n+1}@railstutorial.org"
password = "password"
user = User.create!(name: name,
email: email,
password: password,
password_confirmation: password)
user.skip_confirmation!
user.save!
end
#Blogのサンプルポスト
users = User.order(:created_at).take(3)
7.times do
#image = Rails.root.join("test/fixtures/images/slug.jpg").open /seedを入れるとmount_uploadersの為エラーが出る?
title = "タイトル"
text = "これは、テスト投稿です!!"
users.each { |user| user.blogs.create!(title: title, text: text) }
end
|
require 'test_helper'
require 'nokogiri'
describe Jekyll::Haml::Markup do
before do
options = {}
options['source'] = source_dir('sites', 'fake')
@destination = Dir.mktmpdir 'fake', dest_dir
options['destination'] = @destination
config = Jekyll::Configuration::DEFAULTS.merge options
@site = fixture_site config
@site.process
end
after do
FileUtils.remove_entry @destination
end
it 'should load a complete site' do
html = Nokogiri::HTML File.read File.join(@destination, 'index.html')
expect(html.xpath('/html/head')).wont_be_empty
expect(html.xpath('/html/body')).wont_be_empty
expect(html.xpath('/html/body/header/nav/ul/li').size).must_equal 3
expect(html.xpath('/html/body/header/nav/ul/li/a').size).must_equal 2
expect(html.xpath('/html/body/header/nav/ul/li/p/a').size).must_equal 1
expect(html.xpath('/html/body/main/section/article').size).must_equal 2
expect(html.xpath('/html/body/main/h1')).wont_be_empty
expect(html.xpath('/html/body/footer/div/p')).wont_be_empty
expect(html.xpath('/html/body/script')).wont_be_empty
end
end
|
# REPOS
command :create_repo do |c|
c.syntax = 'archivesspace-cli create_repo [options]'
c.summary = ''
c.description = 'Create a repository'
c.example 'create repository TEST',
'./archivesspace-cli create_repo --repo_code=test --name="Test Archives" --contact="John Doe"'
c.option '--repo_code STRING', String, 'Repository code'
c.option '--name STRING', String, 'Name (i.e. "Test Archives")'
c.option '--contact STRING', String, 'Contact (i.e. "John Doe")'
c.option '--email STRING', String, 'Email (i.e. "jdoe@test.org")'
c.action do |args, options|
options.default admin: false
options.default config: 'config.json'
options.default email: ""
config = options.config
repo_code = options.repo_code
name = options.name
contact = options.contact
email = options.email
raise missing_required_arguments_message('create_repo') and exit(1) unless [repo_code, name, contact].all?
data = {
repo_code: repo_code,
name: name,
agent_contact_name: contact,
agent_contact_email: email,
}
client = get_client config
repository = ArchivesSpace::Template.process_template(:repository_with_agent, data)
response = client.post('/repositories/with_agent', repository)
code = response.status_code.to_s
if code =~ /^2/
puts "Created repository:\t#{repo_code}"
else
puts "#{code} #{response.parsed}"
end
end
end
command :delete_repo do |c|
c.syntax = 'archivesspace-cli delete_repo [options]'
c.summary = ''
c.description = 'Delete a repository'
c.example 'delete repository TEST',
'./archivesspace-cli delete_repo --repo_code=test'
c.option '--repo_code STRING', String, 'Repository code'
c.action do |args, options|
options.default config: 'config.json'
config = options.config
repo_code = options.repo_code
raise missing_required_arguments_message('delete_repo') and exit(1) unless [repo_code].all?
client = get_client config
repo = client.repositories.find { |r| r["repo_code"] == repo_code }
if repo
response = client.delete(repo["uri"])
code = response.status_code.to_s
if code =~ /^2/
puts "Deleted repository:\t#{repo_code}"
else
puts "#{code} #{response.parsed}"
end
else
puts "Repository not found:\t#{repo_code}"
end
end
end |
require File.dirname(__FILE__) + '/test_helper.rb'
class TestCountryCode54 < Test::Unit::TestCase
context "A Buenos Aires phone number" do
setup { @phone_number = PhoneNumber.new("54-11-4444-3333") }
area_code_should_be "11"
city_should_be "Buenos Aires"
country_code_should_be "54"
country_should_be "AR"
default_format_should_be "011 4444 3333"
line_number_should_be "3333"
local_prefix_should_be nil
prefix_should_be "4444"
real_number_should_be "1144443333"
real_number_without_local_prefix_should_be "1144443333"
region_should_be "C"
end
context "A Buenos Aires cell number" do
setup { @phone_number = PhoneNumber.new("11-15-5555-4444", "54") }
area_code_should_be "11"
city_should_be "Buenos Aires"
country_code_should_be "54"
country_should_be "AR"
default_format_should_be "011 15 5555 4444"
line_number_should_be "4444"
local_prefix_should_be "15"
prefix_should_be "5555"
real_number_should_be "111555554444"
real_number_without_local_prefix_should_be "1155554444"
region_should_be "C"
end
context "A Buenos Aires cell number dialed from abroad" do
setup { @phone_number = PhoneNumber.new("54-911-5555-4444") }
area_code_should_be "11"
city_should_be "Buenos Aires"
country_code_should_be "54"
country_should_be "AR"
# default_format_should_be "011 15 5555 4444"
line_number_should_be "4444"
local_prefix_should_be "9"
prefix_should_be "5555"
real_number_should_be "91155554444"
real_number_without_local_prefix_should_be "1155554444"
region_should_be "C"
end
context "A Bahía Blanca phone number" do
setup { @phone_number = PhoneNumber.new("54-291-444-3333") }
area_code_should_be "291"
city_should_be "Bahía Blanca"
country_code_should_be "54"
country_should_be "AR"
default_format_should_be "0291 444 3333"
line_number_should_be "3333"
local_prefix_should_be nil
prefix_should_be "444"
real_number_should_be "2914443333"
real_number_without_local_prefix_should_be "2914443333"
region_should_be "B"
end
context "A Bariloche phone number" do
setup { @phone_number = PhoneNumber.new("54-2944-44-4333") }
area_code_should_be "2944"
city_should_be "San Carlos de Bariloche"
country_code_should_be "54"
country_should_be "AR"
default_format_should_be "02944 44 4333"
line_number_should_be "4333"
local_prefix_should_be nil
prefix_should_be "44"
real_number_should_be "2944444333"
real_number_without_local_prefix_should_be "2944444333"
region_should_be "R"
end
context "A Buenos Aires phone number with no area code specified" do
setup { @phone_number = PhoneNumber.new("4444-3333", "54") }
area_code_should_be "11"
city_should_be "Buenos Aires"
country_code_should_be "54"
country_should_be "AR"
default_format_should_be "011 4444 3333"
line_number_should_be "3333"
local_prefix_should_be nil
prefix_should_be "4444"
real_number_should_be "1144443333"
real_number_without_local_prefix_should_be "1144443333"
region_should_be "C"
end
context "A Buenos Aires cell number with no area code specified" do
setup { @phone_number = PhoneNumber.new("15-5555-4444", "54") }
area_code_should_be "11"
city_should_be "Buenos Aires"
country_code_should_be "54"
country_should_be "AR"
default_format_should_be "011 15 5555 4444"
line_number_should_be "4444"
local_prefix_should_be "15"
prefix_should_be "5555"
real_number_should_be "111555554444"
real_number_without_local_prefix_should_be "1155554444"
region_should_be "C"
end
context "A Villa Gesell number" do
setup { @phone_number = PhoneNumber.new("02255-45-6592", "54") }
area_code_should_be "2255"
city_should_be "Villa Gesell"
country_code_should_be "54"
country_should_be "AR"
default_format_should_be "02255 45 6592"
line_number_should_be "6592"
local_prefix_should_be nil
prefix_should_be "45"
real_number_should_be "2255456592"
real_number_without_local_prefix_should_be "2255456592"
region_should_be "B"
end
end |
require 'mongoid'
module Mongoid #:nodoc:
module MagicCounterCache
extend ActiveSupport::Concern
module ClassMethods
def counter_cache(*args, &block)
options = args.extract_options!
name = options[:class] || args.first.to_s
if options[:field]
counter_name = "#{options[:field].to_s}"
else
counter_name = "#{model_name.demodulize.underscore}_count"
end
after_create do |doc|
if doc.embedded?
parent = doc._parent
parent.inc(counter_name.to_sym, 1) if parent.respond_to? counter_name
else
relation = doc.send(name)
if relation && relation.class.fields.keys.include?(counter_name)
relation.inc(counter_name.to_sym, 1)
end
end
end
after_destroy do |doc|
if doc.embedded?
parent = doc._parent
parent.inc(counter_name.to_sym, -1) if parent.respond_to? counter_name
else
relation = doc.send(name)
if relation && relation.class.fields.keys.include?(counter_name)
relation.inc(counter_name.to_sym, -1)
end
end
end
end
alias :magic_counter_cache :counter_cache
end
end
end |
class Aluno < ActiveRecord::Base
belongs_to :curso
require 'csv'
validates :nome, presence:true
validates :email, presence:true
validates :nota_enade, presence:true
def self.import(file)
CSV.foreach(file.path, headers:true) do |row|
aluno = find_by_id(row["id"]) || new
aluno.attributes = row.to_hash.slice(*['id','nome','email','nota_enade','curso_id','created_at','updated_at'])
aluno.save!
end
end
def self.to_csv
CSV.generate do |csv|
csv << column_names
all.each do |curso|
csv << curso.attributes.values_at(*column_names)
end
end
end
end
|
require '../ruby_setup'
require './buses'
describe WaitInterval do
describe "#wait_time" do
describe "when arrival_time is 0" do
before(:each) do
@arrival_time = 0
end
describe "and start_time is 0.20" do
before(:each) do
@start_time = 0.20
@wait_interval = WaitInterval.new(start_time: @start_time, arrival_time: @arrival_time)
end
it "should be 48" do
@wait_interval.wait_time.must_equal(48.0)
end
end
describe "and start_time is 0.05" do
before(:each) do
@start_time = 0.05
@wait_interval = WaitInterval.new(start_time: @start_time, arrival_time: @arrival_time)
end
it "should be 57" do
@wait_interval.wait_time.must_equal(57.0)
end
end
describe "and start_time is 0.95" do
before(:each) do
@start_time = 0.95
@wait_interval = WaitInterval.new(start_time: @start_time, arrival_time: @arrival_time)
end
it "should be 3" do
@wait_interval.wait_time.must_be_close_to(3.0, 0.001)
end
end
end
describe "when arrival_time is 0.5" do
before(:each) do
@arrival_time = 0.5
end
describe "and start_time is 0.20" do
before(:each) do
@start_time = 0.20
@wait_interval = WaitInterval.new(start_time: @start_time, arrival_time: @arrival_time)
end
it "should be 18" do
@wait_interval.wait_time.must_equal(18.0)
end
end
describe "and start_time is 0.05" do
before(:each) do
@start_time = 0.05
@wait_interval = WaitInterval.new(start_time: @start_time, arrival_time: @arrival_time)
end
it "should be 27" do
@wait_interval.wait_time.must_equal(27.0)
end
end
describe "and start_time is 0.95" do
before(:each) do
@start_time = 0.95
@wait_interval = WaitInterval.new(start_time: @start_time, arrival_time: @arrival_time)
end
it "should be 33" do
@wait_interval.wait_time.must_be_close_to(33.0, 0.001)
end
end
end
end
end
|
# frozen_string_literal: true
# rubocop:todo all
# Copyright (C) 2009-2020 MongoDB Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Crypt
LOCAL_MASTER_KEY_B64 = 'Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBMUN3' +
'YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk'.freeze
LOCAL_MASTER_KEY = Base64.decode64(LOCAL_MASTER_KEY_B64)
# For all FLE-related tests
shared_context 'define shared FLE helpers' do
# 96-byte binary string, base64-encoded local master key
let(:local_master_key_b64) do
Crypt::LOCAL_MASTER_KEY_B64
end
let(:local_master_key) { Crypt::LOCAL_MASTER_KEY }
# Data key id as a binary string
let(:key_id) { data_key['_id'] }
# Data key alternate name
let(:key_alt_name) { 'ssn_encryption_key' }
# Deterministic encryption algorithm
let(:algorithm) { 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' }
# Local KMS provider options
let(:local_kms_providers) { { local: { key: local_master_key } } }
# AWS KMS provider options
let(:aws_kms_providers) do
{
aws: {
access_key_id: SpecConfig.instance.fle_aws_key,
secret_access_key: SpecConfig.instance.fle_aws_secret,
}
}
end
# Azure KMS provider options
let(:azure_kms_providers) do
{
azure: {
tenant_id: SpecConfig.instance.fle_azure_tenant_id,
client_id: SpecConfig.instance.fle_azure_client_id,
client_secret: SpecConfig.instance.fle_azure_client_secret,
}
}
end
let(:gcp_kms_providers) do
{
gcp: {
email: SpecConfig.instance.fle_gcp_email,
private_key: SpecConfig.instance.fle_gcp_private_key,
}
}
end
let(:kmip_kms_providers) do
{
kmip: {
endpoint: SpecConfig.instance.fle_kmip_endpoint,
}
}
end
# Key vault database and collection names
let(:key_vault_db) { 'keyvault' }
let(:key_vault_coll) { 'datakeys' }
let(:key_vault_namespace) { "#{key_vault_db}.#{key_vault_coll}" }
# Example value to encrypt
let(:ssn) { '123-456-7890' }
let(:key_vault_collection) do
authorized_client.with(
database: key_vault_db,
write_concern: { w: :majority }
)[key_vault_coll]
end
let(:extra_options) do
{
mongocryptd_spawn_args: ["--port=#{SpecConfig.instance.mongocryptd_port}"],
mongocryptd_uri: "mongodb://localhost:#{SpecConfig.instance.mongocryptd_port}",
}
end
let(:kms_tls_options) do
{}
end
let(:default_kms_tls_options_for_provider) do
{
ssl_ca_cert: SpecConfig.instance.fle_kmip_tls_ca_file,
ssl_cert: SpecConfig.instance.fle_kmip_tls_certificate_key_file,
ssl_key: SpecConfig.instance.fle_kmip_tls_certificate_key_file,
}
end
let(:encrypted_fields) do
BSON::ExtJSON.parse(File.read('spec/support/crypt/encrypted_fields/encryptedFields.json'))
end
%w[DecimalNoPrecision DecimalPrecision Date DoubleNoPrecision DoublePrecision Int Long].each do |type|
let("range_encrypted_fields_#{type.downcase}".to_sym) do
BSON::ExtJSON.parse(
File.read("spec/support/crypt/encrypted_fields/range-encryptedFields-#{type}.json"),
mode: :bson
)
end
end
let(:key1_document) do
BSON::ExtJSON.parse(File.read('spec/support/crypt/keys/key1-document.json'))
end
end
# For tests that require local KMS to be configured
shared_context 'with local kms_providers' do
let(:kms_provider_name) { 'local' }
let(:kms_providers) { local_kms_providers }
let(:data_key) do
BSON::ExtJSON.parse(File.read('spec/support/crypt/data_keys/key_document_local.json'))
end
let(:schema_map_file_path) do
'spec/support/crypt/schema_maps/schema_map_local.json'
end
let(:schema_map) do
BSON::ExtJSON.parse(File.read(schema_map_file_path))
end
let(:data_key_options) { {} }
let(:encrypted_ssn) do
"ASzggCwAAAAAAAAAAAAAAAAC/OvUvE0N5eZ5vhjcILtGKZlxovGhYJduEfsR\n7NiH68Ft" +
"tXzHYqT0DKgvn3QjjTbS/4SPfBEYrMIS10Uzf9R1Ky4D5a19mYCp\nmv76Z8Rzdmo=\n"
end
end
shared_context 'with local kms_providers and key alt names' do
include_context 'with local kms_providers'
let(:schema_map_file_path) do
'spec/support/crypt/schema_maps/schema_map_local_key_alt_names.json'
end
let(:schema_map) do
BSON::ExtJSON.parse(File.read(schema_map_file_path))
end
end
# For tests that require AWS KMS to be configured
shared_context 'with AWS kms_providers' do
before do
unless SpecConfig.instance.fle_aws_key &&
SpecConfig.instance.fle_aws_secret &&
SpecConfig.instance.fle_aws_region &&
SpecConfig.instance.fle_aws_arn
reason = "This test requires the MONGO_RUBY_DRIVER_AWS_KEY, " +
"MONGO_RUBY_DRIVER_AWS_SECRET, MONGO_RUBY_DRIVER_AWS_REGION, " +
"MONGO_RUBY_DRIVER_AWS_ARN environment variables to be set information from AWS."
if SpecConfig.instance.fle?
fail(reason)
else
skip(reason)
end
end
end
let(:kms_provider_name) { 'aws' }
let(:kms_providers) { aws_kms_providers }
let(:data_key) do
BSON::ExtJSON.parse(File.read('spec/support/crypt/data_keys/key_document_aws.json'))
end
let(:schema_map_file_path) do
'spec/support/crypt/schema_maps/schema_map_aws.json'
end
let(:schema_map) do
BSON::ExtJSON.parse(File.read(schema_map_file_path))
end
let(:data_key_options) do
{
master_key: {
region: aws_region,
key: aws_arn,
endpoint: "#{aws_endpoint_host}:#{aws_endpoint_port}"
}
}
end
let(:aws_region) { SpecConfig.instance.fle_aws_region }
let(:aws_arn) { SpecConfig.instance.fle_aws_arn }
let(:aws_endpoint_host) { "kms.#{aws_region}.amazonaws.com" }
let(:aws_endpoint_port) { 443 }
let(:encrypted_ssn) do
"AQFkgAAAAAAAAAAAAAAAAAACX/YG2ZOHWU54kARE17zDdeZzKgpZffOXNaoB\njmvdVa/" +
"yTifOikvxEov16KxtQrnaKWdxQL03TVgpoLt4Jb28pqYKlgBj3XMp\nuItZpQeFQB4=\n"
end
end
shared_context 'with AWS kms_providers and key alt names' do
include_context 'with AWS kms_providers'
let(:schema_map_file_path) do
'spec/support/crypt/schema_maps/schema_map_aws_key_alt_names.json'
end
let(:schema_map) do
BSON::ExtJSON.parse(File.read(schema_map_file_path))
end
end
shared_context 'with Azure kms_providers' do
before do
unless SpecConfig.instance.fle_azure_client_id &&
SpecConfig.instance.fle_azure_client_secret &&
SpecConfig.instance.fle_azure_tenant_id &&
SpecConfig.instance.fle_azure_identity_platform_endpoint
reason = 'This test requires the MONGO_RUBY_DRIVER_AZURE_TENANT_ID, ' +
'MONGO_RUBY_DRIVER_AZURE_CLIENT_ID, MONGO_RUBY_DRIVER_AZURE_CLIENT_SECRET, ' +
'MONGO_RUBY_DRIVER_AZURE_IDENTITY_PLATFORM_ENDPOINT environment variables to be set information from Azure.'
if SpecConfig.instance.fle?
fail(reason)
else
skip(reason)
end
end
end
let(:kms_provider_name) { 'azure' }
let(:kms_providers) { azure_kms_providers }
let(:data_key) do
BSON::ExtJSON.parse(File.read('spec/support/crypt/data_keys/key_document_azure.json'))
end
let(:schema_map_file_path) do
'spec/support/crypt/schema_maps/schema_map_azure.json'
end
let(:schema_map) do
BSON::ExtJSON.parse(File.read(schema_map_file_path))
end
let(:data_key_options) do
{
master_key: {
key_vault_endpoint: SpecConfig.instance.fle_azure_key_vault_endpoint,
key_name: SpecConfig.instance.fle_azure_key_name,
}
}
end
let(:encrypted_ssn) do
"AQGVERAAAAAAAAAAAAAAAAACFq9wVyHGWquXjaAjjBwI3MQNuyokz/+wWSi0\n8n9iu1cKzTGI9D5uVSNs64tBulnZpywtuewBQtJIphUoEr5YpSFLglOh3bp6\nmC9hfXSyFT4="
end
end
shared_context 'with Azure kms_providers and key alt names' do
include_context 'with Azure kms_providers'
let(:schema_map_file_path) do
'spec/support/crypt/schema_maps/schema_map_azure_key_alt_names.json'
end
let(:schema_map) do
BSON::ExtJSON.parse(File.read(schema_map_file_path))
end
end
shared_context 'with GCP kms_providers' do
before do
unless SpecConfig.instance.fle_gcp_email &&
SpecConfig.instance.fle_gcp_private_key &&
SpecConfig.instance.fle_gcp_project_id &&
SpecConfig.instance.fle_gcp_location &&
SpecConfig.instance.fle_gcp_key_ring &&
SpecConfig.instance.fle_gcp_key_name
reason = 'This test requires the MONGO_RUBY_DRIVER_GCP_EMAIL, ' +
'MONGO_RUBY_DRIVER_GCP_PRIVATE_KEY, ' +
'MONGO_RUBY_DRIVER_GCP_PROJECT_ID, MONGO_RUBY_DRIVER_GCP_LOCATION, ' +
'MONGO_RUBY_DRIVER_GCP_KEY_RING, MONGO_RUBY_DRIVER_GCP_KEY_NAME ' +
'environment variables to be set information from GCP.'
if SpecConfig.instance.fle?
fail(reason)
else
skip(reason)
end
end
end
let(:kms_provider_name) { 'gcp' }
let(:kms_providers) { gcp_kms_providers }
let(:data_key) do
BSON::ExtJSON.parse(File.read('spec/support/crypt/data_keys/key_document_gcp.json'))
end
let(:schema_map_file_path) do
'spec/support/crypt/schema_maps/schema_map_gcp.json'
end
let(:schema_map) do
BSON::ExtJSON.parse(File.read(schema_map_file_path))
end
let(:data_key_options) do
{
master_key: {
project_id: SpecConfig.instance.fle_gcp_project_id,
location: SpecConfig.instance.fle_gcp_location,
key_ring: SpecConfig.instance.fle_gcp_key_ring,
key_name: SpecConfig.instance.fle_gcp_key_name,
}
}
end
let(:encrypted_ssn) do
"ARgjwAAAAAAAAAAAAAAAAAACxH7FeQ7bsdbcs8uiNn5Anj2MAU7eS5hFiQsH\nYIEMN88QVamaAgiE+EIYHiRMYGxUFaaIwD17tjzZ2wyQbDd1qMO9TctkIFzn\nqQTOP6eSajU="
end
end
shared_context 'with GCP kms_providers and key alt names' do
include_context 'with GCP kms_providers'
let(:schema_map_file_path) do
'spec/support/crypt/schema_maps/schema_map_gcp_key_alt_names.json'
end
let(:schema_map) do
BSON::ExtJSON.parse(File.read(schema_map_file_path))
end
end
shared_context 'with KMIP kms_providers' do
let(:kms_provider_name) { 'kmip' }
let(:kms_providers) { kmip_kms_providers }
let(:kms_tls_options) do
{
kmip: default_kms_tls_options_for_provider
}
end
let(:data_key) do
BSON::ExtJSON.parse(File.read('spec/support/crypt/data_keys/key_document_kmip.json'))
end
let(:schema_map_file_path) do
'spec/support/crypt/schema_maps/schema_map_kmip.json'
end
let(:schema_map) do
BSON::ExtJSON.parse(File.read(schema_map_file_path))
end
let(:data_key_options) do
{
master_key: {
key_id: "1"
}
}
end
let(:encrypted_ssn) do
"ASjCDwAAAAAAAAAAAAAAAAAC/ga87lE2+z1ZVpLcoP51EWKVgne7f5/vb0Jq\nt3odeB0IIuoP7xxLCqSJe+ueFm86gVA1gIiip5CKe/043PD4mquxO2ARwy8s\nCX/D4tMmvDA="
end
end
shared_context 'with KMIP kms_providers and key alt names' do
include_context 'with KMIP kms_providers'
let(:schema_map_file_path) do
'spec/support/crypt/schema_maps/schema_map_kmip_key_alt_names.json'
end
let(:schema_map) do
BSON::ExtJSON.parse(File.read(schema_map_file_path))
end
end
end
|
class CreateBills < ActiveRecord::Migration[6.0]
def change
create_table :bills do |t|
t.integer :workspace_id
t.string :name
t.integer :bill_type
t.float :amount
t.float :actual_amount
t.integer :cargo_category_id
t.integer :count
t.date :billed_at
t.timestamps
end
end
end
|
require 'wsdl_mapper_testing/schema_test'
module WsdlMapperTesting
class GenerationTest < SchemaTest
def setup
@tmp_path = TestHelper.get_tmp_path
end
def teardown
@tmp_path.unlink
end
def tmp_path
@tmp_path
end
def path_for(*name)
tmp_path.join(*name)
end
def assert_file_exists(*name)
path = tmp_path.join(*name)
assert File.exist?(path), "Expected file #{name * '/'} to exist."
end
def assert_file_is(*name, expected)
assert_file_exists(*name)
assert_equal expected, file(*name)
end
def assert_file_contains(*name, expected)
assert_file_exists(*name)
content = file(*name)
content_normalized = content.gsub(/^\s+/, '')
expected_normalized = expected.strip.gsub(/^\s+/, '')
assert content_normalized.include?(expected_normalized), "Expected\n\n#{content}\n\n to include\n\n#{expected}\n"
end
def file(*name)
File.read tmp_path.join(*name)
end
def context
@context ||= WsdlMapper::Generation::Context.new @tmp_path.to_s
end
end
end
|
class CreateEdgeAes < ActiveRecord::Migration
def change
create_table :edge_aes do |t|
t.integer :actor_id
t.integer :event_id
t.integer :kind
t.timestamps
end
end
end
|
include_recipe 'apt' if platform?('ubuntu')
node.override['mysql']['bind_address'] = '0.0.0.0'
node.override['mysql']['server_root_password'] = 'root'
include_recipe 'mysql::server'
node.override['sonarqube-mysql']['mysql']['host'] = 'localhost'
node.override['sonarqube-mysql']['mysql']['username'] = 'root'
node.override['sonarqube-mysql']['mysql']['password'] = node['mysql']['server_root_password']
include_recipe 'sonarqube-mysql'
include_recipe 'java'
node.override['sonarqube']['jdbc']['username'] = node['sonarqube-mysql']['username']
node.override['sonarqube']['jdbc']['password'] = node['sonarqube-mysql']['password']
node.override['sonarqube']['jdbc']['url'] = 'jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true'
include_recipe 'sonarqube'
sonarqube_mysql_group_permission_template_entry 'remove user from anyone' do
permission_reference 'user'
permission_template 'default_template'
action :remove
end
sonarqube_mysql_group_permission_template_entry 'remove issueadmin from sonar-administrators' do
permission_reference 'issueadmin'
group 'sonar-administrators'
permission_template 'default_template'
action :remove
end
sonarqube_mysql_group_permission_template_entry 'add issueadmin to anyone' do
permission_reference 'issueadmin'
permission_template 'default_template'
action :add
end
# This should not add another entry to the table
sonarqube_mysql_group_permission_template_entry 'add issueadmin again to anyone' do
permission_reference 'issueadmin'
permission_template 'default_template'
action :add
end
sonarqube_mysql_group_permission_template_entry 'add user to sonar-users' do
permission_reference 'user'
group 'sonar-users'
permission_template 'default_template'
action :add
end
# This should not add another entry to the table
sonarqube_mysql_group_permission_template_entry 'add user again to sonar-users' do
permission_reference 'user'
group 'sonar-users'
permission_template 'default_template'
action :add
end
sonarqube_mysql_user_password 'admin' do
crypted_password 'c69266c47cf046c59db184fd299f26051f1e8b30'
salt '6522f3c5007ae910ad690bb1bdbf264a34884c6d'
end
|
class Bind < ActiveRecord::Base
belongs_to :user
belongs_to :project
validates_presence_of :user, :project
validates_uniqueness_of :user_id, :scope => [:project_id, :kind]
symbolize :kind, :in => [:watch, :owner, :dev]
end
# == Schema Information
#
# Table name: binds
#
# id :integer not null, primary key
# user_id :integer not null, indexed, indexed => [project_id]
# project_id :integer not null, indexed, indexed => [user_id]
# kind :string(255) default("watch"), not null
#
# Indexes
#
# index_binds_on_project_id (project_id)
# index_binds_on_user_id (user_id)
# index_binds_on_user_id_and_project_id (user_id,project_id)
#
|
#
# Be sure to run `pod lib lint NAME.podspec' to ensure this is a
# valid spec and remove all comments before submitting the spec.
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = "BayeuxClient"
s.version = "0.1.1"
s.summary = "A client implementation of the Bayeux protocol for OSX and iOS."
s.description = <<-DESC
Bayeux is an asynchronous protocol for delivering messages between a server and clients. One of the most common server-side implementations is Faye (http://faye.jcoglan.com/).
BayeuxClient is a client implementation of the Bayeux protocol, written in Objective-C, and targetting OSX and iOS development. The library uses SocketRocket to communicate with the server via a WebSocket.
DESC
s.homepage = "https://github.com/bmatcuk/BayeuxClient"
s.license = 'MIT'
s.author = { "Bob Matcuk" => "bayeuxclient@squeg.net" }
s.source = { :git => "https://github.com/bmatcuk/BayeuxClient.git", :tag => s.version.to_s }
s.ios.deployment_target = '5.0'
s.osx.deployment_target = '10.7'
s.requires_arc = true
s.source_files = 'Classes'
#s.resources = 'Assets/*.png'
#is.ios.exclude_files = 'Classes/osx'
#s.osx.exclude_files = 'Classes/ios'
s.public_header_files = 'Classes/**/*.h'
# s.frameworks = 'SomeFramework', 'AnotherFramework'
s.dependency 'SocketRocket', '~> 0.3.1-beta'
end
|
require "test_helper"
describe OrderItem do
# it "does a thing" do
# value(1+1).must_equal 2
# end
describe "validations" do
before do
@item = order_items(:oi1)
end
it "must be connected to a product" do
product = Product.find_by(id: @item.product_id)
expect(product).must_be_instance_of Product
end
it "must not be connected to a product that doesn't exist" do
@item.product_id = "bad_id"
is_valid = @item.valid?
refute(is_valid)
end
it "must have a quantity" do
@item.qty = nil
is_valid = @item.valid?
refute(is_valid)
end
it "must have a quantity greater than 0" do
@item.qty = 0
is_valid = @item.valid?
refute(is_valid)
end
it "must have a quantity that is an integer" do
@item.qty = "twelve"
is_valid = @item.valid?
refute(is_valid)
end
end
describe "relationships" do
before do
@item = order_items(:oi1)
end
it "must be connected to an order" do
assert(@item.order_id)
@item.order_id = nil
is_valid = @item.valid?
refute(is_valid)
end
it "must be connected to a product" do
assert(@item.product_id)
@item.product_id = nil
is_valid = @item.valid?
refute(is_valid)
end
end
describe "custom methods" do
before do
@item = order_items(:oi1)
@merchant = merchants("m1")
end
it "can get a list of order items by merchant" do
items = OrderItem.by_merchant(@merchant.id)
assert(items.length > 0)
end
it "can verify that the related product is in stock" do
assert(@item.in_stock?)
end
it "can verify that the related product is out of stock" do
product = Product.find_by(id: @item.product_id)
product.update(stock: 0)
refute(@item.in_stock?)
end
it "can set the subtotal for an order item" do
@item.subtotal = nil
@item.get_subtotal
assert(@item.subtotal != nil)
end
end
end
|
module Moip
module Header
def default_header json = nil
header = {}
header.merge! :basic_auth => auth
header.merge! :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json' }
header.merge! :body => json if json
header
end
def auth
@auth ||= {:username => Moip.config.token, :password => Moip.config.acount_key}
end
def base_url model, options = {}
url = ""
if Moip.config.env == "production"
url = "https://api.moip.com.br/assinaturas/v1/#{model.to_s}"
else
url = "https://sandbox.moip.com.br/assinaturas/v1/#{model.to_s}"
end
url << "/#{options[:code]}" if options[:code]
url << "/#{options[:status]}" if options[:status]
url << "?#{options[:params]}" if options[:params]
url
end
end
end |
class TopicsController < ApplicationController
before_action :set_topic, only: [:show, :edit, :update, :destroy]
def index
@topic = Topic.all
end
def show
@reference = @topic.references.new
end
def new
@topic = Topic.new
end
def create
@topic = Topic.new(params.require(:topic).permit(:title, :description))
if @topic.save
redirect_to @topic
else
render :new
end
end
def edit
end
def update
if @topic.update(params.require(:topic).permit(:title, :description))
redirect_to @topic
else
render :edit
end
end
def destroy
@topic.destroy
redirect_to topics_url
end
private
def set_topic
@topic = Topic.find(params[:id])
end
end
|
class CreateResearchDirectionUsers < ActiveRecord::Migration
def change
create_table :research_direction_users do |t|
t.integer :research_direction_id
t.integer :user_id
t.timestamps
end
end
end
|
class List < ActiveRecord::Base
# has_paper_trail
extend FriendlyId
friendly_id :title, use: :slugged
include Ownable
has_many :list_items, lambda { order(position: :asc) }, dependent: :destroy
belongs_to :user
# Override friendly_id's original slug generation for not downcasing original characters.
# Because friendly_id uses ActiveSupport::Inflector#parameterize inside,
# following code substitutes implementation of ActiveSupport::Inflector#parameterize.
#
# @param [String] value
# @return [String]
def normalize_friendly_id(value)
sep = '-'
# replace accented chars with their ascii equivalents
parameterized_string = ActiveSupport::Inflector.transliterate(value)
parameterized_string.gsub!(/\+/, '-plus') # Google+ => Google-plus
parameterized_string.gsub!(/\#/, '-sharp') # C# => C-sharp
# Turn unwanted chars into the separator
parameterized_string.gsub!(/[^a-zA-Z0-9\-_]+/, sep)
unless sep.nil? || sep.empty?
re_sep = Regexp.escape(sep)
# No more than one of the separator in a row.
parameterized_string.gsub!(/#{re_sep}{2,}/, sep)
# Remove leading/trailing separator.
parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/, '')
end
parameterized_string
end
# Method to fix bad slug
# This doesn't work if slug duplicated.
def normalize_slug!
self.slug = self.normalize_friendly_id(name)
self.save
end
end
|
require 'rails_helper'
RSpec.describe Comment, :type => :model do
before do
@comment = Comment.create(commenter_id: 1,commentable_id: 1, commentable_type: "photo", text: "comment")
@user = User.create(name: "Jonathan", email_address: "jonyoungg@gmail.com", password: "123456", password_confirmation: "123456")
@post = Post.create(approved: true, text: "text")
@photo = Photo.create(approved: true, url: "www.google.com", caption: "caption", profile: false)
end
it 'a users comments should all be comments' do
@user.comments << Comment.new(commentable_id: 1, commentable_type: "photo", text: "comment")
expect(@user.comments.first).to be_a(Comment)
end
it 'should belong to a user' do
@user.comments << @comment
expect(@comment.commenter).to be_a(User)
end
it 'post should be able to add a comment as a commentable' do
@comment.commentable = @post
@comment.save
expect(@comment.commentable).to be_a(Post)
end
it 'photo should be able to add a coment as a commentable' do
@comment.commentable = @photo
@comment.save
expect(@comment.commentable).to be_a(Photo)
end
end
|
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "NdcTree::Node searching" do
subject { NdcTree << %w{ 913.6 913.6 914 400 007 515 } }
it {
result = subject["913.6"]
result.should be_instance_of NdcTree::Node
result.name.should == "913.6"
result.weight.should == 2
}
it {
result = subject["611"]
result.should be_nil
}
it {
result = subject.search(/^9/)
result.should be_instance_of Array
result.should have(5).items
}
it {
result = subject.search(/^1/)
result.should be_instance_of Array
result.should have(0).items
}
end
|
module MWS
module API
# The Amazon MWS Products API helps you get information to match your
# products to existing product listings on Amazon Marketplace websites and
# to make sourcing and pricing decisions for listing those products on
# Amazon Marketplace websites.
#
# The Amazon MWS Products API returns product attributes, current
# Marketplace pricing information, and a variety of other product and
# listing information.
module Products
def get_competitive_pricing_for_asin
raise NotImplementedError
end
def get_competitive_pricing_for_sku
raise NotImplementedError
end
# Gets the lowest price offer listings for a product
#
# asins - A String or Array list of up to 20 ASINs.
# condition - The String item condition scope (default: nil)
#
# Returns a MWS::Response.
def get_lowest_offer_listings_for_asin(asins, condition = nil)
params = build_list 'ASIN', asins
params['ItemCondition'] = condition if condition
url = products_url 'GetLowestOfferListingsForASIN', params
res = Response.new connection.get url
if res.valid?
res
else
raise BadResponse, res.first('Error')['Message']
end
end
def get_lowest_offer_listings_for_sku
raise NotImplementedError
end
# Gets a list of products and their attributes.
#
# asins - A String or Array list of up to 10 ASINs.
#
# Returns a MWS::Response.
#
# Raises a BadResponse if response is not valid.
def get_matching_product(asins)
params = build_list 'ASIN', asins
url = products_url 'GetMatchingProduct', params
res = Response.new connection.get url
if res.valid?
res
else
raise BadResponse, res.first('Error')['Message']
end
end
def get_my_price_for_asin
raise NotImplementedError
end
def get_my_price_for_sku
raise NotImplementedError
end
def get_product_categories_for_asin
raise NotImplementedError
end
def get_product_categories_for_sku
raise NotImplementedError
end
# Returns the String service status of the Products API.
def get_service_status
url = products_url 'GetServiceStatus'
res = Response.new connection.get url
if res.valid?
res.first 'Status'
else
raise BadResponse, res.first('Error')['Message']
end
end
def list_matching_products
raise NotImplementedError
end
# Builds a MWS Products URL.
#
# action - The String action to perform.
# params - A Hash of parameters (default: {}).
#
# Returns a String URL.
def products_url(action, params = {})
builder = url_builder "https://#{@endpoint.host}/Products/2011-10-01"
builder.update 'Action' => action,
'MarketplaceId' => @endpoint.marketplace_id,
'SellerId' => @endpoint.seller_id
builder.update(params).build :get
end
end
end
end
|
class Tool < ActiveRecord::Base
belongs_to :user
has_many :reservations
has_attached_file :image, :styles => { :medium => "300x300>",
:thumb => "100x100>" },
:storage => :s3,
:bucket => 'chombo',
:url =>':s3_domain_url',
:path => ':class/:attachment/:id_partition/:style/:filename',
:default_url => "/images/:style/missing.png"
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
def self.search(search)
where("kind || name ILIKE ?", "%#{search}%")
end
def self.how_far(tools, user)
tools.sort_by do |tool|
Geocoder::Calculations.distance_between([tool.user.latitude,tool.user.longitude],
[user.latitude,user.longitude]).round(2)
end
end
end
|
class InviteMailer < ApplicationMailer
def invitation(github_member, current_user)
@user = current_user
@github_member = github_member
mail(to: github_member.email, subject: 'Turing Tutorial Invitation')
end
end |
class Cart < ApplicationRecord
belongs_to :user
has_many :selected_items, dependent: :destroy, counter_cache: :items_count
has_many :items, through: :selected_items, class_name: 'AccessoryItem'
# Adds the specified AccessoryItem to Cart
#
# @param [AccessoryItem] item The AccessoryItem to be added into Cart
# @param [Integer] quantity Amount of said item to add
#
# @return [SelectedItem] The created or updated SelectedItem
def add_item(item, quantity = 1)
if self.items.include?(item)
selected_item = self.selected_items.find_by(accessory_item_id: item)
selected_item.quantity += quantity
else
selected_item = self.selected_items.build
selected_item.item = item
selected_item.quantity = quantity
end
selected_item.save
selected_item
end
# Returns total price for all items in cart
def total_price_cents
self.selected_items.map(&:total_price_cents).reduce(0, :+)
end
end
|
class RemoveAnnouncementFromAnnouncements < ActiveRecord::Migration
def change
remove_column :announcements, :announcement, :string
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"
file_to_disk1 = '/home//storage1.vdi'
file_to_disk2 = '/home//storage2.vdi'
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# All Vagrant configuration is done here. The most common configuration
# options are documented and commented below. For a complete reference,
# please see the online documentation at vagrantup.com.
config.vm.define "haproxy" do |haproxy|
haproxy.vm.box = "chef/centos-7.0"
haproxy.vm.provider "virtualbox" do |vb|
vb.customize ["modifyvm", :id, "--memory", "512"]
end
haproxy.vm.hostname = "haproxy"
haproxy.vm.network "private_network", ip: "172.20.1.50", netmask: "255.255.0.0"
end
config.vm.define "hosting1" do |hosting1|
hosting1.vm.box = "chef/centos-7.0"
hosting1.vm.provider "virtualbox" do |vb|
vb.customize ["modifyvm", :id, "--memory", "512"]
end
hosting1.vm.hostname = "hosting.pod1"
hosting1.vm.network "private_network", ip: "172.20.1.100", netmask: "255.255.0.0"
end
config.vm.define "master1" do |master1|
master1.vm.box = "chef/centos-7.0"
master1.vm.provider "virtualbox" do |vb|
vb.customize ["modifyvm", :id, "--memory", "2048"]
end
master1.vm.hostname = "master.pod1"
master1.vm.network "private_network", ip: "172.20.1.120", netmask: "255.255.0.0"
end
(1..2).each do |i|
config.vm.define "slave#{i}1" do |slave1|
slave1.vm.box = "chef/centos-7.0"
slave1.vm.provider "virtualbox" do |vb|
vb.customize ["modifyvm", :id, "--memory", "1024"]
end
slave1.vm.hostname = "slave#{i}.pod1"
slave1.vm.network "private_network", ip: "172.20.1.12#{i}", netmask: "255.255.0.0"
end
end
config.vm.define "app1" do |app1|
app1.vm.box = "chef/centos-7.0"
app1.vm.provider "virtualbox" do |vb|
vb.customize ["modifyvm", :id, "--memory", "512"]
end
app1.vm.hostname = "app.pod1"
app1.vm.network "private_network", ip: "172.20.1.130", netmask: "255.255.0.0"
end
config.vm.define "storage1" do |storage1|
storage1.vm.box = "chef/centos-7.0"
storage1.vm.provider "virtualbox" do |vb|
vb.customize ["modifyvm", :id, "--memory", "2048"]
vb.customize ['createhd', '--filename', file_to_disk1, '--size', 500 * 1024]
vb.customize ['storageattach', :id, '--storagectl', 'IDE Controller', '--port', 1, '--device', 0, '--type', 'hdd', '--medium', file_to_disk1]
end
storage1.vm.hostname = "storage.pod1"
storage1.vm.network "private_network", ip: "172.20.1.140", netmask: "255.255.0.0"
end
config.vm.define "hosting2" do |hosting2|
hosting2.vm.box = "chef/centos-7.0"
hosting2.vm.provider "virtualbox" do |vb|
vb.customize ["modifyvm", :id, "--memory", "512"]
end
hosting2.vm.hostname = "hosting.pod2"
hosting2.vm.network "private_network", ip: "172.20.2.100", netmask: "255.255.0.0"
end
config.vm.define "master2" do |master2|
master2.vm.box = "chef/centos-7.0"
master2.vm.provider "virtualbox" do |vb|
vb.customize ["modifyvm", :id, "--memory", "2048"]
end
master2.vm.hostname = "master.pod2"
master2.vm.network "private_network", ip: "172.20.2.120", netmask: "255.255.0.0"
end
(1..2).each do |i|
config.vm.define "slave#{i}2" do |slave2|
slave2.vm.box = "chef/centos-7.0"
slave2.vm.provider "virtualbox" do |vb|
vb.customize ["modifyvm", :id, "--memory", "1024"]
end
slave2.vm.hostname = "slave#{i}.pod2"
slave2.vm.network "private_network", ip: "172.20.2.12#{i}", netmask: "255.255.0.0"
end
end
config.vm.define "app2" do |app2|
app2.vm.box = "chef/centos-7.0"
app2.vm.provider "virtualbox" do |vb|
vb.customize ["modifyvm", :id, "--memory", "512"]
end
app2.vm.hostname = "app.pod2"
app2.vm.network "private_network", ip: "172.20.2.130", netmask: "255.255.0.0"
end
config.vm.define "storage2" do |storage2|
storage2.vm.box = "chef/centos-7.0"
storage2.vm.provider "virtualbox" do |vb|
vb.customize ["modifyvm", :id, "--memory", "2048"]
vb.customize ['createhd', '--filename', file_to_disk2, '--size', 500 * 1024]
vb.customize ['storageattach', :id, '--storagectl', 'IDE Controller', '--port', 1, '--device', 0, '--type', 'hdd', '--medium', file_to_disk2]
end
storage2.vm.hostname = "storage.pod2"
storage2.vm.network "private_network", ip: "172.20.2.140", netmask: "255.255.0.0"
end
end
|
#!/usr/bin/env ruby
require 'contentful/moderator'
STDOUT.sync = true
trap('TERM') do
puts "Graceful shutdown"
exit
end
def usage
puts "Usage: contentful_moderator <configuration_file>"
end
if ARGV.empty?
usage
exit(1)
end
if ['-h', '-H', '--help'].include?(ARGV.first)
usage
exit(0)
end
if File.file?(ARGV.first)
Contentful::Moderator.start(
Contentful::Moderator::Config.load(ARGV.first)
)
else
puts "File provided not found!\n"
usage
exit(1)
end
|
class StylesheetSweeper < ActionController::Caching::Sweeper
observe Stylesheet
def after_update(asset)
expire_cache_for asset if asset.type == 'Stylesheet'
end
def after_destroy(asset)
expire_cache_for asset if asset.type == 'Stylesheet'
end
private
def expire_cache_for(record)
expire_page :controller => '/stylesheets', :action => 'show', :id => "#{record.attributes['title']}.css"
end
end |
require 'sequel'
existing_methods = Sequel::Dataset::Pagination.instance_methods
Sequel::Dataset::Pagination.module_eval do
# it should quack like a WillPaginate::Collection
alias :total_pages :page_count unless existing_methods.include? 'total_pages'
alias :per_page :page_size unless existing_methods.include? 'per_page'
alias :previous_page :prev_page unless existing_methods.include? 'previous_page'
alias :total_entries :pagination_record_count unless existing_methods.include? 'total_entries'
def out_of_bounds?
current_page > total_pages
end
# Current offset of the paginated collection
def offset
(current_page - 1) * per_page
end
end |
# == Schema Information
#
# Table name: movies
#
# id :integer not null, primary key
# description :text
# duration :integer
# image :string
# title :string
# year :integer
# created_at :datetime not null
# updated_at :datetime not null
# director_id :integer
#
class Movie < ApplicationRecord
validates(:title, { :presence => true })
validates(:director, { :presence => true })
def Movie.last_decade
return Movie.where("year > ?", 10.years.ago.year)
end
def Movie.short
return Movie.where("duration < ?", 90)
end
def Movie.long
return Movie.where("duration > ?", 180)
end
def director
return Director.where({ :id => self.director_id }).at(0)
end
def characters
return Character.where({ :movie_id => self.id })
end
def cast
array_of_actor_ids = self.characters.pluck(:actor_id)
return Actor.where({ :id => array_of_actor_ids })
end
end
|
class ProjectsStatisticsService
def initialize(project)
@project = project
@statistics_for_phase = {}
@overall_stat = Hash.new(0)
end
def count_statistics
if @statistics_for_phase.empty?
PhaseType.all.each do |phase|
time_logs = @project.time_logs.where(phase_type: phase)
defects = @project.defects.where(phase_type: phase)
time_on_logs = time_logs.inject(0) {|sum, log| sum + difference_min_between_dates(log.start_date, log.stop_date)}
time_on_defects = defects.inject(0) {|sum, defect| sum + defect.fix_time }
@statistics_for_phase[phase.name.downcase.to_sym] = { defects_count: defects.count,
time_logs_count: time_logs.count,
time_on_logs: time_on_logs,
time_on_defects: time_on_defects ,
time_on_phase: time_on_logs + time_on_defects,
defects_removed: defects.where(fixed: true).count,
defects_injected: defects.where(fixed: false).count
}
end
end
@statistics_for_phase
end
def count_overall_statistics
if @overall_stat.empty?
count_statistics.each do |phase, stats|
@overall_stat[:spent_time] += stats[:time_on_phase]
end
end
@overall_stat
end
private
def difference_min_between_dates(start_date, end_date)
((end_date - start_date)/60).round(0)
end
end |
require 'open-uri'
require 'nokogiri'
require 'date'
require 'line-notify-client'
require_relative 'contribution_count/version'
require_relative 'contribution_count/client'
module ContributionCount
class Error < StandardError; end
def self.new(account_name)
ContributionCount::Client.new(account_name)
end
end
|
module HomeHelper
def to_euro(amount, currency)
return btc_to_euro(amount) if currency == 'BTC'
return ltc_to_euro(amount) if currency == 'LTC'
bch_to_euro(amount) if currency == 'BCH'
end
def btc_to_euro(amount)
round_income(amount * Currency.bitcoin_rate, 8)
end
def ltc_to_euro(amount)
round_income(amount * Currency.litcoin_rate, 8)
end
def bch_to_euro(amount)
round_income(amount * Currency.bitcash_rate, 8)
end
def round_income(income, decimal)
"%.#{decimal}f" % income
end
def currency_icon_box(currency)
return image_tag("LTC-icon.png", class: "ltc-icon custom-icon box-icon", alt: "Litcoin") if currency == 'LTC'
return image_tag("BCH-icon.png", class: "bch-icon custom-icon box-icon", alt: "Bitcoin Cash") if currency == 'BCH'
"<div class='icon'><i class='ion ion-social-bitcoin'></i></div>".html_safe if currency == 'BTC'
end
def currency_icon_balance(currency)
return image_tag("LTC-icon.png", class: "ltc-icon custom-icon", alt: "Litcoin") if currency == 'LTC'
return image_tag("BCH-icon.png", class: "bch-icon custom-icon", alt: "Bitcoin Cash") if currency == 'BCH'
"<i class='ion ion-social-bitcoin'></i>".html_safe if currency == 'BTC'
end
def show_respective_mining_address_for_code(user, code)
return user.btc_mining_address? ? user.btc_mining_address : "Not Found" if code == 'BTC'
return user.ltc_mining_address? ? user.ltc_mining_address : "Not Found" if code == 'LTC'
user.bch_mining_address? ? user.bch_mining_address : "Not Found" if code == 'BCH'
end
end
|
class EvaluateTargetController < BaseController
before_filter :authenticate_user!
def create
create_params
country = Country.where(country_code: params[:country_code]).first
if country
panel_provider_id = country.panel_provider_id
panel_provider_price_service = PanelProviderPriceService.new()
return render json: panel_provider_price_service.calculate_panel_provider_price(panel_provider_id)
else
return not_found!
end
end
def create_params
params.require(:country_code)
params.require(:target_group)
params.require(:locations)
end
end |
require 'rails_helper'
describe Api::V1::ProjectsController, type: :controller do
context 'POST #create' do
before(:each) do
@user = FactoryGirl.create(:user)
@organization = FactoryGirl.create(:organization)
@project = {
name: 'Test',
description: 'Test create project',
organization_id: @organization.id
}
end
subject do
@project_json = @project.as_json
post :create, project: @project_json
end
it 'success project with no collaborator' do
allow(controller).to receive(:current_user).and_return(@user)
subject
expect(response).to have_http_status(:created)
end
it 'success project with collaborators' do
@col = FactoryGirl.create(:user)
@project['users'] = [ @col ]
allow(controller).to receive(:current_user).and_return(@user)
subject
expect(response).to have_http_status(:created)
end
end
end
|
class CreateCallslots < ActiveRecord::Migration
def change
create_table :callslots do |t|
t.integer :user_id
t.date :starts_on
t.date :ends_on
t.time :starts_at
t.time :ends_at
t.integer :frequency
t.integer :f_day
t.integer :f_week
t.integer :f_month
t.integer :separation
t.integer :count
t.date :until
t.timestamps
end
add_index :callslots, :user_id
end
end
|
require 'spec_helper'
describe 'nexus::postconfig' do
let(:default_parameters) {
{
'nexus_root' => '/nexus/root',
'admin_password' => 'some_password',
'enable_anonymous_access' => false,
'initialize_passwords' => true
}
}
context 'with default parameters' do
let(:params) { default_parameters }
it { should contain_augeas('security-configuration.xml').with(
'incl' => '/nexus/root/sonatype-work/nexus/conf/security-configuration.xml',
'lens' => 'Xml.lns',
'context' => '/files//nexus/root/sonatype-work/nexus/conf/security-configuration.xml/security-configuration',
'changes' => [
'rm realms',
'set realms/realm[last()+1]/#text XmlAuthorizingRealm',
'set realms/realm[last()+1]/#text XmlAuthenticatingRealm',
'clear anonymousAccessEnabled',
'set anonymousAccessEnabled/#text false'
]
) }
it { should contain_exec('delete user deployment') }
it { should contain_exec('update password for the admin user') }
end
context 'when initialize_passwords parameter is set to false' do
let(:params) { default_parameters.merge!( { 'initialize_passwords' => false }) }
it { should_not contain_exec('delete user deployment') }
it { should_not contain_exec('update password for the admin user') }
end
context 'when enable_anonymous_access is set to true' do
let(:params) { default_parameters.merge!( { 'enable_anonymous_access' => true }) }
it { should contain_augeas('security-configuration.xml').with(
'incl' => '/nexus/root/sonatype-work/nexus/conf/security-configuration.xml',
'lens' => 'Xml.lns',
'context' => '/files//nexus/root/sonatype-work/nexus/conf/security-configuration.xml/security-configuration',
'changes' => [
'rm realms',
'set realms/realm[last()+1]/#text XmlAuthorizingRealm',
'set realms/realm[last()+1]/#text XmlAuthenticatingRealm',
'clear anonymousAccessEnabled',
'set anonymousAccessEnabled/#text true'
]
) }
end
end
|
require 'rails_helper'
RSpec.describe Comment, type: :model do
before do
@comment = FactoryBot.build(:comment)
end
describe 'コメントする' do
context 'コメントできる時' do
it 'textが存在する時' do
expect(@comment).to be_valid
end
end
context 'コメントできない時' do
it 'textが空の時コメントできない' do
@comment.text = nil
@comment.valid?
expect(@comment.errors.full_messages).to include("Text can't be blank")
end
it 'コメントがuserに紐づいていない時' do
@comment.user = nil
@comment.valid?
expect(@comment.errors.full_messages).to include('User must exist')
end
it 'コメントがerrorに紐づいていない時' do
@comment.error = nil
@comment.valid?
expect(@comment.errors.full_messages).to include('Error must exist')
end
end
end
end
|
require 'singleton'
def Option val
(not val.nil?) ? Some.new(val) : None
end
class Option
include Enumerable
include Comparable
end
class None < Option
include Singleton
def self.get
raise "None has no value"
end
# can either take a normal argument or a block if laziness is desired
def self.getOrElse *args
if not args.empty?
args.first
else
yield if block_given?
end
end
def self.each &block
self
end
def self.map &block
self
end
def self.flatMap &block
self
end
def self.filter &block
self
end
# FIXME: thinks that filter is a private method when I do this:
class << self
# compatible with Ruby's stupid standards
alias_method :select, :filter
end
end
def Some val
Some.new val
end
class Some < Option
def initialize val
@val = val
end
def get
@val
end
# can either take a normal argument or a block if laziness is desired
def getOrElse *args
@val
end
def each &block
block.call(@val)
end
def map &block
Some.new(block.call(@val))
end
def flatMap &block
r = block.call(@val)
if r.is_a?(Some) or r.is_a?(None)
r
else
raise "Did not return an Option"
end
end
def filter &block
r = block.call(@val)
r ? self : None
end
# compatible with Ruby's stupid standards
alias_method :select, :filter
def == other
other.is_a?(Some) and @val == other.get
end
def <=> other
if other.is_a?(Some)
@val <=> other.get
else
0
end
end
def eql? other
self == other
end
def hash
@val.hash
end
def to_s
"Some(#{@val.to_s})"
end
end
def tryo &block
begin
Option(block.call)
rescue
None
end
end |
class AddFeatureOnHomepageToProject < ActiveRecord::Migration
def change
add_column :projects, :feature_on_homepage, :boolean
add_index :projects, :feature_on_homepage
end
end
|
require_relative '../../../defaults'
require_relative '../action_item'
require 'fileutils'
module Simp; end
class Simp::Cli; end
module Simp::Cli::Config
class Item::WarnLockoutRiskAction < ActionItem
attr_accessor :warning_file
attr_reader :warning_message
def initialize(puppet_env_info = DEFAULT_PUPPET_ENV_INFO)
super(puppet_env_info)
@key = 'login::lockout::check'
@description = 'Check for login lockout risk'
@category = :sanity_check
@warning_file = Simp::Cli::BOOTSTRAP_START_LOCK_FILE
@warning_message_brief = 'Locking bootstrap due to potential login lockout.'
@warning_message = <<DOC
#{'#'*72}
Per security policy, SIMP, by default, disables login via `ssh` for all users,
including `root`, and beginning with SIMP 6.0.0, disables `root` logins at
the console by default. So, if one of the following scenarios applies, you
should configure a local user for this server to have both `su` and `ssh`
privileges, in order to prevent `root` lockout from the system:
* Console access is available but not allowed for `root` and no other
administrative user account has yet been created.
* This can happen when SIMP is installed from RPM and the user accepts
`simp config`'s default value for `useradd:securetty` (an empty array).
* Both console access is not available and the administrative user's `ssh`
access has not yet been enabled (permanently) via Puppet.
* This can happen when SIMP is installed from RPM on cloud systems.
If you have access to the console, have the `root` password, and have enabled
`root` console access by specifying an appropriate TTY when `simp config`
asked you about `useradd::securetty` (e.g., `tty0`), this warning is not
applicable. If there are no other issues identified in this file, you can
simply remove it and run `simp bootstrap`.
Otherwise, to address the potential `root` lockout issue, follow the
instructions below.
Configure Local User for Access
-------------------------------
In these instructions, you will create a manifest in a local module, `mymodule`,
in the `production` Puppet environment. Execute these operations as `root`.
* See https://puppet.com/docs/puppet/latest/modules.html for information on how
to create a Puppet module.
* Be sure to create a metadata.json file for your module.
1. Create a local user account, as needed, using `useradd`. This example
assumes the local user is `userx`.
* Be sure to set the user's password if the user is logging in with a password.
* SIMP is configured to create a home directory for the user, if it does
not exist when the user first logs in.
2. Create a `local_user.pp` manifest in `mymodule/manifests` to enable
`sudo su - root` and allow `ssh` access for the user you created/selected:
a) Create the manifest directory
$ mkdir -p /etc/puppetlabs/code/environments/production/modules/mymodule/manifests
b) Create /etc/puppetlabs/code/environments/production/modules/mymodule/manifests/local_user.pp
with the following content:
class mymodule::local_user (
Boolean $pam = simplib::lookup('simp_options::pam', { 'default_value' => false }),
) {
sudo::user_specification { 'default_userx':
user_list => ['userx'],
runas => 'root',
cmnd => ['/bin/su root', '/bin/su - root']
}
if $pam {
include 'pam'
pam::access::rule { 'allow_userx':
users => ['userx'],
origins => ['ALL'],
comment => 'The local user, used to remotely login to the system in the case of a lockout.'
}
}
}
3. Make sure the permissions are correct on the module:
$ sudo chown -R root:puppet /etc/puppetlabs/code/environments/production/modules/mymodule
$ sudo chmod -R g+rX /etc/puppetlabs/code/environments/production/modules/mymodule
4. Add the module to the SIMP server's host YAML file class list:
Edit the SIMP server's YAML file,
`/etc/puppetlabs/code/environments/production/data/<SIMP server FQDN>.yaml`
and add the `mymodule::local_user` to the `classes` array:
classes:
- mymodule::local_user
5. If the local user is configured to login with pre-shared keys instead of a
password (typical cloud configuration), copy the `authorized_keys` file for
that user to the SIMP-managed location for authorized keys `/etc/ssh/local_keys`:
$ sudo mkdir -p /etc/ssh/local_keys
$ sudo chmod 755 /etc/ssh/local_keys
$ sudo cp ~userx/.ssh/authorized_keys /etc/ssh/local_keys/userx
$ sudo chmod 644 /etc/ssh/local_keys/userx
6. Add the module to the `Puppetfile` in the `production` environment:
Edit the `Puppetfile` used to deploy the modules,
`/etc/puppetlabs/code/environments/production/Puppetfile`, and add a line
under the section that says "Add your own Puppet modules here"
mod 'mymodule', :local => true
Next Steps
----------
If `root` lockout is the only issue identified in this file, remove the file
and continue with `simp bootstrap`. If not, address any remaining issues,
remove the file, and then run `simp bootstrap`.
DOC
end
def apply
warn( "\nWARNING: #{@warning_message_brief}", [:RED] )
warn( "See #{@warning_file} for details", [:RED] )
# append/create file that will prevent bootstrap from running until problem
# is fixed
FileUtils.mkdir_p(File.expand_path(File.dirname(@warning_file)))
File.open(@warning_file, 'a') do |file|
file.write @warning_message
end
@applied_status = :failed
end
def apply_summary
if @applied_status == :failed
"'simp bootstrap' has been locked due to potential login lockout.\n * See #{@warning_file} for details"
else
"Check for login lockout risk #{@applied_status}"
end
end
end
end
|
module Fog
module Compute
class Google
class Mock
def insert_image(_image_name, _image = {})
# :no-coverage:
Fog::Mock.not_implemented
# :no-coverage:
end
end
class Real
def insert_image(image_name, image = {}, project = @project)
image = image.merge(:name => image_name)
@compute.insert_image(
project,
::Google::Apis::ComputeV1::Image.new(**image)
)
end
end
end
end
end
|
class Project < ActiveRecord::Base
attr_accessible :due_date, :name
validates_presence_of :name
has_many :tasks
#has_many :users
#has_one :teams
def progress_in_percentage
return (completed_task_by_project.to_f /
total_assigned_tasks_by_project.to_f ) * 100
end
def completed_task_by_project
count = 0
self.tasks.each do |task|
count += task.completed_task_by_task
end
return count
end
def total_assigned_tasks_by_project
count = 0
self.tasks.each do |task|
count += task.user_tasks.count
end
return count
end
end
|
class RemoveColumnImgUrlFromDogsTable < ActiveRecord::Migration[5.2]
def change
remove_column :dogs, :img_url
end
end
|
######################################################################
# Copyright (c) 2008-2014, Alliance for Sustainable Energy.
# All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
######################################################################
# Prepares the directory for the EnergyPlus simulation
class RunPreprocess < OpenStudio::Workflow::Job
require 'openstudio/workflow/util'
include OpenStudio::Workflow::Util::EnergyPlus
include OpenStudio::Workflow::Util::Model
include OpenStudio::Workflow::Util::Measure
def initialize(input_adapter, output_adapter, registry, options = {})
super
end
def perform
@logger.debug "Calling #{__method__} in the #{self.class} class"
# Ensure that the directory is created (but it should already be at this point)
FileUtils.mkdir_p(@registry[:run_dir])
# save the pre-preprocess file
File.open("#{@registry[:run_dir]}/pre-preprocess.idf", 'w') { |f| f << @registry[:model_idf].to_s }
# Add any EnergyPlus Output Requests from Reporting Measures
@logger.info 'Beginning to collect output requests from Reporting measures.'
energyplus_output_requests = true
apply_measures('ReportingMeasure'.to_MeasureType, @registry, @options, energyplus_output_requests)
@logger.info('Finished collect output requests from Reporting measures.')
# Perform pre-processing on in.idf to capture logic in RunManager
@registry[:time_logger].start('Running EnergyPlus Preprocess') if @registry[:time_logger]
energyplus_preprocess(@registry[:model_idf], @logger)
@registry[:time_logger].start('Running EnergyPlus Preprocess') if @registry[:time_logger]
@logger.info 'Finished preprocess job for EnergyPlus simulation'
# Save the model objects in the registry to the run directory
if File.exist?("#{@registry[:run_dir]}/in.idf")
# DLM: why is this here?
@logger.warn 'IDF (in.idf) already exists in the run directory. Will simulate using this file'
else
save_idf(@registry[:model_idf], @registry[:run_dir])
end
# Save the generated IDF file if the :debug option is true
return nil unless @options[:debug]
@registry[:time_logger].start('Saving IDF') if @registry[:time_logger]
idf_name = save_idf(@registry[:model_idf], @registry[:root_dir])
@registry[:time_logger].stop('Saving IDF') if @registry[:time_logger]
@logger.debug "Saved IDF as #{idf_name}"
nil
end
end
|
class SubmissionMailer < ApplicationMailer
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.submission_mailer.new_submission_notification.subject
#
def new_submission_notification(submission)
@submission = submission
reviewers = Reviewer.all
reviewers.each do |rev|
mail to: rev.email, subject: "New submission: #{@submission.name}"
end
end
def mail_script_to_reviewer(desc)
@submission = desc.submission
mail.attachments['script.docx'] = File.read("#{Rails.root}/public#{desc.screenplay_url.to_s}")
mail to: desc.reviewer.email, subject: "Script for #{desc.submission.name} is here!"
end
end
|
Quando("faço uma requisão POST sem enviar dados") do
body_sem_dados()
@response = JSON.parse(@consulta_idwall.Consulta.body)
end
Então("recebo o código {string} e a mensagem {string}") do |codigo, mensagem|
expect(@response["message"]).to eql mensagem
expect(@response["status_code"].to_s).to eql codigo
end
Dado("que faço uma requição POST com data diferente") do
body_dados_errados()
@response = JSON.parse(@consulta_idwall.Consulta.body)
@id = @response["result"]["numero"]
puts "Id do Processo: #{@id}"
end
Quando("consulto o relatório usando o id da requisição") do
@response = statusRelatorio(@id)
end
Dado("que faço uma requição POST com nome diferente") do
body_nome_errado()
response = JSON.parse(@consulta_idwall.Consulta.body)
@id = response["result"]["numero"]
puts "Id do Processo: #{@id}"
end
Dado("que faço uma requição POST com dados reais") do
body_dados_reais()
response = JSON.parse(@consulta_idwall.Consulta.body)
@id = response["result"]["numero"]
puts "Id do Processo: #{@id}"
end
Então("recebo o resultado {string} e a mensagem {string}") do |resultado, mensagem|
expect(@response["result"]["resultado"]).to eql resultado
expect(@response["result"]["mensagem"]).to include(mensagem)
end |
#encoding: utf-8
module Refinery
module Fg
class Student < Refinery::Core::BaseModel
attr_accessible :name, :address, :email, :qq, :msn, :know_from, :leave_message, :tel, :profession_id,
:staying, :grade, :study_class, :interest, :job, :avatar, :avatar_id, :feedback, :position,
:remittance, :gender, :graduation
acts_as_indexed :fields => [:name]
validates :name, :profession, :tel, :presence => true
validates :know_from, :numericality => true
belongs_to :avatar, :class_name => '::Refinery::Image'
belongs_to :profession
KNOW_FROMS = [
"谷歌",
"腾讯",
"新浪",
"搜狐",
"百度",
"朋友推荐",
"宣传广告",
"其他",
]
GENDER = {
true => "男",
false => "女"
}
def know_from_desc
KNOW_FROMS[know_from]
end
end
end
end
|
# require '../librerias/bcrypt/crypt'
require_relative 'crypt'
class Student
include Crypt # incluye los métodos del módulo Crypt
# insertar getters y setters automaticamente
attr_accessor :first_name, :last_name, :email, :username, :password
# insertar solo getters
# attr_reader :username
@first_name
@last_name
@username
@email
@password
# @username = "criselayala98" # no va a mostrar nada cuando se imprima el
# objeto, tocaría crear un metodo setter y llamarlo al crear el objeto, o volver la variable username como un atributo de clase (@@username)
# método constructor
def initialize(first_name, last_name, email, username, password)
@first_name = first_name
@last_name = last_name
@email = email
@username = username
@password = create_hash_password(password)
end
def set_username
@username = "criselayala98"
end
# configurar un método setter
# def first_name=(name)
# @first_name = name
# end
# configurar un método getter
# def first_name
# @first_name
# end
# Método to_string
def to_s
"First name: #{@first_name} \n" +
"Last name: #{@last_name} \n" +
"Nombre de usuario: #{@username} \n" +
"Correo: #{@email} \n" +
"Contraseña: #{@password}\n"
end
end
# Jazmin = Student.new("", "", "", "", "")
# Jazmin.first_name("Crisel Jazmin")
# Jazmin.first_name = "Crisel Jazmin"
# Jazmin.set_username
# puts Jazmin # imprime el método to_s por defecto
# puts Jazmin.first_name
# Abel = Student.new("Abel", "Ayala", "unamoscaentupared@gmail.com", "tito2005", "12345")
# puts Abel
# hashed_password = Abel.create_hash_password("12345") # puede utilizar los métodos del módulo Crypt porq ue están incluídos en la clase estudiante
# puts hashed_password
|
require "clustering/ai4r_modifications"
require 'csv'
module ClusteringModule
class GeneticErrorClustering
attr_accessor :last_run_stats
=begin
def initialize(prosumers: Prosumer.all,
startDate: Time.now - 1.week,
endDate: Time.now,
algorithm: Ai4r::GeneticAlgorithm::StaticChromosome,
penalty_violation: 0.3, penalty_satisfaction: 0.2,
population_size: 200, generations: 100)
method(__method__).parameters.each do |type, k|
next unless type == :key
v = eval(k.to_s)
instance_variable_set("@#{k}", v) unless v.nil?
end
forecasts = Hash[DataPoint.where(prosumer: @prosumers,
interval: 2,
f_timestamp: @startDate .. @endDate)
.select("f_timestamp, prosumer_id, COALESCE(f_consumption,0) - COALESCE(f_production,0) as f_prosumption")
.map do |dp|
[[dp.prosumer_id, dp.f_timestamp.to_i], dp.f_prosumption]
end]
real = Hash[DataPoint.where(prosumer: @prosumers,
interval: 2,
timestamp: @startDate .. @endDate)
.select("timestamp, prosumer_id, COALESCE(consumption,0) - COALESCE(production,0) as prosumption")
.map do |dp|
[[dp.prosumer_id, dp.timestamp.to_i], dp.prosumption]
end]
@errors = Hash[real.map do |k, v|
[k, (v || 0) - (forecasts[k] || 0)]
end]
end
=end
def prepare_input_dataset(instance_id , kappa = 5)
@lastRunSTats = {start_run: Time.now}
params = [@population_size, @generations, {errors: @errors, prosumer_ids: @prosumers.map{|p| p.id}, kappa: kappa,
penalty_violation: @penalty_violation,
penalty_satisfaction: @penalty_satisfaction,
class: @algorithm,
stats: @lastRunSTats}]
filename = Rails.root.join("storage/"+instance_id.to_s+"_input_dataset.json")
File.open(filename, "w") do |file|
file.puts JSON.pretty_generate params
end
end
end
end
|
class EmailBuilder
EMAIL_REGEX = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/
WHITESPACE = /\s+/
DELIMITERS = /[\n,;]+/
def initialize(attributes)
@recipients = attributes[:recipients] || ''
end
def invalid_recipients
recipient_list.map do |item|
unless item.match(EMAIL_REGEX)
item
end
end.compact
end
def recipient_list
@recipients.gsub(WHITESPACE, '').split(DELIMITERS)
end
def valid_recipients?
invalid_recipients.empty?
end
end |
# frozen_string_literal: true
class MessageCreateWorker
include Sidekiq::Worker
sidekiq_options queue: :message_create
def perform(chat_id, message_number, body)
@chat = Message.create(chat_id: chat_id, message_number: message_number, body: body)
if @chat.save
puts "Saved"
else
puts "Error"
print @chat.errors.full_messages
raise 'An error has occured' + @chat.errors.full_messages
end
end
end |
class AddVideoAndDescriptionAndSubtitlesToSlides < ActiveRecord::Migration[5.0]
def change
add_column :slides, :video, :string
add_column :slides, :description, :text
add_column :slides, :subtitles, :string
end
end
|
require_relative '../bank.rb'
describe Bank do
describe "#add_account" do
let(:bank){ Bank.new }
it "should create an account with the given value" do
bank.add_account("Paul", 200)
expect(bank.account_value("Paul")).to eq 200
end
it "should prevent duplicate account names" do
bank.add_account("Paul", 200)
expect(bank.add_account("Paul", 300)).to eq false
expect(bank.account_value("Paul")).to eq 200
end
it "should return true when successfully added account" do
expect(bank.add_account("Paul", 200)).to eq true
end
end
describe "#account_value" do
let(:bank){ Bank.new }
it "should return the correct value for an account" do
bank.add_account("Paul",100)
expect(bank.account_value("Paul")).to eq 100
end
it "should return false if the account does not exist" do
expect(bank.account_value("Paul")).to eq false
end
end
describe "#transfer" do
it "should subtract the transfer amount from the transferer"
it "should add the ammount to the reciever"
it "should return false if transfer does not exist"
it "should return false if reciver does not exist"
it "should return false if transferer does not have enough money"
end
end
|
require 'test_helper'
require 'mocha'
class MathHotSpotErrorsTest < ActionView::TestCase
test "message.display" do
msg = MathHotSpotErrors::Message.display(MathHotSpotErrors::ProblemReplacementErrors::UNIQUE_PROBLEM_REPLACE_ERROR.new)
assert_equal MathHotSpotErrors::Message::UNIQUE, msg
end
test "EmptyProblem has error message for question markup" do
assert_respond_to MathHotSpotErrors::EmptyProblem, :question_markup
end
test "EmptyProblem returns empty string for answer markup" do
assert_equal "", MathHotSpotErrors::EmptyProblem.answer_markup
end
test "EmptyProblem display_mode returns false" do
assert !MathHotSpotErrors::EmptyProblem.display_mode?
end
test "Empty Problem instruction_text returns expected message" do
assert_equal MathHotSpotErrors::Message::NO_INSTRUCTIONS_SPECIFIED, MathHotSpotErrors::EmptyProblem.instruction_text
end
end |
require 'csv'
class Transaction < ApplicationRecord
belongs_to :user
before_create :generate_id
self.per_page = 10
def generate_id
begin
self.transaction_id = SecureRandom.hex
end while Transaction.where(transaction_id: transaction_id).exists?
end
def self.to_csv(options = {})
CSV.generate(options) do |csv|
csv << column_names
all.each do |transaction|
csv << transaction.attributes.values
end
end
end
end
|
cities = {
"London" => { "country" => "England", "monument" => "Big Ben" },
"Paris" => { "country" => "France", "monument" => "Tour Eiffel" }
}
cities["Paris"]["monument"]
"name" # This is a string
:name # This is a symbol
# Having symbols as keys
cities = {
:London => { :country => "England", :monument => "Big Ben" },
:Paris => { :country => "France", :monument => "Tour Eiffel" }
}
# How to read
cities[:Paris][:monument] # => "Big Pen"
cities[:Paris]["monument"] # => nil, as the "monument" key doesn't exist
######## New syntaxxx ##########
# The : comes after the symbol, not before, and the => goes away
cities = {
London: { country: "England", monument: "Big Ben" },
Paris: { country: "France", monument: "Tour Eiffel" }
}
# But that was just when creating the hash!
# To read it, we read it normally as :monument, not monument:
cities[:Paris][:monument] # => "Big Pen"
# cities[:Paris][monument:] # => SYNTAX ERROR
|
require_relative "../github_client"
require_relative "./update_version"
class UpdatePackage
include Sidekiq::Worker
include GithubClient
def perform(full_name)
puts "Updating: #{full_name}"
# List all files in tree
client.tree(full_name, "gh-pages").tree.each do |file|
if match_data = file["path"].match(/(.*)\.json\.js$/)
ref = match_data[1]
sha = file["sha"]
# Create jobs to ingest the .json.js files into S3
UpdateVersion.perform_async(full_name, ref, sha)
end
end
end
end
|
class OrdersController < ApplicationController
include ActionView::Helpers::NumberHelper
load_and_authorize_resource :order, except: :confirm_payment
helper_method :sort_column, :sort_direction, :pool_sort_column
def index
if current_admin
@orders = current_admin.orders.order(sort_column + ' ' + sort_direction)
flash[:success] = "Welcome to CADsurf.com! Check out the order pool to
find projects you're interested in and start getting business." if @orders.count == 0
elsif current_user
@orders = current_user.orders.order(sort_column + ' ' + sort_direction)
flash[:success] = "Welcome to CADsurf.com! Click on the 'New Order' button to
post a project and watch quality makers compete for your business." if @orders.count == 0
end
respond_with @orders
end
def pool
if current_admin
@order_pool = Order.pool.order(pool_sort_column + ' ' + sort_direction)
respond_with @order_pool
end
end
def mybids
if current_admin
@mybids = Order.mybids
respond_with @mybids
end
end
def new
@order = Order.new(params[:order])
end
def create
@order = Order.create(params[:order])
if current_user
@order.user_id = current_user.id
end
@order.save
respond_with @order
end
def update
@order.update(params[:order])
if @order.subtotal
@order.subtotal = @order.subtotal.round
@order.price = (@order.subtotal * (1 + MARKUP)).round
end
if @order.save
respond_with @order
else
redirect_to order_path(@order)
end
end
def destroy
@order.destroy
redirect_to root_path
end
def estimate
unless @order.update(params[:order]) and @order.estimate!
flash[:error] = 'Estimate failed'
end
respond_with @order
end
def pay
@order.process_payment!(params[:card_uri])
@order.pay!
flash[:success] = "Thanks, you paid #{number_to_currency(@order.price)}"
respond_with @order
end
def ship
unless @order.update(params[:order]) and @order.ship!
flash[:error] = 'Shipment failed'
end
respond_with @order
end
def complete
@order.complete!
respond_with @order
end
def archive
@order.archive!
redirect_to root_path
end
private
def sort_column
params[:sort] || "title"
end
def pool_sort_column
params[:sort] || "created_at"
end
def sort_direction
params[:direction] || "asc"
end
def order_params
case action_name
when 'create'
if current_admin
params[:order].permit(:order_type, :budget, :city, :province, :subtotal, :title, :description, :price,
:file_objects ,file_object_ids: [], file_objects_attributes: [:order_id,
:url, :filename, :size, :mimetype])
else
params[:order].permit(:order_type, :budget, :subtotal, :city, :province, :admin_id, :title, :deadline, :color, :material,
:budget, :description, :file_objects, :quantity, :software_program, :file_format,
file_object_ids: [], file_objects_attributes: [:order_id, :url, :filename,
:size, :mimetype])
end
when 'estimate'
params[:order].permit(:price)
when 'pay'
params.require(:card_uri)
when 'complete'
params[:order].permit()
when 'ship'
params[:order].permit(:carrier, :tracking_number,
shippable_file_ids: [], shippable_files_attributes: [:order_id, :url,
:filename, :size, :mimetype])
when 'archive'
params[:order].permit()
else
if current_admin
params[:order].permit(:title, :city, :budget, :province, :subtotal, :description,:price, :file_objects,
file_object_ids: [], file_objects_attributes: [:order_id, :url, :filename,
:size, :mimetype], shippable_files_attributes: [:order_id, :url, :filename,
:size, :mimetype])
else
params[:order].permit(:order_type, :budget, :subtotal, :city, :province, :admin_id, :title, :deadline, :color, :material,
:budget, :description, :file_objects, :quantity, :software_program, :file_format,
file_object_ids: [], file_objects_attributes: [:order_id, :url, :filename,
:size, :mimetype])
end
end
# TODO allow carrier/tracking number/shipping files if admin and state completed
end
end
|
require 'test_helper'
class ApiControllerTest < ActionDispatch::IntegrationTest
test "should get error response" do
post api_path, params: { "asd" => { "kek" => "000" } }, as: :json
assert_equal JSON.parse(@response.body), { "error" => "JSON validation failed" }
end
test "should get booking response" do
post api_path, params: { "booking" => { "room" => "001", "date" => "01-01-2018" } }, as: :json
assert (JSON.parse(@response.body)).key?("booked")
end
end
|
require 'card'
describe Card do
def card(params = {})
defaults = {
suit: :hearts,
rank: 7,
}
Card.new(**defaults.merge(params))
end
it 'has a suit' do
raise unless card(suit: :spades).suit == :spades
end
it 'has a rank' do
raise unless card(rank: :queen).rank == 12
end
it 'is equal to itself' do
subject = card(suit: :spades, rank: 4)
other = card(suit: :spades, rank: 4)
raise unless subject == other
end
it 'is not equal to a card of different suit' do
subject = card(suit: :spades, rank: 4)
other = card(suit: :hearts, rank: 4)
raise unless subject != other
end
it 'is not equal to a card of different rank' do
subject = card(suit: :spades, rank: 4)
other = card(suit: :spades, rank: 5)
raise unless subject != other
end
describe 'a jack' do
it 'ranks higher than a 10' do
lower = card(rank: 10)
higher = card(rank: :jack)
raise unless higher.rank > lower.rank
end
end
describe 'a queen' do
it 'ranks higher than a jack' do
lower = card(rank: :jack)
higher = card(rank: :queen)
raise unless higher.rank > lower.rank
end
end
describe 'a king' do
it 'ranks higher than a queen' do
lower = card(rank: :queen)
higher = card(rank: :king)
raise unless higher.rank > lower.rank
end
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
puts 'Cleaning database...'
Restaurant.destroy_all
puts 'Creating restaurants...'
restaurants_attributes = [
{
name: 'Dishoom',
address: '7 Boundary St, London E2 7JE',
category: 'french',
phone_number: '689-762-7621'
},
{
name: 'Pizza East',
address: '56A Shoreditch High St, London E1 6PQ',
category: 'italian',
phone_number: '689-762-7622'
},
{
name: 'Sushi Sushi',
address: '7 Warlock Road, London W9 34E',
category: 'japanese',
phone_number: '689-762-7624'
},
{
name: 'China East',
address: '28 Middleton Avenue, London N9 2PF',
category: 'chinese',
phone_number: '689-762-7634'
},
{
name: 'Casa Cha',
address: '55 Rua do Cabo, Lisbon 34613',
category: 'belgian',
phone_number: '689-762-7231'
}
]
Restaurant.create!(restaurants_attributes)
puts 'Finished!'
|
class Word < ActiveRecord::Base
belongs_to :List
def record
"#{correct_guess_count}/#{guess_count}"
end
def streak
return "n/a" if streak_type.nil?
"#{streak_type}#{streak_count}"
end
def guessed_correctly
self.guess_count += 1
self.correct_guess_count += 1
if self.streak_type == "C"
self.streak_count += 1
else
self.streak_type = "C"
self.streak_count = 1
end
end
def guessed_incorrectly
self.guess_count += 1
if self.streak_type == "W"
self.streak_count += 1
else
self.streak_type = "W"
self.streak_count = 1
end
end
end
|
class TextFieldForm < Form
@@name = TextField.new("Purchase", :required=>true)
@@cost = TextField.new("Cost", :required=>true)
def redefine_defaults
{ :wrapper => :div, :wrapper_attributes => {:class => :field}, :hash_wrapper => :purchase }
end
def cleaned_cost(cost)
cost = cost.to_i
raise FieldValidationError.new("There is a $100 limit.") if cost > 100
return cost
end
def cleaned_name(name)
raise FieldValidationError.new("You cannot name a puchase 'Chumpy.'") if name == "Chumpy"
return name
end
def cleaned_form(data)
raise FormValidationError.new("This is right out!") if data[:cost].to_i > 100 && data[:name] == "Chumpy"
return data
end
end
|
require 'rails_helper'
RSpec.describe 'Profiles', type: :request do
let!(:user) { create(:user, :with_profile) }
describe 'GET /profiles' do
context 'ログインしている場合' do
before do
sign_in user
end
it 'レスポンスが正常に表示' do
get profile_path
expect(response).to render_template('profiles/show')
end
end
end
describe 'Edit /profiles' do
context 'ログインしている場合' do
before do
sign_in user
end
it '有効なプロフィール編集' do
get edit_profile_path
expect(response).to render_template('profiles/edit')
patch profile_path(user), params: { profile: { introduction: '営業してます',
gender: Profile.genders.keys.sample,
age: Profile.ages.keys.sample,
type: Profile.types.keys.sample } }
redirect_to profile_path
follow_redirect!
expect(response).to render_template('profiles/show')
end
end
context 'ログインしていないユーザーの場合' do
it 'ログイン画面にリダイレクト,401エラー発生すること' do
# 編集
get edit_profile_path
expect(response).to redirect_to(new_user_session_path)
# 更新
patch profile_path(user), params: { profile: { introduction: '営業してます',
gender: Profile.genders.keys.sample,
age: Profile.ages.keys.sample,
type: Profile.types.keys.sample } }
expect(response).to have_http_status(401)
end
end
end
end
|
require 'spec_helper'
describe SessionsController do
let(:user_attrs) { { email: "me@example.com", password: "testing123" } }
let!(:user) { User.create(user_attrs) }
context "sign in" do
it "should create a session" do
post :create, user_attrs
expect(session[:user_id]).to eq user.id
end
end
context "sign out" do
it "should clear the session" do
delete :destroy, id: user.id
expect(session.empty?).to be_true
end
end
end
|
require 'test_helper'
class UserStoriesTest < ActionDispatch::IntegrationTest
# test "the truth" do
# assert true
# end
LineItem.delete_all
Order.delete_all
ruby_book = products(:ruby)
get '/'
assert_response :success
assert_template "index"
post_via_redirect "/orders",
order: {name: "Kane Nguyen",
address: "123 Hidden Street",
email: "khanhthietbi@gmail.com",
pay_type: "Check"}
assert_response :success
assert_template "index"
cart = Cart.find(session[:cart_id])
assert_equal 0, cart.line_items.size
orders = Order.all
assert_equal 1, orders.size
order = order[0]
assert_equal "Kane Nguyen", order.name
assert_equal "123 Hidden Street", order.address
assert_equal "khanhthietbi@gmail.com", order.email
assert_equal "Check", order.pay_type
assert_equal 1, order.line_items.size
line_item = order.line_items[0]
assert_equal ruby_book, line_item.product
end
|
class AchievementCategoriesController < ApplicationController
before_action :require_administrator
before_action :set_achievement_category, only: [:show, :edit, :update,:destroy]
def index
@achievement_categories = AchievementCategory.order(:name)
end
def show
end
def new
@achievement_category = AchievementCategory.new
end
def edit
end
def create
@achievement_category = AchievementCategory.new(achievement_category_params)
if @achievement_category.save!
redirect_to @achievement_category, notice: "Achievement category created successfully"
else
render action 'new'
end
end
def update
if @achievement_category.update(achievement_category_params)
redirect_to @achievement_category, notice: "Achievement category updated successfully"
else
render action 'edit'
end
end
def destroy
@achievement_category.destroy
redirect_to achievement_categories_path
end
private
def set_achievement_category
@achievement_category = AchievementCategory.find(params[:id])
end
def achievement_category_params
params.require(:achievement_category).permit(:name, :description)
end
end
|
class Menu < ApplicationRecord
belongs_to :chef, class_name: 'User', foreign_key: :user_id
has_many :menu_selections
has_many :menu_items, through: :menu_selections
validates :start_date, presence: true
def self.add_menu_items(item_ids)
end
end
|
class DayChip < ApplicationRecord
belongs_to :user ,foreign_key: [:id], optional: true
end
|
require 'rails_helper'
RSpec.describe Event, type: :model do
let(:event) { FactoryGirl.build(:event) }
it 'is valid with a valid title, description, location, start time, and end time' do
expect(event).to be_valid
end
it 'is not valid with a missing title' do
event.title = nil
expect(event).to_not be_valid
end
it 'is not valid with a missing description' do
event.description = nil
expect(event).to_not be_valid
end
it 'is not valid with a missing location' do
event.location = nil
expect(event).to_not be_valid
end
it 'is not valid with a missing start time' do
event.start_time = nil
expect(event).to_not be_valid
end
it 'is not valid with a missing end time' do
event.end_time = nil
expect(event).to_not be_valid
end
end
|
require 'boxzooka/list_request'
module Boxzooka
# The InboundDiscrepancy data set is used by Boxzooka to provide you with information about
# discrepancies between what your Inbound notifications declared, and what we actually received.
class InboundDiscrepancyListRequest < ListRequest
root node_name: 'InboundDiscrepancyList'
end
end
|
require 'yaml'
class S3Wrapper
class Profile
attr_accessor :name, :aws_access_key, :aws_secret_key, :bucket_name, :host_name
CONFIG_FILE = '.s3-wrapper.rc'
def self.config_default(params)
self::create('default', params)
end
def self.create(name, params)
config = read_config(name, false)
params.each do |key, value|
config[name][key] = value
end
self::write_config(config)
S3Wrapper::Profile.new(name, config[name])
end
def self.delete(name)
config = read_config(name, false)
config.delete(name)
self::write_config(config)
end
def self.get(name)
config = read_config(name, true)
S3Wrapper::Profile.new(name, config[name])
end
def initialize(name, params = {})
self.name = name
params.each do |key, value|
instance_variable_set("@#{key}", value)
end
end
def to_hash
Hash[*instance_variables.map { |v|
[v.to_sym, instance_variable_get(v)]
}.flatten]
end
private
def self.read_config(name, with_default)
config = {}
begin
config = File.open(ENV['HOME'] + '/' + CONFIG_FILE) { |f| YAML.load(f) }
rescue
end
config = {} unless config
config[name] = {} unless config[name]
if with_default && config['default'] && name != 'default'
config['default'].each do |key, value|
config[name][key] = value unless config[name][key] && value;
end
end
config
end
def self.write_config(config)
open(ENV['HOME'] + '/' + CONFIG_FILE, 'w+') { |f| YAML.dump(config, f) }
end
end
end
|
class UserDecorator
include ActionView::Helpers::DateHelper
attr_reader :user
def initialize(user)
@user = user
end
def simple_decorate
{
:average_rating => average_rating,
:client => @user.client?,
:country => country,
:email => email,
:first_name => first_name,
:last_name => last_name,
:languages => languages,
:language_ids => language_ids,
:last_logged_in => last_logged_in,
:current_sign_in => current_sign_in,
:locale => locale,
:phone_number => phone_number,
:programs => programs,
:program_ids => program_ids,
:rating_count => rating_count,
:state => state,
:thumbnail_image => picture,
:timezone => user_timezone,
:url_slug => url_slug,
:volunteer => @user.volunteer?,
:city => city
}.merge(availabilities_hash)
end
def updateable
{
:programs => programs,
:locale => locale,
:address => address,
:city => city,
:country => country,
:state => state,
:client => @user.client?,
:volunteer => @user.volunteer?,
:email => email,
:email_notification => email_notification,
:phone_number => phone_number,
:first_name => first_name,
:last_name => last_name,
:thumbnail_image => picture,
:description => description,
:timezone => user_timezone,
:languages => languages,
:rating_count => rating_count,
:average_rating => average_rating
}
end
def availabilities_hash
if @user.volunteer?
{
:available_days => available_days,
}
else
{ }
end
end
def decorate
{
:address => address,
:average_rating => average_rating,
:city => city,
:client => @user.client?,
:country => country,
:description => description,
:email => email,
:first_name => first_name,
:last_name => last_name,
:how_they_found_us => how_they_found_us,
:languages => languages,
:language_ids => language_ids,
:last_logged_in => last_logged_in,
:locale => locale,
:phone_number => phone_number,
:programs => programs,
:program_ids => program_ids,
:rating_count => rating_count,
:state => state,
:thumbnail_image => picture,
:timezone => user_timezone,
:url_slug => url_slug,
:volunteer => @user.volunteer?
}.merge(availabilities_hash)
end
def email_notification
@user.email_notification
end
def locale
@user.locale || 'en'
end
def rating_count
@user.rating_count
end
def average_rating
@user.average_rating
end
def languages
@user.languages.pluck(:name)
end
def language_ids
@user.languages.pluck(:id)
end
def user_timezone
@user.timezone
end
def description
@user.description ||= ''
end
def url_slug
@user.url_slug
end
def first_name
@user.first_name
end
def last_name
@user.last_name
end
def email
@user.email
end
def phone_number
@user.phone_number
end
def picture
if Rails.env.production?
URI.join('https:' + @user.thumbnail_image.url(:thumbnail)).to_s
else
URI.join(Rails.configuration.static_base_url, @user.thumbnail_image.url(:thumbnail)).to_s
end
end
def availabilities
@user.availabilities
end
def programs
@user.programs.pluck(:name)
end
def program_ids
@user.programs.pluck(:id)
end
def address
@user.address ||= ''
end
def city
@user.city ||= ''
end
def country
@user.country ||= ''
end
def state
@user.state ||= ''
end
def how_they_found_us
@user.how_they_found_us ||= ''
end
def available_days
availabilities.pluck(:day)
end
def last_logged_in
if @user.last_sign_in_at?
time_ago_in_words(@user.last_sign_in_at)
else
nil
end
end
def current_sign_in
if @user.current_sign_in_at?
time_ago_in_words(@user.current_sign_in_at)
else
nil
end
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :configure_permitted_parameters, if: :devise_controller?
def destroy
@djoker.destroy
respond_to do |format|
format.html { redirect_to djoques_url, notice: "Votre Djoque à bien été supprimée :(" }
format.json { head :no_content }
end
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit(:username, :email, :password)}
devise_parameter_sanitizer.permit(:account_update) { |u| u.permit(:username, :email, :password, :current_password)}
end
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.