text stringlengths 10 2.61M |
|---|
require 'rest-client'
module StructoUrlGen
def self.create_query(app_name, modl, public_key, private_key, attributes = {} )
p_params = post_params(modl, attributes)
return RestClient::Resource.new "#{app_name}.structoapp.com/api/#{modl.downcase}.json?public_key=#{public_key}&private_key=#{private_key}#{p_params}"
end
def self.retrieve_query(app_name, modl, public_key, private_key, id)
RestClient::Resource.new "#{app_name}.structoapp.com/api/#{modl.downcase}/#{id}.json?public_key=#{public_key}&private_key=#{private_key}"
end
def self.update_query(app_name, modl, public_key, private_key, id, attributes)
p_params = post_params( modl, attributes)
return RestClient::Resource.new "#{app_name}.structoapp.com/api/#{modl.downcase}/#{id}.json?public_key=#{public_key}&private_key=#{private_key}#{p_params}"
end
def self.delete_query(app_name, modl, public_key, private_key, id)
"#{app_name}.structoapp.com/api/#{modl.downcase}/#{id}.json?public_key=#{public_key}&private_key=#{private_key}"
end
def self.search_query(app_name, modl, public_key, private_key, attributes = {})
if attributes != {}
q_params = search_params( attributes )
return RestClient::Resource.new "#{app_name}.structoapp.com/api/#{modl.downcase}.json?public_key=#{public_key}&private_key=#{private_key}#{q_params}"
else
return RestClient::Resource.new "#{app_name}.structoapp.com/api/#{modl.downcase}.json?public_key=#{public_key}&private_key=#{private_key}"
end
end
def self.search_params( attributes )
record_fields = ""
attributes.each do |key, value|
record_fields << "&#{key}=#{value}"
end
record_fields
end
def self.post_params(modl, attributes)
record_fields = ""
if attributes != {}
attributes.each do |key, value|
record_fields << "&#{modl.downcase}[#{key}]=#{value}"
end
end
record_fields
end
end
|
FactoryGirl.define do
factory :mood do
local_date Faker::Date.backward(10)
organization nil
end
end
|
class ModelService
def initialize(serviceable)
type = serviceable.class.to_s
@var = "@#{type.underscore}"
self.instance_variable_set(@var, serviceable)
end
def get_serviceable
self.instance_variable_get(@var)
end
end |
#
# Cookbook Name:: cubrid
# Attributes:: database
#
# Copyright 2012, Esen Sagynov <kadishmal@gmail.com>
#
# Distributed under MIT license
#
# the default target directory to install CUBRID
default['cubrid']['home'] = "/opt/cubrid"
# the directory to store CUBRID databases
set['cubrid']['databases_dir'] = "#{node['cubrid']['home']}/databases"
# "db_volume_size" parameter value used in conf/cubrid.conf
default['cubrid']['db_volume_size'] = "512M"
# "log_volume_size" parameter value used in conf/cubrid.conf
default['cubrid']['log_volume_size'] = "#{node['cubrid']['db_volume_size']}"
|
=begin
input: integer
output: string
problem domain:
- case for 4 digit numbers
- 1000, 2000, 3000, 4000 ...
- Letter M
- Case 1 - M * (current_number / 1000)
- case for 3 digit numbers
- 100, 200, 300 ... 900
- Letter C, D
- Case 1 - 100:300
- Letter C
- Case 2 - 400
- Case 3 - 500:800
- Case 2 - 900
- CM
- case for 2 digit numbers
- Letters L, X
- 10, 20, 30 40 ...90
- Case 1: 10:30
- X * (current_number / 10)
- Case 2: 40
- XL
- Case 3: 50:80
- L + X * (current_number / 10)
- Case 4: 90
- XC
- case for 1 digit number
- Letters I V
- Case 1: 1:3
- Case 2: 4
- Case 3: 5:8
- Case 4: 9
- For 3 digits
- There is a midpoint at 500
- C, D
- Ranges: [100-300][400][500-800][900]
- For 2 digits
- There is a midpoint at 50
- X, L
- [10-30][40][50-80][90]
- For 1 digit
- There is a midpoint at 5
- I V
- [1-3][4][5-8][9]
ALGORITHM
- Split number into thousands, hundredths, decimals etc into a collection
- Go through each number in collection
- If a number has 4 digits
- call method convert_roman_four_digits
- If a number has 3 digits
- call method convert_roman_three_digits
- If a number has 2 digits
- call method convert_roman_two_digits
- If a number has 1 digits
- call method convert_roman_one_digits
=end
class Integer
def to_roman
digits = self.digits.map.with_index do |num, index|
num * (10 ** index)
end.reverse
convert_digits(digits)
end
def convert_digits(digits)
digits.map do |current_number|
number_length = current_number.to_s.size
case number_length
when 4
convert_roman_four_digits(current_number)
when 3
convert_roman_three_digits(current_number)
when 2
convert_roman_two_digits(current_number)
when 1
convert_roman_one_digits(current_number)
end
end.join
end
def convert_roman_four_digits(integer)
'M' * (integer / 1000)
end
def convert_roman_three_digits(integer)
case integer
when 100..300
'C' * (integer / 100)
when 400
'CD'
when 500..800
'D' + 'C' * (integer / 100 - 5)
when 900
'CM'
end
end
def convert_roman_two_digits(integer)
case integer
when 10..30
'X' * (integer / 10)
when 40
'XL'
when 50..80
'L' + 'X' * (integer / 10 - 5)
when 90
'XC'
end
end
def convert_roman_one_digits(integer)
case integer
when 1..3
'I' * integer
when 4
'IV'
when 5..8
'V' + 'I' * (integer - 5)
when 9
'IX'
end
end
end
|
# frozen_string_literal: true
class GroupSemestersController < ApplicationController
before_action :instructor_required, except: :show
before_action :authenticate_user, only: :show
def index
@group_semesters = GroupSemester.includes(:semester).order('semesters.start_on DESC').to_a
end
def show
@group_semester = GroupSemester.includes(group: :group_schedules).find(params[:id])
end
def new
@group_semester ||= GroupSemester.new params[:group_semester]
load_form_data
render action: :new
end
def edit
@group_semester ||= GroupSemester.find(params[:id])
load_form_data
end
def create
@group_semester = GroupSemester.new(params[:group_semester])
if @group_semester.save
redirect_to @group_semester, notice: 'Group semester was successfully created.'
else
new
end
end
def update
@group_semester = GroupSemester.find(params[:id])
if @group_semester.update(params[:group_semester])
redirect_to @group_semester, notice: 'Semesterplan er lagret'
else
edit
render action: 'edit'
end
end
def destroy
@group_semester = GroupSemester.find(params[:id])
@group_semester.destroy
redirect_to group_semesters_url
end
def insert_new_practice_before
practice = Practice.find(params[:id])
group_semester = practice.group_semester
upcoming_practices = group_semester.practices.select do |p|
p.date >= practice.date && p.movable?
end.sort_by(&:date)
Practice.transaction do
previous_message = nil
upcoming_practices.each do |pr|
new_message = previous_message
previous_message = pr.message
pr.update! message: new_message
break if previous_message.blank?
end
if previous_message.present?
upcoming_practices.last
.update! message: "#{upcoming_practices.last.message}\n#{previous_message}".strip
end
end
redirect_to edit_group_semester_path(group_semester, anchor: :plan_tab)
end
def delete_practice
practice = Practice.find(params[:id])
group_semester = practice.group_semester
upcoming_practices = group_semester.practices.select { |p| p.date >= practice.date && p.movable? }
.sort_by(&:date)
Practice.transaction do
upcoming_practices.each_cons(2) do |pr, next_practice|
pr.update! message: next_practice.message
next_practice.update! message: nil
end
end
redirect_to edit_group_semester_path(group_semester, anchor: :plan_tab)
end
private
def load_form_data
@groups = Group.active(@group_semester.semester.try(:start_on) || Date.current)
.order(:from_age).to_a
@semesters = Semester.order('start_on DESC').to_a
@instructors = Member.instructors(@group_semester.start_on).to_a.sort_by(&:current_rank).reverse
end
end
|
class AddSeedingToCompetitionRosters < ActiveRecord::Migration[4.2]
def change
add_column :competition_rosters, :seeding, :integer, null: true, default: nil
end
end
|
Rails.application.routes.draw do
#SignUp and Login
post '/sign_up', to: 'register#sign_up'
post '/login', to: 'session#login'
#Animal
get '/animals/page/:page', to: 'animals#animal_page'
post '/animals/answer/:animal', to: 'animals#answer'
resources :animals
#Authentication
get '/authentication/confirm/:validation_token', to: 'authentication#confirm'
post '/authentication/repeat_token', to: "authentication#repeat_validation_token"
#User
get '/users/animals', to: 'users#my_animals'
resources :users, except: [:create]
#Password
post '/password/forgot', to: 'password#forgot'
post '/recover_password/:token', to: 'password#reset'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
|
require 'test_helper'
class MemberElementsControllerTest < ActionDispatch::IntegrationTest
setup do
@member_element = member_elements(:one)
end
test 'should get index' do
get member_elements_url
assert_response :success
end
test 'should get new' do
get new_member_element_url
assert_response :success
end
test 'should create member_element' do
assert_difference('MemberElement.count') do
post member_elements_url, params: {
member_element: {
item1_id: @member_element.item1_id,
item2_id: @member_element.item2_id,
item3_id: @member_element.item3_id,
item4_id: @member_element.item4_id,
item5_id: @member_element.item5_id,
member_id: @member_element.member_id
}
}
end
assert_redirected_to member_element_path(MemberElement.last)
end
test 'should show member_element' do
get member_element_url(@member_element)
assert_response :success
end
test 'should get edit' do
get edit_member_element_url(@member_element)
assert_response :success
end
test 'should update member_element' do
patch member_element_url(@member_element), params: {
member_element: {
item1_id: @member_element.item1_id,
item2_id: @member_element.item2_id,
item3_id: @member_element.item3_id,
item4_id: @member_element.item4_id,
item5_id: @member_element.item5_id,
member_id: @member_element.member_id
}
}
assert_redirected_to member_element_path(@member_element)
end
test 'should destroy member_element' do
assert_difference('MemberElement.count', -1) do
delete member_element_url(@member_element)
end
assert_redirected_to member_elements_path
end
end
|
FactoryGirl.define do
factory :amendment do |amendment|
body "And amendment's body"
association :proposal
# association :user
accepted false
created_at Time.now
updated_at Time.now
end
factory :proposal do |proposal|
title "A title to a Proposal"
summary "Summarize concisely"
body "With a large body"
# association :user
created_at Time.now
updated_at Time.now
end
factory :proposal_comment, class: Comment do |comment|
title "A title to a Comment"
body "With a small comment body"
# association :user
association :commentable, factory: :proposal
created_at Time.now
updated_at Time.now
end
factory :amendment_comment, class: Comment do |comment|
title "A title to a Comment"
body "With a small comment body"
association :commentable, factory: :amendment
# association :user
created_at Time.now
updated_at Time.now
end
factory :user do
email "#{SecureRandom.base64}@stub.com"
password "password"
password_confirmation "password"
end
end |
class Api::V1::AttendancesController < ApiController
def create
authorize do |user|
event = Event.find(params[:event][:id])
user = user
Attendance.find_or_create_by!(event: event, user: user)
end
end
end
|
require 'cucumber/rake/task'
#
# --- Cuke tasks
#
namespace :test do
Dir.chdir("./test")
Cucumber::Rake::Task.new(:run) do |task|
profile = ENV['PROFILE'] || 'default'
task.cucumber_opts = "--tags @vt14 --format html -o vt14_test_report.html"
end
Cucumber::Rake::Task.new(:run_search) do |task|
profile = ENV['PROFILE'] || 'default'
task.cucumber_opts = "--tags @search --format html -o vt14_search_report.html"
end
Cucumber::Rake::Task.new(:create_user) do |task|
profile = ENV['PROFILE'] || 'default'
task.cucumber_opts = "--tags @create_user"
end
end |
require 'spec_helper'
require 'natives/catalog/merger'
describe Natives::Catalog::Merger do
describe "#merge_catalog!" do
let(:merger) { Natives::Catalog::Merger.new }
it "validates both master_hash and hash_to_merge" do
master_hash = {}
hash_to_merge = {"rubygems" => {}}
validator = double("Natives::Catalog::Validator")
merger = Natives::Catalog::Merger.new(validator: validator)
validator.should_receive(:ensure_valid_catalog_groups).with(master_hash)
validator.should_receive(:ensure_valid_catalog_groups).with(hash_to_merge)
merger.merge_catalog!(master_hash, hash_to_merge)
end
it "returns master_hash" do
master_hash = {}
expect(merger.merge_catalog!(master_hash, {})).to equal(master_hash)
end
it "adds new catalog group into master_hash" do
master_hash = {}
hash_to_merge = {"rubygems" => {}}
merger.merge_catalog!(master_hash, hash_to_merge)
expect(master_hash).to include("rubygems" => {})
end
it "adds new entries into existing catalog group" do
master_hash = {"rubygems" => { "curb" => {} }}
hash_to_merge = {"rubygems" => { "nokogiri" => {} }}
merger.merge_catalog!(master_hash, hash_to_merge)
expect(master_hash).to include(
"rubygems" => {"curb" => {}, "nokogiri" => {}})
end
it "replaces existing entries in existing catalog group" do
master_hash = {"rubygems" => {
"webkit-capybara" => {},
"curb" => {} }}
hash_to_merge = {"rubygems" => {
"curb" => {"foo" => "bar"}, "nokogiri" => {} }}
merger.merge_catalog!(master_hash, hash_to_merge)
expect(master_hash).to include(
"rubygems" => {
"webkit-capybara" => {},
"curb" => {"foo" => "bar"}, "nokogiri" => {}})
end
end
end
|
# frozen_string_literal: true
App.boot(:logger) do
init do
require 'logger'
end
start do
logger_output =
if ENV['APP_ENV'] == 'test'
IO::NULL
else
$stdout
end
logger = Logger.new(logger_output)
logger.level = Logger::INFO
register(:logger, logger)
end
end
|
require "rails_helper"
require "tasks/scripts/move_facility_data"
RSpec.describe MoveFacilityData do
let(:source_facility) { create(:facility) }
let(:destination_facility) { create(:facility) }
let(:another_source_facility) { create(:facility) }
let(:user) { create(:user, registration_facility: destination_facility) }
describe "#fix_patient_data" do
it "Moves all patients registered at the source facility to the destination facility" do
patient_1 = create(:patient, registration_user: user, registration_facility: source_facility)
patient_2 = create(:patient, registration_user: user, registration_facility: source_facility, assigned_facility: create(:facility))
described_class.new(source_facility, destination_facility, user: user).fix_patient_data
expect(Patient.where(id: [patient_1, patient_2]).pluck(:registration_facility_id)).to all eq(destination_facility.id)
expect(patient_1.reload.assigned_facility_id).to eq(destination_facility.id)
expect(patient_2.reload.assigned_facility_id).not_to eq(destination_facility.id)
end
it "Does not move patients from a different facility" do
create_list(:patient, 2, registration_user: user, registration_facility: another_source_facility)
expect {
described_class.new(source_facility, destination_facility, user: user).fix_patient_data
}.not_to change(Patient.where(registration_user: user, registration_facility: another_source_facility), :count)
end
it "Updates the patients at source facility's updated at timestamp" do
patients_at_source_facility = create_list(:patient, 2, registration_user: user, registration_facility: source_facility)
described_class.new(source_facility, destination_facility, user: user).fix_patient_data
patients_at_source_facility.each do |patient|
patient.reload
expect(patient.updated_at).not_to eq(patient.created_at)
end
end
it "Doesn't update the patients at destination facility's updated at timestamp" do
patients_at_destination_facility = create_list(:patient, 2, registration_user: user, registration_facility: destination_facility)
described_class.new(source_facility, destination_facility, user: user).fix_patient_data
patients_at_destination_facility.each do |patient|
patient.reload
expect(patient.updated_at).to eq(patient.created_at)
end
end
it "Updates the patients at source facility's business identifier metadata" do
patients_at_source_facility = create_list(:patient, 2, registration_user: user, registration_facility: source_facility)
described_class.new(source_facility, destination_facility, user: user).fix_patient_data
patients_at_source_facility.each do |patient|
patient.reload
expect(patient.business_identifiers.first.metadata).to eq("assigning_user_id" => user.id,
"assigning_facility_id" => destination_facility.id)
end
end
end
describe "#fix_blood_pressures_data" do
it "Moves all blood pressures recorded at the source facility to the destination facility" do
create_list(:blood_pressure, 2, user: user, facility: source_facility)
expect {
described_class.new(source_facility, destination_facility, user: user).fix_blood_pressure_data
}.to change(BloodPressure.where(user: user, facility: destination_facility), :count).by 2
end
it "Updates the bps_at_source_facility's updated at timestamp" do
bps_at_source_facility = create_list(:blood_pressure, 2, user: user, facility: source_facility)
described_class.new(source_facility, destination_facility, user: user).fix_blood_pressure_data
bps_at_source_facility.each do |blood_pressure|
blood_pressure.reload
expect(blood_pressure.updated_at).not_to eq(blood_pressure.created_at)
end
end
it "Doesn't update the bps_at_destination_facility's updated at timestamp" do
bps_at_destination_facility = create_list(:blood_pressure, 2, facility: destination_facility, user: user)
described_class.new(source_facility, destination_facility, user: user).fix_blood_pressure_data
bps_at_destination_facility.each do |blood_pressure|
blood_pressure.reload
expect(blood_pressure.updated_at).to eq(blood_pressure.created_at)
end
end
it "Moves the blood pressures' encounters away from the source facility" do
create_list(:blood_pressure, 2, :with_encounter, user: user, facility: source_facility)
described_class.new(source_facility, destination_facility, user: user).fix_blood_pressure_data
expect(Encounter.where(facility: source_facility).count).to eq(0)
expect(Encounter.where(facility: destination_facility).count).to eq(2)
end
it "Does not move encounters from a different source facility" do
expect {
described_class.new(source_facility, destination_facility, user: user).fix_blood_sugar_data
}.not_to(change { Encounter.where(facility: another_source_facility).pluck(:id) })
end
end
describe "#fix_appointments_data" do
it "Moves all appointments recorded at the source facility to the destination facility" do
create_list(:appointment, 2, facility: source_facility, user: user)
expect {
described_class.new(source_facility, destination_facility, user: user).fix_appointment_data
}.to change(Appointment.where(facility: destination_facility), :count).by 2
end
it "Updates the appointments_at_source_facility's updated at timestamp" do
appointments_at_source_facility = create_list(:appointment, 2, facility: source_facility, user: user)
described_class.new(source_facility, destination_facility, user: user).fix_appointment_data
appointments_at_source_facility.each do |appointment|
appointment.reload
expect(appointment.updated_at).not_to eq(appointment.created_at)
end
end
it "Doesn't update the appointments_at_destination_facility's updated at timestamp" do
appointments_at_destination_facility = create_list(:appointment, 2, facility: destination_facility, user: user)
described_class.new(source_facility, destination_facility, user: user).fix_appointment_data
appointments_at_destination_facility.each do |appointment|
appointment.reload
expect(appointment.updated_at).to eq(appointment.created_at)
end
end
end
describe "#fix_prescription_drugs_data" do
it "Moves all prescription_drugs recorded at the source facility to the destination facility" do
create_list(:prescription_drug, 2, facility: source_facility, user: user)
expect {
described_class.new(source_facility, destination_facility, user: user).fix_prescription_drug_data
}.to change(PrescriptionDrug.where(facility: destination_facility), :count).by 2
end
it "Updates the prescription_drugs_at_source_facility's updated at timestamp" do
prescription_drugs_at_source_facility = create_list(:prescription_drug, 2, facility: source_facility, user: user)
described_class.new(source_facility, destination_facility, user: user).fix_prescription_drug_data
prescription_drugs_at_source_facility.each do |prescription_drug|
prescription_drug.reload
expect(prescription_drug.updated_at).not_to eq(prescription_drug.created_at)
end
end
it "Doesn't update the prescription_drugs_at_destination_facility's updated at timestamp" do
prescription_drugs_at_destination_facility = create_list(:prescription_drug, 2, facility: destination_facility, user: user)
described_class.new(source_facility, destination_facility, user: user).fix_prescription_drug_data
prescription_drugs_at_destination_facility.each do |prescription_drug|
prescription_drug.reload
expect(prescription_drug.updated_at).to eq(prescription_drug.created_at)
end
end
end
describe "#fix_teleconsultations_data" do
it "Moves all teleconsultations recorded at the source facility to the destination facility" do
create_list(:teleconsultation, 2, facility: source_facility, requester: user)
expect {
described_class.new(source_facility, destination_facility, user: user).fix_teleconsultation_data
}.to change(Teleconsultation.where(facility: destination_facility), :count).by 2
end
it "Updates the teleconsultations_at_source_facility's updated at timestamp" do
teleconsultations_at_source_facility = create_list(:teleconsultation, 2, facility: source_facility, requester: user)
described_class.new(source_facility, destination_facility, user: user).fix_teleconsultation_data
teleconsultations_at_source_facility.each do |teleconsultation|
teleconsultation.reload
expect(teleconsultation.updated_at).not_to eq(teleconsultation.created_at)
end
end
it "Doesn't update the teleconsultations_at_destination_facility's updated at timestamp" do
teleconsultations_at_destination_facility = create_list(:teleconsultation, 2, facility: destination_facility, requester: user)
described_class.new(source_facility, destination_facility, user: user).fix_teleconsultation_data
teleconsultations_at_destination_facility.each do |teleconsultation|
teleconsultation.reload
expect(teleconsultation.updated_at).to eq(teleconsultation.created_at)
end
end
end
describe "#fix_blood_sugars_data" do
it "Moves all blood sugars recorded at the source facility to the destination facility" do
create_list(:blood_sugar, 2, user: user, facility: source_facility)
expect {
described_class.new(source_facility, destination_facility, user: user).fix_blood_sugar_data
}.to change(BloodSugar.where(user: user, facility: destination_facility), :count).by 2
end
it "Updates the blood_sugars_at_source_facility's updated at timestamp" do
blood_sugars_at_source_facility = create_list(:blood_sugar, 2, user: user, facility: source_facility)
described_class.new(source_facility, destination_facility, user: user).fix_blood_sugar_data
blood_sugars_at_source_facility.each do |blood_sugar|
blood_sugar.reload
expect(blood_sugar.updated_at).not_to eq(blood_sugar.created_at)
end
end
it "Doesn't update the blood_sugars_at_destination_facility's updated at timestamp" do
blood_sugars_at_destination_facility = create_list(:blood_sugar, 2, facility: destination_facility, user: user)
described_class.new(source_facility, destination_facility, user: user).fix_blood_sugar_data
blood_sugars_at_destination_facility.each do |blood_sugar|
blood_sugar.reload
expect(blood_sugar.updated_at).to eq(blood_sugar.created_at)
end
end
it "Moves the blood sugar's encounters away from the source facility" do
create_list(:blood_sugar, 2, :with_encounter, user: user, facility: source_facility)
described_class.new(source_facility, destination_facility, user: user).fix_blood_sugar_data
expect(Encounter.where(facility: source_facility).count).to eq(0)
expect(Encounter.where(facility: destination_facility).count).to eq(2)
end
it "Does not move encounters from a different source facility" do
expect {
described_class.new(source_facility, destination_facility, user: user).fix_blood_sugar_data
}.not_to(change { Encounter.where(facility: another_source_facility).pluck(:id) })
end
end
describe "#move_data" do
context "when user is not supplied" do
it "moves all data from source facility to destination facility" do
create_list(:patient, 2, registration_facility: source_facility)
create_list(:blood_pressure, 2, facility: source_facility)
create_list(:blood_sugar, 2, facility: source_facility)
create_list(:appointment, 2, facility: source_facility)
create_list(:prescription_drug, 2, facility: source_facility)
create_list(:teleconsultation, 2, facility: source_facility)
described_class.new(source_facility, destination_facility).move_data
expect(Patient.where(registration_facility: destination_facility).count).to eq(2)
expect(BloodPressure.where(facility: destination_facility).count).to eq(2)
expect(Appointment.where(facility: destination_facility).count).to eq(2)
expect(BloodSugar.where(facility: destination_facility).count).to eq(2)
expect(PrescriptionDrug.where(facility: destination_facility).count).to eq(2)
expect(Teleconsultation.where(facility: destination_facility).count).to eq(2)
end
end
end
end
|
class NorecordSalesController < ApplicationController
before_action :set_norecord_sale, only: [:error_remittance, :create_sale, :update]
before_action :logged_in_user
def index
@q = current_user.norecord_sales.search(params[:q])
@norecord_sales = @q.result(distinct: true)
end
def error_remittance
if @norecord_sale.remitter.present?
settle_number = "誤入金(" + @norecord_sale.remitter + ")"
bank = current_user.banks.find_by(platform: "楽天").name if current_user.banks.find_by(platform: "楽天").present?
receipt_amount = @norecord_sale.amount
receipt_date = @norecord_sale.sale_date
if current_user.accounts.find_by(account: "仮受金").blank?
current_user.accounts.create(account: "仮受金", debit_credit: "貸方", bs_pl: "BS", display_position: "負債", tax_position: "不課税")
end
@summary = current_user.summaries.build(settle_number: settle_number, bank: bank, account: "仮受金", platform: "楽天", receipt_amount: receipt_amount, receipt_date: receipt_date)
if @summary.save
import_from_summaries(@summary)
target_summaries = current_user.summaries.where(bank: bank).order(:receipt_date)
balance = 0
target_summaries.each do |summary|
balance += summary.receipt_amount.to_i
summary.update(balance: balance)
end
end
end
@norecord_sale.destroy
redirect_to norecord_sales_path
end
def create_sale
new_pladmin = current_user.pladmins.build(date: @norecord_sale.sale_date, order_num: @norecord_sale.order_num, sale_place: "楽天", sales_amount: @norecord_sale.amount)
if new_pladmin.save
if @norecord_sale.order_num =~ /-\d{8}-/
match = Regexp.last_match(0)
match_date = match.gsub("-", "")
order_date = Date.parse(match_date).to_date if match_date.present?
end
if @norecord_sale.amount > 0
unit_price = @norecord_sale.amount
number = 1
elsif @norecord_sale.amount < 0
unit_price = @norecord_sale.amount * -1
number = -1
end
current_user.rakutens.create(pladmin_id: new_pladmin.id, order_date: order_date, order_num: @norecord_sale.order_num, unit_price: unit_price, number: number)
import_from_sales_pladmins(new_pladmin)
end
@norecord_sale.destroy
redirect_to edit_rakuten_path(new_pladmin)
end
def update
@norecord_sale.update(norecord_sale_params)
redirect_to norecord_sales_path
end
def destroy
current_user.norecord_sales.where(destroy_check: true).delete_all
redirect_to :back
end
private
def norecord_sale_params
params.require(:norecord_sale).permit(:user_id, :order_num, :sale_date, :amount, :remitter, :destroy_check)
end
def set_norecord_sale
@norecord_sale = current_user.norecord_sales.find(params[:id])
end
end |
#!/usr/bin/env ruby
require 'TestSetup'
require 'test/unit'
#require 'rubygems'
require 'ibruby'
include IBRuby
class AddRemoveUserTest < Test::Unit::TestCase
CURDIR = "#{Dir.getwd}"
DB_FILE = "#{CURDIR}#{File::SEPARATOR}add_remove_user_unit_test.ib"
def setup
puts "#{self.class.name} started." if TEST_LOGGING
# Remove existing database files.
@database = Database.new(DB_FILE)
if File.exist?(DB_FILE)
@database.drop(DB_USER_NAME, DB_PASSWORD)
end
Database.create(DB_FILE, DB_USER_NAME, DB_PASSWORD)
end
def teardown
# Remove existing database files.
if File.exist?(DB_FILE)
@database.drop(DB_USER_NAME, DB_PASSWORD)
end
puts "#{self.class.name} finished." if TEST_LOGGING
end
def test01
sm = ServiceManager.new('localhost')
sm.connect(DB_USER_NAME, DB_PASSWORD)
au = AddUser.new('newuser', 'password', 'first', 'middle', 'last')
au.execute(sm)
sleep(3)
cxn = @database.connect('newuser', 'password')
cxn.close
ru = RemoveUser.new('newuser')
ru.execute(sm)
sm.disconnect
begin
cxn = @database.connect('newuser', 'password')
cxn.close
assert(false, "Able to connect as supposedly removed user.")
rescue IBRubyException
end
end
end
|
require 'rails_helper'
RSpec.describe "contents/edit", type: :view do
before(:each) do
@content = assign(:content, Content.create!(
:userid => 1,
:post => "MyText"
))
end
it "renders the edit content form" do
render
assert_select "form[action=?][method=?]", content_path(@content), "post" do
assert_select "input#content_userid[name=?]", "content[userid]"
assert_select "textarea#content_post[name=?]", "content[post]"
end
end
end
|
set :application, 'tracker'
set :repo_url, 'git@github.com:juliangiuca/tracker.git'
# ask :branch, proc { `git rev-parse --abbrev-ref HEAD`.chomp }
set :deploy_to, '/data/tracker'
# set :scm, :git
# set :format, :pretty
# set :log_level, :debug
# set :pty, true
set :linked_files, %w{config/settings.json newrelic.js}
set :linked_dirs, %w{log}
# set :default_env, { path: "/opt/ruby/bin:$PATH" }
set :keep_releases, 3
namespace :deploy do
desc 'Restart application'
task :restart do
on roles(:app), in: :sequence, wait: 5 do
# Your restart mechanism here, for example:
# execute :touch, release_path.join('tmp/restart.txt')
#if test("[ -f #{shared_path}/tmp/pids/unicorn.pid ]")
#execute "cat #{shared_path}/tmp/pids/unicorn.pid"
#execute "kill -USR2 `cat #{shared_path}/tmp/pids/unicorn.pid`"
#else
#info "No unicorn process found"
#end
end
end
task :pull_down_secret_files do
on roles(:all) do
#execute "mkdir -p /data/tracker/shared/config/"
execute "wget --user=#{ENV['BITBUCKET_USER']} --password='#{ENV['BITBUCKET_PASSWORD']}' -q -N https://bitbucket.org/localtoast/secret-files/raw/master/tracker/settings.production.json -O /data/tracker/shared/config/settings.json"
execute "wget --user=#{ENV['BITBUCKET_USER']} --password='#{ENV['BITBUCKET_PASSWORD']}' -q -N https://bitbucket.org/localtoast/secret-files/raw/master/tracker/newrelic.js -O /data/tracker/shared/newrelic.js"
end
end
after :finishing, 'deploy:cleanup'
before :starting, 'deploy:pull_down_secret_files'
end
|
class VisitorsController < ApplicationController
def index
if current_user
@profile = current_user.profile
@active_users = User.includes(:profile).recent_active.except_user(current_user.id)
end
end
end
|
module EasyPatch
module GanttsControllerPatch
def self.included(base)
base.send(:include, InstanceMethods)
base.class_eval do
helper :easy_query
include EasyQueryHelper
helper :entity_attribute
include EntityAttributeHelper
helper :custom_fields
alias_method_chain :show, :easy_extensions
alias_method_chain :find_optional_project, :easy_extensions
skip_before_filter :find_project, :only => [:update_issues]
def render_to_fullscreen
retrieve_query(EasyIssueQuery)
@query.group_by = nil
@query.display_filter_sort_on_index, @query.display_filter_columns_on_index, @query.display_filter_group_by_on_index = false, false, false
@query.export_formats = {}
additional_statement = "#{Issue.table_name}.start_date IS NOT NULL"
if @query.additional_statement.blank?
@query.additional_statement = additional_statement
else
@query.additional_statement << ' AND ' + additional_statement
end
@zoom = if params[:zoom].present?
params[:zoom]
else
(@query.settings && @query.settings['zoom']) || 'week'
end
@grouped_issues = @query.issues_with_versions(:limit => Setting.gantt_items_limit.blank? ? nil : Setting.gantt_items_limit.to_i, :order => "#{Issue.table_name}.start_date ASC")
render :partial => 'super_gantt', :locals => {:element_id => 'easygantt-container-fs'}
end
def update_issues
errors = []
if params[:items]
errors = update_items(params[:items], true)
end
render :json => {:type => errors.any? ? 'error' : 'notice', :html => errors.any? ? errors.join('<br/>') : l(:notice_successful_update)}
end
def validate_issue
issue = Issue.find(params[:issue_id])
issue.due_date = params['end']
issue.start_date = params['start']
if issue.valid?
render_api_ok
else
render :json => {:type => 'error', :html => issue.errors.full_messages.join('<br/>')}
end
end
def projects
retrieve_query(EasyProjectQuery)
@query.settings = params[:easy_query][:settings] if params[:easy_query]
@query.display_filter_fullscreen_button = false
@query.display_filter_sort_on_index, @query.display_filter_columns_on_index, @query.display_filter_group_by_on_index = false, false, false
@query.export_formats = {}
additional_statement = "#{Project.table_name}.easy_is_easy_template=#{@query.connection.quoted_false}"
unless EasySetting.value('project_calculate_start_date')
additional_statement << " AND #{Project.table_name}.easy_start_date IS NOT NULL"
end
unless EasySetting.value('project_calculate_due_date')
additional_statement << " AND #{Project.table_name}.easy_due_date IS NOT NULL"
end
get_zoom
if @query.additional_statement.blank?
@query.additional_statement = additional_statement
else
@query.additional_statement << ' AND ' + additional_statement
end
respond_to do |format|
format.html
format.api {
@projects = @query.entities(:limit => Setting.gantt_items_limit.blank? ? nil : Setting.gantt_items_limit.to_i, :order => "#{Project.table_name}.lft ASC").delete_if {|p| p.start_date.blank? || p.due_date.blank?}
add_non_filtered_projects if @projects.any?
}
end
end
private
def update_items(items, save=false)
errors = []
items.each do |k, item|
if item['type'] == 'issue'
issue = Issue.find(item['id'].to_i)
if issue
issue.init_journal(User.current)
issue.due_date = item['end']
issue.start_date = item['start']
if save
saved = true
begin
saved = issue.save
rescue ActiveRecord::StaleObjectError
issue.reload
issue.init_journal(User.current)
issue.due_date = item['end']
issue.start_date = item['start']
saved = issue.save
end
unless saved
errors << l(:notice_failed_to_save_issues2, :issue => '"' + issue.subject + '"', :error => issue.errors.full_messages.first)
end
elsif !issue.valid?
errors << l(:notice_failed_to_save_issues2, :issue => '"' + issue.subject + '"', :error => issue.errors.full_messages.first)
end
end
end
if item['type'] == 'milestone'
version = Version.find(item['id'].to_i)
if version
version.effective_date = item['date']
version.save
end
end
if item['type'] == 'project'
project = Project.find(item['id'].to_i)
if project
project.start_date = item['start']
project.due_date = item['end']
project.save
end
end
end
errors
end
def add_non_filtered_projects
ancestors = []
ancestor_conditions = @projects.collect{|project| "(#{Project.left_column_name} < #{project.left} AND #{Project.right_column_name} > #{project.right})"}
if ancestor_conditions.any?
ancestor_conditions = "(#{ancestor_conditions.join(' OR ')}) AND (#{Project.table_name}.id NOT IN (#{@projects.collect(&:id).join(',')}))"
ancestors = Project.find(:all, :conditions => ancestor_conditions)
end
ancestors.each do |p|
p.nofilter = 'nofilter'
end
@projects << ancestors
@projects = @projects.flatten.uniq.sort_by(&:lft)
end
def get_zoom
if params[:zoom].present? && !request.xhr?
@zoom = params[:zoom]
unless @query.new_record?
@query.settings ||= {}
@query.settings['zoom'] = @zoom
@query.save
end
else
@zoom = (@query.settings && @query.settings['zoom']) || 'week'
end
end
def set_versions_setting
if @query && @query.project && !request.xhr?
show_all_versions, versions_above = false, false
if @query.settings.is_a?(Hash)
show_all_versions = true if @query.settings.has_key?('gantt_show_all_versions')
versions_above = true if @query.settings.has_key?('gantt_versions_above')
end
s = EasySetting.where(:name => 'gantt_show_all_versions', :project_id => @query.project.id).first || EasySetting.new(:name => 'gantt_show_all_versions', :project_id => @query.project.id)
s.value = show_all_versions
s.save
s = EasySetting.where(:name => 'gantt_versions_above', :project_id => @query.project.id).first || EasySetting.new(:name => 'gantt_versions_above', :project_id => @query.project.id)
s.value = versions_above
s.save
end
end
end
end
module InstanceMethods
def show_with_easy_extensions
retrieve_query(EasyIssueQuery)
@query.settings ||= {}
@query.settings.merge! params[:easy_query][:settings] if params[:easy_query] && params[:easy_query][:settings].is_a?(Hash)
@query.display_filter_fullscreen_button = false
@query.display_filter_sort_on_index, @query.display_filter_columns_on_index, @query.display_filter_group_by_on_index = false, true, true
@query.export_formats.delete_if{|k| ![:msp].include?(k)}
get_zoom
set_versions_setting
first_issue = @query.entities(:limit => 1, :order => "#{Issue.table_name}.start_date ASC", :conditions => "#{Issue.table_name}.start_date IS NOT NULL").try(:first)
if first_issue
@start_date = first_issue.start_date
else
first_due_issue = @query.entities(:limit => 1, :order => "#{Issue.table_name}.due_date ASC", :conditions => "#{Issue.table_name}.due_date IS NOT NULL").try(:first)
if first_due_issue
@start_date = first_due_issue.due_date - 1.day
else
@start_date = Date.today
end
end
if params[:format] != 'html'
@grouped_issues = @query.issues_with_versions(:limit => Setting.gantt_items_limit.blank? ? nil : Setting.gantt_items_limit.to_i,
:order => "COALESCE(#{Issue.table_name}.due_date, (#{Issue.table_name}.start_date + INTERVAL '1' DAY)) ASC", :include => [:relations_to, :time_entries])
end
respond_to do |format|
format.html { render :action => 'show', :layout => !request.xhr? }
format.pdf {
theme = EasyGanttTheme.find_by_id(params[:easy_gantt_theme_id]) if params[:easy_gantt_theme_id]
gantt = EasyExtensions::PdfGantt.new(:project => @project, :entities => @grouped_issues, :zoom => @zoom, :query => @query, :theme => theme, :format => params[:pdf_format] || 'A4')
send_data(gantt.output(@start_date || Date.today), :type => 'application/pdf',
:disposition => 'inline',
:filename => "#{(@project ? "#{@project.identifier}-" : '') + 'gantt'}.pdf")
}
format.api
end
end
def find_optional_project_with_easy_extensions
#easy query workaround
return if params[:project_id] && params[:project_id].match(/\A(=|\!|\!\*|\*)\S*/)
find_optional_project_without_easy_extensions
end
end
end
end
EasyExtensions::PatchManager.register_controller_patch 'GanttsController', 'EasyPatch::GanttsControllerPatch'
|
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
def do_omniauth
@user = User.from_omniauth(request.env["omniauth.auth"])
provider_kind = @user.provider.capitalize
if @user.persisted?
flash[:notice] = I18n.t("devise.omniauth_callbacks.success", kind: "#{provider_kind}")
sign_in_and_redirect @user, :event => :authentication
else
flash[:notice] = "We were not able to authenticate you. Try signing up directly with MANIAC chess by entering an email address and creating a new password."
redirect_to new_user_registration_url
end
end
alias_method :facebook, :do_omniauth
alias_method :google, :do_omniauth
def failure
flash[:alert] = "Uh oh, looks like something went wrong! Please try again later or sign up with MANIAC Chess directly by providing an email address and password."
redirect_to root_path
end
end
|
require 'spec_helper'
RSpec.describe Raven::Processor::HTTPHeaders do
before do
@client = double("client")
allow(@client).to receive_message_chain(:configuration, :sanitize_http_headers) { ['User-Defined-Header'] }
@processor = Raven::Processor::HTTPHeaders.new(@client)
end
it 'should remove HTTP headers we dont like' do
data = {
:request => {
:headers => {
"Authorization" => "dontseeme",
"AnotherHeader" => "still_here"
}
}
}
result = @processor.process(data)
expect(result[:request][:headers]["Authorization"]).to eq("********")
expect(result[:request][:headers]["AnotherHeader"]).to eq("still_here")
end
it 'should be configurable' do
data = {
:request => {
:headers => {
"User-Defined-Header" => "dontseeme",
"AnotherHeader" => "still_here"
}
}
}
result = @processor.process(data)
expect(result[:request][:headers]["User-Defined-Header"]).to eq("********")
expect(result[:request][:headers]["AnotherHeader"]).to eq("still_here")
end
it "should remove headers even if the keys are strings" do
data = {
"request" => {
"headers" => {
"Authorization" => "dontseeme",
"AnotherHeader" => "still_here"
}
}
}
result = @processor.process(data)
expect(result["request"]["headers"]["Authorization"]).to eq("********")
expect(result["request"]["headers"]["AnotherHeader"]).to eq("still_here")
end
end
|
class AddMidiumToUrlBuilders < ActiveRecord::Migration
def change
add_reference :url_builders, :campaign_medium, index: true, foreign_key: true
end
end
|
require 'formula'
class PysideTools < Formula
homepage 'http://www.pyside.org'
url 'https://github.com/PySide/Tools/archive/0.2.15.tar.gz'
sha1 'b668d15e8d67e25a653db5abf8f542802e2ee2dd'
head 'git://gitorious.org/pyside/pyside-tools.git'
depends_on 'cmake' => :build
depends_on 'pyside'
def install
system "cmake", ".", "-DSITE_PACKAGE=lib/python2.7/site-packages", *std_cmake_args
system "make install"
end
end
|
class Activity < ActiveRecord::Base
# attr_accessible :title, :body
belongs_to :user
after_create :send_email_notification
def send_email_notification
# Check if notification is allowed
#begin
case true
when self.description.downcase.include?("admire") && self.user.noti_admire
UserMailer.notification(self.user, self).deliver
when self.description.downcase.include?("message") && self.user.noti_message
UserMailer.notification(self.user, self).deliver
when self.description.downcase.include?("retip") && self.user.noti_retips
UserMailer.notification(self.user, self).deliver
when self.description.downcase.include?("acquainted") && self.user.noti_follow
puts "Sending aquaint email"
UserMailer.notification(self.user, self).deliver
when self.description.downcase.include?("mention") && self.user.noti_mention
end
#rescue => error
# puts error.message
#end
end
end
|
require 'language_mapper/mapper/us_county_mapper'
describe USCountyMapper do
let(:output_file_name) { Tempfile.new('foo').path }
let(:counties) {{ 'county1': 2 }}
let(:color_scaler) { double('ColorScaler') }
let(:svg_mapper) { double('SVGMapper') }
subject { USCountyMapper.new(output_file_name, color_scaler: color_scaler, svg_mapper: svg_mapper) }
it "Should map counties" do
expect(color_scaler).to receive(:create_scale!).with(counties)
expect(color_scaler).to receive(:color_for).with(2).and_return(:red)
expect(svg_mapper).to receive(:color_county!).with(:'county1', :red)
expect(svg_mapper).to receive(:close).and_return(output_file_name)
expect(subject.map(counties)).to eq(output_file_name)
end
end
|
module HealthChecks
module Checks
class MongoidCheck
attr_reader :db_name
def initialize(mongo_database)
@db_name = mongo_database[:name]
@client = create_client(mongo_database)
end
def run
@client.command(dbStats: 1).first['db']
rescue => e
raise "#{e}, Database Name: #{@db_name}"
end
private
def create_client(database)
client_name = "#{database[:name]}_sidekiq_health_check"
::Mongoid::Config.clients[client_name] = {
hosts: database[:hosts],
database: "#{client_name}_db",
options: {
server_selection_timeout: 1,
connect_timeout: 1,
socket_timeout: 1,
wait_queue_timeout: 1
}
}
::Mongoid::Clients.with_name(client_name)
end
end
end
end
|
class AddCredentialsToAuthentications < ActiveRecord::Migration
def change
add_column :authentications, :credentials, :jsonb
end
end
|
class Food
attr_reader :name, :color, :price
attr_writer :price
def initialize(item_hash)
@name = item_hash[:name]
@color = item_hash[:color]
@price = item_hash[:price]
end
def info
"a #{color} #{name} cost Rwf#{price}"
end
end
|
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# provider :string
# uid :string
# name :string
# avatar_url :string
# url :string
# created_at :datetime not null
# updated_at :datetime not null
#
class UserSerializer < ActiveModel::Serializer
attributes :id, :name, :avatar_url
# look up :subject on the model, but use +title+ in the JSON
# attribute :subject, :key => :title
# has_many :comments
end
|
#!/usr/bin/ruby
# Modules
# Modules are very similar to Classes. In fact a Module is a superclass of a Class:
puts Class.superclass #=> Module
=begin
We use a module to group together a collection of variables and methods
(very similar to a class). However, we should use a module if it is meant
to be included within a class and we should use a class if we are going
to instantiate something. What does it mean by including a module?
=end
# Enumerable
=begin
Enumerable is just a module that is included in Arrays and Hashes. We can verify this by looking at the ancestors. Ancestors contain the list of Classes and Modules that a class inherits/includes.
=end
print "ancestors for Array: ", Array.ancestors.to_s
puts
print "ancestors for Hash: ", Hash.ancestors.to_s
puts
=begin
Arrays and Hashes both have the Enumerable and the Kernel module included.
This means that any methods declared in these two methods are available to
the instances of the Array or Hash class. Arrays and Hashes also inherit from
the Object class and the BasicObject class. This is what people mean when they
say: in Ruby everything is an object. If we look at the ancestor chain, it
always ends with Object and BasicObject.
=end
print "ancestors for Fixnum: ", Fixnum.ancestors.to_s
=begin
The Enumerable module has many methods that make Ruby very fun to work with.
The Enumerable module is equivalent to the underscore library for JavaScript
except that it comes pre-baked with Ruby.
=end
# Method Lookup
=begin
When we send a message to an object, it first looks within its own class if that method exists. If not we move up our ancestor chain to see if that message
exists. We keep going up until we either find the message that we know how to
respond to or we reach the end of our ancestor chain and say no message (method)
was found.
=end
#.any? {|obj| block} -> true or false
["ant", "bear", "cat"].any? {|word| word.length >= 3}
# => true
#.each -> calls block once for each element in self, passing that element as
# a parameter.
["ant", "bear", "cat"].each {|word| print word, "--"}
# => ant--bear--cat--
#.collect {|obj| block} -> array; returns a new array with the results of
# running block once for every element in enum
(1..4).collect {|i| i*i}
# => [1, 4, 9, 16]
(1..4).collect { "cat" }
# => ["cat", "cat", "cat", "cat"]
# .map {|obj| block} -> enumerator; returns a new array with the results of running block once for every element in enum. it's exactly like .collect
# .detect/.find -> enumerator; returns the first for which block is not false.
(1..10).detect { |i| i %5 == 0 and i % 7 == 0 }
# => nil
(1..100).detect { |i| i %5 == 0 and i % 7 == 0 }
# => 35
# .find_all {|obj| block} or .select {|obj| block} ; returns an array
# containing all elements of enum for which block is not false
(1..10).find_all { |i| i % 3 == 0 }
# => [3, 6, 9]
# .reject {|obj| block} -> opposite of find_all
(1..10).reject { |i| i % 3 == 0 }
# => [1, 2, 4, 5, 7, 8, 10]
# .upto(limit) -> iterates block up to the int number
5.upto(10) { |i| print i, " " }
# => 5 6 7 8 9 10
# .has_key?(key) -> true or false
# .has_value?(value) -> true or false
# .key(value) -> returns the key of an occurrence of a given value. If the
# value is not found, returns nil
# .keys -> returns a new array populated with the keys from the hash
|
class Station
attr_reader :station_name,
:street_address,
:fuel_type_code,
:distance,
:access_days_time
def initialize(attrs = {})
@station_name = attrs[:station_name]
@street_address = attrs[:street_address]
@fuel_type_code = attrs[:fuel_type_code]
@distance = attrs[:distance]
@access_days_time = attrs[:access_days_time]
end
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
namespace :admin do
resources :m_jurusans, :m_prodis, :m_nilais
end
# resources :m_jurusans
# resources :m_prodis
# resources :m_nilais
root 'pages#dashboard'
end
|
class SponsorsController < ApplicationController
before_action :authenticate_sponsor!, only: [:feed]
def feed
check_for_bank_details
end
private
def check_for_bank_details
if current_sponsor.bank_detail.nil?
redirect_to new_sponsor_bank_detail_path(current_sponsor)
end
end
end
|
class Admins::DepartmentsController < ApplicationController
def index
@department = Department.new
@departments = Department.page(params[:page]).reverse_order.per(10)
end
def create
@department = Department.new(department_params)
if @department.save
flash[:success] = '登録が完了しました'
redirect_to admins_departments_path
else
@departments = Department.page(params[:page]).reverse_order
render :index
end
end
def edit
@department = Department.find(params[:id])
end
def update
@department = Department.find(params[:id])
if @department.update(department_params)
flash[:success] = '変更しました'
redirect_to admins_departments_path
else
render :edit
end
end
private
def department_params
params.require(:department).permit(:name, :is_valid)
end
end
|
json.array!(@phones) do |phone|
json.extract! phone, :id, :number, :phone_type, :user_id
json.url phone_url(phone, format: :json)
end
|
require 'sequel'
# Inner workings of Ticket
module TicketService
=begin
# Here is an example how to implement "simple" upload value management.
#
# Define the component in yaml like this:
#
# - class: HUploader
# rect: [ 10, 10, 200, 24 ]
# bind: :values.upload
# options:
# label: Upload
# events:
# click: true
#
#
# Expects a value named :upload, it is defined like this in values.yaml:
#
# :upload:
# :responders:
# - :method: upload
#
#
class UploadPlugin < GUIPlugin
def init_ses_values( msg )
super
upload_id( msg )
end
def restore_ses_values( msg )
super
upload_id( msg )
end
def upload_id( msg )
upload_ticket = ticket.upload_key( msg, get_ses( msg, :upload ).value_id )
get_ses( msg, :upload ).set( msg, upload_ticket )
end
def upload( msg, value )
if value.data.start_with?('2:::') # upload is completed
ticket_id = value.data.split(':::')[1]
ticket_data = ticket.get_uploads( ticket_id, true )
ticket_data.each do |ticket_item|
file_write( bundle_path( ticket_item[:name], 'uploaded' ), ticket_item[:data] )
end
ticket.del_uploads( msg, ticket_id )
value.set( msg, '3:::' + ticket_id ) # upload is processed
elsif value.data.start_with?('4:::') # client wants a new id
upload_id( msg )
end
return true
end
end
=end
module Upload
=begin
Handles uploads by using tickets and other filters.
Upload success states:
0: Idle, default, ready to upload
1: Upload started
2: Upload completed
3: Upload processed
4: Client requests new key
Upload failure states:
-1: Invalid request (missing query keys)
-2: Invalid or missing key
-3: Invalid mime-type (invalid data format)
-4: File too big
-5: Key request forbidden (when calling upload_key)
-6: Post-processing failed
Default upload table:
create table rsence_uploads (
id int primary key auto_increment,
ses_id int not null,
upload_date int not null,
upload_done tinyint not null default 0,
file_size int not null default 0,
file_mime varchar(255) not null default 'text/plain',
file_data mediumblob
)
=end
def upload(request,response)
ticket_id = request.unparsed_uri.match(/^#{::RSence.config[:broker_urls][:u]+'/'}(.*)$/)[1]
value_id = request.query['value_id']
if not @upload_slots[:by_id].has_key?(ticket_id)
done_value = '-2:::Invalid or missing key'
else
## Get data stored in the upload slot
(mime_allow,max_size,ses_id,value_key,allow_multi) = @upload_slots[:by_id][ticket_id]
if not allow_multi
@upload_slots[:by_id].delete( ticket_id )
end
## The upload form field
file_data = request.query['file_data']
file_mimetype = file_data[:type]
file_filename = file_data[:filename]
## Get the size from the temporary file
file_size = file_data[:tempfile].stat.size
## Check for errors
if not mime_allow.match(file_mimetype)
done_value = "-3:::#{ticket_id}"
elsif not file_size < max_size
done_value = "-4:::#{ticket_id}"
else
done_value = "2:::#{ticket_id}"
## Insert basic data about the upload and get its key
insert_hash = {
:ses_id => ses_id,
:ticket_id => ticket_id,
:upload_date => Time.now.to_i,
:upload_done => false,
:file_name => file_filename,
:file_size => file_size,
:file_mime => file_mimetype,
:file_data => ''
}
if @db
upload_id = RSence.session_manager.new_upload_data( insert_hash )
else
@upload_id += 1
upload_id = @upload_id
@upload_slots[:rsence_uploads] = {} unless @upload_slots.has_key?(:rsence_uploads)
@upload_slots[:rsence_uploads][upload_id] = insert_hash
end
if not @upload_slots[:uploaded].has_key?(ticket_id)
@upload_slots[:uploaded][ticket_id] = []
end
@upload_slots[:uploaded][ticket_id].push( upload_id )
update_hash = {
:file_data => file_data[:tempfile].read,
:upload_done => true
}
if @db
RSence.session_manager.set_upload_data( upload_id, update_hash[:file_data] )
else
@upload_slots[:rsence_uploads][upload_id].merge!( update_hash )
end
end
end
response_body = %{<html><head><script>parent.HVM.values[#{value_id.to_json}].set(#{done_value.to_json});</script></head></html>}
response.status = 200
response['Content-Type'] = 'text/html; charset=UTF-8'
response['Content-Length'] = response_body.bytesize.to_s
response.body = response_body
end
def get_uploads( ticket_id, with_data=false )
uploads = []
if @upload_slots[:uploaded].has_key?(ticket_id)
@upload_slots[:uploaded][ticket_id].each do |row_id|
if with_data
if @db
row_data = RSence.session_manager.get_upload_data( row_id )
else
row_data = @upload_slots[:rsence_uploads][row_id].first
end
unless row_data.nil?
row_hash = {
:date => Time.at(row_data[:upload_date]),
:done => row_data[:upload_done],
:size => row_data[:file_size],
:mime => row_data[:file_mime],
:name => row_data[:file_name],
:data => row_data[:file_data].to_s
}
uploads.push(row_hash)
end
else
if @db
row_data = RSence.session_manager.get_upload_meta( row_id )
else
row_data = @upload_slots[:rsence_uploads][row_id].first
end
unless row_data.nil?
row_hash = {
:date => Time.at(row_data[:upload_date]),
:done => row_data[:upload_done],
:size => row_data[:file_size],
:mime => row_data[:file_mime],
:name => row_data[:file_name],
:data => nil
}
uploads.push(row_hash)
end
end
end
end
return uploads
end
def del_upload( ticket_id, row_id )
@upload_slots[:uploaded][ticket_id].delete(row_id)
if @db
RSence.session_manager.del_upload( row_id )
else
@upload_slots[:rsence_uploads].delete(row_id)
end
end
# removes uploaded files
def del_uploads( ticket_id, ses_id=false )
if ses_id and @upload_slots[:ses_ids].has_key?( ses_id )
if @upload_slots[:ses_ids][ses_id].include?( ticket_id )
@upload_slots[:ses_ids][ses_id].delete( ticket_id )
end
end
if @upload_slots[:uploaded].has_key?( ticket_id )
@upload_slots[:uploaded][ticket_id].each do |row_id|
@upload_slots[:uploaded][ticket_id].delete( row_id )
if @db
RSence.session_manager.del_upload( row_id )
else
@upload_slots[:rsence_uploads].delete(row_id)
end
end
@upload_slots[:uploaded].delete( ticket_id )
end
if @upload_slots[:by_id].has_key?( ticket_id )
@upload_slots[:by_id].delete( ticket_id )
end
if @db
RSence.session_manager.del_uploads( ticket_id, ses_id )
end
end
def upload_key(msg,value_key,max_size=1000000,mime_allow=/(.*?)\/(.*?)/,allow_multi=true)
key = @randgen.gen
while @upload_slots[:by_id].has_key?(key)
key = @randgen.gen
end
@upload_slots[:by_id][key] = [mime_allow,max_size,msg.ses_id,value_key,allow_multi]
@upload_slots[:uploaded][key] = []
@upload_slots[:ses_ids][msg.ses_id] = [] unless @upload_slots[:ses_ids].has_key?(msg.ses_id)
@upload_slots[:ses_ids][msg.ses_id].push( key )
return "0:::#{key}"
end
end
end
|
require 'json'
require 'rest-client'
require 'net/http'
require_relative 'lib/CityPick.rb'
def show_message(message)
puts message
end
def get_input
gets.chomp
end
def get_choice
gets.to_i
end
def generate_json(city)
city_url = "http://api.flickr.com/services/rest/?format=json&nojsoncallback=1&method=flickr.photos.search&tags=#{city}&tag_mode=all&api_key=62ed9b3c3446bd0e761414b999310390"
city_resp = Net::HTTP.get_response(URI.parse(city_url))
city_data = city_resp.body
city_ruby = JSON.parse(city_data)
city = CityPick.new(city, city_ruby['photos']['total'])
city.tag_count.to_i
end
def evaluate_destination(city1, city2, profile)
#Method will return 1 for city1, 2 for city2
#Value is decided based on whether user likes bustling spots and quieter spots
#Number of pics that is returned from Flickr API determines whether city is highly photographed, i.e. highly visited or not
if profile == 1 && city1 > city2
1
elsif profile == 1 && city1 < city2
2
elsif profile == 2 && city1 > city2
2
elsif profile == 2 && city1 < city2
1
end
end
show_message("It's Flickr Time! Let's use shutterbug stats to choose a vacation spot")
show_message("Let's figure out your style. Enter 1 if you like bustling spots or Enter 2 if you like quieter spots:")
user_type = get_choice
show_message("Cool. Now enter your first city pick:")
first_city = get_input
show_message("Now enter your second city pick:")
second_city = get_input
city_choice = evaluate_destination(generate_json(first_city), generate_json(second_city), user_type)
puts "Your next city should be " + (city_choice == 1 ? first_city : second_city)
puts "Goodbye!"
puts "Thank you for using Shutterbug!"
|
# 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)
Flower.create(name: "Daisy", smokeable: false, price: 2)
Flower.create(name: "Poppy", smokeable: true, price: 10)
|
require 'rubygems'
require 'ruby-growl'
require 'open-uri'
require 'json'
require 'yaml'
module RcrNotify
class Notifier
attr_reader :settings, :last_projects
def initialize
@settings = {:interval => 30}
@growl = Growl.new "localhost", "run>code>run notifier", %w(success failure)
end
def poll
data = JSON::parse open(url).read
print '.'
projects = data["user"]["projects"].inject({}) do |hash, project|
hash.merge project.delete("name") => project
end
if last_projects
projects.each do |name, this_time|
notify_for name, last_projects[name], this_time if notify_for? name
end
end
@last_projects = projects
rescue
print 'o'
end
private
def notify_for?(name)
if settings[:blacklist]
!settings[:blacklist].include? name
elsif settings[:whitelist]
settings[:whitelist].include? name
else
true
end
end
def notify_for(name, last_time, this_time)
return if this_time['commit'] == last_time['commit']
commit_message = "#{this_time['commit_message']}\n" +
"\t\t—#{this_time['author_name']}"
title = if success?(this_time)
success?(last_time) ? 'success' : 'fixed'
else
success?(last_time) ? 'broken' : 'still broken'
end
notify "#{name} build #{title}", commit_message, success?(this_time)
end
def success?(hash)
hash && hash["status"] == "success"
end
def url
"http://runcoderun.com/api/v1/json/#{settings[:username]}"
end
def notify(title, body, success)
type = success ? 'success' : 'failure'
puts "\n\n#{title} (#{type})\n#{body}\n\n"
@growl.notify type, title, body
end
end
end
|
require 'rubygems'
require 'time'
class BusRoute
def initialize(route_file)
@route_file = route_file
end
def get_actual_duration
read_file
return nil unless actual_times_posted?
times = @actual_times.values.sort!
duration = (times.last - times.first)/60.0
end
def get_expected_duration
read_file
times = @expected_times.values.sort!
duration = (times.last - times.first)/60.0
end
def calculate_average_delay
read_file
return nil unless actual_times_posted?
avg_time = @delays.values.inject(0) { |sum,n| sum += n }.to_f / @delays.length
end
def find_stop_with_longest_delay
read_file
return nil unless actual_times_posted?
@delays.sort_by{|k,v| v}.last[0]
end
def find_length_of_longest_delay
read_file
return nil unless actual_times_posted?
@delays.sort_by{|k,v| v}.last[1]
end
private
def read_file
set_instance_variable_hashes
process_file if @expected_times.empty?
end
def set_instance_variable_hashes
@expected_times ||= Hash.new
@actual_times ||= Hash.new
@delays ||= Hash.new
end
def process_file
file = File.open(@route_file)
file.each_line do |line|
stop, expected, actual = line.split(",")
expected_numeric = convert_to_numeric(expected)
actual_numeric = convert_to_numeric(actual)
@expected_times[stop] = expected_numeric
unless actual_numeric.nil?
@actual_times[stop] = actual_numeric
@delays[stop] = (actual_numeric - expected_numeric)/60.0
end
end
end
def convert_to_numeric(value)
return nil if value.nil?
Time.parse(value.chomp).to_i
end
def actual_times_posted?
!@actual_times.empty?
# !@actual_times.nil? && !@actual_times.empty? ## really only needed if I didn't trust myself to read_file first
end
end |
class RecipesController < ApplicationController
skip_before_action :require_login, only: [:index, :show]
before_action :find_recipe, except: [:index, :new, :create]
before_action :correct_user, only: [:edit, :update, :destroy]
def index
@recipes = Recipe.all
end
def show
end
def new
@recipe = Recipe.new
@recipe.instructions.build
@recipe.ingridients.build
end
def create
@recipe = Recipe.create(recipe_params)
@recipe.user = current_user
if @recipe.save
redirect_to root_path
else
render :new
end
end
def edit
end
def update
if @recipe.update(recipe_params)
redirect_to @recipe
else
render :edit
end
end
def destroy
if @recipe.destroy
redirect_to root_path
else
render @recipe
end
end
private
def recipe_params
params.require(:recipe).permit(:title, :description,
instructions_attributes: [:id, :order, :instruction_info, :_destroy],
ingridients_attributes: [:id, :name, :_destroy])
end
def find_recipe
@recipe = Recipe.find(params[:id])
end
def correct_user
unless user_equals?(@recipe.user)
flash[:danger] = 'You dont have permission!'
redirect_to root_path and return
end
end
end
|
#
# Be sure to run `pod spec lint PYData.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
s.name = "PYData"
s.version = "1.0.1"
s.summary = "A data cache written in Objective-C"
s.description = <<-DESC
A data cache written in Objective-C.
I use sqlite as the persistence layer, and a LRU in-mem cache to store
most used data.
Any object implements protocol NSCoding can be put into this cache.
DESC
s.homepage = "https://github.com/littlepush/PYData"
s.license = { :type => "LGPLv3", :file => "LICENSE" }
s.author = { "Push Chen" => "littlepush@gmail.com" }
s.social_media_url = "https://github.com/littlepush"
s.platform = :ios, "8.0"
s.source = { :git => "https://github.com/littlepush/PYData.git", :tag => "1.0.1" }
s.source_files = "static-library/*.{h,m}"
s.library = "sqlite3"
s.requires_arc = true
s.dependency "PYCore"
end
|
class ConsultantExamProcessController < ApplicationController
skip_load_and_authorize_resource
before_action :set_and_authorize, except: [:show]
def show
@title = _('Consultant Exam')
end
def results
@title = _('Consultant Exam Review')
end
private
def set_and_authorize
@user = current_user
return authorize! :take_exam, @user if action_name == 'update'
end
end
|
Gem::Specification.new do |s|
s.name = 'acos_jekyll_openapi_helper'
s.version = '1.4.5'
s.date = '2019-05-28'
s.summary = "Open API json file helper"
s.description = "A gem to generate page entries for jekyll sites"
s.authors = ["Acos AS"]
s.email = 'utvikling@acos.no'
s.files = ["lib/acos_jekyll_openapi.rb", "bin/start.rb"]
s.homepage =
'https://rubygems.org/gems/acos_jekyll_openapi_helper'
s.license = 'MIT'
s.add_dependency "json", "~> 2.2"
s.require_path = "lib"
end |
class AddNameToCredentials < ActiveRecord::Migration[5.1]
def change
add_column :credentials, :name, :string
add_index :credentials, :name
end
end
|
require './lib/mail/version'
Gem::Specification.new do |s|
s.name = "mail"
s.version = Mail::VERSION::STRING
s.author = "Mikel Lindsaar"
s.email = "raasdnil@gmail.com"
s.homepage = "https://github.com/mikel/mail"
s.description = "A really Ruby Mail handler."
s.summary = "Mail provides a nice Ruby DSL for making, sending and reading emails."
s.license = "MIT"
s.has_rdoc = true
s.extra_rdoc_files = ["README.md", "CONTRIBUTING.md", "CHANGELOG.rdoc", "TODO.rdoc"]
s.rdoc_options << '--exclude' << 'lib/mail/values/unicode_tables.dat'
s.add_dependency('mime-types', [">= 1.16", "< 3"])
s.add_development_dependency('bundler', '>= 1.0.3')
s.add_development_dependency('rake', '> 0.8.7')
s.add_development_dependency('rspec', '~> 3.0')
s.add_development_dependency('rdoc')
s.files = %w(README.md MIT-LICENSE CONTRIBUTING.md CHANGELOG.rdoc Dependencies.txt Gemfile Rakefile TODO.rdoc) + Dir.glob("lib/**/*")
end
|
class Api::V1::ApplicationController < ApplicationController
before_action :authorize_request
# NOTE: attr_accessorとbefore_actionの相性が悪いため
# setterはインスタンス変数を使用
attr_reader :current_user
protected
def authorize_request
token = request.headers["Authorization"]&.split(" ")&.last
return render json: { errors: "No token" }, status: :unauthorized unless token
payload = JsonWebToken.decode(token)
return render json: { errors: "Invalid token" }, status: :unauthorized unless payload
@current_user = User.find_by(uid: payload[:user_id])
return render json: { errors: "Record not found" }, status: :unauthorized unless @current_user
end
end
|
require 'csv'
namespace :csv_worker do
desc 'Populate customer data from the CSV to the database customer table.'
task populate_customer: :environment do
puts "Populating the customer database table"
file = File.read("#{Rails.root}/customer_test.csv")
csv = CSV.parse(file, headers: true)
# will run the csv object and populate the database
csv.each do |row|
row.to_hash
data_generate(row)
# or you can also use this one
# see below for the reference
# another_data_generate(row)
end
puts '\n'
puts '-'*10
puts 'Completed'
end
private
def data_generate(row)
begin
Customer.create!(
name: row['name'],
first_name: row['first_name'],
phone: row['phone'],
address_street: row['address_street'],
address_zipcode: row['address_zipcode'],
address_city: row['address_city'],
address_country: row['address_country'],
bank_account_no: row['bank_account_no'],
bank_name: format_date(row['bank_name']),
email: row['email']
)
rescue => exception
raise ActiveRecord::Rollback, "There are errors -> #{exception.message}"
end
end
def another_data_generate(row)
@customer = Customer.new
ActiveRecord::Base.transaction do
@customer.assign_attirbutes({
name: row['name'],
first_name: row['first_name'],
phone: row['phone'],
address_street: row['address_street'],
address_zipcode: row['address_zipcode'],
address_city: row['address_city'],
address_country: row['address_country'],
bank_account_no: row['bank_account_no'],
bank_name: format_date(row['bank_name']),
email: row['email']
})
# if not save
unless @customer.save!
raise ActiveRecord::Rollback, @cutomer.errors.full_messages
else
p '.'
end
end
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'Can submit adoption application', type: :feature do
before(:each) do
visit "/pets/#{@pet1.id}"
click_on('Favorite This Pet')
visit "/pets/#{@pet2.id}"
click_on('Favorite This Pet')
end
it 'After favoriting pets can view application form to adopt' do
visit '/favorites'
click_link('Adopt Favorited Pets')
expect(current_path).to eq('/applications/new')
end
it 'I can select multiple favorited pet to adopt by filling in application like this' do
visit '/applications/new'
expect(page).to have_css("#checkbox-#{@pet1.id}")
expect(page).to have_css("#checkbox-#{@pet2.id}")
expect(page).to_not have_css("#checkbox-#{@pet3.id}")
expect(page).to_not have_css("#checkbox-#{@pet3.id}")
end
it 'can fill in info and be redirected to favorites page with flash message and no longer see pets that have been applied for' do
visit '/applications/new'
find("#checkbox-#{@pet2.id}").set(true)
fill_in :name, with: 'Test Address'
fill_in :address, with: 'Test Address'
fill_in :city, with: 'Test City'
fill_in :state, with: 'Test State'
fill_in :zip, with: 'Test Zip'
fill_in :phone_number, with: 'Test Number '
fill_in :description, with: 'Test Description'
click_button 'Submit'
expect(current_path).to eq('/favorites')
expect(page).to have_content('Your application for the selected pets has been submitted.')
expect(page).to_not have_content(@pet2.shelter)
expect(page).to have_content(@pet1.sex)
end
end
|
require 'feature_helper'
feature 'Signup', js: true do
given(:user) { User.last }
Steps 'a new user signs up' do
When 'I visit the homepage' do
visit '/'
end
Then 'I should see links meant for a non-authenticated user' do
within '.nav' do
should_see 'Login'
should_see 'Signup'
should_not_see 'Offers'
should_not_see 'Trade Requests'
should_not_see 'Account'
end
end
When 'I click the Signup link' do
within '.nav' do
click_link 'Signup'
end
end
Then 'I should be on the sign up page' do
within '.content' do
should_see 'Signup'
should_see 'Password * (6 characters minimum)'
should_see 'Password Confirmation *'
end
end
When 'I submit the form' do
click_button 'Signup'
end
Then 'I should see validation errors' do
within '.content' do
within '.field[data-field-for="email"]' do
should_see "can't be blank"
end
within '.field[data-field-for="username"]' do
should_see "can't be blank"
end
within '.field[data-field-for="password"]' do
should_see "can't be blank"
end
within '.field[data-field-for="password_confirmation"]' do
should_see "can't be blank"
end
within '.field[data-field-for="terms_and_conditions"]' do
should_see 'must be accepted'
end
end
end
When 'I fill out and submit the form' do
fill_in :user_email, with: 'test@example.com'
fill_in :user_username, with: 'John Doe'
fill_in :user_password, with: '123456'
fill_in :user_password_confirmation, with: '123456'
end
And 'I submit the form' do
click_button 'Signup'
end
And 'I enter in a valid username' do
fill_in :user_username, with: 'JohnDoe'
end
And 'I submit the form' do
click_button 'Signup'
end
Then 'I should see validation errors' do
within '.field[data-field-for="email"]' do
should_not_see "can't be blank"
end
within '.field[data-field-for="username"]' do
should_not_see "can't be blank"
end
within '.field[data-field-for="password"]' do
should_not_see "can't be blank"
end
within '.field[data-field-for="password_confirmation"]' do
should_not_see "can't be blank"
end
within '.field[data-field-for="terms_and_conditions"]' do
should_see 'must be accepted'
end
end
When 'I accept the terms and conditions and re-enter the password' do
check 'I accept the terms and conditions *'
fill_in :user_password, with: '123456'
fill_in :user_password_confirmation, with: '123456'
end
And 'I submit the form' do
click_button 'Signup'
end
Then 'I should see a message about checking my email' do
should_see 'A message with a confirmation link has been sent to your email address. Please follow the link to activate your account.'
end
And 'I should not be logged in' do
within '.nav' do
should_see 'Login'
should_see 'Signup'
should_not_see 'Offers'
should_not_see 'Trade Requests'
should_not_see 'Account'
end
end
And 'The user should be created' do
expect(user).to be_present
expect(user.username).to eq 'JohnDoe'
expect(user.currency).to eq 'usd'
end
When 'I visit the link' do
visit "/u/confirmation?confirmation_token=#{user.confirmation_token}"
end
Then 'I should see a success message' do
should_see 'Your email address has been successfully confirmed.'
end
And 'I should not be logged in' do
within '.nav' do
should_see 'Login'
should_see 'Signup'
should_not_see 'Offers'
should_not_see 'Trade Requests'
should_not_see 'Account'
end
end
When 'I log in' do
fill_in :user_username, with: 'JohnDoe'
fill_in :user_password, with: '123456'
click_button 'Login'
end
Then 'I see the success message' do
should_see 'Signed in successfully.'
end
And 'I should see links meant for an internal account' do
within '.nav' do
should_not_see 'Login'
should_not_see 'Signup'
should_see 'Offers'
should_see 'Trade Requests'
should_see 'Account'
end
end
end
Steps 'a new user signs up but has to resend the confirmation email' do
When 'I visit the signup page' do
visit '/signup'
end
When 'I fill out and submit the form' do
fill_in :user_email, with: 'test@example.com'
fill_in :user_username, with: 'JohnDoe'
fill_in :user_password, with: '123456'
fill_in :user_password_confirmation, with: '123456'
check 'I accept the terms and conditions *'
end
And 'I submit the form' do
click_button 'Signup'
end
Then 'I should see a message about checking my email' do
should_see 'A message with a confirmation link has been sent to your email address. Please follow the link to activate your account.'
end
When 'I go to the login page' do
visit '/login'
end
And 'I try to act like I did not receive an email' do
click_link "Didn't receive confirmation instructions?"
end
Then 'I should see the resend confirmation page' do
within 'h1' do
should_see 'Resend confirmation instructions'
end
end
When 'I enter in my username' do
fill_in :user_username, with: 'JohnDoe'
end
And 'I submit the form' do
click_button 'Resend confirmation instructions'
end
Then 'I should see a success message' do
should_see 'You will receive an email with instructions for how to confirm your email address in a few minutes.'
end
When 'I visit the link' do
visit "/u/confirmation?confirmation_token=#{user.reload.confirmation_token}"
end
Then 'I should see a success message' do
should_see 'Your email address has been successfully confirmed.'
end
When 'I log in' do
fill_in :user_username, with: 'JohnDoe'
fill_in :user_password, with: '123456'
click_button 'Login'
end
Then 'I see the success message' do
should_see 'Signed in successfully.'
end
end
Steps 'invalid usernames' do
When 'I visit the signup page' do
visit '/signup'
end
And 'I enter in an invalid username' do
fill_in :user_username, with: 'John Doe'
end
And 'I click submit' do
click_button 'Signup'
end
Then 'I should see an error' do
should_see 'is invalid'
end
When 'I fill out and submit the form' do
fill_in :user_email, with: 'test@example.com'
fill_in :user_username, with: 'JohnDoe'
fill_in :user_password, with: '123456'
fill_in :user_password_confirmation, with: '123456'
check 'I accept the terms and conditions *'
click_button 'Signup'
end
Then 'I should see a message about checking my email' do
should_see 'A message with a confirmation link has been sent to your email address. Please follow the link to activate your account.'
end
end
context 'restricted usernames' do
Steps 'restricted username dashous' do
When 'I visit the signup page' do
visit '/signup'
end
And 'I enter in an invalid username' do
fill_in :user_username, with: 'dashous'
end
And 'I click submit' do
click_button 'Signup'
end
Then 'I should see an error' do
within '.field[data-field-for="username"]' do
should_see 'is reserved'
end
end
end
Steps 'restricted username Dashous' do
When 'I visit the signup page' do
visit '/signup'
end
And 'I enter in an invalid username' do
fill_in :user_username, with: 'Dashous'
end
And 'I click submit' do
click_button 'Signup'
end
Then 'I should see an error' do
within '.field[data-field-for="username"]' do
should_see 'is reserved'
end
end
end
Steps 'restricted username DASHOUS' do
When 'I visit the signup page' do
visit '/signup'
end
And 'I enter in an invalid username' do
fill_in :user_username, with: 'DASHOUS'
end
And 'I click submit' do
click_button 'Signup'
end
Then 'I should see an error' do
within '.field[data-field-for="username"]' do
should_see 'is reserved'
end
end
end
Steps 'restricted username dash' do
When 'I visit the signup page' do
visit '/signup'
end
And 'I enter in an invalid username' do
fill_in :user_username, with: 'dash'
end
And 'I click submit' do
click_button 'Signup'
end
Then 'I should see an error' do
within '.field[data-field-for="username"]' do
should_see 'is reserved'
end
end
end
end
Steps 'non-matching passwords' do
When 'I visit the signup page' do
visit '/signup'
end
And 'I enter in an invalid username' do
fill_in :user_username, with: 'John Doe'
end
When 'I fill out and submit the form' do
fill_in :user_email, with: 'test@example.com'
fill_in :user_username, with: 'JohnDoe'
fill_in :user_password, with: '123456'
fill_in :user_password_confirmation, with: '654321'
check 'I accept the terms and conditions *'
click_button 'Signup'
end
Then 'I should see an error' do
should_see "doesn't match Password"
should_not_see 'A message with a confirmation link has been sent to your email address. Please follow the link to activate your account.'
end
When 'I fill out and submit the form' do
fill_in :user_password, with: '123456'
fill_in :user_password_confirmation, with: '123456'
click_button 'Signup'
end
Then 'I should see a message about checking my email' do
should_see 'A message with a confirmation link has been sent to your email address. Please follow the link to activate your account.'
end
end
end
|
require 'rails_helper'
RSpec.describe 'admin - recommendation requests' do
include_context 'logged in as admin'
example 'index page' do
with_no_req = create_account(:eligible)
with_resolved_req = create_account(:eligible)
solo_with_req = create_account(:eligible)
couples_with_owner_req = create_account(:couples, :eligible)
couples_with_comp_req = create_account(:couples, :eligible)
couples_with_two_reqs = create_account(:couples, :eligible)
create_recommendation_request('owner', with_resolved_req)
complete_recs(with_resolved_req.owner)
create_recommendation_request('owner', solo_with_req)
create_recommendation_request('owner', couples_with_owner_req)
create_recommendation_request('companion', couples_with_comp_req)
create_recommendation_request('both', couples_with_two_reqs)
visit admin_recommendation_requests_path
expect(page).to have_content solo_with_req.email
expect(page).to have_content couples_with_owner_req.email
expect(page).to have_content couples_with_comp_req.email
expect(page).to have_content couples_with_two_reqs.email
expect(page).to have_no_content with_no_req.email
expect(page).to have_no_content with_resolved_req.email
end
end
|
#Encoding.default_external = "utf-8"
http_path = "/"
css_dir = "css"
css_path = "css"
sass_dir = "sass"
fonts_dir = "fonts"
javascripts_dir = "js"
images_dir = "img"
line_comments = false
output_style = :expanded
#:compressed :expanded
# This line tells compass to look at the Upbase styles in your bower_components dir
add_import_path "bower_components/Upbase/components"
# Add Autoprefixer Support
# https://github.com/ai/autoprefixer#usage
require 'autoprefixer-rails'
on_stylesheet_saved do |file|
css = File.read(file)
File.open(file, 'w') do |io|
io << AutoprefixerRails.process(css)
end
end
|
module Pushr
module Daemon
module WnsSupport
class ConnectionManager
attr_accessor :name
def initialize(app_name, access_token, i)
@pool = {}
@app_name = app_name
@access_token = access_token
@i = i
@name = "#{app_name}: ConnectionWns #{i}"
end
def get(uri)
key = "#{uri.scheme}://#{uri.host}"
unless @pool.key? key
@pool[key] = ConnectionWns.new(@app_name, @access_token, @i)
end
@pool[key]
end
def write(message)
uri = URI.parse(message.channel_uri)
connection = get(uri)
connection.write(message)
end
def size
@pool.size
end
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)
Doctor.destroy_all
User.destroy_all
Appointment.destroy_all
AppointmentType.destroy_all
doctors = [
{name: 'Doctor Who', speciality: 'cardiovascular', post_code: 'SE1P 4EW'},
{name: 'Doctor Strange', speciality: 'allergies', post_code: 'N1 2HL'},
{name: 'Doctor Smith', speciality: 'forensics', post_code: 'E1 6SE'},
{name: 'Doctor Lisa', speciality: 'cardiovascular', post_code: 'NW8 9LB'},
{name: 'Doctor Luke', speciality: 'neurology', post_code: 'NE47 6DT'},
{name: 'Doctor Stone', speciality: 'biochemical genetics', post_code: 'NW9 5GR'},
{name: 'Doctor Sasha', speciality: 'dermatology', post_code: 'SW19 8RF'},
{name: 'Doctor John', speciality: 'forensics', post_code: 'SE15 5HD'},
{name: 'Doctor Jules', speciality: 'radiology', post_code: 'SW17 0NP'}
]
doctors.each {|doctor| Doctor. create(doctor)}
users = [
{username: 'ljiscool', password: 'ilovecake', name: 'Louis Jackson', birth_date: "2002-10-02", gender: 'male', allergies: 'ibuprofen'},
{username: 'rdawson', password: 'dawsonr', name: 'Ronald Dawson', birth_date: "1983-02-17", gender: 'male', allergies: 'nuts'},
{username: 'alessa', password: '2cool4school', name: 'Alessandra Lake', birth_date: "1964-12-26", gender: 'female', allergies: ''},
]
users.each {|user| User. create(user)}
appointments = [
{doctor_id: 2, user_id: 1, appointment_type_id: 1, note: "Diagnosis: Mild Flu and Chest Infection", appointment_date: "2018-10-22"},
{doctor_id: 4, user_id: 2, appointment_type_id: 2, note: "Vaccine: MMR", appointment_date: "2017-09-18"},
{doctor_id: 6, user_id: 3, appointment_type_id: 1, note: "Diagnosis: Period cramp and pain in lower back", appointment_date: "2018-03-05"},
{doctor_id: 3, user_id: 2, appointment_type_id: 3, note: "Emergency: Displaced shoulder", appointment_date: "2014-11-28"},
{doctor_id: 6, user_id: 1, appointment_type_id: 1, note: "Diagnosis: Twisted ankle", appointment_date: "2017-08-09"},
{doctor_id: 4, user_id: 3, appointment_type_id: 3, note: "Emergency: Asthma attack due to nut allergic reaction", appointment_date: "2016-04-18"},
{doctor_id: 5, user_id: 1, appointment_type_id: 1, note: "Diagnosis: Mild UTI", appointment_date: "2018-04-15"},
{doctor_id: 1, user_id: 2, appointment_type_id: 2, note: "Vaccine: Chickenpox", appointment_date: "2017-06-02"},
{doctor_id: 9, user_id: 3, appointment_type_id: 2, note: "Vaccine: Flu", appointment_date: "2018-03-27"},
{doctor_id: 3, user_id: 2, appointment_type_id: 1, note: "Diagnosis: Nausea and dizziness due to low blood pressure", appointment_date: "2018-05-08"}
]
appointments.each {|appointment| Appointment. create(appointment)}
appointment_types = [
{name: 'General Check-up'},
{name: 'Vaccination'},
{name: 'Emergency'}
]
appointment_types.each {|appointment_type| AppointmentType. create(appointment_type)}
|
require 'rails_helper'
describe Employee do
let(:employee) { create(:employee) }
describe 'has associations for' do
it 'many teams' do
expect { employee.teams }.to_not raise_error
end
it 'many owned teams' do
expect { employee.owned_teams }.to_not raise_error
end
it 'many progress reports' do
expect { employee.progress_reports }.to_not raise_error
end
end
end
|
class ClientUser
include UserHelper::GeneralUser
attr_accessor :login_id, :password, :id, :client_id
def initialize(isp_client)
self.login_id = isp_client.username
self.password = isp_client.passwort
self.client_id = isp_client.client_id
self.id = isp_client.id
end
# copied from ActiveRecord
def persisted?
!(self.id.nil?)
end
# copied from ActiveRecord
def new_record?
!persisted?
end
def set_id(id)
@id = id
end
def is_admin?
false
end
def user_type
UserHelper::CLIENT_TYPE
end
end
|
=begin
* ****************************************************************************
* BRSE-SCHOOL
* HELPER - AlbumsHelper
*
* 処理概要 :
* 作成日 : 2017/08/31
* 作成者 : daonx – daonx@ans-asia.com
*
* 更新日 :
* 更新者 :
* 更新内容 :
*
* @package : HELPER
* @copyright : Copyright (c) ANS-ASIA
* @version : 1.0.0
* ****************************************************************************
=end
require 'fileutils'
module Admin
module AlbumsHelper
class AlbumsHlp
include ApplicationHelper #app/helpers/application_helper.rb
###
# get data of table album
# -----------------------------------------------
# @author : daonx - 2017/08/31 - create
# @param : null
# @return : null
# @access : public
# @see : remark
###
def self.getAlbums
return Album.where(deleted_at: nil)
.select('
id,
img,
thumb
').order(id: :DESC)
end
###
# save photos user upload
# -----------------------------------------------
# @author : quypn - 2017/09/12 - create
# @param : photos - list info file image neeed to save
# @return : null
# @access : public
# @see : remark
###
def self.savePhotos(photos)
result = Hash.new
result['status'] = true
image = Hash.new
thumb = Hash.new
begin
ActiveRecord::Base.transaction do
photos.each do |item|
file_type = item['name'].split('.').last
# info file image
linkImage = '/images/event/album/image/'
new_name_file_image = Time.now.to_i
new_name_file_image_with_type = "#{new_name_file_image}_" + item['id'] + "." + file_type
imageTemp = linkImage + new_name_file_image_with_type
image.store(imageTemp,item['data'])
# info file thumb
linkThumb = '/images/event/album/thumb/'
new_name_file_thumb = Time.now.to_i
new_name_file_thumb_with_type = "#{new_name_file_thumb}_" + item['id'] + "." + file_type
thumbTemp = linkThumb + new_name_file_thumb_with_type
thumb.store(thumbTemp,item['thumb'])
# save to DB
id = Helper.getID('albums')
Album.create(
id: id,
img: imageTemp,
thumb: thumbTemp,
created_by: $user_id
)
end
end
rescue
result['status'] = false
result['error'] = "#{$!}"
# Roll back
raise ActiveRecord::Rollback
ensure
if result['status']
if image.present?
image.each do |index,item|
# save image
File.open('public' + index, "wb") do |f|
f.write(Base64.decode64(item.split(';base64,').last))
end
end
end
if thumb.present?
thumb.each do |index,item|
# save thumnail
File.open('public' + index, "wb") do |f|
f.write(Base64.decode64(item.split(';base64,').last))
end
end
end
end
return result
end
end
###
# delete photos
# -----------------------------------------------
# @author : quypn - 2017/09/12 - create
# @param : ids - list id of photo need to delete
# @return : null
# @access : public
# @see : remark
###
def self.deleteAlbum(ids)
result = Hash.new
result['status'] = true
begin
ActiveRecord::Base.transaction do
ids.each do |id|
update = Album.where(:id => id)
.update_all(
deleted_by: $user_id,
deleted_at: Time.now
)
end
end
rescue
result['status'] = false
result['error'] = "#{$!}"
# Roll back
raise ActiveRecord::Rollback
ensure
if result['status']
ids.each do |id|
photo = Album.find_by(id: id)
checkIssetImage = Album.where(img: photo['img'], deleted_at: nil).where.not(id: id).first
if checkIssetImage == nil
begin
FileUtils.rm('public' + photo['img'])
rescue
end
end
checkIssetThumb = Album.where(thumb: photo['thumb'], deleted_at: nil).where.not(id: id).first
if checkIssetThumb == nil
begin
FileUtils.rm('public' + photo['thumb'])
rescue
end
end
end
end
return result
end
end
end
end
end |
module WizardOfAwes
module ViewHelpers
# ==== Options
# * <tt>:slug</tt> - Which snippet to look up. Defaults to the current_page slug
def woa_snippet(*slug)
s = slug.present? ? slug : request.fullpath
snippet = HelperSnippet.find_by_slug(s)
if snippet
woa_markdown(snippet)
else
"No Snippet Found"
end
end
def woa_markdown(snippet)
snippet.body
end
end
end
|
require 'spec_helper'
describe SysActionOnTablesController do
describe "GET 'index'" do
it "be OK" do
p = FactoryGirl.create(:sys_action_on_table)
get 'index'
response.should be_success
assigns(:sys_action_on_tables).should eq([p])
end
end
describe "GET 'new'" do
it "be OK" do
p = FactoryGirl.attributes_for(:sys_action_on_table)
get 'new'
response.should be_success
end
end
describe "GET 'create'" do
it "be OK" do
p = FactoryGirl.attributes_for(:sys_action_on_table)
lambda do
get 'create', :sys_action_on_table => p
response.should redirect_to sys_action_on_tables_path
end.should change(SysActionOnTable, :count).by(1)
end
it "should reject nil action" do
p = FactoryGirl.attributes_for(:sys_action_on_table, :action => nil)
lambda do
get 'create', :sys_action_on_table => p
response.should render_template("new")
end.should change(SysActionOnTable, :count).by(0)
end
end
describe "GET 'edit'" do
it "returns http success" do
p = FactoryGirl.create(:sys_action_on_table)
get 'edit', :id => p.id
response.should be_success
end
end
describe "GET 'update'" do
it "be OK" do
p = FactoryGirl.create(:sys_action_on_table)
get 'update', :id => p.id, :sys_action_on_table => {:action => 'a new action'}
response.should redirect_to sys_action_on_tables_path
end
it "should reject nil table name" do
p = FactoryGirl.create(:sys_action_on_table)
get 'update', :id => p.id, :sys_action_on_table => {:table_name => ''}
response.should render_template('edit')
end
end
describe "GET 'destroy'" do
it "be success" do
p = FactoryGirl.create(:sys_action_on_table)
get 'destroy', :id => p.id
response.should redirect_to sys_action_on_tables_path
end
end
end
|
class AddTagIdToRole < ActiveRecord::Migration
def change
add_column :roles, :tag_id, :integer
end
end
|
module Meter
module Metric
class Histogram < Meter::Metric::Base
def type
:histogram
end
end
end
end
|
module Alf
module Operator
#
# Specialization of Operator for operators that simply convert single tuples
# to single tuples.
#
module Transform
include Unary
protected
# (see Operator#_each)
def _each
each_input_tuple do |tuple|
yield _tuple2tuple(tuple)
end
end
#
# Transforms an input tuple to an output tuple
#
def _tuple2tuple(tuple)
end
end # module Transform
end # module Operator
end # module Alf
|
class ChangeColumnAlergia1TypeFromFormularios < ActiveRecord::Migration[5.1]
def change
change_column :formularios, :alergia1, :string
end
end
|
require 'prawn_charts/layouts/layout'
module PrawnCharts
module Layouts
# Experimental, do not use.
class Sparkline < Layout
def define_layout
self.components << PrawnCharts::Components::Graphs.new(:sparkline, :position => [0, 0], :size => [100, 100])
end
end # SparkLine
end # Layouts
end # PrawnCharts |
require "./Board.rb"
require "./Pieces.rb"
require "./Game.rb"
describe Game do
subject(:game) {Game.new}
describe "#valid_and_occupied?" do
it "returns false if square is unoccupied" do
expect(game.valid_and_occupied?(:a4)).to eq false
end
it "returns false if square is out of bounds by rank" do
expect(game.valid_and_occupied?(:j4)).to eq false
end
it "returns false if square is out of bounds by file" do
expect(game.valid_and_occupied?(:a9)).to eq false
end
it "returns true if square is in bounds and valid" do
expect(game.valid_and_occupied?(:a2)).to eq true
end
end
describe "#valid_coord?" do
it "returns false if square is out of bounds by rank" do
expect(game.valid_coord?(:j4)).to eq false
end
it "returns false if square is out of bounds by file" do
expect(game.valid_coord?(:a9)).to eq false
end
it "returns true if square is in bounds" do
expect(game.valid_coord?(:a4)).to eq true
end
end
describe "#right_coloured_piece?" do
it "returns true on a white piece when the turn is white" do
expect(game.right_coloured_piece?(:white,:a2)).to eq true
end
it "returns false on a black piece when the turn is white" do
expect(game.right_coloured_piece?(:white,:h7)).to eq false
end
it "returns true on a black piece when the turn is black" do
expect(game.right_coloured_piece?(:black,:h7)).to eq true
end
it "returns false on a white piece when the turn is black" do
expect(game.right_coloured_piece?(:black,:a2)).to eq false
end
end
describe "#free_way?" do
it "returns false if there is a piece in the way" do
expect(game.free_way?(:d1,:d3)).to eq false
end
it "retruns true if there is not a piece in the way" do
game.board.move_piece(:g2,:g3)
expect(game.free_way?(:f1,:h3)).to eq true
end
it "returns true if the piece is a knight" do
expect(game.free_way?(:b1,:c3)).to eq true
end
end
end
|
class ProfilesController < ApplicationController
include ProfilesHelper
include CategoriesHelper
include ActsAsTaggableOn::TagsHelper
before_action :set_profile, only: [:show, :edit, :update, :destroy, :require_permission]
before_filter :require_permission, only: [:edit, :destroy, :update]
def index
if params[:topic]
@profiles = profiles_for_scope(params[:topic])
else
@profiles = profiles_for_index
end
@tags = ActsAsTaggableOn::Tag.most_used(100)
end
def category
@category = Category.find(params[:category_id])
@tags = @category.tags
if @tags.any?
@tag_names = @tags.pluck(:name)
@profiles = profiles_for_scope(@tag_names)
@published_tags = @profiles.map { |p| p.topics.pluck(:name) }.flatten.uniq
@tags = @tags.select { |t| @published_tags.include?(t.to_s) }
else
@profiles = profiles_for_index
redirect_to profiles_url, notice: ('No Tag for that Category found!')
end
end
def show
if @profile.published? || can_edit_profile?(current_profile, @profile)
@message = Message.new
@medialinks = @profile.medialinks.order(:position)
else
redirect_to profiles_url, notice: (I18n.t('flash.profiles.show_no_permission'))
end
end
# should reuse the devise view
def edit
build_missing_translations(@profile)
end
def update
if @profile.update_attributes(profile_params)
redirect_to @profile, notice: (I18n.t('flash.profiles.updated', profile_name: @profile.name_or_email))
elsif current_profile
build_missing_translations(@profile)
render action: 'edit'
end
end
def destroy
@profile.destroy
redirect_to profiles_url, notice: (I18n.t('flash.profiles.destroyed', profile_name: @profile.name_or_email))
end
def require_permission
return if can_edit_profile?(current_profile, @profile)
redirect_to profiles_url, notice: (I18n.t('flash.profiles.no_permission'))
end
def render_footer?
false
end
private
# Use callbacks to share common setup or constraints between actions.
def set_profile
@profile = Profile.friendly.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def profile_params
params.require(:profile).permit(
:email,
:password,
:password_confirmation,
:remember_me,
:city,
:languages,
:firstname,
:lastname,
:picture,
:twitter,
:remove_picture,
:talks,
:website,
:content,
:name,
:topic_list,
:media_url,
:medialinks,
:slug,
:admin_comment,
translations_attributes: [:id, :bio, :main_topic, :locale])
end
def profiles_for_index
Profile.is_published.order('created_at DESC').page(params[:page]).per(24)
end
def profiles_for_scope(tag_names)
Profile.is_published
.tagged_with(tag_names, any: true)
.order('created_at DESC')
.page(params[:page])
.per(24)
end
end
|
class CreateDataSources < ActiveRecord::Migration
def self.up
create_table :data_sources do |t|
t.string :title
t.string :description
t.string :logo_url
t.string :web_site_url
t.string :data_url
t.string :metadata_url
t.boolean :data_zip_compressed
t.integer :refresh_period_days, :default => 14
# t.string :rights
# t.string :citation
# t.string :endpoint_url
# t.string :data_uri
# t.references :uri_type, :nill => true
# t.references :response_format, :nill => true
# t.string :taxonomic_scope
# t.string :geospatial_scope_wkt
# t.boolean :in_gni
# t.date :created
# t.date :updated
t.timestamps
end
add_index :data_sources, [:data_url], :name => "index_data_sources_1", :unique => true
end
def self.down
remove_index :data_sources, :name => :index_data_sources_1
drop_table :data_sources
end
end
|
require 'pry'
class CashRegister
def initialize(*discount)
@total = 0
discount[0] ? @discount = discount[0] : @discount = 0
@items = []
end
attr_accessor :total, :discount, :title, :price, :quantity, :items
def total
@total
end
def add_item(title, price, *quantity)
if quantity[0]
@total += price * quantity[0]
quantity[0].times do
@items << title
end
else
@total += price
@items << title
end
@price = price
end
def apply_discount
if @discount == 0
"There is no discount to apply."
else
@total = @total.to_f - (@total.to_f * @discount.to_f/100.0)
"After the discount, the total comes to $#{@total.to_i}."
end
end
def items
@items
end
def void_last_transaction
@total -= @price
end
end
|
class AddPredecessorIdToCourse < ActiveRecord::Migration
def change
add_column :courses, :predecessor_id, :integer
end
end
|
$LOAD_PATH.unshift("#{File.expand_path(File.dirname(__FILE__))}/../../lib")
require "red_sky_test_case"
class TC_R001_01_GOOGLE_SEARCH < Test::Unit::TestCase
include RedSkyTestCase
def setup
# specify setup parameters
@certificate = :regular # this is the default user for this test
@initialBrowser = :none # if you want this test to navigate to your webapp automatically as part of setup, change this value to the value referring to your webapp
super # must call super so that the common setup method in RedSkyTestCase is called
end
def test_r001_01_google_search
############################################################################################
# PURPOSE :
# Verify that Google searches can be made
#
# PRECONDITIONS :
# None
############################################################################################
@help.ui_helper_test
# Step 1 :
# Open the Google Search page
google_login
# Expected Result :
# The RED SKY homepage is displayed
assert(googleSearch.displayed?, "The Google search page is not displayed")
# Step 3 :
# Enter in a search term and click the Search button.
term = "Ruby"
puts "Will now search for '#{term}'"
#googleSearch.search_term = term
@help.enter_google_term(term) # use @help to set the field, demonstrating that this can be done outside the test
googleSearch.click_search_button
# Expected Result :
# Results are displayed
assert(googleSearchResults.displayed?, "The Google search results page is not displayed")
puts googleSearchResults.result_stats
assert_not_nil(googleSearchResults.result_stats, "The Google search results page did not display any result-stats")
assert_not_empty(googleSearchResults.result_stats, "The Google search results page did not display any result-stats")
end
end
|
class AddLevelDefaultToQuizzes < ActiveRecord::Migration[5.2]
def change
change_column_default :quizzes, :level, to: 0
end
end
|
class ShortVisitsController < ApplicationController
before_filter :authorize
def show
@short_visit=ShortVisit.where(short_url_id:params[:short_url_id]).last(5)
end
end
|
class Class
def attr_accessor_with_history(attr_name)
attr_name = attr_name.to_s # make sure it's a string
attr_reader attr_name # create the attribute's getter
attr_reader attr_name+"_history" # create bar_history getter
class_eval {
# create a setter method named value of attr_name
define_method "#{attr_name}=" do |value|
# history is either already existing or we make array with member of nil
history = send("#{attr_name}_history") || [nil]
# push the value for the setter to history
# history.push() returns the new history array, which we set to be the "attr_name"_history variable
instance_variable_set "@#{attr_name}_history", history.push(value)
# set the actual attr_name variable to the value - replacement for attr_writer
instance_variable_set "@#{attr_name}", value
end
}
end
end
class Foo
attr_accessor_with_history :bar
end
f = Foo.new
f.bar = 1
f.bar = 2
p f.bar_history
|
require("minitest/autorun")
require('minitest/reporters')
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new
require_relative("./drinks")
class TestStudent < MiniTest::Test
def setup
drinkdata = {"name" => 'Gin', "type" => "Spirit", "abv" => 40}
@drink = Drink.new(drinkdata)
mixerdata = {"name" => 'Cola', "type" => "Fizzy"}
@mixer = Mixer.new(mixerdata)
cocktaildata = {"name" => drink1.id + mixer1.id}
@cocktail = Cocktail.new(cocktaildata)
end
def test_drink_initialize
assert_equal("Gin", @drink.name)
assert_equal("Spirit", @drink.type)
assert_equal(40, @drink.abv)
end
def test_mixer_initialize
assert_equal("Cola", @mixer.name)
assert_equal("Fizzy", @mixer.type)
end
def test_cocktail_initialize
assert_equal("Vodka & Coke", @cocktail.type)
end
end
|
# In the exercises below, write your own code where indicated
# to achieve the desired result. You should be able to run this
# file from your terminal with the command `ruby day_3/exercises/if_statements.rb`
# example, using the weather variable below, determine what you need to take
# with you to be prepared based on the following conditions:
# if it is sunny, print "sunscreen"
# if it is rainy, print "umbrella"
# if it is snowy, print "coat"
# if it is icy, print "yak traks"
weather = 'snowy'
if weather == 'sunny'
p "sunscreen"
elsif weather == 'rainy'
p "umbrella"
elsif weather == 'snowy'
p "coat"
elsif weather == 'icy'
p "yak traks"
else
p "good to go!"
end
# Manipulate the variable 'weather' to see if you can print something other
# than 'coat'
def what_to_take(outside)
outside.each do |today|
if today == 'sunny'
p "The weather is #{today}, wear sunscreen"
elsif today == 'rainy'
p "The weather is #{today}, bring an umbrella"
elsif today == 'snowy'
p "The weather is #{today}, wear a coat"
elsif today == 'icy'
p "The weather is #{today}, bring yak traks"
else
p "The weather is perfect today, you're good to go!"
end
end
end
weather = ['sunny', 'rainy', 'snowy', 'icy','']
what_to_take(weather)
##################
# Using the num_quarters variable defined below, determine
# if you have enough money to buy a gumball. A gumball costs
# two quarters. Right now, the program will print
# out both "I have enough money for a gumball" and
# "I don't have enough money for a gumball". Write
# a conditional statement that only prints one or the
# other.
# You should be able to change num_quarters and achieve these outputs:
# When num_quarters = 0, program should print "I don't have enough money for a gumball"
# When num_quarters = 1, program should print "I don't have enough money for a gumball"
# When num_quarters = 2, program should print "I have enough money for a gumball"
# When num_quarters = 3, program should print "I have enough money for a gumball"
def gumball(quarters)
if quarters == 0 || quarters == 1
puts "I don't have enough money for a gumball"
elsif quarters == 2 || quarters == 3
puts "I have enough money for a gumball"
end
end
num_quarters = 0
puts "How many quarters do I have? (type a value between 0-3)"
print "> "
num_quarters = $stdin.gets.chomp.to_i
gumball(num_quarters)
#####################
# Using the variables defined below, determine if you have the
# ingredients to make a pizza. A pizza requires at least two cups
# of flour and sauce.
# You should be able to change the variables to achieve the following outputs:
# When cups_of_flour = 1 and has_sauce = true, your program should print "I cannot make pizza"
# When cups_of_flour = 1 and has_sauce = false, your program should print "I cannot make pizza"
# When cups_of_flour = 2 and has_sauce = true, your program should print "I can make pizza"
# When cups_of_flour = 3 and has_sauce = true, your program should print "I can make pizza"
cups_of_flour = 1
def enough_cups_of_flour
puts "How many cups of flour do I have?"
print "> "
cups = $stdin.gets.chomp.to_i
if cups >= 2
true
else
false
end
end
def has_sauce
puts " Do I have sauce?"
puts "1. Yes"
puts "2. No"
print "> "
sauce = $stdin.gets.chomp
if sauce == "1"
true
elsif sauce == "2"
false
end
end
if enough_cups_of_flour && has_sauce
puts "I can make pizza"
else
puts " I cannot make pizza"
end
|
# 2 Busqueda Generalizada
# Patrick Rengifo 09-10703
# Daniela Rodriguez 09-10735
# Recorrido BFS en un comportamiento
module Bfs
# Recorrido BFS para encontrar un nodo que cumpla predicate
def find(start, predicate)
if !(predicate.is_a?(Proc))
puts "No se ha pasado un predicado valido"
return nil
end
# Conjunto de nodos visitados
nodes = {start.value => false}
# Creamos la pila de nodos
items = [start]
nodes[start.value] = true
while item = items.delete_at(0)
# Si es el nodo cumple con el predicado, lo retornamos.
return item if predicate.call(item.value)
# Sino buscamos sus adyacentes y los empilamos.
item.each do |x|
unless nodes[x.value]
nodes[x.value] = true
items.push(x)
end
end
end
# Si no encontramos nada
return nil
end
# Recorrido BFS que devuelve el camino desde la raiz hasta el nodo que cumpla
# el predicate
def path(start, predicate)
if !(predicate.is_a?(Proc))
puts "No se ha pasado un predicado valido"
return nil
end
# Conjunto de nodos visitados
nodes = {start.value => false}
# Camino vacio
path = []
# Creamos la pila de nodos
items = [start]
nodes[start.value] = true
while item = items.delete_at(0)
path.push(item.value)
# Si es el nodo cumple con el predicado, lo retornamos.
return path if predicate.call(item.value)
# Sino buscamos sus adyacentes y los empilamos.
item.each do |x|
unless nodes[x.value]
nodes[x.value] = true
items.push(x)
end
end
end
# Si no encontramos nada
return nil
end
# Recorrido BFS que recorre en su totalidad el espacio de busqueda ejecutando
# el action en cada nodo y retornando la lista de nodos recorridos. Si se
# omite action, solo devuelve la lista de nodos recorridos.
def walk(start, action)
# Conjunto de nodos visitados
nodes = {start.value => false}
# Camino vacio
path = []
# Creamos la pila de nodos
items = [start]
nodes[start.value] = true
while item = items.delete_at(0)
if action.is_a?(Proc)
path.push(action.call(item.value))
else
path.push(item.value)
end
# Sino buscamos sus adyacentes y los empilamos.
item.each do |x|
unless nodes[x.value]
nodes[x.value] = true
items.push(x)
end
end
end
# Si no encontramos nada
return path
end
end
# Arboles y Grafos Explicitos
class BinTree
include Bfs
attr_accessor :value, # Valor almacenado en el nodo
:left, # BinTree izquierdo
:right # BinTree derecho
def initialize(v,l=nil,r=nil)
@value = v
@left = l
@right = r
end
# Metodo propio de each
def each
yield self
yield @left unless @left.nil?
yield @right unless @right.nil?
end
end
class GraphNode
include Bfs
attr_accessor :value, # Valor alamacenado en el nodo
:children # Arreglo de sucesores GraphNode
def initialize(v,c=nil)
@value = v
@children = c
end
# Metodo propio de each
def each
yield self
@children.each {|x| yield x } unless @children.nil?
end
end
# Arboles Implicitos
class LCR
include Bfs
attr_reader :value
# Un estado del problema se modela con un hash con keys :where (donde esta
# el bote), :left (que hay en la orilla izquierda, y :right (que hay en la
# orilla derecha). Con los valores :repollo, :lobo, :cabra.
def initialize(w,l,r)
@value = {:where => w,
:left => l,
:right => r}
end
# Metodo para saber si un estado generado es valido para nuestro
# problema a resolver. I.e. la cabra no puede estar con el lobo en la
# misma orilla sin el humano. Ademas mantiene que solo haya un elemento
# en cada orilla.
def is_valid?
if @value.has_value?([:cabra,:lobo]) ||
@value.has_value?([:cabra,:lobo]) ||
@value.has_value?([:lobo,:cabra]) ||
@value.has_value?([:lobo,:cabra]) ||
@value.has_value?([:cabra,:repollo]) ||
@value.has_value?([:cabra,:repollo]) ||
@value.has_value?([:repollo,:cabra]) ||
@value.has_value?([:repollo,:cabra]) ||
(@value[:left].include?(:lobo) && @value[:right].include?(:lobo)) ||
(@value[:left].include?(:cabra) && @value[:right].include?(:cabra)) ||
(@value[:left].include?(:repollo) && @value[:right].include?(:repollo))
return false
else
return true
end
end
# Metodo propio de each.
def each
# Self es valido
if is_valid?
# Movemos el barco a la orilla contraria solo o con algo
if @value[:where] == :izquierda
# Barco solo
barco = LCR.new(:derecha, @value[:left], @value[:right])
yield barco unless !(barco.is_valid?)
# Barco con algo
@value[:left].each do |x| barco = LCR.new(:derecha,
@value[:left].delete(x),
@value[:right].push(x))
yield barco unless !(barco.is_valid?)
end
else
# Barco solo
barco = LCR.new(:izquierda, @value[:left], @value[:right])
yield barco unless !(barco.is_valid?)
# Barco con algo
@value[:right].each do |x| barco = LCR.new(:izquierda,
@value[:left].push(x),
@value[:right].delete(x))
yield barco unless !(barco.is_valid?)
end
end
end
end
# Dado el estado final del problema LCR, se busca el camino que proporcione
# la solucion al mismo.
# NOTA: Este metodo tiene un bug ya que no resuelve el problema que se le
# plantea. Se intento corregir.
def solve
final = lambda{|x| x[:right] == [:cabra,:lobo,:repollo] ||
x[:right] == [:lobo,:repollo,:cabra] ||
x[:right] ==[:cabra,:repollo,:lobo]}
result = self.path(self, final)
if result.nil?
puts "El problema no tiene solucion"
else
puts "El resultado al problema es"
puts result
end
end
end |
class Event < ApplicationRecord
validates_presence_of :title, :location, :start_datetime
validates :title, length: { minimum: 3 }
validate :start_datetime_cannot_be_in_past
private
def start_datetime_cannot_be_in_past
if start_datetime.present? && start_datetime < Time.now
errors.add :start_datetime, "can't be in the past"
end
end
end
|
# Copyright © Emilio González Montaña
# Licence: Attribution & no derivates
# * Attribution to the plugin web page URL should be done if you want to use it.
# https://redmine.ociotec.com/projects/redmine-plugin-scrum
# * No derivates of this plugin (or partial) are allowed.
# Take a look to licence.txt file at plugin root folder for further details.
class ChangeMilestonesDates < ActiveRecord::Migration
def self.up
rename_column :milestones, :effective_date, :milestone_effective_date
end
def self.down
rename_column :milestones, :milestone_effective_date, :effective_date
end
end |
require 'rails_helper'
RSpec.describe MasterSale, type: :model do
it 'Accepts nested attributes for Sale' do
is_expected.to accept_nested_attributes_for(:sales).
allow_destroy(true)
end
context 'Associations' do
it { is_expected.to have_many(:sales) }
end
context 'Validations' do
it { is_expected.to validate_presence_of(:date) }
end
it 'Is valid' do
master_sale = create(:master_sale)
expect(master_sale).to be_valid
end
end
|
# frozen_string_literal: true
# Abstraction of model persistence in controllers
module Persistence
extend ActiveSupport::Concern
def save_record(model)
if model.save
yield(model) if block_given?
render json: model
else
render json: {errors: model.errors}, status: :unprocessable_entity
end
end
def update_record(model, params)
if model.update(params)
yield(model) if block_given?
render json: model
else
render json: {errors: model.errors}, status: :unprocessable_entity
end
end
def destroy_record(model)
if model.destroy
head :no_content
else
render json: {errors: model.errors}, status: :unprocessable_entity
end
end
end
|
class MenuServer < ActiveRecord::Base
attr_accessible :menu_id, :server_id, :server
belongs_to :menu
belongs_to :server
end |
require 'spec_helper'
describe SqlExecutor do
let(:check_id) { "0.1234" }
describe "#preview_dataset" do
context "with live data", :database_integration do
let(:account) { GpdbIntegration.real_gpdb_account }
let(:database) { GpdbDatabase.find_by_name_and_gpdb_instance_id(GpdbIntegration.database_name, GpdbIntegration.real_gpdb_instance) }
let(:table) { database.find_dataset_in_schema('pg_all_types', 'test_schema') }
subject { SqlExecutor.preview_dataset(table, account, check_id) }
it "returns a SqlResult object with the correct rows" do
subject.rows.should == [[
"(1,2)",
"1.2",
"{1,2,3}",
"1",
"1",
"10101",
"101",
"t",
"(2,2),(1,1)",
"xDEADBEEF",
"var char",
"char ",
"192.168.100.128/25",
"<(1,2),3>",
"2011-01-01",
"10.01",
"192.168.100.128",
"10",
"3 days 04:05:06",
"[(1,1),(2,2)]",
"08:00:2b:01:02:03",
"$1,000.00",
"0.02000",
"[(1,1),(2,2),(3,3)]",
"(0,0)",
"((10,10),(20,20),(30,30))",
"1.1",
"1",
"2",
"text",
"04:05:06",
"01:02:03-08",
"1999-01-08 04:05:06",
"1999-01-08 04:05:06-08"
]]
end
it "gives each column the right 'name' attribute" do
subject.columns.map(&:name).should == %w{
t_composite
t_decimal
t_array
t_bigint
t_bigserial
t_bit
t_varbit
t_bool
t_box
t_bytea
t_varchar
t_char
t_cidr
t_circle
t_date
t_double
t_inet
t_integer
t_interval
t_lseg
t_macaddr
t_money
t_numeric
t_path
t_point
t_polygon
t_real
t_smallint
t_serial
t_text
t_time_without_time_zone
t_time_with_time_zone
t_timestamp_without_time_zone
t_timestamp_with_time_zone
}
end
it "gives each column the right 'data_type' attribute" do
subject.columns.map(&:data_type).should == %w{
complex
numeric
_int4
int8
bigserial
bit
varbit
bool
box
bytea
varchar
bpchar
cidr
circle
date
float8
inet
int4
interval
lseg
macaddr
money
numeric
path
point
polygon
float4
int2
serial
text
time
timetz
timestamp
timestamptz
}
end
end
context "without live data" do
it "limits the preview to 100 rows" do
mock(SqlExecutor).execute_sql(anything, anything, anything, anything, :limit => 100)
SqlExecutor.preview_dataset(Dataset.first, Object.new, Object.new)
end
end
end
describe "#execute_sql", :database_integration do
let(:account) { instance_accounts(:chorus_gpdb42_test_superuser) }
let(:schema) { GpdbSchema.find_by_name!('test_schema') }
let(:sql) { 'select 1' }
let(:check_id) { '42' }
it "returns a SqlResult" do
result = SqlExecutor.execute_sql(schema, account, check_id, sql)
result.should be_a SqlResult
end
it "sets the schema on the SqlResult" do
result = SqlExecutor.execute_sql(schema, account, check_id, sql)
result.schema.should == schema
end
it "passes the limit to CancelableQuery" do
called = false
any_instance_of(CancelableQuery) do |query|
called = true
mock.proxy(query).execute(sql, :limit => 42)
end
result = SqlExecutor.execute_sql(schema, account, check_id, sql, :limit => 42)
end
end
describe "#cancel_query" do
it "cancels the query" do
fake_connection = Object.new
fake_query = Object.new
connection_provider = Object.new
account = Object.new
mock(connection_provider).with_gpdb_connection(account).yields(fake_connection)
mock(CancelableQuery).new(fake_connection, check_id) { fake_query }
mock(fake_query).cancel
SqlExecutor.cancel_query(connection_provider, account, check_id)
end
end
end
|
# == Schema Information
#
# Table name: vendors
#
# id :integer(4) not null, primary key
# vendor_code :string(255)
# name :string(255)
# address1 :string(255)
# address2 :string(255)
# city :string(255)
# state :string(255)
# zip_code :string(255)
# phone :string(255)
# contact :string(255)
# email :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# status_id :integer(4)
#
class Vendor < ActiveRecord::Base
attr_protected :id
validates :name, :presence => true
has_many :products
belongs_to :status
end
|
# == Schema Information
#
# Table name: planning_items
#
# id :bigint not null, primary key
# planning_id :bigint
# day :string
# start_time :time
# end_time :time
# status :string
# created_at :datetime not null
# updated_at :datetime not null
#
class PlanningItem < ApplicationRecord
belongs_to :planning
end
|
FactoryGirl.define do
factory :user do
email "test@example.com"
password "password"
password_confirmation "password"
end
factory :location do
location_name "Boston, MA"
end
factory :unit do
name "Ruby on Rails"
date "2015-01-05"
end
end
|
namespace :data do
desc 'This will delete all orphaned data'
task clean: :environment do
Assignment.where.not(person_id: Person.pluck(:id)).destroy_all
Assignment.where.not(location_id: Location.pluck(:id)).destroy_all
end
end
|
module Yaks
class Resource
module HasFields
def map_fields(&block)
with(
fields: fields_flat(&block)
)
end
def fields_flat(&block)
return to_enum(__method__) unless block_given?
fields.map do |field|
next field if field.type.equal? :legend
if field.respond_to?(:map_fields)
field.map_fields(&block)
else
block.call(field)
end
end
end
end
end
end
|
class HouseholdController < ApplicationController
require 'will_paginate/array'
before_filter :controller_sign_in_check, only: [:new, :create]
before_filter :member_of_household, only: [:show]
before_filter :households_owner, only: [:destroy]
def new
@household = Household.new
end
def create
hname = params[:household][:hhname]
@household = Household.new(hhname: hname, hhowner: current_user.id)
if @household.save # TODO This is crappy nested if-statements, fix this at some point
@householdmember = Householdmembers.new(hhid: @household.id, member: current_user.id)
if @householdmember.save
flash[:success] = "Household " + hname + " created!"
redirect_to controller: 'household', action: 'show', id: @household.id
else
render 'new'
end
else
render 'new'
end
end
def show
@household = Household.find(params[:id])
#Get an array of all users in the household.
members = HHoldSnapshot.where(hhid: params[:id]).map{|x| x.users_arr}.flatten.uniq
users = User.where(id: members ).collect{ |y| [y.nickname,y.id] };
@users_array = users.collect{ |y| [y[0],y[1]] }
#Make an array which excludes current_user
@users_array_prime = @users_array.dup
@users_array.each_with_index do |usr,indx|
if usr[1]==current_user.id
@users_array_prime.delete_at(indx)
break
end
end
#Ensure that current_user is first in array
@users_array = @users_array_prime.dup
@users_array.unshift([current_user.nickname,current_user.id]);
@users_array_indx = @users_array.map{|y| y[1]}
#HHold Snapshot
@hhold_snapshot_all = HHoldSnapshot.where(hhid: params[:id]).order("created_at")
@hhold_snapshot = @hhold_snapshot_all.last
#Lineitems for the household
@household_lineitems2 = Lineitem.where(hhid: params[:id]).order("txdate ASC");
#Debt statistics - before pagination
@debts = Lineitem.calculate_debts(@household_lineitems2,params[:id],current_user.id, @hhold_snapshot_all)
#Create and Paginate the Lineitems and HHoldSnapshot chronology
@household_lineitems = HHoldSnapshot.createLineitemsAndSnapshotChronology( @household_lineitems2.to_a, params[:id], {"users_array"=>@users_array, "users_array_indx"=>@users_array_indx} )
@household_lineitems = @household_lineitems.paginate(page: params[:page])
=begin
lineitems = Lineitem.where(hhid: params[:id]);
payers = Array.new;
for n in 0..lineitems.length-1
payers.push(lineitems[n].payer)
end
users_id = User.where(id: payers).select("id").map {|i| i.id};
users_names = User.where(id: payers).select("nickname").map {|i| i.nickname};
temphouseholds_lineitems = Array.new;
for n in 0..lineitems.length-1
temp_hash = {"txdate" => lineitems[n].txdate.to_s, "amount" => lineitems[n].amount.to_s,
"txtype" => lineitems[n].txtype.to_s,
"txname" => lineitems[n].txname.to_s,
"payer" => lineitems[n].payer.to_s,
"id" => lineitems[n].id.to_s,
"nickname" => users_names[users_id.index(lineitems[n].payer)].to_s }
temphouseholds_lineitems.push(temp_hash);
end
if params[:page].nil?
page_num = 1;
else
page_num = params[:page].to_i
end
@households_lineitems = WillPaginate::Collection.create(page_num, 20) do |pager|
pager.replace(temphouseholds_lineitems)
end
#Then placed in /views/shared/_household_lineitem.html.erb
<%= household_lineitem["txdate"] + " " + household_lineitem["amount"] + " " +
household_lineitem["txtype"] + " " + household_lineitem["txname"] + " " + household_lineitem["nickname"] %>
=end
# New lineitem object for the form
@lineitem = Lineitem.new
@invitation = Invitation.new
end
def destroy
Household.find(params[:id]).destroy
flash[:success] = "Household deleted."
redirect_to current_user
end
private
def member_of_household
if Householdmembers.where(hhid: params[:id], member: current_user.id).empty?
flash[:error] = "Incorrect credentials for given request."
redirect_to current_user
else
#allow to pass
end
end
def households_owner
if Household.where(id: params[:id], hhowner: current_user.id).empty?
flash[:error] = "Incorrect credentials for given request."
redirect_to current_user
else
#allow to pass
end
end
end |
define :set_ftp_loader, thenode: nil, code_directory: '/usr/local/share/kafka-contrib/current/', command: 'bundle exec ruby scripts/ftp2s3.rb' do
thenode = params[:thenode]
conf_dir = node[:kafka][:ftp_loader][:conf_dir]
config_file = File.join(conf_dir, "#{thenode[:name]}.yaml")
unix_user = 'root'
ftp_loader_path = '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin'
directory conf_dir do
recursive true
end
template config_file do
source "ftp2s3.yaml.erb"
owner "root"
mode "0644"
variables({:config => thenode})
end
directory thenode[:input_directory] do
owner unix_user
recursive true
mode 0700
end
directory thenode[:output_directory] do
owner unix_user
recursive true
mode 0700
end
directory thenode[:meta_directory] do
owner unix_user
recursive true
mode 0700
end
file thenode[:log_file] do
owner unix_user
action :touch
mode 0644
end
cron "FTP Loader #{thenode[:name]}" do
minute '*/' + thenode[:interval_minutes]
user unix_user
# This doesn't appear to work. not sure what I'm doing wrong... -- josh
path ftp_loader_path
command "PATH=#{ftp_loader_path} bash -l -c 'cd #{params[:code_directory]} && PATH=#{ftp_loader_path} #{params[:command]} #{config_file} 2>&1 | PATH=#{ftp_loader_path} cat >> #{thenode[:log_file]}'"
end
announce(:ftp, :listener, logs: { main: thenode[:log_file] })
end
|
require 'spec_helper'
describe Hitimes::TimedMetric do
before( :each ) do
@tm = Hitimes::TimedMetric.new( 'test-timed-metric' )
end
it "knows if it is running or not" do
@tm.running?.must_equal false
@tm.start
@tm.running?.must_equal true
@tm.stop
@tm.running?.must_equal false
end
it "#split returns the last duration and the timer is still running" do
@tm.start
d = @tm.split
@tm.running?.must_equal true
d.must_be :>, 0
@tm.count.must_equal 1
@tm.duration.must_equal d
end
it "#stop returns false if called more than once in a row" do
@tm.start
@tm.stop.must_be :>, 0
@tm.stop.must_equal false
end
it "does not count a currently running interval as an interval in calculations" do
@tm.start
@tm.count.must_equal 0
@tm.split
@tm.count.must_equal 1
end
it "#split called on a stopped timer does nothing" do
@tm.start
@tm.stop
@tm.split.must_equal false
end
it "calculates the mean of the durations" do
2.times { @tm.start ; sleep 0.05 ; @tm.stop }
@tm.mean.must_be_close_to(0.05, 0.002)
end
it "calculates the rate of the counts " do
5.times { @tm.start ; sleep 0.05 ; @tm.stop }
@tm.rate.must_be_close_to(20.00, 0.5)
end
it "calculates the stddev of the durations" do
3.times { |x| @tm.start ; sleep(0.05 * x) ; @tm.stop }
@tm.stddev.must_be_close_to(0.05)
end
it "returns 0.0 for stddev if there is no data" do
@tm.stddev.must_equal 0.0
end
it "keeps track of the min value" do
2.times { @tm.start ; sleep 0.05 ; @tm.stop }
@tm.min.must_be_close_to(0.05, 0.01)
end
it "keeps track of the max value" do
2.times { @tm.start ; sleep 0.05 ; @tm.stop }
@tm.max.must_be_close_to(0.05, 0.01)
end
it "keeps track of the sum value" do
2.times { @tm.start ; sleep 0.05 ; @tm.stop }
@tm.sum.must_be_close_to(0.10, 0.01)
end
it "keeps track of the sum of squars value" do
3.times { @tm.start ; sleep 0.05 ; @tm.stop }
@tm.sumsq.must_be_close_to(0.0075)
end
it "keeps track of the minimum start time of all the intervals" do
f1 = Time.now.gmtime.to_f * 1_000_000
5.times { @tm.start ; sleep 0.05 ; @tm.stop }
f2 = Time.now.gmtime.to_f * 1_000_000
@tm.sampling_start_time.must_be :>=, f1
@tm.sampling_start_time.must_be :<, f2
# distance from now to start time should be greater than the distance from
# the start to the min start_time
(f2 - @tm.sampling_start_time).must_be :>, ( @tm.sampling_start_time - f1 )
end
it "keeps track of the last stop time of all the intervals" do
f1 = Time.now.gmtime.to_f * 1_000_000
sleep 0.01
5.times { @tm.start ; sleep 0.05 ; @tm.stop }
sleep 0.01
f2 = Time.now.gmtime.to_f * 1_000_000
@tm.sampling_stop_time.must_be :>, f1
@tm.sampling_stop_time.must_be :<=, f2
# distance from now to max stop time time should be less than the distance
# from the start to the max stop time
(f2 - @tm.sampling_stop_time).must_be :<, ( @tm.sampling_stop_time - f1 )
end
it "can create an already running timer" do
t = Hitimes::TimedMetric.now( 'already-running' )
t.running?.must_equal true
end
it "can measure a block of code from an instance" do
t = Hitimes::TimedMetric.new( 'measure a block' )
3.times { t.measure { sleep 0.05 } }
t.duration.must_be_close_to(0.15, 0.01)
t.count.must_equal 3
end
it "returns the value of the block when measuring" do
t = Hitimes::TimedMetric.new( 'measure a block' )
x = t.measure { sleep 0.05; 42 }
t.duration.must_be_close_to(0.05, 0.002)
x.must_equal 42
end
describe "#to_hash" do
it "has name value" do
h = @tm.to_hash
h['name'].must_equal "test-timed-metric"
end
it "has an empty hash for additional_data" do
h = @tm.to_hash
h['additional_data'].must_equal Hash.new
h['additional_data'].size.must_equal 0
end
it "has the right sum" do
10.times { |x| @tm.measure { sleep 0.01*x } }
h = @tm.to_hash
h['sum'].must_be_close_to(0.45, 0.01)
end
fields = ::Hitimes::Stats::STATS.dup + %w[ name additional_data sampling_start_time sampling_stop_time ]
fields.each do |f|
it "has a value for #{f}" do
@tm.measure { sleep 0.001 }
h = @tm.to_hash
h[f].wont_be_nil
end
end
end
end
|
class PostPhotosController < ApplicationController
def create
post_photo = PostPhoto.create(safe_params)
redirect_to [:edit, post_photo.post]
end
def destroy
post_photo = PostPhoto.find(params[:id])
post_photo.destroy
redirect_to [:edit, post_photo.post]
end
private
def safe_params
params.require(:post_photo).permit!
end
def authorized?
current_user&.parent?
end
end
|
class User < ActiveRecord::Base
validates :name, presence:true
validates :email, presence:true, uniqueness:true
validates :password, presence:true,
length: {minimum: 8}
has_secure_password
end
|
class Company < ApplicationRecord
mount_uploader :company_image, CompanyUploader
belongs_to :country
belongs_to :state
belongs_to :city
has_many :places
has_many :nodes
has_many :users
# validates :name, presence: true,
# length: { minimum: 3 }
# validates :name, uniqueness: true
end
|
require './spec/spec_helper'
require './lib/ticket'
require './lib/gate'
describe '改札機プログラム' do
let(:umeda_gate) {Gate.new(:umeda)}
let(:jyuso_gate) {Gate.new(:jyuso)}
let(:mikuni_gate) {Gate.new(:mikuni)}
context '梅田乗車の時' do
context '150円きっぷの場合' do
let(:ticket) {Ticket.new(150)}
it '十三で降りられる' do
umeda_gate.enter(ticket)
expect(jyuso_gate.exit(ticket)).to be_truthy
end
it '三国で降りられない' do
umeda_gate.enter(ticket)
expect(mikuni_gate.exit(ticket)).to be_falsey
end
end
context '190円きっぷの場合' do
let(:ticket) {Ticket.new(190)}
it '十三で降りられる' do
umeda_gate.enter(ticket)
expect(jyuso_gate.exit(ticket)).to be_truthy
end
it '三国で降りられる' do
umeda_gate.enter(ticket)
expect(mikuni_gate.exit(ticket)).to be_truthy
end
end
end
context '十三乗車の時' do
context '150円きっぷの場合' do
let(:ticket) {Ticket.new(150)}
it '梅田で降りられる' do
jyuso_gate.enter(ticket)
expect(umeda_gate.exit(ticket)).to be_truthy
end
it '三国で降りられる' do
jyuso_gate.enter(ticket)
expect(mikuni_gate.exit(ticket)).to be_truthy
end
end
end
context '三国乗車の時' do
context '150円きっぷの場合' do
let(:ticket) {Ticket.new(150)}
it '十三で降りられる' do
mikuni_gate.enter(ticket)
expect(jyuso_gate.exit(ticket)).to be_truthy
end
it '梅田で降りられれない' do
mikuni_gate.enter(ticket)
expect(umeda_gate.exit(ticket)).to be_falsey
end
end
context '190円きっぷの場合' do
let(:ticket) {Ticket.new(190)}
it '十三で降りられる' do
mikuni_gate.enter(ticket)
expect(jyuso_gate.exit(ticket)).to be_truthy
end
it '梅田で降りられる' do
mikuni_gate.enter(ticket)
expect(umeda_gate.exit(ticket)).to be_truthy
end
end
end
end
|
# frozen_string_literal: true
module Bridgetown
class PluginContentReader
attr_reader :site, :content_dir
def initialize(site, plugin_content_dir)
@site = site
@content_dir = plugin_content_dir
@content_files = Set.new
end
def read
return unless content_dir
Find.find(content_dir) do |path|
next if File.directory?(path)
if File.symlink?(path)
Bridgetown.logger.warn "Plugin content reader:", "Ignored symlinked asset: #{path}"
else
read_content_file(path)
end
end
end
def read_content_file(path)
dir = File.dirname(path.sub("#{content_dir}/", ""))
name = File.basename(path)
@content_files << if Utils.has_yaml_header?(path)
Bridgetown::Page.new(site, content_dir, dir, name, from_plugin: true)
else
Bridgetown::StaticFile.new(site, content_dir, "/#{dir}", name)
end
add_to(site.pages, Bridgetown::Page)
add_to(site.static_files, Bridgetown::StaticFile)
end
def add_to(content_type, klass)
existing_paths = content_type.map(&:relative_path).compact
@content_files.select { |item| item.is_a?(klass) }.each do |item|
content_type << item unless existing_paths.include?(item.relative_path)
end
end
end
end
|
module Hydramata
module Works
# Responsible for finding an appropriate constant that can be used
# to build a ValuePresenter like object.
module ValuePresenterFinder
module_function
def call(predicate)
klass =
if predicate.respond_to?(:value_presenter_class_name) && predicate.value_presenter_class_name
class_name = predicate.value_presenter_class_name
begin
class_name.constantize
rescue NameError, NoMethodError
begin
Hydramata::Works.const_get(class_name.to_s)
rescue NameError
require 'hydramata/works/value_presenter'
ValuePresenter
end
end
else
require 'hydramata/works/value_presenter'
ValuePresenter
end
klass
end
end
end
end
|
#!/usr/bin/ruby
require 'uri'
def delete_artifact(artifact_uri)
# %r|.*/#{$repo}/(.*)| =~ artifact_uri # delete artifacts only
%r|.*/#{$repo}/(.*)/.*| =~ artifact_uri # delete artifacts and their parent directories
url = URI.escape("#{$artifactory_root_path}/#{$repo}/#{$1}")
http = Net::HTTP.new($host_url, $host_port)
request = Net::HTTP::Delete.new(url)
request.basic_auth($user, $password)
response = http.request(request)
succeeded = true
if response.code == "404"
# do nothing. Since we're deleting each artifact's folder, it's fairly common to try to delete an artifact only to find it's already been deleted.
# Note that if the artifactory cannot be found an error will be thrown while retrieving artifacts, so this isn't masking that case.
puts "Not found: #{artifact_uri}. Assuming already deleted, moving on"
elsif response.code != "204"
puts "Errored: #{artifact_uri}. Non-204 response received: #{get_pretty_error_from_http_response(response)}"
succeeded = false
else
puts "Deleted: #{artifact_uri}"
end
succeeded
end
def get_artifact_details(artifact_uri)
artifact_uri_spaces_handled = URI.escape(artifact_uri)
http = Net::HTTP.new($host_url, $host_port)
request = Net::HTTP::Get.new(artifact_uri_spaces_handled)
request.basic_auth($user, $password)
response = http.request(request)
JSON.parse(response.body)
end
def retrieve_unused_artifacts_by_age()
since = (Time.now - $age_days * 3600*24).to_i * 1000
url = "#{$artifactory_root_path}/api/search/usage?notUsedSince=#{since}&createdBefore=#{since}&repos=#{$repo}"
http = Net::HTTP.new($host_url, $host_port)
http.read_timeout = 500
request = Net::HTTP::Get.new(url)
request.basic_auth($user, $password)
response = http.request(request)
if response.code == "404"
puts "404 response received from Artifactory while retrieving artifacts: #{get_pretty_error_from_http_response(response)}"
puts "Either artifact url or repo not found, or no artifacts found older than #{$age_days} days."
exit!
elsif response.code != "200"
puts "Non-200 response received from Artifactory while retrieving artifacts: #{get_pretty_error_from_http_response(response)}"
exit!
end
unused_artifacts_by_age = JSON.parse(response.body)["results"] # we want to spit out an array, so the rest of the code doesn’t have to handle a json body
return unused_artifacts_by_age
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)
a1 = Dish.create(name: "Green Salat", description: "Cucumbers, Tomatoes, Iceberg, Feta, Olive oil", image: "", course_name: "first course", price: 10)
a2 = Dish.create(name: "New salat Boom", description: "Rad Papper, Sparja, Cucumber", image: "", course_name: "first course", price: 8)
a3 = Dish.create(name: "Sparja Salat", description: "Sparja, Black Papper, Cucumber", image: "", course_name: "first course", price: 7)
a4 = Dish.create(name: "Fried Potato", description: "Potato, Onion, Green, Oil", image: "", course_name: "main course", price: 12)
a5 = Dish.create(name: "Fish Salat", description: "Fish, Black Papper, Tomatoes, Green, Feta", image: "", course_name: "first course", price: 14.99)
a6 = Dish.create(name: "Pizza", description: "Mozzarella, Parmesan, Cheddar, Cherry, Bell pepper", image: "", course_name: "main course", price: 13.08)
a7 = Dish.create(name: "Coffee Cappucino", description: "220 ml", image: "", course_name: "drink", price: 1.5)
a8 = Dish.create(name: "Coffee Latte", description: "300 ml", image: "", course_name: "drink", price: 2)
a9 = Dish.create(name: "Juice", description: "Orange, Apple, Papaya Banana, Strawberry", image: "", course_name: "drink", price: 2)
a10 = Dish.create(name: "Veg Stew", description: "Panner, Zucchini, Carrot, Onion, Tomatoes", image: "", course_name: "main course", price: 9)
d1 = Day.create(weekday: "Monday", month: "September", year: "2020")
d2 = Day.create(weekday: "Tuesday", month: "September", year: "2020")
d3 = Day.create(weekday: "Wednesday", month: "September", year: "2020")
d4 = Day.create(weekday: "Thursday", month: "September", year: "2020")
d5 = Day.create(weekday: "Friday", month: "September", year: "2020")
d6 = Day.create(weekday: "Saturday", month: "September", year: "2020")
d7 = Day.create(weekday: "Sunday", month: "September", year: "2020")
c1 = Course.create(day_id:d1.id, dish_id:a2.id, name: "first course")
c2 = Course.create(day_id:d2.id, dish_id:a1.id, name: "first course")
c3 = Course.create(day_id:d1.id, dish_id:a3.id, name: "first course")
c4 = Course.create(day_id:d1.id, dish_id:a4.id, name: "main course")
c5 = Course.create(day_id:d2.id, dish_id:a5.id, name: "first course")
с6 = Course.create(day_id:d2.id, dish_id:a6.id, name: "main course")
с7 = Course.create(day_id:d1.id, dish_id:a7.id, name: "drink")
с8 = Course.create(day_id:d1.id, dish_id:a8.id, name: "drink")
с9 = Course.create(day_id:d1.id, dish_id:a9.id, name: "drink")
с10 = Course.create(day_id:d1.id, dish_id:a10.id, name: "main course")
с11 = Course.create(day_id:d2.id, dish_id:a7.id, name: "drink")
с12 = Course.create(day_id:d2.id, dish_id:a8.id, name: "drink")
с13 = Course.create(day_id:d2.id, dish_id:a9.id, name: "drink")
с14 = Course.create(day_id:d3.id, dish_id:a9.id, name: "drink")
с15 = Course.create(day_id:d4.id, dish_id:a8.id, name: "drink")
с16 = Course.create(day_id:d5.id, dish_id:a7.id, name: "drink")
с16 = Course.create(day_id:d6.id, dish_id:a9.id, name: "drink")
с17 = Course.create(day_id:d7.id, dish_id:a9.id, name: "drink")
c18 = Course.create(day_id:d3.id, dish_id:a2.id, name: "first course")
c19 = Course.create(day_id:d4.id, dish_id:a3.id, name: "first course")
c20 = Course.create(day_id:d5.id, dish_id:a1.id, name: "first course")
c21 = Course.create(day_id:d6.id, dish_id:a2.id, name: "first course")
c22 = Course.create(day_id:d7.id, dish_id:a3.id, name: "first course")
c23 = Course.create(day_id:d3.id, dish_id:a10.id, name: "main course")
c24 = Course.create(day_id:d4.id, dish_id:a4.id, name: "main course")
c25 = Course.create(day_id:d5.id, dish_id:a10.id, name: "main course")
c26 = Course.create(day_id:d6.id, dish_id:a4.id, name: "main course")
c26 = Course.create(day_id:d7.id, dish_id:a4.id, name: "main course") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.