text stringlengths 10 2.61M |
|---|
require './user.rb'
require './sorters.rb'
require 'faker' # from Gemfile
# setup some users using faker
def generate_random_login(length = 6)
(('a'..'z').to_a + (0..9).to_a).sample(length).join
end
def print_user_list(user_list)
puts " \tfirst name\tlast name\tlogin"
user_list.each_with_index do |user, idx|
puts "#{idx}\t#{user.firstname}\t#{user.lastname}\t#{user.login}"
end
end
user_list = 10.times.map do
# create a dummy user
User.new(Faker::Name.first_name, Faker::Name.last_name, generate_random_login)
end
# show me the users before they are sorted
print_user_list(user_list)
# sort the list by first name
puts "Sort by last name"
print_user_list(user_list.sort(&Sorters.by_lastname))
puts "Sort by first name"
print_user_list(user_list.sort(&Sorters.by_firstname))
# Generate data where there are duplicate last names
last_names = 2.times.map { Faker::Name.last_name }
first_names = 5.times.map { Faker::Name.last_name }
user_list = 10.times.map do |idx|
# create a dummy user
User.new(first_names.sample, last_names.sample, generate_random_login)
end
puts "By last name then first name"
print_user_list(user_list.sort(&Sorters.by_lastname_then_firstname))
|
class AddCharityNumberToCharity < ActiveRecord::Migration
def change
add_column :charities, :charity_number, :integer
end
end
|
class ManageIQ::Providers::Amazon::AgentCoordinatorWorker < MiqWorker
include ProviderWorkerMixin
include MiqWorker::ReplicaPerWorker
require_nested :Runner
self.required_roles = ['smartproxy']
self.workers = 1
def self.has_required_role?
super && all_valid_ems_in_zone.any?
end
def self.ems_class
ManageIQ::Providers::Amazon::CloudManager
end
def self.kill_priority
MiqWorkerType::KILL_PRIORITY_REFRESH_WORKERS
end
def self.service_base_name
"manageiq-providers-#{minimal_class_name.underscore.tr("/", "_")}"
end
end
|
# Andrew Horsman
# Millipede Remake
# Error handling.
require 'configuration'
module GameHelpers
module Errors
def self.throw(error_message, severity)
log_string = "[#{Time.now.to_i}] [#{severity.to_s}] #{error_message}"
File.open(Configuration::LOG_FILE, "a") do |log_file|
log_file.puts log_string
end
puts log_string if Configuration::DEBUG_MODE
$errors ||= []
$errors << log_string
severity_based_log = log_file_path_for_severity(severity)
if severity_based_log.nil?
throw("Tried to log error message '#{error_message}' but encountered an invalid severity level.", :error)
else
File.open(severity_based_log, "a") do |file|
file.puts error_message
end
end
end
def self.log_file_path_for_severity(severity)
return case severity
when :notice then Configuration::NOTICE_LOG_FILE
when :warning then Configuration::WARNING_LOG_FILE
when :error then Configuration::ERROR_LOG_FILE
else nil
end
end
end
end
|
class AddPermissionsToAppzips < ActiveRecord::Migration
def change
add_column :appzips, :permissions, :string, :limit => 3, :default => "FFF"
end
end
|
require 'wsdl_mapper/type_mapping/base'
require 'wsdl_mapper/dom/builtin_type'
require 'bigdecimal'
module WsdlMapper
module TypeMapping
Boolean = Base.new do
register_xml_types %w[
boolean
]
def to_ruby(string)
case string.to_s
when 'true', '1'
true
when 'false', '0'
false
end
end
def to_xml(object)
object ? 'true' : 'false'
end
def ruby_type
nil
end
end
end
end
|
# frozen_string_literal: true
require 'item'
describe Item do
subject { described_class.new('name', 'sell_in', 'quality') }
describe '#to_s' do
it 'converts item to string name, sell_in, quality' do
expect(subject.to_s).to eq 'name, sell_in, quality'
end
end
end
|
# "[Luke:] I can't believe it. [Yoda:] That is why you fail.".include?('Yoda')
# "Ruby is a beautiful language".start_with?('Ruby')
# "I can't work with any other language but Ruby".end_with?('Ruby')
# puts "I am a Rubyist".index('R')
# puts 'Fear is the path to the dark side'.split(/ /)
# Heap
# The standard and most common way for Ruby to save string data is in the 'heap'.
# The heap is a core concept of the C language
# # Pointers
# In computer science, a pointer is a programming language object whose value refers to (or 'points to') another value stored elsewhere in the computer memory using its memory address.
# A pointer references a location in memory and obtaining the value stored at that lodcation is known as dereferencing the pointer.
# As an analogy, a page number in a book's index could be considered a pointer to the corresponding
# C programmers can allocate from and use via a call to the malloc function. For example, this line of C code allocates a 100 byte chunk of memory from the heap and saves its memory address into a pointer:
# char *ptr = malloc(100);
# Later, when the c programmer is done with this memory, she can release it and return it to the system using free:
# free(ptr);
# Ruby String Creation
# Avoiding the need to manage memory in this very manual and explicit way is one of the biggest benefits of using any high level programming language such as Ruby, Java, C#, etc.
|
class CreateUsers < ActiveRecord::Migration[5.2]
def up
create_table :users do |t|
t.string "email", :limit => 200 #user email
t.string "username", :limit => 200 #user email
t.string "password_digest" #user password
t.string "first_name", :limit => 100 #user first name
t.string "last_name", :limit => 100 #user last name
t.string "display_name", :limit => 200 #user display name
t.date "dob", :default => '' #user date of birth
t.date "start_date" #date user joined Toastmasers
t.date "end_date" #date user left Toastmasers
t.string "mobile", :limit => 50 #user mobile
t.string "comments", :limit => 200 #user comments
t.timestamps #audit
end
end
def down
drop_table :users
end
end
|
# :nocov:
require 'aws-sdk-s3'
require 'typhoeus'
module WorkbenchUpload
def self.upload_file_to_workbench(workflow_id:, step_id:, api_token:, path:, filename:)
s3_config = get_s3_config_from_workbench(workflow_id, step_id, api_token)
puts "Uploading to s3://#{s3_config['bucket']}/#{s3_config['key']}"
upload_file_to_s3(path, s3_config)
finish_workbench_upload(s3_config['finishUrl'], api_token, filename)
end
protected
def self.raise_on_http_problem(response)
if not response.success?
if response.timed_out?
raise 'HTTP request timed out'
elsif response.code == 0
raise "HTTP request did not complete: #{response.return_message}"
else
puts response.inspect
raise "HTTP #{response.status_message}"
end
end
end
def self.get_s3_config_from_workbench(workflow_id, step_id, api_token)
url = "https://app.workbenchdata.com/api/v1/workflows/#{workflow_id}/steps/#{step_id}/uploads"
response = Typhoeus.post(url, headers: {Authorization: "Bearer #{api_token}"})
raise_on_http_problem(response)
JSON.parse(response.response_body)
end
def self.upload_file_to_s3(path, s3_config)
s3_client = Aws::S3::Client.new(
# Commented out: aws-sdk v3 format
# endpoint: s3_config['endpoint'],
# force_path_style: true,
# credentials: Aws::Credentials(
# s3_config['credentials']['accessKeyId'],
# s3_config['credentials']['secretAccessKey'],
# s3_config['credentials']['sessionToken'],
# )
# aws-sdk v1 format:
endpoint: s3_config['endpoint'],
force_path_style: true,
access_key_id: s3_config['credentials']['accessKeyId'],
secret_access_key: s3_config['credentials']['secretAccessKey'],
session_token: s3_config['credentials']['sessionToken'],
)
s3_resource = Aws::S3::Resource.new(client: s3_client)
s3_resource.bucket(s3_config['bucket']).object(s3_config['key']).upload_file(path)
end
def self.finish_workbench_upload(finish_url, api_token, filename)
response = Typhoeus.post(
finish_url,
body: JSON.dump({'filename': filename}),
headers: {
Authorization: "Bearer #{api_token}",
'Content-Type': 'application/json'
}
)
raise_on_http_problem(response)
response
end
end
# :nocov:
|
class InscritoContactado
include Mongoid::Document
field :nombre_inscrito, type: String
field :cedula_inscrito, type: Float
field :celular_inscrito, type: String
field :codigo_mesa, type: Integer
field :edad_inscrito, type: Integer
field :sexo_inscrito, type: Mongoid::Boolean
embedded_in :mesa, :inverse_of => :inscrito_contactados
end
|
class CreateRepository
class << self
%w( create create! ).each do |sym|
define_method sym do |*args|
new.send(sym, *args)
end
end
end
def klass
self.class.name.gsub(/^Create/, '').constantize
end
%w( create create! ).each do |sym|
define_method sym do |hash|
sanitize_attributes!(hash)
klass.send(sym, hash).tap do |obj|
after_create(obj) if obj.persisted?
end
end
end
def after_create(obj)
after_create_hooks.each do |klass|
klass.new(obj).perform
end
end
def sanitize_attributes!(hash)
end
def after_create_hooks
[]
end
end
|
require 'spec_helper'
feature "when signed in" do
feature "when on the goal index page" do
before(:each) do
visit new_user_url
fill_in 'Username', :with => "user1"
fill_in 'Password', :with => "password1"
click_on("Submit")
click_link("Create New Goal")
fill_in 'Title', :with => "Title"
fill_in 'Body', :with => "BODY"
end
it "should not list private goals" do
choose "Private"
click_on "Submit"
click_link("All Public Goals")
expect(page).not_to have_content("Title")
end
it "should list public goals" do
choose "Public"
click_on "Submit"
click_link("All Public Goals")
expect(page).to have_content("Title")
end
# it "should not list completed goals" do
# click_on "Submit"
# expect(page).not_to have_content(completed_goal.title)
# end
it "each goal title is a link to it's show page" do
choose "Public"
click_on "Submit"
click_link("All Public Goals")
expect(page).to have_link("Title")
click_on("Title")
expect(page).to have_content("Title")
end
end
feature "creating a goal" do
before(:each) do
visit new_user_url
fill_in 'Username', :with => "user1"
fill_in 'Password', :with => "password1"
click_on("Submit")
click_link("Create New Goal")
end
it "redirects to new goal page" do
expect(page).to have_content("Create a Goal")
end
it "after creating goal, redirects to show page" do
fill_in 'Title', :with => "Title"
fill_in 'Body', :with => "BODY"
choose "Private"
click_on "Submit"
expect(page).to have_content("Title")
end
end
feature "when on a goal's show page" do
feature "editing a goal" do
it "should let the user edit his/her own goal" do
end
it "should not let a user edit a public goal that isn't theirs" do
end
it "should return the user to the goal show page after editing" do
end
end
end
end
feature "when not signed in" do
#can't do anything
end |
class FileFormatProfilesController < ApplicationController
before_action :require_medusa_user, except: [:index, :show]
before_action :find_file_format_profile, only: [:show, :edit, :update, :destroy, :clone]
def index
@file_format_profiles = FileFormatProfile.order(:name)
end
def show
@file_formats = @file_format_profile.file_formats
end
def edit
authorize! :update, @file_format_profile
end
def update
authorize! :update, @file_format_profile
if @file_format_profile.update(allowed_params)
redirect_to @file_format_profile
else
render 'edit'
end
end
def new
authorize! :create, FileFormatProfile
@file_format_profile = FileFormatProfile.new
end
def create
authorize! :create, FileFormatProfile
@file_format_profile = FileFormatProfile.new(allowed_params)
if @file_format_profile.save
redirect_to @file_format_profile
else
render 'new'
end
end
def clone
authorize! :create, FileFormatProfile
@cloned_file_format_profile = @file_format_profile.create_clone
redirect_to edit_file_format_profile_path(@cloned_file_format_profile)
end
def destroy
authorize! :destroy, @file_format_profile
if @file_format_profile.destroy
redirect_to file_format_profiles_path
else
redirect_back alert: 'Unable to destroy this rendering profile', fallback_location: file_format_profiles_path
end
end
protected
def find_file_format_profile
@file_format_profile = FileFormatProfile.find(params[:id])
end
def allowed_params
params[:file_format_profile].permit(:name, :status, :software, :software_version, :os_environment, :os_version, :notes, file_format_ids: [],
content_type_ids: [], file_extension_ids: [])
end
end
|
require 'spec_helper'
#This tests the mechanism for all user accounts
#Ex. The faciliity to log in, sign up, delete, edit etc
describe User do
#This command is run before carrying out all the tests.
before { @user = User.new(name: "Example User", email: "user@example.com", password:"foobar", password_confirmation:"foobar") }
#Make the IVAR @user the subject of the test
subject { @user }
#Test the existence of various attributes
it{ should respond_to(:name) }
it{ should respond_to(:email) }
it{ should respond_to(:password_digest) }
it{ should respond_to(:password) }
it{ should respond_to(:password_confirmation) }
it{ should respond_to(:remember_token) }
it{ should respond_to(:authenticate) }
it{ should respond_to(:admin) }
#Test the passing of any validation
it{ should be_valid }
it{ should_not be_admin }
#create a toggle method when it should be admin
describe "with admin attribute set to true" do
before do
@user.save!
@user.toggle!(:admin) #this changes admin attribtute from false to true
end
it { should be_admin }
end
describe "when name is not present" do
#Set the username to be blank - this should fail validation
before { @user.name = " " }
it { should_not be_valid }
end
describe "when email is not present" do
#Set the email to be blank - this should fail validation
before { @user.email = " " }
it { should_not be_valid }
end
describe "when password is not present" do
#Set the password to be blank - this should fail validation
before { @user.password = " ", @user.password_confirmation = " " }
it { should_not be_valid }
end
describe "when name is too long" do
#Set the username to be over 50 Characters - this should fail validation
before { @user.name = "a"*40 }
it { should_not be_valid }
end
describe "when email is too long" do
#Set the email to be over 128 Characters - this should fail validation
before { @user.email = "a" * 129 }
it { should_not be_valid }
end
describe "when email address is not valid" do
#ensuring invalid email addresses dont get through
it "should be invalid" do
# %w[x y z] makes a string array of x y z
# setting an array of invalid email addresses
addresses = %w[user@foo,com user_at_foo.org example.user@foo. foo@bar_baz.com foo@bar+baz.com foo@bar..com .@c.c shane@cd2.solutions]
addresses.each do |invalid_address|
@user.email = invalid_address
expect(@user).not_to be_valid
end
end
end
describe "when email address is valid" do
#ensuring valid email addresses get through
it "should be valid" do
# setting an array of valid email addresses
addresses = %w[user@foo.COM A_US-ER@f.b.org frst.lst@foo.jp a+b@baz.cn shane@cd2s.co.uk]
addresses.each do |valid_address|
@user.email = valid_address
expect(@user).to be_valid
end
end
end
describe "email address with mixed case" do
let(:mixed_case_email) { "User@ExAmPle.COM" }
it "should be saved as all lower case" do
@user.email = mixed_case_email
@user.save
#reload method recalls the value from the database
expect(@user.reload.email).to eq mixed_case_email.downcase
end
end
describe "when email address is already taken" do
#ensuring the same email isnt used more then once
before do
#user.dup creates a duplicate user
user_with_same_email = @user.dup
#make it uppercase and set the user to uppercase so case insensitive
user_with_same_email.email = @user.email.upcase
user_with_same_email.save
end
it {should_not be_valid}
end
describe "when username is already taken" do
#ensuring the username isnt already taken
before do
#user.dup creates a duplicate user
user_with_same_name = @user.dup
#make it uppercase and set the user to uppercase so case insensitive
user_with_same_name.name = @user.name.upcase
user_with_same_name.save
end
it {should_not be_valid}
end
describe "when password and confirmation dont match" do
#ensuring the same value is in the password and password confirmation boxes
before { @user.password_confirmation = "mismatch" }
#set confo to diff string
it { should_not be_valid }
end
describe "when password password is too short" do
#Set the password to be 5 Characters - this should fail validation
before { @user.password = "a"*5 }
it { should_not be_valid }
end
describe "retrieving the user using authentication" do
#these methods test the return values given email/password combo
#begin method by saving a user to the database as this tests existing user
before { @user.save }
#Create a variable found_user and set equal to result of the find by email
let(:found_user) { User.find_by(email: @user.email) }
describe "with valid password" do
#user.authenticate(password) returns the user if true
#this says the user found by email should equal the user saved by password
it { should eq found_user.authenticate(@user.password) }
end
describe "with invalid password" do
#This returns false as the password "invalid" is wrong
let(:user_with_invalid_password) { found_user.authenticate("invalid") }
it { should_not eq user_with_invalid_password }
#specify does the same as it
specify { expect(user_with_invalid_password).to be_false }
end
end
describe "remember token" do
#test that a user is allocated a session token upon saving a user
before { @user.save }
its(:remember_token){ should_not be_blank }
end
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
root 'tops#index'
resources :tops do
resources :artists
end
resources :artists do
resources :songs
end
end
|
class RawPlane
include Mongoid::Document
field :created_at, type: Time
field :deal_tweeted, type: Boolean, default: false
field :last_updated, type: Time
field :region
field :locality
field :full_address
field :price, type: Float
field :make
field :model
field :year, type: Integer
field :reg_number
field :serial_no
field :location
field :avionics_package
field :engines_mods
field :interior_exterior
field :airframe
field :image_count
field :condition
field :flight_rules
field :link
field :archived_link
field :listing_id
field :category_level
field :total_time, type: Float
field :num_of_seats, type: Float
field :engine_1_time
field :prop_1_time
field :year_painted
field :interior_year
field :engine_2_time
field :useful_load
field :prop_2_time
field :fractional_ownership
field :delisted
field :latest_certficate_reissue_date
field :header_image
after_create :store_standardized_version
def list_date
self.last_updated || self.created_at || self.id.generation_time
end
def self.store_standardized_versions
StandardizedAircraft.where(:likely_avionics_ids.ne => nil).count
while true
print(".")
set = Hash[StandardizedAircraft.where(likely_avionics_ids: nil, original_source: "trade_a_plane").all.shuffle.first(500).collect{|x| [x.original_id, x]}]
rp_slice = RawPlane.where(:id.in => set.values.collect(&:original_id))
likely_avionics_id_set = AvionicsModel.new.analyze(rp_slice.collect(&:avionics_package))
rp_slice.zip(likely_avionics_id_set).each do |rp, avionics|
next if set[rp.id].nil?
set[rp.id].likely_avionics_ids = avionics
set[rp.id].save!
end
end
RawPlane.all.to_a.select{|x| StandardizedAircraft.where(original_id: x.id, original_source: "trade_a_plane").first.nil?}.each_slice(100) do |rp_slice|
likely_avionics_id_set = AvionicsModel.new.analyze(rp_slice.collect(&:avionics_package))
rp_slice.zip(likely_avionics_id_set).each do |rp, avionics|
rp.store_standardized_version(avionics)
end
end
end
def get_make_model_response
MakeModelModel.new.analyze([self.year_make_model_text.strip])
end
def store_standardized_version(likely_avionics_ids=nil)
response = self.get_make_model_response.select{|x| x["success"] == true}
mm = MakeModel.where("make.id" => AircraftSpecRecord.find(response.first["ids"].first).aircraft['make']['id']).first rescue nil
sa = StandardizedAircraft.where(original_id: self.id, original_source: "trade_a_plane").first_or_create
sa.make_model_id = mm.id rescue nil
sa.year = self.year
sa.aftt = self.total_time
sa.smoh_1 = self.engine_1_time.split("_").first.to_i rescue nil
sa.smoh_2 = self.engine_2_time.split("_").first.to_i rescue nil
sa.smoh_3 = nil
sa.smoh_4 = nil
sa.tbo = AircraftSpecRecord.where("aircraft.make.id" => mm.make["id"]).collect{|x| x.aircraft_engines.flatten.collect{|x| x["tbo"]}}.flatten.average rescue nil
sa.interior_quality = self.interior_year ? 1-(self.created_at.year-self.interior_year.to_i).abs/44.0 : 0.5 #magic number from RawPlane.where(:interior_year.ne => nil).collect{|x| x.created_at.year-x.interior_year.to_i}.sort.percentile(0.95)
sa.exterior_quality = self.year_painted ? 1-(self.created_at.year-self.year_painted.to_i).abs/45.0 : 0.5 #magic number from RawPlane.where(:year_painted.ne => nil).collect{|x| x.created_at.year-x.year_painted.to_i}.sort.percentile(0.95)
sa.num_seats = self.num_of_seats
if likely_avionics_ids
sa.likely_avionics_ids = likely_avionics_ids
else
sa.likely_avionics_ids = AvionicsModel.new.analyze([self.avionics_package])[0]
end
sa.reg_no = self.reg_number
sa.serial_no = self.serial_no
sa.category = self.category_level
sa.location = self.full_address
sa.price = self.price
sa.airframe_description = self.airframe
sa.avionics_description = self.avionics_package
sa.list_date = self.list_date
sa.save!
end
def predicted_stock_in_days(days=90)
times = self.similar_planes.collect(&:created_at).sort
per_day = times.count / ((times.last-times.first)/(60*60*24))
{average_per_timeframe: per_day*days, probability_of_stock_in_timeframe: 1-Distribution::Poisson.pdf(0, per_day*days), timeframe: days}
end
def self.get_predictions(filename="plane_preds2.csv")
csv = CSV.open(filename, "w")
RawPlane.where(:price.ne => 0).all.to_a.shuffle.collect{|rp| csv << [rp.make, rp.model, rp.category_level, rp.price, rp.predicted_price]}
csv.close
end
def location_text
self.location && !self.location.empty? ? " in #{self.location}" : ""
end
def year_make_model_text
"#{self.year.to_i == 0 ? "" : self.year} #{self.make.to_s.capitalize} #{self.model.to_s.capitalize}"
end
def pretty_price
self.price.to_i.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse
end
def full_link
"https://trade-a-plane.com#{self.link}"
end
def post_time
(self.created_at || self._id.generation_time).strftime("%Y-%m-%d")
end
def valuation_text
predicted_price = self.predicted_price
return nil if predicted_price.nil?
residual = self.price.to_i-predicted_price
residual_pct = residual.abs/self.price.to_f
return nil if residual_pct.abs > 0.40
"#{residual > 0 ? "overvalued" : "undervalued"} by #{((residual_pct).round(2)*100).to_i}%"
end
def price_with_valuation_text
valuation_text = self.valuation_text
if valuation_text.nil?
"Priced at $#{self.pretty_price}"
else
"Priced at $#{self.pretty_price}, #{self.valuation_text}"
end
end
def predicted_price
RawPlaneObservation.where(raw_plane_id: self.id).first.predict_price rescue nil
end
def predicted_price_python_load
RawPlaneObservation.where(raw_plane_id: self.id).first.predict_price(false, true) rescue nil
end
def plane_online?
page_data = Nokogiri.parse(RestClient::Request.execute(:url => "https://trade-a-plane.com"+self.link, :method => :get, :verify_ssl => false));false
page_data.search("title").text.include?(self.listing_id)
end
def imputed_record
similar_planes = self.similar_planes.to_a
# similar_planes = self.similar_planes.to_a.select{|x| x.created_at < self.created_at}
record = self.to_hash.merge(Hash[self.empty_fields.collect do |field|
[field, determine_likeliest_value(field, similar_planes.collect{|x| x.send(field)})]
end].merge(similar_price: similar_planes.collect(&:price).collect(&:to_i).reject(&:zero?).average))
record["appraisal_range"] = appraisal_range(record)
record
end
def appraisal_range(imputed_record)
Appraiser.likely_appraisal_for_imputed_record(imputed_record)[-1]
end
def to_hash
Hash[self.fields.keys.collect{|f| [f, self.send(f)]}]
end
def empty_fields
Hash[self.fields.collect{|k,v| [k, self.send(k)]}.select{|k,v| self.bad_value(k,v)}].keys
end
def bad_value(field,value)
if ["price", "year", "interior_year", "exterior_year"].include?(field)
value.nil? || value.to_f.zero?
else
value.nil?
end
end
def similar_models
if RawPlane.where(make: self.make).count > 10 and RawPlane.where(make: self.make, model: self.model).count <= 10
model_counts = RawPlane.where(make: self.make, :id.ne => self.id).collect(&:model).counts
similarities = Hash[model_counts.collect{|alter, count| [alter, String::Similarity.cosine(self.model, alter)]}]
cur_count = 0
models = []
similarities.collect{|k,v| val= (v/similarities.values.max+model_counts[k]/model_counts.values.sum); [k, val.nan? ? 0 : val]}.sort_by{|k,v| v}.reverse.each do |model, score|
cur_count += model_counts[model]
models << model
break if cur_count > 10
end
return models
elsif RawPlane.where(make: self.make).count <= 10
return RawPlane.where(make: self.make).collect(&:model).uniq
elsif RawPlane.where(make: self.make, model: self.model).count > 10
return [self.model]
end
end
def similar_years
if self.year && self.year.to_i != 0
return (self.year-3).upto((self.year+3)).to_a
else
average_years = RawPlane.where(make: self.make, :model.in => self.similar_models).collect(&:year).collect(&:to_i).reject{|x| x == 0}
average_years = RawPlane.where(make: self.make).collect(&:year).collect(&:to_i).reject{|x| x == 0} if average_years.empty?
average_years = RawPlane.where(:year.nin => ["0", 0, nil]).only(:year).collect(&:year).reject{|x| x == 0} if average_years.empty?
average_year = average_years.average.to_i
return (average_year-3).upto((average_year+3)).to_a
end
end
def similar_planes
RawPlane.where(make: self.make).and(RawPlane.or({:model.in => self.similar_models}, {:year.in => self.similar_years}).selector)
end
def determine_likeliest_value(field, values)
if ["price", "total_time", "num_seats", "engine_1_time", "prop_1_time", "engine_2_time", "prop_2_time", "year_painted", "interior_year", "useful_load"].include?(field)
return values.compact.empty? ? 0 : values.compact.collect(&:to_i).average
elsif field == "year"
return values.compact.reject(&:zero?).empty? ? 0 : values.compact.reject(&:zero?).average
else
return values.compact.mode
end
end
def disambiguated_avionics(avionic, limit=100)
AvionicDisambiguator.disambiguation_candidates(avionic, limit)
end
def imputed_avionics
NewAvionicsMatchRecord.generate(self.avionics_package)
NewAvionicsMatchRecord.where(:given_name.in => self.avionics_package, :probability.gte => 0.5).collect(&:resolved_avionic)
end
def old_imputed_avionics
self.avionics_package.collect{|av| GenerateAvionicsMatchRecord.new.perform(av) if AvionicsMatchRecord.where(given_name: av).first.nil? ; [av, AvionicsMatchRecord.where(given_name: av).first.likeliest_choice]}.select{|k,v| v.last > 0.5}.collect{|k,x| [x[0][1]["avionic_type"], x[0][1]["manufacturer"], x[0][1]["device"]]}
end
def imputed_results
imputed_record.merge({
"avionics_package" => imputed_avionics
})
end
def future_outlook(days=90)
obs = RawPlane.where(:price.nin => [nil, 0.0], make: self.make, model: self.model, :year.gte => self.year-10, :year.lte => self.year+10, :created_at.gte => Time.now-60*60*24*365*2).order(:created_at.asc).to_a
if obs.to_a.length < 10
obs = self.similar_planes.select{|x| x.created_at > Time.now-60*60*24*365}
end
low = obs.collect(&:price).percentile(0.15)
high = obs.collect(&:price).percentile(0.85)
x, y = obs.select{|r| r.price > low && r.price < high}.collect{|r| [(r.created_at-obs.first.created_at)/(60*60*24), r.price]}.transpose
lineFit = LineFit.new
return nil if x.nil? || x.to_a.length == 1
lineFit.setData(x,y)
intercept, slope = lineFit.coefficients
residuals = lineFit.residuals
r2 = lineFit.rSquared
if r2 > 0.2 && x.to_a.length > 8
return {future_value: ((slope * days) / y.average).percent, days_out: days, future_error: (residuals.collect(&:abs).median / y.average).percent}
else
return {error: "No discernible trend - market is stable right now."}
end
end
def self.distinct_values
@@distinct_values ||= BSON::Document.new({
category_level: RawPlane.distinct(:category_level),
region: RawPlane.distinct(:region),
make: RawPlane.distinct(:make),
model: RawPlane.distinct(:model),
condition: RawPlane.distinct(:model),
flight_rules: RawPlane.distinct(:flight_rules),
avionic_avionic_type: AvionicDisambiguator.avionics_manifest.keys,
avionic_manufacturer: AvionicDisambiguator.avionics_manifest.values.collect(&:keys).flatten.uniq,
avionic_device: AvionicDisambiguator.avionics_manifest.values.collect(&:values).flatten.uniq,
})
end
def self.avionic_data(imputed_results, distinct_values)
imputed_results["avionics_package"].collect{|x|
[
distinct_values[:avionic_avionic_type].index(x[0]),
distinct_values[:avionic_manufacturer].index(x[1]),
distinct_values[:avionic_device].index(x[2])
]
}.transpose.collect(&:counts)
end
def self.transform_to_row(imputed_results, distinct_values)
{base_record: [
(imputed_results["last_updated"]||Time.now).strftime("%Y").to_i,
(imputed_results["last_updated"]||Time.now).strftime("%m").to_i,
(imputed_results["last_updated"]||Time.now).strftime("%w").to_i,
distinct_values[:region].index(imputed_results["region"])||-1,
distinct_values[:category_level].index(imputed_results["category_level"])||-1,
distinct_values[:make].index(imputed_results["make"])||-1,
distinct_values[:model].index(imputed_results["model"])||-1,
imputed_results["year"].to_i,
imputed_results["image_count"],
distinct_values[:condition].index(imputed_results["condition"])||-1,
distinct_values[:category_level].index(imputed_results["category_level"])||-1,
imputed_results["total_time"].to_i,
imputed_results["num_of_seats"].to_i,
imputed_results["engine_1_time"].to_i,
imputed_results["prop_1_time"].to_i,
imputed_results["year_painted"].to_i,
imputed_results["interior_year"].to_i,
imputed_results["engine_2_time"].to_i,
imputed_results["useful_load"].to_i,
imputed_results["prop_2_time"].to_i,
imputed_results["similar_price"]||imputed_results[:similar_price],
(imputed_results["appraisal_range"][0] rescue 0),
(imputed_results["appraisal_range"][1] rescue 0),
# ].collect{|x| x.nan? ? 0 : x}}.merge(avionic_data: self.avionic_data(imputed_results, distinct_values), price: imputed_results["price"])
]}.merge(avionic_data: self.avionic_data(imputed_results, distinct_values), price: imputed_results["price"])
end
def self.generate_make_model_variations
make_models = RawPlane.only(:make, :model).collect{|k| [k.make, k.model]};false
csv = CSV.open("model_name_variations.csv", "w")
i = 0
make_models.each do |make, model|
i += 1
puts i
makes = [AvionicDisambiguator.avionic_substring_generator(make), AvionicDisambiguator.avionic_substring_generator(make.downcase), AvionicDisambiguator.avionic_substring_generator(make.split(" ").collect(&:capitalize).join(" "))].flatten
models = [AvionicDisambiguator.avionic_substring_generator(model), AvionicDisambiguator.avionic_substring_generator(model.downcase), AvionicDisambiguator.avionic_substring_generator(model.split(" ").collect(&:capitalize).join(" "))].flatten
makes.each do |m|
models.each do |mm|
f = m+" "+mm
csv << [f] if f.gsub(" ", "").length > 4
f = mm+" "+m
csv << [f] if f.gsub(" ", "").length > 4
end
end
end;false
csv.close
end
def self.generate_price_history_high_level
mapped = {}
RawPlane.all.each do |rp|
if rp.price > 0
mapped[rp.category_level] ||= {}
mapped[rp.category_level][rp.make+" "+rp.model] ||= {}
mapped[rp.category_level][rp.make+" "+rp.model][rp.id.generation_time.strftime("%Y-%m")] ||= []
mapped[rp.category_level][rp.make+" "+rp.model][rp.id.generation_time.strftime("%Y-%m")] << rp.price
end
end;false
normalized = {}
mapped.each do |catlevel, makes|
normalized[catlevel] ||= {}
makes.each do |make, data|
sorted = data.sort_by{|k,v| k}.collect{|k,v| [k, v.sort.median]}
sorted[1..-1].collect{|k,v|
normalized[catlevel][k] ||= []
normalized[catlevel][k] << v.to_f/sorted.first.last
}
end
end;false
puts normalized.collect{|c, d| [c, d.sort_by{|k,v| k}.collect{|k,v| [k,v.median].join(",")}]}
end
end
|
class PlayerActivityJob < ActiveJob::Base
queue_as :urgent
def perform(player_id)
player = Player.find(player_id)
Player::SaveActivity.call(player)
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe RouteStop do
it { should belong_to(:bus_route) }
it { should belong_to(:bus_route) }
it { should have_many(:pickups) }
it { should have_many(:dropoffs) }
it { should have_db_column(:stop_time) }
it { should validate_presence_of(:stop_time) }
end
|
module::Dieroll
class Roller
attr_reader :total
# Roll 1dX
def self.d(sides)
rand(1..sides)
end
# Roll arbitrary dice notation string
def self.from_string(string)
rolls = [0]
sets = s_to_set(string)
sets.each do |set|
if(set.respond_to?(:count) && set.count == 4)
rolls << roll(set[0], set[1])
rolls[0] += rolls.last.total if set[2] == '+'
rolls[0] -= rolls.last.total if set[2] == '-'
elsif
rolls[0] += set
end
end
rolls
end
# Create roller object
def initialize(string)
@string = string
@sets = Roller.s_to_set(string)
@dice_sets = []
@mods = []
@total = 0
@sets.each do |set|
if(set.respond_to?(:count))
@dice_sets << Dieroll::DiceSet.new(set[0], set[1],
set[2], set[3])
else
@mods << set
end
end
end
# Updates the object to use a new dice notation string
def string=(string)
@string = string
@odds = nil
initialize(@string)
end
# Rolls the Roller. Returns the total.
def roll(save=false)
total = 0
@dice_sets.each do |set|
if save
total += set.roll!
else
total += set.roll
end
end
@mods.each do |mod|
total += mod
end
@total = total if save
total
end
# Rolls the Roller. Returns the total. Sets @total.
def roll!
roll(true)
end
# Return roll result as string
def report(formatted=true)
if(formatted)
output = @total.to_s + "\n"
output += @string.to_s + ":\n"
@dice_sets.each do |set|
output += set.report + "\n"
end
@mods.each do |mod|
output += "+" if mod >= 0
output += mod.to_s + "\n"
end
else
set_reports = []
@dice_sets.each do |set|
set_reports << set.report
end
output = {
:total => @total,
:string => @string,
:sets => set_reports,
:mods => @mods}
end
output
end
# Returns @odds. Creates an Odds object if !@odds.
def odds
calculate_odds unless !!@odds
@odds
end
# Returns @total as a string
def to_s
@total.to_s
end
private
# Creates the the Odds object for the roller.
def calculate_odds
@dice_sets.each_with_index do |set, index|
if(index == 0)
@odds = set.odds
else
@odds *= set.odds
end
end
@mods.each do |mod|
@odds += mod
end
end
def self.roll(num, sides)
total = 0
dice = []
num.times do
dice << d(sides)
end
Dieroll::Result.new(sides, dice)
end
# Parse str and return an array to create DiceSets.
def self.s_to_set(str)
sets = []
set_strings = str.scan(/^[^+|-]+|[+|-][^+|-]+/)
set_strings.each do |set_string|
set_string =~ /^([^\/]+)\/?([^\/]*)$/
set_string, drop_string = $1, $2
drop_string = nil if drop_string.empty?
set_string =~ /^([+|-]?)(\d+)(d\d+)?/
sign, num, sides = $1, $2, $3
sign = '+' if sign.empty?
set = []
if(!!sides)
sides.delete! "d"
set = [num.to_i, sides.to_i, sign, drop_string]
else
set = num.to_i
set *= -1 if sign == '-'
end
sets << set
end
sets
end
end
end
|
require 'test_helper'
class Liquid::Drops::UserDropTest < ActiveSupport::TestCase
include Liquid
def setup
@buyer = FactoryBot.create(:buyer_account)
@user = @buyer.users.first
@drop = Drops::User.new(@user)
end
test '#display_name' do
assert_equal @user.decorate.display_name, @drop.display_name
end
test '#informal_name' do
assert_equal @user.decorate.informal_name, @drop.informal_name
end
test '#name' do
assert_equal @user.decorate.full_name, @drop.name
end
def test_oauth2
@user.signup.expects(:oauth2?).returns(true)
assert @drop.oauth2?
@user.signup.expects(:oauth2?).returns(false)
refute @drop.oauth2?
end
should 'returns roles_collection' do
User.current = @user
assert_kind_of Array, @drop.roles_collection
assert_kind_of Liquid::Drops::User::Role, @drop.roles_collection[0]
end
should 'returns url' do
assert_equal "/admin/account/users/#{@user.id}", @drop.url
end
should 'returns edit_url' do
assert_equal "/admin/account/users/#{@user.id}/edit", @drop.edit_url
end
should 'return the role as string' do
assert_equal(@user.role.to_s, @drop.role)
end
context 'by a buyer' do
setup do
::User.current = @user
@drop2 = Drops::User.new(FactoryBot.create(:user, account: @buyer))
end
should "can be destroyed" do
assert @drop2.can.be_destroyed?
end
should "can be managed" do
assert @drop2.can.be_managed?
end
should "can be update role" do
assert @drop2.can.be_update_role?
end
end
context 'by a normal user' do
setup do
::User.current = FactoryBot.create(:user, account: @buyer)
end
should "can't be destroyed" do
assert !@drop.can.be_destroyed?
end
should "can't be managed" do
assert !@drop.can.be_managed?
end
should "can't be update role" do
assert !@drop.can.be_update_role?
end
end
context '#sections' do
context 'users with no sections' do
should 'be empty' do
user_drop = Drops::User.new(@user)
assert user_drop.sections.empty?
end
end # users with no sections
context 'users with sections' do
setup do
@section = FactoryBot.create(:cms_section, :public => false,
:provider => @buyer.provider_account,
:title => "protected-section",
:parent => @buyer.provider_account.sections.root)
grant_buyer_access_to_section @buyer, @section
end
should 'return sections paths' do
user_drop = Drops::User.new(@user)
assert user_drop.sections == ["/protected-section"]
end
end # users with sections
end # sections
context "field definitions" do
setup do
[{ target: "User", name: "first_name", label: "first_name", hidden: true },
{ target: "User", name: "visible_extra", label: "visible_extra" },
{ target: "User", name: "hidden_extra", label: "hidden_extra", hidden: true }]
.each do |field|
FactoryBot.create :fields_definition, field.merge({account_id: @buyer.provider_account.id})
end
@buyer.reload
@user = FactoryBot.create :user, account: @buyer
@user.extra_fields = {"visible_extra" => "visible extra value", "hidden_extra" => "hidden extra value" }
@user.save!
@drop = Drops::User.new(@user)
end
should '#fields' do
assert @drop.fields.first.is_a?(Drops::Field)
end
should '#fields contain both visible and invisible' do
@user.username = 'someone'
@user.first_name = 'John'
assert_equal 'someone', @drop.fields["username"].to_str
assert_equal 'John', @drop.fields["first_name"].to_str
end
should '#fields include extra fields and builtin fields' do
#regression test
assert_not_nil @drop.fields["visible_extra"]
assert_not_nil @drop.fields["first_name"]
assert_not_nil @drop.fields["username"]
end
should 'be fields' do
assert @drop.extra_fields.first.is_a?(Drops::Field)
end
should '#extra visible and invisible' do
assert_equal "visible extra value", @drop.extra_fields["visible_extra"]
assert_equal "hidden extra value", @drop.extra_fields["hidden_extra"]
end
should 'not return builtin fields' do
assert_nil @drop.extra_fields["username"]
end
end # field definitions
end
|
class User < ApplicationRecord
has_secure_password
has_many :addresses, dependent: :destroy
has_many :cart_items, dependent: :destroy
has_many :orders, dependent: :destroy
validates :roll, presence: true
validates_acceptance_of :roll, accept: ["admin", "user", "clerk"]
validates :email, presence: true
validates :email, :uniqueness => true
validates :password, presence: true
validates :password, length: { minimum: 8, maximum: 16 }
validates :phonenumber, presence: true
validates :phonenumber, length: { minimum: 10, maximum: 13 }
validates :name, presence: true
validates :name, length: { minimum: 2 }
end
|
module FreeKindleCN
class Item
def initialize(subject)
@subject = subject
end
# asin, title, amount, details_url, review*, image_url, author*,
# binding*, brand, ean, edition, isbn,
# item_dimensions, item_height, item_length, item_width, item_weight,
# package_dimensions, package_height, package_length, package_width, package_weight,
# label, language, formatted_price, manufacturer, mpn,
# page_count*, part_number, product_group, publication_date, publisher*,
# sku, studio, total_new, total_used
def method_missing(sym, *args, &block)
@subject.send sym, *args, &block
end
def thumb_url
medium_image!.url
end
def book_price
load_price unless @book_price
@book_price
end
def kindle_price
load_price unless @kindle_price
@kindle_price
end
# get author using the following orders:
# - use Author (or CSV when it is an array)
# - use Creator (or CSV when it is an array)
# - empty string
def author
@author ||=
convert_content(item_attributes!.author) ||
convert_content(item_attributes!.creator) ||
""
end
def review
convert_content(editorial_reviews!.editorial_review!, true).content
end
def publisher
# have to prefix @subject to avoid loop
@subject.publisher.to_s
end
def num_of_pages
page_count.to_i
end
def release_date
item_attributes!.release_date
end
def binding
case item_attributes!.binding
when "平装"
"paperback"
when "Kindle版"
when "Kindle电子书"
"kindle"
when "精装"
"hardcover"
else
# other known bindings: "CD"
nil
end
end
def isbn13
# only keep first 13 digits
# e.g. for B008H0H9FO, the EAN is 9787510407550 01
isbn = ean[0..12] rescue nil
self.class.is_valid_isbn?(isbn) ? isbn : nil
end
def save
now = Time.now
DB::Item.first_or_create({:asin => asin},
{:title => title,
:review => review,
:image_url => image_url,
:thumb_url => thumb_url,
:author => author,
:publisher => publisher,
:num_of_pages => num_of_pages,
:publication_date => publication_date,
:release_date => release_date,
:book_price => -1,
:kindle_price => -1,
:discount_rate => 1.0,
:created_at => now,
:updated_at => now}
)
rescue => e
d "Skip saving because of Exception: #{e.message}"
nil
end
private
def load_price
parser = Updater.fetch_price(asin)
if parser.parse_result == FreeKindleCN::Parser::Base::RESULT_SUCCESSFUL
@kindle_price = parser.kindle_price
@book_price = parser.book_price
end
end
# when content is an array, return first element or CSV string
def convert_content(content, array_get_first_element = false)
if content.is_a?(Array)
if array_get_first_element
content.first
else
content.join(",")
end
else
content
end
end
class << self
# this is probably wrong in some case for paper book (some even uses ISBN directly)
def is_valid_asin?(asin)
asin =~ /^B[A-Z0-9]{9}$/
end
def is_valid_isbn?(isbn)
isbn =~ /^\d+$/
end
def douban_api_url(douban_id)
douban_id ? "http://api.douban.com/v2/book/#{douban_id}" : "#"
end
def douban_page_url(douban_id)
douban_id ? "http://book.douban.com/subject/#{douban_id}/" : "#"
end
def goldread_url(asin)
asin ? "http://goldread.net/dp/#{asin}" : "#"
end
def amazon_url(asin)
asin ? "http://www.amazon.cn/dp/#{asin}" : "#"
end
def formatted_discount_rate(discount_rate)
"%.1f折" % (discount_rate.to_f * 10)
end
def formatted_rating(average, num_of_votes)
"#{average.to_f / 10} (#{num_of_votes})" if (average && num_of_votes)
end
end
end
end
|
class IsHideByAdminInItemComments < ActiveRecord::Migration
def change
add_column :item_comments, :is_hide_reward_by_admin, :integer,:default => 0
end
end
|
class Exercise < ActiveRecord::Base
self.per_page = 10
# default_scope where("visibility IS 'Published'")
attr_accessible :name, :type, :information, :visibility, :information_attributes, :owner,
:distance, :hours, :minutes, :seconds, :reps, :unit
has_one :information
belongs_to :owner, :class_name => "User", :foreign_key => "owner_id"
has_and_belongs_to_many :trainings_sessions
has_many :likes, :as => :likable
validates_presence_of :name
validates_presence_of :type
validates_presence_of :information
validates_presence_of :owner
accepts_nested_attributes_for :information, allow_destroy: true
scope :published, where("visibility IS 'Published'")
scope :unpublished, where("visibility IS 'Private'")
scope :owned_by, lambda { |id| where("owner_id = ?", id) }
scope :liked_by, lambda { |id| joins(:likes).where("likes.user_id = ?", id) }
def self.visibility_options
["Published", "Private"]
end
def self.unit_options
["Km","Mile","Meter"]
end
def self.type_options
["DistanceExercise", "RepsExercise", "TimeExercise"]
end
validates_inclusion_of :visibility, :in=>visibility_options, :allow_nil => false
def self.search_by_name(name)
if name && ! name.empty?
where('name LIKE ?', "%#{name}%")
else
scoped
end
end
def self.search_by_type(type)
if type && ! type.empty?
where('type LIKE ?', "%#{type}%")
else
scoped
end
end
def self.search_by_owner(username)
if username && ! username.empty?
joins(:owner).where('users.username LIKE ?', "%#{username}%")
else
scoped
end
end
def self.select_options
descendants.map{ |c| c.to_s }.sort
end
def self.inherited(child)
child.instance_eval do
def model_name
Exercise.model_name
end
end
super
end
end
class DistanceExercise < Exercise
attr_accessible :distance, :unit, :hours, :minutes, :seconds
validates_presence_of :distance
validates_presence_of :unit
end
class TimeExercise < Exercise
attr_accessible :hours, :minutes, :seconds
validates_presence_of :hours
validates_presence_of :minutes
validates_presence_of :seconds
end
class RepsExercise < Exercise
attr_accessible :reps, :hours, :minutes, :seconds
validates_presence_of :reps
end
|
require 'tmpdir'
require 'fileutils'
module Guard
class PHPUnit2
# The Guard::PHPUnit runner handles running the tests, displaying
# their output and notifying the user about the results.
#
class RealtimeRunner < Runner
def self.run(paths, options)
self.new.run(paths, options)
end
protected
def parse_output(log)
LogReader.parse_output(log)
end
# Generates the phpunit command for the tests paths.
#
# @param (see #run)
# @param (see #run)
# @see #run_tests
#
def phpunit_command(path, options, logfile)
super(path, options) do |cmd_parts|
cmd_parts << "--log-json #{logfile}"
end
end
# Executes a system command but does not return the output
#
# @param [String] command the command to be run
#
def execute_command(command)
system(command)
end
def execute_phpunit(tests_folder, options)
require 'tempfile'
log_file = Tempfile.new "guard-phpunit2"
execute_command(phpunit_command(tests_folder, options, log_file.path))
log = log_file.read
log_file.close
log_file.unlink
log
end
end
end
end
|
class MapsController < ApplicationController
before_action :authenticate_entity!
# Definition: Gets all online startups in the db and shows them on the map.
# Input: Startup Table.
# Output: Online Startups.
# Author: Alia Tarek.
def show_online
if params[:sector] == "please select a sector..."
@online = Startup.where(:online_status => true)
end
if params[:sector ]!= "please select a sector..."
@online = Startup.where(sector: params[:sector]).where(:online_status == true)
end
@markers = Gmaps4rails.build_markers(@online) do |online, marker|
marker.lat online.latitude
marker.lng online.longitude
marker.infowindow online.name
marker.picture({
"url" => "http://rideforclimate.com/nukes/all/images/blue.png",
"width" => 32,
"height" => 32})
end
render :json => @markers
end
# Definition: Gets all offline startups in the db and shows them on the map.
# Input: Startup Table.
# Output: Onffline Startups.
# Author: Alia Tarek.
def show_offline
if params[:sector] == "please select a sector..."
@offline = Startup.where(:online_status => false)
end
if params[:sector] != "please select a sector..."
@offline = Startup.where(sector: params[:sector]).where(:online_status == false)
end
@markers = Gmaps4rails.build_markers(@offline) do |offline, marker|
marker.lat offline.latitude
marker.lng offline.longitude
marker.infowindow offline.name
marker.picture({
"url" => "http://rideforclimate.com/nukes/all/images/red.png",
"width" => 32,
"height" => 32})
end
render :json => @markers
end
# Definition: Gets all Investors in the db and shows them on the map.
# Input: Investors Table.
# Output: All Investors.
# Author: Alia Tarek.
def show_investors
if params[:sector] == "please select a sector..."
@investors = Investor.all
end
if params[:sector] != "please select a sector..."
@investors = Investor.where(sector: params[:sector])
end
@markers = Gmaps4rails.build_markers(@investors) do |investors, marker|
marker.lat investors.latitude
marker.lng investors.longitude
marker.infowindow investors.name
marker.picture({
"url" => "http://rideforclimate.com/nukes/all/images/orange.png",
"width" => 32,
"height" => 32})
end
render :json => @markers
end
# Definition: Gets all Services in the db and shows them on the map.
# Input: Services Table.
# Output: All Services.
# Author: Alia Tarek.
def show_services
if params[:sector] == "please select a sector..."
@services = Service.all
end
if params[:sector] != "please select a sector..."
@services = Service.where(sector: params[:sector])
end
@markers = Gmaps4rails.build_markers(@services) do |services, marker|
marker.lat services.latitude
marker.lng services.longitude
marker.infowindow services.name
marker.picture({
"url" => "http://rideforclimate.com/nukes/all/images/green.png",
"width" => 32,
"height" => 32})
end
render :json => @markers
end
# Definition: Gets all merged startups in the db and shows them on the map.
# Input: Startup Table.
# Output: Merged Startups.
# Author: Alia Tarek.
def show_merged
if params[:sector] == "please select a sector..."
@merged = Startup.where.not(:joint_ventures => "")
end
if params[:sector] != "please select a sector..."
@merged = Startup.where(sector: params[:sector]).where.not(:joint_ventures => "")
end
@markers = Gmaps4rails.build_markers(@merged) do |joint, marker|
marker.lat joint.latitude
marker.lng joint.longitude
marker.infowindow joint.name
marker.picture({
"url" => "http://rideforclimate.com/nukes/all/images/yellow.png",
"width" => 32,
"height" => 32})
end
render :json => @markers
end
end
|
# frozen_string_literal: true
require "dry/core/equalizer"
require "dry/types/options"
require "dry/types/meta"
module Dry
module Types
module Composition
include Type
include Builder
include Options
include Meta
include Printable
include Dry::Equalizer(:left, :right, :options, :meta, inspect: false, immutable: true)
# @return [Type]
attr_reader :left
# @return [Type]
attr_reader :right
module Constrained
def rule
left.rule.public_send(self.class.operator, right.rule)
end
def constrained?
true
end
end
def self.included(base)
composition_name = Inflector.demodulize(base)
ast_type = Inflector.underscore(composition_name).to_sym
base.define_singleton_method(:ast_type) { ast_type }
base.define_singleton_method(:composition_name) { composition_name }
base.const_set("Constrained", Class.new(base) { include Constrained })
end
# @param [Type] left
# @param [Type] right
# @param [Hash] options
#
# @api private
def initialize(left, right, **options)
super
@left, @right = left, right
freeze
end
# @return [String]
#
# @api public
def name
[left, right].map(&:name).join(" #{self.class.operator} ")
end
# @return [false]
#
# @api public
def default?
false
end
# @return [false]
#
# @api public
def constrained?
false
end
# @return [Boolean]
#
# @api public
def optional?
false
end
# @param [Object] input
#
# @return [Object]
#
# @api private
def call_unsafe(input)
raise NotImplementedError
end
# @param [Object] input
#
# @return [Object]
#
# @api private
def call_safe(input, &block)
raise NotImplementedError
end
# @param [Object] input
#
# @api public
def try(input)
raise NotImplementedError
end
# @api private
def success(input)
result = try(input)
if result.success?
result
else
raise ArgumentError, "Invalid success value '#{input}' for #{inspect}"
end
end
# @api private
def failure(input, _error = nil)
result = try(input)
if result.failure?
result
else
raise ArgumentError, "Invalid failure value '#{input}' for #{inspect}"
end
end
# @param [Object] value
#
# @return [Boolean]
#
# @api private
def primitive?(value)
raise NotImplementedError
end
# @see Nominal#to_ast
#
# @api public
def to_ast(meta: true)
[self.class.ast_type,
[left.to_ast(meta: meta), right.to_ast(meta: meta), meta ? self.meta : EMPTY_HASH]]
end
# Wrap the type with a proc
#
# @return [Proc]
#
# @api public
def to_proc
proc { |value| self.(value) }
end
end
end
end
|
class AlterFlightsTable < ActiveRecord::Migration[6.0]
def change
add_column :flights, :seconds_duration, :integer
remove_column :flights, :duration
end
end
|
require 'spec_helper'
module Categoryz3
describe Item do
let(:category) { FactoryGirl.build(:category) }
let(:item) { FactoryGirl.create(:item, category: category) }
context "child items" do
context "first level item" do
it "should create child items when created" do
item
child_item = category.child_items.first
child_item.categorizable.should == item.categorizable
child_item.category.should == item.category
end
it "should remove the child items when deleted" do
item
count = category.child_items.count
item.destroy
category.reload
category.child_items.count.should == count - 1
end
end
context "multi level item" do
let(:subcategory) { FactoryGirl.create(:category, :child, parent: FactoryGirl.create(:category, :child, parent: category))}
it "should create child items for all subcategories when created" do
item = FactoryGirl.create(:item, category: subcategory)
subcategory.path.each do |category|
child_item = category.child_items.first
child_item.categorizable.should == item.categorizable
end
end
it "should remove child items from all categories when deleted" do
item = FactoryGirl.create(:item, category: subcategory)
subcategory.path.each { |category| category.child_items.count.should == 1 }
item.destroy
subcategory.path.each { |category| category.child_items.count.should == 0 }
end
end
context "reprocessing items" do
let(:root_category) { FactoryGirl.create(:category) }
let(:category) { FactoryGirl.create(:category, :child, parent: root_category) }
it "should recreate all child items on reprocess" do
expect {
item.reprocess_child_items!
}.to_not change { item.reload.child_items.count }
end
end
end
end
end
|
# frozen_string_literal: true
require "rails_helper"
module Renalware
module Diaverum
module Incoming
RSpec.describe SessionBuilders::Factory do
context "when the Diaverum XML treatment node has a start time" do
it "returns a SessionBuilders::Closed instance" do
args = {
treatment_node: instance_double(Nodes::Treatment, StartTime: "13:00"),
user: instance_double(User),
patient: instance_double(Patient),
patient_node: instance_double(Nodes::Patient)
}
builder = described_class.builder_for(**args)
expect(builder).to be_kind_of(Renalware::Diaverum::Incoming::SessionBuilders::Closed)
end
end
context "when the Diaverum XML treatment node has NO start time" do
it "returns a SessionBuilders::DNA instance" do
args = {
treatment_node: instance_double(Nodes::Treatment, StartTime: nil),
user: instance_double(User),
patient: instance_double(Patient),
patient_node: instance_double(Nodes::Patient)
}
builder = described_class.builder_for(**args)
expect(builder).to be_kind_of(Renalware::Diaverum::Incoming::SessionBuilders::DNA)
end
end
end
end
end
end
|
require_relative '../helper'
# require_relative 'app_identifier_guesser'
module PantographCore
class ActionLaunchContext
UNKNOWN_P_HASH = 'unknown'
attr_accessor :action_name
attr_accessor :p_hash
attr_accessor :platform
attr_accessor :pantograph_client_language # example: ruby pantfile
def initialize(action_name: nil, p_hash: UNKNOWN_P_HASH, platform: nil, pantograph_client_language: nil)
@action_name = action_name
@p_hash = p_hash
@platform = platform
@pantograph_client_language = pantograph_client_language
end
def self.context_for_action_name(action_name, pantograph_client_language: :ruby, args: nil)
# app_id_guesser = PantographCore::AppIdentifierGuesser.new(args: args)
return self.new(
action_name: action_name,
p_hash: UNKNOWN_P_HASH,
# platform: nil,
pantograph_client_language: pantograph_client_language
)
end
def build_tool_version
case platform
when :linux
return 'linux'
when :windows
return 'windows'
else
return "Xcode #{Helper.xcode_version}"
end
end
end
end
|
describe SetupWizardController do
describe '/apply' do
it 'should not apply the settings if an env is duplicate' do
payload = {
application: {
name: 'WEBv1'
},
envs: [
{ name: 'dev' }, { name: 'uat2' }, { name: 'prod2' }
],
hosts: {
dev: [
name: 'dev.myapp.lan',
fqdn: 'dev.myapp.lan',
ip: '127.0.0.1'
],
uat: [
name: 'uat.myapp.lan',
fqdn: 'uat.myapp.lan',
ip: '127.0.0.1'
],
prod: [
name: 'prod.myapp.lan',
fqdn: 'prod.myapp.lan',
ip: '127.0.0.1'
]
},
credentials: {
dev: 'myapp',
uat: 'myapp',
prod: 'myapp'
}
}
post(
'/setup_wizard/apply',
payload.to_json,
'CONTENT_TYPE': 'application/json'
)
expect(last_response.status).to eq 409
result = JSON.parse(last_response.body, symbolize_names: true)
expect(result[:conflicts][:application].length).to eq 0
expect(result[:conflicts][:envs]).to eq ['dev']
expect(result[:conflicts][:hosts].length).to eq 0
expect(result[:conflicts][:credentials].length).to eq 0
end
it 'should apply the settings' do
payload = {
application: {
name: 'SetupWizardApplication'
},
envs: [
{ name: 'dev' }, { name: 'uat' }, { name: 'prod' }
],
hosts: {
dev: [
name: 'dev.myapp.lan',
fqdn: 'dev.myapp.lan',
ip: '127.0.0.1'
],
uat: [
name: 'uat.myapp.lan',
fqdn: 'uat.myapp.lan',
ip: '127.0.0.1'
],
prod: [
name: 'prod.myapp.lan',
fqdn: 'prod.myapp.lan',
ip: '127.0.0.1'
]
},
credentials: {
dev: 'myapp',
uat: 'myapp',
prod: 'myapp'
}
}
post(
'/setup_wizard/apply',
payload.to_json,
'CONTENT_TYPE': 'application/json'
)
expect(last_response.status).to eq 200
result = JSON.parse(last_response.body, symbolize_names: true)
expect(result[:results][:application].length).to eq 1
app = Application.find_by_id(result[:results][:application][0][:application_id])
app_envs = app.envs.sort_by(&:id).map do |env|
{ name: env.name }
end
app_hosts = {}
app.envs.each do |env|
app_hosts[env.name.to_sym] = env.hosts.map do |host|
{
name: host.name,
fqdn: host.fqdn,
ip: host.ip
}
end
end
app_credentials = {}
app.envs.each do |env|
app_credentials[env.name.to_sym] = env.credential.depuser.username
end
expect(app.name).to eq payload[:application][:name]
expect(app_envs).to eq payload[:envs]
expect(app_hosts).to eq payload[:hosts]
expect(app_credentials).to eq payload[:credentials]
end
end
end
|
require 'cgi'
module Imdb #:nordoc:
module StringExtensions
if RUBY_VERSION.to_f < 1.9
# Unescape HTML
require 'iconv'
def imdb_unescape_html
Iconv.conv("UTF-8", 'ISO-8859-1', CGI::unescapeHTML(self)).strip
end
else
def imdb_unescape_html
CGI::unescapeHTML(self).encode(Encoding::UTF_8, :invalid => :replace, :undef => :replace, :replace => '').strip
end
end
# Strip tags
def imdb_strip_tags
gsub(/<\/?[^>]*>/, "")
end
# Strips out whitespace then tests if the string is empty.
def blank?
strip.empty?
end unless method_defined?(:blank?)
end
end
String.send :include, Imdb::StringExtensions
|
require 'ruby-kong/request/plugin'
module RubyKong
module Plugin
class << self
# Params: api:,
# plugin: {name:, consumer_id: nil, config.{property}}
#
# Usage: RubyKong::Plugin.create api: 'shipit',
# plugin: {name: 'key-auth'}
def create(*args)
RubyKong::Request::Plugin.create args[0]
end
# Params: id, name, api_id, consumer_id, size, offset
#
# Usage: RubyKong::Plugin.list
def list(*args)
RubyKong::Request::Plugin.list args[0]
end
# Params: api: id,
# filter: {name, api_id, consumer_id, size, offset}
#
# Usage: RubyKong::Plugin.list_by_api api: 'shipit',
# filter: {name: 'key-auth'}
def list_by_api(*args)
RubyKong::Request::Plugin.list_by_api args[0]
end
# Params: id
#
# Usage: RubyKong::Plugin.retrieve id: '90e6e8f4-2d51-444d-ac28-3f1dc1b3b3ed'
def retrieve(*args)
RubyKong::Request::Plugin.retrieve args[0]
end
#
# Usage: RubyKong::Plugin.retrieve_enabled
def retrieve_enabled(*args)
RubyKong::Request::Plugin.retrieve_enabled args[0]
end
# Params: plugin_name
#
# Usage: RubyKong::Plugin.retrieve_schema plugin_name: 'basic_auth'
def retrieve_schema(*args)
RubyKong::Request::Plugin.retrieve_schema args[0]
end
# Params: api:, plugin:,
# params: {name:, consumer_id:, config.{property}}
#
# Usage: RubyKong::Plugin.update api: 'shipit',
# plugin: '90e6e8f4-2d51-444d-ac28-3f1dc1b3b3ed'
# params: {name: 'basic-auth'}
def update(*args)
RubyKong::Request::Plugin.update args[0]
end
# Params: id, name
#
# Usage: RubyKong::Plugin.update name: 'shipit',
# upstream_url: 'https://api.shipit.vn/v2/'
def delete(*args)
RubyKong::Request::Plugin.delete args[0]
end
end
end
end
|
class CurriculumVitaeJobsController < ApplicationController
before_action :find_job, only: :create
def create
command = CurriculumVitaeUpload.call current_user, @job, cv_job_params
if command.success?
flash[:success] = t ".success"
else
flash[:danger] = command.errors[:failed]
end
redirect_to @job
end
private
def find_job
@job = Job.find_by id: params[:job_id]
return if @job
flash[:danger] = t ".not_found"
redirect_to root_path
end
def cv_job_params
params.require(:curriculum_vitae_job).permit :curriculum_vitae_id,
:cv_upload
end
end
|
# The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145:
# 1! + 4! + 5! = 1 + 24 + 120 = 145
# Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169;
# it turns out that there are only three such loops that exist:
# 169 → 363601 → 1454 → 169
# 871 → 45361 → 871
# 872 → 45362 → 872
# It is not difficult to prove that EVERY starting number will eventually get stuck in a loop. For example,
# 69 → 363600 → 1454 → 169 → 363601 (→ 1454)
# 78 → 45360 → 871 → 45361 (→ 871)
# 540 → 145 (→ 145)
# Starting with 69 produces a chain of five non-repeating terms,
# but the longest non-repeating chain with a starting number below one million is sixty terms.
# How many chains, with a starting number below one million, contain exactly sixty non-repeating terms?
require_relative 'commons.rb'
tests = []
has_60 = []
calcs = Hash.new
factorials = [
factorial(0),
factorial(1),
factorial(2),
factorial(3),
factorial(4),
factorial(5),
factorial(6),
factorial(7),
factorial(8),
factorial(9),
]
1.upto(1_000_000) do |n|
puts n
60.times do
x = n
if cached = calcs[n.to_s[1..-1].to_i]
x = factorials[n.to_s[0].to_i] + cached
else
x = n.
to_s.
split('').
map { |d| factorials[d.to_i] }.
sum
calcs[n] = x
end
tests << x
n = x
end
if tests.length == tests.uniq.length
has_60 << tests
end
end
puts has_60.inspect
puts has_60.length
# Answer = 402
|
# frozen_string_literal: true
# rubocop:disable RSpec/DescribeClass
require 'rails_helper'
RSpec.describe 'load_seeds' do
let(:valid_email) { 'jan@gmail.com' }
include_context 'rake'
it 'raises an error when user is not found' do
expect { subject.invoke('jan@jan.pl') }.to raise_error(RuntimeError)
end
it 'raises an error with no parameters' do
expect { subject.invoke }.to raise_error(RuntimeError)
end
end
|
require 'rubygems'
require 'rake'
require './lib/rfm'
task :default => :spec
#require 'spec/rake/spectask'
#require 'rspec'
require 'rspec/core/rake_task'
# Manual
# desc "Manually run rspec 2 - works but ugly"
# task :spec do
# puts exec("rspec -O spec/spec.opts") #RUBYOPTS=W0 # silence ruby warnings.
# end
RSpec::Core::RakeTask.new(:spec) do |task|
task.rspec_opts = '-O spec/spec.opts'
end
desc "run specs with all parser backends"
task :spec_multi do
require 'benchmark'
require 'yaml'
Benchmark.bm do |b|
[:ox, :libxml, :nokogiri, :rexml].each do |parser|
ENV['parser'] = parser.to_s
b.report("RSPEC with #{parser.to_s.upcase}\n") do
begin
Rake::Task["spec"].execute
rescue Exception
puts "ERROR in rspec with #{parser.to_s.upcase}: #{$!}"
end
end
end
end
end
require 'rdoc/task'
Rake::RDocTask.new do |rdoc|
version = Rfm::VERSION
rdoc.main = 'README.md'
rdoc.rdoc_dir = 'rdoc'
rdoc.title = "Rfm #{version}"
rdoc.rdoc_files.include('lib/**/*.rb', 'README.md', 'CHANGELOG.md', 'VERSION', 'LICENSE')
end
require 'yard'
require 'rdoc'
YARD::Rake::YardocTask.new do |t|
# See http://rubydoc.info/docs/yard/file/docs/GettingStarted.md
# See 'yardoc --help'
t.files = ['lib/**/*.rb', 'README.md', 'LICENSE', 'VERSION', 'CHANGELOG.md'] # optional
t.options = ['-oydoc', '--no-cache', '-mrdoc', '--no-private'] # optional
end
desc "Print the version of Rfm"
task :version do
puts Rfm::VERSION
end
desc "Print info about Rfm"
task :info do
puts Rfm.info
end
desc "Benchmark loading & parsing XML data into Rfm classes"
task :benchmark do
require 'benchmark'
require 'yaml'
#load "spec/data/sax_models.rb"
@records = File.read 'spec/data/resultset_large.xml'
#@template = 'lib/rfm/utilities/sax/fmresultset.yml'
@template = 'fmresultset.yml'
@base_class = Rfm::Resultset
@layout = 'spec/data/layout.xml'
Benchmark.bm do |b|
[:rexml, :nokogiri, :libxml, :ox].each do |backend|
b.report("#{backend}\n") do
5.times do
Rfm::SaxParser.parse(@records, @template, @base_class.new, backend)
end
end
end
end
end
desc "Profile the sax parser"
task :profile_sax do
# This turns on tail-call-optimization. Was needed in past for ruby 1.9, maybe not now.
# See http://ephoz.posterous.com/ruby-and-recursion-whats-up-in-19
# if RUBY_VERSION[/1.9/]
# RubyVM::InstructionSequence.compile_option = {
# :tailcall_optimization => true,
# :trace_instruction => false
# }
# end
require 'ruby-prof'
# Profile the code
@data = 'spec/data/resultset_large.xml'
min = ENV['min']
min_percent= min ? min.to_i : 1
result = RubyProf.profile do
# The parser will choose the best available backend.
@rr = Rfm::SaxParser.parse(@data, 'fmresultset.yml', Rfm::Resultset.new).result
#Rfm::SaxParser.parse(@data, 'lib/rfm/utilities/sax/fmresultset.yml', Rfm::Resultset.new)
end
# Print a flat profile to text
flat_printer = RubyProf::FlatPrinter.new(result)
flat_printer.print(STDOUT, {:min_percent=>0})
# Print a graph profile to text. See https://github.com/ruby-prof/ruby-prof/blob/master/examples/graph.txt
graph_printer = RubyProf::GraphPrinter.new(result)
graph_printer.print(STDOUT, {:min_percent=>min_percent})
graph_html_printer = RubyProf::GraphHtmlPrinter.new(result)
File.open('ruby-prof-graph.html', 'w') do |f|
graph_html_printer.print(f, {:min_percent=>min_percent})
end
# Print call_tree to html
tree_printer = RubyProf::CallStackPrinter.new(result)
File.open('ruby-prof-stack.html', 'w') do |f|
tree_printer.print(f, {:min_percent=>min_percent})
end
puts @rr.class
puts @rr.size
puts @rr[5].to_yaml
end
desc "Run test data thru the sax parser"
task :sample do
@records = 'spec/data/resultset_large.xml'
r= Rfm::SaxParser.parse(@records, 'lib/rfm/utilities/sax/fmresultset.yml', Rfm::Resultset.new).result
puts r.to_yaml
puts r.field_meta.to_yaml
end
desc "pre-commit, build gem, tag with version, push to git, push to rubygems.org"
task :release do
gem_name = 'ginjo-rfm'
shell = <<-EEOOFF
current_branch=`git rev-parse --abbrev-ref HEAD`
if [ $current_branch != 'master' ]; then
echo "Aborting: You are not on the master branch."
exit 1
fi
echo "--- Pre-committing ---"
git add .; git commit -m'Releasing version #{Rfm::VERSION}'
echo "--- Building gem ---" &&
mkdir -p pkg &&
output=`gem build #{gem_name}.gemspec` &&
gemfile=`echo "$output" | awk '{ field = $NF }; END{ print field }'` &&
echo $gemfile &&
mv -f $gemfile pkg/ &&
echo "--- Tagging with git ---" &&
git tag -m'Releasing version #{Rfm::VERSION}' v#{Rfm::VERSION} &&
echo "--- Pushing to git origin ---" &&
git push origin master &&
git push origin --tags &&
echo "--- Pushing to rubygems.org ---" &&
gem push pkg/$gemfile
EEOOFF
puts "----- Shell script to release gem -----"
puts shell
puts "----- End shell script -----"
print exec(shell)
end
|
module XClarityClient
#
# Exposes UpdateRepoManagement features
#
module Mixins::UpdateRepoMixin
def discover_update_repo(opts = {})
UpdateRepoManagement.new(@config).fetch_all(opts)
end
def read_update_repo
UpdateRepoManagement.new(@config).read_update_repo
end
def refresh_update_repo(scope, mt, os)
UpdateRepoManagement.new(@config).refresh_update_repo(scope, mt, os)
end
def acquire_firmware_updates(scope, fixids, mt)
UpdateRepoManagement.new(@config).acquire_firmware_updates(scope,
fixids, mt)
end
def delete_firmware_updates(file_types, fixids)
UpdateRepoManagement.new(@config).delete_firmware_updates(file_types,
fixids)
end
def export_firmware_updates(file_types, fixids)
UpdateRepoManagement.new(@config).export_firmware_updates(file_types,
fixids)
end
end
end
|
require 'spec_helper'
require 'yt/models/ownership'
describe Yt::Ownership, :partner do
subject(:ownership) { Yt::Ownership.new asset_id: asset_id, auth: $content_owner }
context 'given an asset managed by the authenticated Content Owner' do
let(:asset_id) { ENV['YT_TEST_PARTNER_ASSET_ID'] }
describe 'the ownership can be updated' do
let(:general_owner) { {ratio: 100, owner: 'FullScreen', type: 'include', territories: ['US', 'CA']} }
it { expect(ownership.update general: [general_owner]).to be true }
end
describe 'the complete ownership can be obtained' do
before { ownership.release! }
it { expect(ownership.obtain!).to be true }
end
describe 'the complete ownership can be released' do
after { ownership.obtain! }
it { expect(ownership.release!).to be true }
end
end
end |
#!/usr/bin/env ruby
# Encoding : UTF-8
require "shellwords"
class UTF8
def initialize(*args)
@files = args.map do |file|
File.expand_path(file)
end
end
def get_encoding(file)
output = %x[file -bi #{file.shellescape}]
matches = output.match(/(.*)charset=(.*)/)
return nil unless matches
return matches[2].downcase
end
def run
@files.each do |file|
encoding = get_encoding(file)
case encoding
when "iso-8859-1"
%x[recode latin1..utf8 #{file.shellescape}]
when "iso-8859-2"
%x[recode latin2..utf8 #{file.shellescape}]
when "utf-8"
next
else
puts "Unknown encoding for #{File.basename(file)}"
end
end
end
end
UTF8.new(*ARGV).run()
|
class Article < ApplicationRecord
validates :title, presence:true, length: {minium: 3, maximun: 50}
validates :description, presence: true, length: {minimum:10, maximun: 300}
end
|
require 'text_order/matcher'
RSpec.describe TextOrder::Matcher do
it 'detects included text' do
matcher = described_class.new('lolwat')
expect(matcher.matches?('hahalolwatok')).to be(true)
expect(matcher.matches?('lolno')).to be(false)
end
it 'returns failure message' do
matcher = described_class.new('lol')
matcher.matches?('wat')
expect(matcher.failure_message).to eq(%{expected "wat" to include the text "lol"})
end
it 'returns negated failure message' do
matcher = described_class.new('lol')
matcher.matches?('wat')
expect(matcher.failure_message_when_negated).to eq(%{expected "wat" not to include the text "lol"})
end
end
|
class StoreController < ApplicationController
before_filter :find_cart, :except => :empty_cart
def index
#initialize
@count = increment_count
@time = Time.now
@date = Date.today
@products = Product.find_products_for_sale
@cart = find_cart
@current_item = nil
end
def increment_count
session[:counter] ||= 0
session[:counter] += 1
end
def add_to_cart
begin
product = Product.find(params[:id])
rescue ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid product #{params[:id]}")
redirect_to_index("Invalid product")
else
@cart = find_cart
@current_item = @cart.add_product(product)
if request.xhr?
respond_to { |format| format.js }
else
redirect_to_index
end
end
end
def empty_cart
session[:cart] = nil
@current_item = nil
redirect_to_index
end
def checkout
@cart = find_cart
if @cart.items.empty?
redirect_to_index("Your cart is empty")
else
@order = Order.new
end
end
def save_order
@cart = find_cart
@order = Order.new(params[:order])
@order.add_line_items_from_cart(@cart)
if @order.save
session[:cart] = nil
redirect_to_index("Thank you for your order")
else
render :action => :checkout
end
end
private
def find_cart
@cart = (session[:cart] ||= Cart.new)
end
def redirect_to_index(msg = nil)
flash[:notice] = msg if msg
redirect_to :action => :index
end
protected
def authorize
end
end |
class AddIndexToFollow < ActiveRecord::Migration[5.1]
def change
add_index :follows, :followee_id
add_index :follows, :follower_id
end
end
|
module Vuf
class Batch
def initialize(size,&batch)
@mutex = Mutex.new
@batchQ = []
@size = size
@batch = batch
end
def push(obj)
@mutex.synchronize { @batchQ << obj }
objsToProc = get_objs(@size)
@batch.call(objsToProc) unless objsToProc.nil?
end
def flush
objsToProc = get_objs(0)
@batch.call(objsToProc)
end
private
def get_objs(size_condition)
objToProc = nil
@mutex.synchronize do
if size_condition <= @batchQ.size
objToProc = @batchQ
@batchQ = []
end
end
return objToProc
end
end
end
|
ActiveAdmin.register_page "Dashboard" do
menu priority: 1, label: proc{ I18n.t("active_admin.dashboard") }
content title: proc{ I18n.t("active_admin.dashboard") } do
columns do
column do
panel "Últimas 10 compras realizadas HOJE" do
purchases = Purchase.where(status: PurchaseStatus::PAID,
created_at: Date.today.beginning_of_day..Date.today.end_of_day)
.last(10)
table do
th "Usuário"
th "Realizado em"
th "No valor de"
purchases.each do |purchase|
tr do
td link_to(purchase.user.name, admin_purchase_path(purchase))
td l purchase.created_at
td number_to_currency purchase.total
end
end
end
table do
th "Total"
tr do
td number_to_currency purchases.sum(&:total)
end
end
end
end
column do
panel "Churn rate do mês de #{l Date.today, format: '%B'}" do
month = Date.today.beginning_of_month..Date.today.end_of_month
query = User.joins(:purchases).where(purchases: {created_at: month}).group('users.id')
buyers = query.having('count(purchases.id) > 0').length
new_users = query.having('count(purchases.id) = 1').length
recurrent_users = query.having('count(purchases.id) > 1').length
table do
th "Total de compradores"
th "Usuários com 1 compra"
th "Usuários com 1+ compras"
th "Chorn Rate este mês"
tr do
td buyers
td new_users
td recurrent_users
td number_to_percentage(recurrent_users*100.0/buyers, precision: 2)
end
end
end
end
end
columns do
column do
panel "Faturamento das últimas ofertas" do
offers = Offer.last(5)
table do
th "N"
th "Produtor"
th "Data"
th "Bairro"
th "Coordenador"
th "Cota"
th "C. Vend."
th "Prod"
th "Tribo"
th "Coord"
th "Cota"
th "T. Prod."
th "T. Tribo"
th "T. Coord"
th "Total"
th "Lucro"
offers.each do |offer|
tr do
td offer.id
td offer.producer.name
td offer.collect_starts_at.strftime('%d/%m/%Y')
td offer.deliver_coordinator.neighborhood
td offer.deliver_coordinator.name
td offer.stock
td offer.stock - offer.remaining
td number_to_currency(offer.value)
td number_to_currency(offer.operational_tax)
td number_to_currency(offer.coordinator_tax)
td number_to_currency(offer.total)
td number_to_currency(offer.total*((offer.stock - offer.remaining)+1))
td number_to_currency(offer.operational_tax * (offer.stock - offer.remaining))
td number_to_currency(offer.coordinator_tax * (offer.stock - offer.remaining))
td number_to_currency(((offer.total*(((offer.stock - offer.remaining)+1))-offer.value))+
offer.operational_tax * (offer.stock - offer.remaining)+
offer.coordinator_tax * (offer.stock - offer.remaining))
td number_to_currency((offer.coordinator_tax * (offer.stock - offer.remaining) - offer.value)+(offer.operational_tax * (offer.stock - offer.remaining)))
#+(offer.operational_tax * (offer.stock - offer.remaining)))
end
end
tr do
td link_to "Ver todos", admin_faturamento_path
end
end
end
end
end
end
end
|
class SavedSearch < ActiveRecord::Base
belongs_to :user
def count
feeds = user.feeds.collect { |item| item.id }
if feeds.count > 0
search_params = {:query => query, :after => last_access, :feeds => feeds}
Article.count(search_params)
else
0
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)
User.create(first_name: 'Alastar', last_name: 'Corr', email: 'house.labs@gmail.com', password: 'qwerty', password_confirmation: 'qwerty', type: 'Admin')
Category.create(title: 'HTML & CSS')
Category.create(title: 'Javascript')
Category.create(title: 'Ruby')
Category.create(title: 'Ruby on Rails')
Test.create(title: 'HTML & CSS Basic', level: 1, category_id: 1, user_id: 1)
Test.create(title: 'HTML & CSS Pro', level: 2, category_id: 1, user_id: 1)
Test.create(title: 'Javascript Basic', level: 2, category_id: 2, user_id: 1)
Test.create(title: 'Javascript Pro', level: 3, category_id: 2, user_id: 1)
Test.create(title: 'Ruby', level: 2, category_id: 3, user_id: 1)
Test.create(title: 'Ruby On Rails', level: 4, category_id: 4, user_id: 1)
Question.create(body: 'С помощью каких свойств CSS можно задать цвета фона в блоке?', test_id: 1)
Question.create(body: 'Какой тег отвечает за инициализацию таблицы?', test_id: 1)
Question.create(body: 'Какой тег используется для отображения нумерованного списка?', test_id: 1)
Question.create(body: 'Для чего используется тег <canvas>', test_id: 2)
Question.create(body: 'Что означает атрибут «poster» для тега <video>', test_id: 2)
Question.create(body: 'Как создаются переменные в SASS', test_id: 2)
Question.create(body: 'Как узнать длину строки a?', test_id: 3)
Question.create(body: 'Как при помощи jQuery получить элемент с ID my-element?', test_id: 3)
Question.create(body: 'Javascript это диалект Java для клиента?', test_id: 3)
Question.create(body: 'Выберите допустимые способы записи числа в JavaScript:', test_id: 4)
Question.create(body: 'Что содержит объект даты, созданный с помощью инструкции “new Date()”?', test_id: 4)
Question.create(body: 'Какими способами можно создать новый пустой объект?', test_id: 4)
Question.create(body: 'Что возвращает следующее выражение? <code>[1, 2, 3, 4, 5].reject { |x| x.even? }.map { |x| x * x }</code>', test_id: 5)
Question.create(body: 'Что будет возвращено следующим выражением? <code>[1, 2, 3] | [2, 3, 4]</code>', test_id: 5)
Question.create(body: 'Что возвращает следующее выражение? <code>[1, 2, 3, 4, 5].select(&:odd?)</code>', test_id: 5)
Question.create(body: 'В какой директории ROR приложения лежит основной код?', test_id: 6)
Question.create(body: 'Как создать новое ROR приложение?', test_id: 6)
Question.create(body: "Что вернет выражение? <code>['abc', 'def', 'gnt'].sort!</code>", test_id: 6)
Answer.create(title: 'bk-color', correct: false, question_id: 1)
Answer.create(title: 'background-color', correct: true, question_id: 1)
Answer.create(title: 'color', correct: false, question_id: 1)
Answer.create(title: 'background', correct: true, question_id: 1)
Answer.create(title: '<div>', correct: false, question_id: 2)
Answer.create(title: '<p>', correct: false, question_id: 2)
Answer.create(title: '<span>', correct: false, question_id: 2)
Answer.create(title: '<table>', correct: true, question_id: 2)
Answer.create(title: '<ul>', correct: false, question_id: 3)
Answer.create(title: '<list>', correct: false, question_id: 3)
Answer.create(title: '<nlist>', correct: false, question_id: 3)
Answer.create(title: '<ol>', correct: true, question_id: 3)
Answer.create(title: 'Создает список вариантов, которые можно выбирать при наборе в текстовом поле', correct: false, question_id: 4)
Answer.create(title: 'Создает область, в которой при помощи JavaScript можно рисовать разные объекты, выводить изображения', correct: true, question_id: 4)
Answer.create(title: 'Используется для редактирования шрифта текста', correct: false, question_id: 4)
Answer.create(title: 'При завершении композиции она запустится вновь', correct: false, question_id: 5)
Answer.create(title: 'Отсутствие автоматической загрузки видеофайла', correct: false, question_id: 5)
Answer.create(title: 'Выставляет изображение которое браузер будет использовать пока загружается', correct: true, question_id: 5)
Answer.create(title: 'Добавление аудиодорожки', correct: false, question_id: 5)
Answer.create(title: '&name', correct: false, question_id: 6)
Answer.create(title: '@name', correct: false, question_id: 6)
Answer.create(title: '$name', correct: true, question_id: 6)
Answer.create(title: '#name', correct: false, question_id: 6)
Answer.create(title: 'count(length)', correct: false, question_id: 7)
Answer.create(title: 'a.length', correct: true, question_id: 7)
Answer.create(title: 'Нет правильных вариантов', correct: false, question_id: 7)
Answer.create(title: 'strlen(a)', correct: false, question_id: 7)
Answer.create(title: '$("my-element")', correct: false, question_id: 8)
Answer.create(title: '$(".my-element")', correct: false, question_id: 8)
Answer.create(title: '$("#my-element")', correct: true, question_id: 8)
Answer.create(title: 'document.get("#my-element")', correct: false, question_id: 8)
Answer.create(title: 'Да', correct: false, question_id: 9)
Answer.create(title: 'Нет', correct: true, question_id: 9)
Answer.create(title: '015', correct: true, question_id: 10)
Answer.create(title: '5e-2', correct: true, question_id: 10)
Answer.create(title: '0x55', correct: true, question_id: 10)
Answer.create(title: '0b1001', correct: true, question_id: 10)
Answer.create(title: 'Текущую дату и время на начало дня', correct: false, question_id: 11)
Answer.create(title: 'Пустую дату', correct: false, question_id: 11)
Answer.create(title: 'Текущую дату и текущее время', correct: true, question_id: 11)
Answer.create(title: 'var obj = {}', correct: true, question_id: 12)
Answer.create(title: 'var obj = new {}', correct: false, question_id: 12)
Answer.create(title: 'var obj = new Object()', correct: true, question_id: 12)
Answer.create(title: 'var obj = []', correct: false, question_id: 12)
Answer.create(title: "NoMethodError: undefined method 'map'", correct: false, question_id: 13)
Answer.create(title: '[4, 16]', correct: false, question_id: 13)
Answer.create(title: '[1, 9, 25]', correct: true, question_id: 13)
Answer.create(title: '[1, 2, 3, 4]', correct: true, question_id: 14)
Answer.create(title: '[1, 4]', correct: false, question_id: 14)
Answer.create(title: '[2, 3, 4]', correct: false, question_id: 14)
Answer.create(title: '[1, 2, 3, 2, 3, 4]', correct: false, question_id: 14)
Answer.create(title: '[1, 2, 3, [2, 3, 4]]', correct: false, question_id: 14)
Answer.create(title: '[2, 4]', correct: false, question_id: 15)
Answer.create(title: '[1, 2, 3, 4, 5]', correct: false, question_id: 15)
Answer.create(title: '[1, 3, 5]', correct: true, question_id: 15)
Answer.create(title: "NoMethodError: undefined method 'select'", correct: false, question_id: 15)
Answer.create(title: 'nil', correct: false, question_id: 15)
Answer.create(title: 'bin/', correct: false, question_id: 16)
Answer.create(title: 'doc/', correct: false, question_id: 16)
Answer.create(title: 'app/', correct: true, question_id: 16)
Answer.create(title: 'log/', correct: false, question_id: 16)
Answer.create(title: 'ruby on rails new app first_app', correct: false, question_id: 17)
Answer.create(title: 'ROR magic', correct: false, question_id: 17)
Answer.create(title: 'Create application with ROR', correct: false, question_id: 17)
Answer.create(title: 'rails new first_app', correct: true, question_id: 17)
Answer.create(title: "['abc', 'def', 'gnt']", correct: true, question_id: 18)
Answer.create(title: "{'abc', 'def', 'gnt'}", correct: false, question_id: 18)
Answer.create(title: 'undefined', correct: false, question_id: 18)
Answer.create(title: 'error', correct: false, question_id: 18)
Answer.create(title: 'nil', correct: false, question_id: 18)
|
class TimeslotsController < PlatformController
def index
@study = current_user.studies.find(params[:study_id])
# Use the provided date_from and then add 8 days to get the date to (an
# extra day to account for this being a DateTime, so we want to get all
# timeslots on the last day, up to 23:59)
from = DateTime.parse(params[:page][:date_from])
to = from + 8.days
@timeslots = @study.timeslots
.where('timeslots.from >= ? AND timeslots.from < ?',
from, to)
respond_to do |format|
format.json { render json: @timeslots.to_json }
end
end
def new
@study = current_user.studies.find(params[:study_id])
return redirect_to @study if @study.timeslots_finalised
@number = 10
end
def create
@study = current_user.studies.find(params[:study_id])
@new_timeslot = Timeslot.new
timeslot = params[:timeslot]
from = DateTime.parse("#{timeslot[:date]} #{timeslot[:start_time]}")
to = DateTime.parse("#{timeslot[:date]} #{timeslot[:end_time]}")
return if from == to
@new_timeslot.to = to
@new_timeslot.from = from
@new_timeslot.study = @study
@new_timeslot.save
respond_to do |format|
format.json { render json: @new_timeslot }
end
end
def destroy
@timeslot = Timeslot.find(params[:id])
if @timeslot.study.researcher == current_user
@timeslot.delete
response = { status: 204 }
else
response = { status: 403, error: "Forbidden" }
end
respond_to do |format|
format.json { render json: response }
end
end
def finalise
@study = current_user.studies.find(params[:id])
if @study.timeslots.count >= @study.number_of_participants
@study.timeslots_finalised = true
@study.save
else
flash[:error] = 'You must have at least as many timeslots as the number '\
'of participants that you have set for your study.'
end
redirect_to @study
end
end
|
class State < ActiveRecord::Base
has_many :cities
validates :name, :presence=>true
default_scope { order('name ASC') }
end
|
class AddSharingTypeToTools < ActiveRecord::Migration
def change
add_column :tools, :sharing_type, :string
end
end
|
class Room < ApplicationRecord
belongs_to :user
has_and_belongs_to_many :themes
has_many :bookings, dependent: :destroy
has_many :guests, through: :bookings, source: :user
validates :address, presence: true
validates :home_type, presence: true
validates :room_type, presence: true
validates :accommodate, presence: true
validates :bedroom_count, presence: true
validates :bathroom_count, presence: true
validates :listing_name, presence: true, length: { maximum: 50 }
validates :description, presence: true, length: { maximum: 500 }
def single_bedroom?
accommodate == 1
end
def for_couples?
accommodate == 2
end
def self.order_by_price
order :price
end
# scope :couple_bedrooms, -> { where(accommodate: 2) }
def self.couple_bedrooms
where(accommodate: 2)
.order(id: "desc")
end
end
|
require_relative 'intervals/genome_region'
require 'zlib'
def cages_initial_hash
cages = {:+ => Hash.new{|h, chromosome| h[chromosome] = Hash.new{|h2,pos| h2[pos] = 0 } },
:- => Hash.new{|h, chromosome| h[chromosome] = Hash.new{|h2,pos| h2[pos] = 0 } } }
end
# returns {strand => {chromosome => {position => num_reads} } } structure
def read_cages(input_file)
read_cages_to(input_file, cages = cages_initial_hash)
cages
end
# chr1 19287 19288 chr1:19287..19288,+ 1 +
def print_cages(cages, out)
cages.each do |strand_key, strand|
strand.each do |chromosome_key, chromosome|
chromosome.each do |pos_start, cage_value|
pos_end = pos_start + 1
out.puts([chromosome_key, pos_start, pos_end, "#{chromosome_key}:#{pos_start}..#{pos_end},#{strand_key}", cage_value, strand_key].join("\t"))
end
end
end
end
def mul_cages_inplace(cages, multiplier)
cages.each do |strand_key, strand|
cages[strand_key].each do |chromosome_key, chromosome|
cages[strand_key][chromosome_key].each do |pos, cage_value|
cages[strand_key][chromosome_key][pos] *= multiplier
end
end
end
cages
end
# adds cages from new file to a hash (summing cages) and calculating number of files affected each position
# input file has lines in format: chr1 564462 564463 chr1:564462..564463,+ 1 +
# pos_end is always pos_start+1 because each line is reads from the single position
def read_cages_from_stream(stream, cages, cage_count = nil)
stream.each_line do |line|
chromosome, pos_start, _pos_end, _region_annotation, num_reads, strand = line.chomp.split("\t")
strand = strand.to_sym
chromosome = chromosome.to_sym
pos_start, num_reads = pos_start.to_i, num_reads.to_i
cages[strand][chromosome][pos_start] += num_reads
cage_count[strand][chromosome][pos_start] += 1 if cage_count
end
if cage_count
return cages, cage_count
else
return cages
end
end
def read_cages_from_file_to(cages_bed_file, cages, cage_count = nil)
if File.extname(cages_bed_file) == '.gz'
reader = Zlib::GzipReader
else
reader = File
end
reader.open(cages_bed_file) do |f|
read_cages_from_stream(f, cages, cage_count)
end
end
def read_cages_to(bed_filename, cages, cage_count = nil)
File.open(bed_filename) do |f|
read_cages_from_stream(f, cages, cage_count)
end
end
def read_cages_from_gzip_to(gzip_bed_filename, cages, cage_count = nil)
Zlib::GzipReader.open(gzip_bed_filename) do |gz_f|
read_cages_from_stream(gz_f, cages, cage_count)
end
end
def sum_cages(genome_region_list, all_cages)
genome_region_list.each_region.map{|region| region.load_cages(all_cages).inject(0, :+) }.inject(0, :+)
end
# iterate cages on a chromosome
def each_cage_line_on_chromosome_from_stream(stream, chr)
chr = "#{chr}\t"
stream.each_line.lazy.select do |line|
line.start_with?(chr)
end.each do |line|
yield line, GenomeRegion.new_by_bed_line(line)
end
end
# reader: File or Zlib::GzipReader
def select_cages_from(gzip_bed_filename, output_stream, region_of_interest, reader: File)
reader.open(gzip_bed_filename) do |gz_f|
each_cage_line_on_chromosome_from_stream(gz_f, region_of_interest.chromosome) do |line, region|
if region_of_interest.intersect?(region)
output_stream.puts(line)
end
end
end
end
|
require 'vanagon/common/user'
describe 'Vanagon::Common::User' do
describe 'initialize' do
it 'group defaults to the name of the user' do
user = Vanagon::Common::User.new('willamette')
expect(user.group).to eq('willamette')
end
end
describe 'equality' do
it 'is not equal if the names differ' do
user1 = Vanagon::Common::User.new('willamette')
user2 = Vanagon::Common::User.new('columbia')
expect(user1).not_to eq(user2)
end
it 'is not equal if there are different attributes set' do
user1 = Vanagon::Common::User.new('willamette', 'group1')
user2 = Vanagon::Common::User.new('willamette', 'group2')
expect(user1).not_to eq(user2)
end
it 'is equal if there are the same attributes set to the same values' do
user1 = Vanagon::Common::User.new('willamette', 'group')
user2 = Vanagon::Common::User.new('willamette', 'group')
expect(user1).to eq(user2)
end
it 'is equal if the name are the same and the only attribute set' do
user1 = Vanagon::Common::User.new('willamette')
user2 = Vanagon::Common::User.new('willamette')
expect(user1).to eq(user2)
end
end
end
|
# frozen_string_literal: true
# rubocop:todo all
require 'spec_helper'
describe 'SDAM error handling' do
require_topology :single, :replica_set, :sharded
clean_slate
after do
# Close all clients after every test to avoid leaking expectations into
# subsequent tests because we set global assertions on sockets.
ClientRegistry.instance.close_all_clients
end
# These tests operate on specific servers, and don't work in a multi
# shard cluster where multiple servers are equally eligible
require_no_multi_mongos
let(:diagnostic_subscriber) { Mrss::VerboseEventSubscriber.new }
let(:client) do
new_local_client(SpecConfig.instance.addresses,
SpecConfig.instance.all_test_options.merge(
socket_timeout: 3, connect_timeout: 3,
heartbeat_frequency: 100,
populator_io: false,
# Uncomment to print all events to stdout:
#sdam_proc: Utils.subscribe_all_sdam_proc(diagnostic_subscriber),
**Utils.disable_retries_client_options)
)
end
let(:server) { client.cluster.next_primary }
shared_examples_for 'marks server unknown' do
before do
server.monitor.stop!
end
after do
client.close
end
it 'marks server unknown' do
expect(server).not_to be_unknown
RSpec::Mocks.with_temporary_scope do
operation
expect(server).to be_unknown
end
end
end
shared_examples_for 'does not mark server unknown' do
before do
server.monitor.stop!
end
after do
client.close
end
it 'does not mark server unknown' do
expect(server).not_to be_unknown
RSpec::Mocks.with_temporary_scope do
operation
expect(server).not_to be_unknown
end
end
end
shared_examples_for 'requests server scan' do
it 'requests server scan' do
RSpec::Mocks.with_temporary_scope do
expect(server.scan_semaphore).to receive(:signal)
operation
end
end
end
shared_examples_for 'does not request server scan' do
it 'does not request server scan' do
RSpec::Mocks.with_temporary_scope do
expect(server.scan_semaphore).not_to receive(:signal)
operation
end
end
end
shared_examples_for 'clears connection pool' do
it 'clears connection pool' do
generation = server.pool.generation
RSpec::Mocks.with_temporary_scope do
operation
new_generation = server.pool_internal.generation
expect(new_generation).to eq(generation + 1)
end
end
end
shared_examples_for 'does not clear connection pool' do
it 'does not clear connection pool' do
generation = server.pool.generation
RSpec::Mocks.with_temporary_scope do
operation
new_generation = server.pool_internal.generation
expect(new_generation).to eq(generation)
end
end
end
describe 'when there is an error during an operation' do
before do
client.cluster.next_primary
# we also need a connection to the primary so that our error
# expectations do not get triggered during handshakes which
# have different behavior from non-handshake errors
client.database.command(ping: 1)
end
let(:operation) do
expect_any_instance_of(Mongo::Server::Connection).to receive(:deliver).and_return(reply)
expect do
client.database.command(ping: 1)
end.to raise_error(Mongo::Error::OperationFailure, exception_message)
end
shared_examples_for 'not master or node recovering' do
it_behaves_like 'marks server unknown'
it_behaves_like 'requests server scan'
context 'server 4.2 or higher' do
min_server_fcv '4.2'
it_behaves_like 'does not clear connection pool'
end
context 'server 4.0 or lower' do
max_server_version '4.0'
it_behaves_like 'clears connection pool'
end
end
shared_examples_for 'node shutting down' do
it_behaves_like 'marks server unknown'
it_behaves_like 'requests server scan'
it_behaves_like 'clears connection pool'
end
context 'not master error' do
let(:exception_message) do
/not master/
end
let(:reply) do
make_not_master_reply
end
it_behaves_like 'not master or node recovering'
end
context 'node recovering error' do
let(:exception_message) do
/DueToStepDown/
end
let(:reply) do
make_node_recovering_reply
end
it_behaves_like 'not master or node recovering'
end
context 'node shutting down error' do
let(:exception_message) do
/shutdown in progress/
end
let(:reply) do
make_node_shutting_down_reply
end
it_behaves_like 'node shutting down'
end
context 'network error' do
# With 4.4 servers we set up two monitoring connections, hence global
# socket expectations get hit twice.
max_server_version '4.2'
let(:operation) do
expect_any_instance_of(Mongo::Socket).to receive(:read).and_raise(exception)
expect do
client.database.command(ping: 1)
end.to raise_error(exception)
end
context 'non-timeout network error' do
let(:exception) do
Mongo::Error::SocketError
end
it_behaves_like 'marks server unknown'
it_behaves_like 'does not request server scan'
it_behaves_like 'clears connection pool'
end
context 'network timeout error' do
let(:exception) do
Mongo::Error::SocketTimeoutError
end
it_behaves_like 'does not mark server unknown'
it_behaves_like 'does not request server scan'
it_behaves_like 'does not clear connection pool'
end
end
end
describe 'when there is an error during connection establishment' do
require_topology :single
# The push monitor creates sockets unpredictably and interferes with this
# test.
max_server_version '4.2'
# When TLS is used there are two socket classes and we can't simply
# mock the base Socket class.
require_no_tls
{
SystemCallError => Mongo::Error::SocketError,
Errno::ETIMEDOUT => Mongo::Error::SocketTimeoutError,
}.each do |raw_error_cls, mapped_error_cls|
context raw_error_cls.name do
let(:socket) do
double('mock socket').tap do |socket|
allow(socket).to receive(:set_encoding)
allow(socket).to receive(:setsockopt)
allow(socket).to receive(:getsockopt)
allow(socket).to receive(:connect)
allow(socket).to receive(:close)
socket.should receive(:write).and_raise(raw_error_cls, 'mocked failure')
end
end
it 'marks server unknown' do
server = client.cluster.next_primary
pool = client.cluster.pool(server)
client.cluster.servers.map(&:disconnect!)
RSpec::Mocks.with_temporary_scope do
Socket.should receive(:new).with(any_args).ordered.once.and_return(socket)
allow(pool).to receive(:paused?).and_return(false)
lambda do
client.command(ping: 1)
end.should raise_error(mapped_error_cls, /mocked failure/)
server.should be_unknown
end
end
it 'recovers' do
server = client.cluster.next_primary
# If we do not kill the monitor, the client will recover automatically.
RSpec::Mocks.with_temporary_scope do
Socket.should receive(:new).with(any_args).ordered.once.and_return(socket)
Socket.should receive(:new).with(any_args).ordered.once.and_call_original
lambda do
client.command(ping: 1)
end.should raise_error(mapped_error_cls, /mocked failure/)
client.command(ping: 1)
end
end
end
end
after do
# Since we stopped monitoring on the client, close it.
ClientRegistry.instance.close_all_clients
end
end
describe 'when there is an error on monitoring connection' do
clean_slate_for_all
let(:subscriber) { Mrss::EventSubscriber.new }
let(:set_subscribers) do
client.subscribe(Mongo::Monitoring::SERVER_DESCRIPTION_CHANGED, subscriber)
client.subscribe(Mongo::Monitoring::CONNECTION_POOL, subscriber)
end
let(:operation) do
expect(server.monitor.connection).not_to be nil
set_subscribers
RSpec::Mocks.with_temporary_scope do
expect(server.monitor).to receive(:check).and_raise(exception)
server.monitor.scan!
end
expect_server_state_change
end
shared_examples_for 'marks server unknown - sdam event' do
it 'marks server unknown' do
expect(server).not_to be_unknown
#subscriber.clear_events!
events = subscriber.select_succeeded_events(Mongo::Monitoring::Event::ServerDescriptionChanged)
events.should be_empty
RSpec::Mocks.with_temporary_scope do
operation
events = subscriber.select_succeeded_events(Mongo::Monitoring::Event::ServerDescriptionChanged)
events.should_not be_empty
event = events.detect do |event|
event.new_description.address == server.address &&
event.new_description.unknown?
end
event.should_not be_nil
end
end
end
shared_examples_for 'clears connection pool - cmap event' do
it 'clears connection pool' do
#subscriber.clear_events!
events = subscriber.select_published_events(Mongo::Monitoring::Event::Cmap::PoolCleared)
events.should be_empty
RSpec::Mocks.with_temporary_scope do
operation
events = subscriber.select_published_events(Mongo::Monitoring::Event::Cmap::PoolCleared)
events.should_not be_empty
event = events.detect do |event|
event.address == server.address
end
event.should_not be_nil
end
end
end
shared_examples_for 'marks server unknown and clears connection pool' do
=begin These tests are not reliable
context 'via object inspection' do
let(:expect_server_state_change) do
server.summary.should =~ /unknown/i
expect(server).to be_unknown
end
it_behaves_like 'marks server unknown'
it_behaves_like 'clears connection pool'
end
=end
context 'via events' do
# When we use events we do not need to examine object state, therefore
# it does not matter whether the server stays unknown or gets
# successfully checked.
let(:expect_server_state_change) do
# nothing
end
it_behaves_like 'marks server unknown - sdam event'
it_behaves_like 'clears connection pool - cmap event'
end
end
context 'via stubs' do
# With 4.4 servers we set up two monitoring connections, hence global
# socket expectations get hit twice.
max_server_version '4.2'
context 'network timeout' do
let(:exception) { Mongo::Error::SocketTimeoutError }
it_behaves_like 'marks server unknown and clears connection pool'
end
context 'non-timeout network error' do
let(:exception) { Mongo::Error::SocketError }
it_behaves_like 'marks server unknown and clears connection pool'
end
end
context 'non-timeout network error via fail point' do
require_fail_command
let(:admin_client) { client.use(:admin) }
let(:set_fail_point) do
admin_client.command(
configureFailPoint: 'failCommand',
mode: {times: 2},
data: {
failCommands: %w(isMaster hello),
closeConnection: true,
},
)
end
let(:operation) do
expect(server.monitor.connection).not_to be nil
set_subscribers
set_fail_point
server.monitor.scan!
expect_server_state_change
end
it_behaves_like 'marks server unknown and clears connection pool'
after do
admin_client.command(configureFailPoint: 'failCommand', mode: 'off')
end
end
end
context "when there is an error on the handshake" do
# require appName for fail point
min_server_version "4.9"
let(:admin_client) do
new_local_client(
[SpecConfig.instance.addresses.first],
SpecConfig.instance.test_options.merge({
connect: :direct,
populator_io: false,
direct_connection: true,
app_name: "SDAMMinHeartbeatFrequencyTest",
database: 'admin'
})
)
end
let(:cmd_client) do
# Change the server selection timeout so that we are given a new cluster.
admin_client.with(server_selection_timeout: 5)
end
let(:set_fail_point) do
admin_client.command(
configureFailPoint: 'failCommand',
mode: { times: 5 },
data: {
failCommands: %w(isMaster hello),
errorCode: 1234,
appName: "SDAMMinHeartbeatFrequencyTest"
},
)
end
let(:operation) do
expect(server.monitor.connection).not_to be nil
set_fail_point
end
it "waits 500ms between failed hello checks" do
operation
start = Mongo::Utils.monotonic_time
cmd_client.command(hello: 1)
duration = Mongo::Utils.monotonic_time - start
expect(duration).to be >= 2
expect(duration).to be <= 3.5
# The cluster that we use to set up the failpoint should not be the same
# one we ping on, so that the ping will have to select a server. The admin
# client has already selected a server.
expect(admin_client.cluster.object_id).to_not eq(cmd_client.cluster.object_id)
end
after do
admin_client.command(configureFailPoint: 'failCommand', mode: 'off')
cmd_client.close
end
end
end
|
module WsdlMapper
module Naming
# Represents the value of an enumeration value, consisting of the constant to
# generate and the string key, that will be the enumeration value.
class EnumerationValueName
attr_reader :constant_name, :key_name
# @param [String] constant_name Name for the constant to generate.
# @param [String] key_name String value.
def initialize(constant_name, key_name)
@constant_name = constant_name
@key_name = key_name
end
end
end
end
|
require 'active_record'
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: 'development.sqlite3'
)
class ReviewsMigration < ActiveRecord::Migration
def change
create_table :employees do |t|
t.references :department
t.string :name
t.decimal :salary, precision: 8, scale: 2
t.string :phone
t.string :email
t.text :review
t.boolean :satisfactory, default: true
t.timestamps null: false
end
create_table :departments do |t|
t.string :name
t.timestamps null: false
end
create_table :committees do |t|
t.string :name
t.timestamps null: false
end
# create_table :committees_employees do |t|
# t.references :committee
# t.references :employee
# end
create_join_table(:committees, :employees)
create_table :reviews do |t|
t.references :employee
t.text :body
end
end
end
|
# encoding: utf-8
describe Faceter::Functions, ".keep_symbol" do
let(:function) { -> value { value.to_s.reverse.to_i } }
it_behaves_like :transforming_immutable_data do
let(:arguments) { [:keep_symbol, function] }
let(:input) { 123 }
let(:output) { 321 }
end
it_behaves_like :transforming_immutable_data do
let(:arguments) { [:keep_symbol, function] }
let(:input) { :"123" }
let(:output) { :"321" }
end
end # describe Faceter::Functions.keep_symbol
|
require 'SssSEMapp.rb'
require 'SssSEMtriggerBase.rb'
# Sends 'o' or 'O' command to all SBAMFDDDs
# read SssSEMtriggerBase for ruby-side-usage.
#
# 0 = stop loop; any other value = start loop
#
# Usage from cli (start demo loop):
# echo -n '1' >> triggers/demoID
# Usage from php (stop demo loop):
# file_put_contents('triggers/demoID', '0', FILE_APPEND);
class SssSEMtriggerDemoID < SssSEMtriggerBase
def initialize(sPathFile = nil)
sPathFile = 'triggers/demoID' if sPathFile.nil?
super(sPathFile)
end # initialize
# send 'o' or 'O' command to all SBAMFDDDs
# controller calls hasData? if yes controller calls process
def process()
# first byte defines action
i = @sBuffer[0];
# nil == i that would mean buffer is empty -> should never happen
return super if i.nil?
# convert byte-value to natural-value
i = i.chr.to_i;
# start or stop
if (0 == i)
# stop loop
sData = 'O'
puts 'OK:ft:Got stop-demo-loop-signal from Trigger '
else
# start loop
sData = 'o'
puts 'OK:ft:Got start-demo-loop-signal from Trigger '
end # if start or stop loop
# target serial ID
iFDD = SssSEMapp.get(:serialBroadcastID, SBSerialBroadcastID);
SssSEMapp.oIOframeHandler.writeFramed(iFDD, sData)
# clear buffer and return self
super
end # process
end # SssSEMtriggerDemoID
|
class PizzaandrollsSharesController < ApplicationController
def index
@shares = Share.all.where(type:'PIZZA&ROLLS').order_by(to: 'asc').where({:from.lte => Date.current()}).where({:to.gte => Date.current()})
end
end
|
# In the code below, sun is randomly assigned as 'visible' or 'hidden'.
sun = ['visible', 'hidden'].sample
# Write an if statement that prints "The sun is so bright!" if sun equals visible. Also, write an unless statement that prints "The clouds are blocking the sun!" unless sun equals visible.
if sun == 'visible'
puts "The sun is so bright!"
end
unless sun == 'visible'
puts "The clouds are blocking the sun!"
end
# When writing these statements, take advantage of Ruby's expressiveness and use statement modifiers instead of an if...end statement to print results only when some condition is met or not met.
# This I was not sure how to do...
# Solution
puts 'The sun is so bright!' if sun == 'visible'
puts 'The clouds are blocking the sun!' unless sun == 'visible'
# LS Discussion
# This solution gives us an opportunity to take advantage of how expressive Ruby is. We can call #puts and simply append an if or unless condition to form a shorter, more readable expression. Such conditions, when added to the end of a statement like this, are called modifiers.
|
require "set"
require "tsort"
module Gem
# A really, really stupid resolver stub. Doesn't do source pinning,
# platforms, or really much of anything. Just a placeholder to play
# with API.
class Resolver
include TSort
attr_reader :sources
# Initialize a resolver, providing the initial set of +sources+ to
# use for resolution. Sources can be anything that quacks like
# Gem::Source, so it's perfectly reasonable to, e.g., use a
# resolver against a Gem::Repo during activation or a Gem::Source
# during installation.
def initialize *sources, &block
@sources = sources.flatten
@entries = Set.new
yield self if block_given?
end
def needs name, requirement = nil
dependency = name if Gem::Dependency === name
dependency ||= Gem::Dependency.new name, requirement
@entries |= get([dependency], :all)
end
def get dependencies, dev = false
dependencies.reject! { |d| :development == d.type } unless dev
dependencies.map do |dep|
candidates = search dep.name, dep.requirement
if candidates.empty?
others = search dep.name
message = "Can't find a gem for #{dep}."
unless others.empty?
versions = others.map { |o| o.version }
message = "Found #{dep.name} (#{versions.join ', '}), " +
"but nothing #{dep.requirement}."
end
raise ::LoadError, message
end
candidates.first
end
end
def search name, *requirements
results = sources.map do |source|
source.gems.search name, *requirements
end
results.inject { |m, i| m.concat i }
end
def tsort_each_node &block
@entries.each(&block)
end
def tsort_each_child node, &block
get(node.dependencies).each(&block)
end
alias_method :gems, :tsort
end
end
|
class CustomerJobsController < ApplicationController
before_action :set_customer_job, only: [:show, :edit, :update, :destroy]
# GET /customer_jobs
# GET /customer_jobs.json
def index
@customer_jobs = CustomerJob.all
end
# GET /customer_jobs/1
# GET /customer_jobs/1.json
def show
end
# GET /customer_jobs/new
def new
@customer_job = CustomerJob.new
end
# GET /customer_jobs/1/edit
def edit
end
# POST /customer_jobs
# POST /customer_jobs.json
def create
@customer_job = CustomerJob.new(customer_job_params)
respond_to do |format|
if @customer_job.save
format.html { redirect_to @customer_job, notice: 'Customer job was successfully created.' }
format.json { render :show, status: :created, location: @customer_job }
else
format.html { render :new }
format.json { render json: @customer_job.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /customer_jobs/1
# PATCH/PUT /customer_jobs/1.json
def update
respond_to do |format|
if @customer_job.update(customer_job_params)
format.html { redirect_to @customer_job, notice: 'Customer job was successfully updated.' }
format.json { render :show, status: :ok, location: @customer_job }
else
format.html { render :edit }
format.json { render json: @customer_job.errors, status: :unprocessable_entity }
end
end
end
# DELETE /customer_jobs/1
# DELETE /customer_jobs/1.json
def destroy
@customer_job.destroy
respond_to do |format|
format.html { redirect_to customer_jobs_url, notice: 'Customer job was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_customer_job
@customer_job = CustomerJob.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def customer_job_params
params.require(:customer_job).permit(:job_reference, :name, :description, :status)
end
end
|
require 'bundler/setup'
require 'ruby2d'
require './lib/snake_square.rb'
require './lib/snake_controller.rb'
RSpec.describe SnakeController, "#initialize" do
context "New snake" do
it "can it create a new snake?" do
snake = []
s = SnakeSquare.new(x:0,y:20,size:20, color:'red', dir:'right')
snake << SnakeController.new([s])
expect(snake.size).to eq 1
end
end
end
RSpec.describe SnakeController, "#moveRight" do
context "Move snake to the right" do
it "can it move to the right" do
s = SnakeSquare.new(x:0,y:0,size:20,color:'red', dir:'right')
s2 = SnakeSquare.new(x:0,y:20,size:20,color:'red', dir:'right')
op = "+"
dir = "right"
SnakeController.moveRight(s,s2, op, dir)
expect(s2.y).to eq 20
expect(s2.x).to eq 0
end
end
end
RSpec.describe SnakeController, "#moveLeft" do
context "Move snake to the left" do
it "can it move to the left" do
s = SnakeSquare.new(x:0,y:0,size:20,color:'red', dir:'right')
s2 = SnakeSquare.new(x:0,y:20,size:20,color:'red', dir:'right')
op = "+"
dir = "left"
SnakeController.moveLeft(s,s2, op, dir)
expect(s2.x).to eq 20
expect(s2.y).to eq 0
end
end
end
RSpec.describe SnakeController, "#sum" do
context "sum a val to the snake" do
it "can the sum be made?" do
s = SnakeSquare.new(x:0,y:0,size:20,color:'red', dir:'right')
s2 = SnakeSquare.new(x:0,y:0,size:20,color:'red', dir:'right')
op = "+"
s2.y = SnakeController.sum(s.y, op)
expect(s2.y).to eq 20
end
end
end
RSpec.describe SnakeController, "#turnRight" do
context "Move snake to the turn right" do
it "can it move to the right" do
s = SnakeSquare.new(x:0,y:0,size:20,color:'red', dir:'right')
s2 = SnakeSquare.new(x:0,y:20,size:20,color:'red', dir:'right')
SnakeController.turnRight(s,s2)
expect(s2.y).to eq 20
expect(s2.x).to eq 0
end
end
end
RSpec.describe SnakeController, "#turnLeft" do
context "Move snake to the turn left" do
it "can it move to the left" do
s = SnakeSquare.new(x:0,y:0,size:20,color:'red', dir:'right')
s2 = SnakeSquare.new(x:0,y:20,size:20,color:'red', dir:'right')
SnakeController.turnLeft(s,s2)
expect(s2.x).to eq 580
expect(s2.y).to eq 0
end
end
end
RSpec.describe SnakeController, "#moveStraight" do
context "Move snake in straight line" do
it "can it go straight?" do
s = SnakeSquare.new(x:0,y:0,size:20,color:'red', dir:'right')
s2 = SnakeSquare.new(x:0,y:20,size:20,color:'red', dir:'right')
SnakeController.moveStraight(s,s2)
expect(s2.x).to eq 20
expect(s2.y).to eq 0
end
end
end
RSpec.describe SnakeController, "#nextMove" do
context "snakes next movement" do
it "can the snake make a move?" do
snakes = []
s = SnakeSquare.new(x:0,y:0,size:20,color:'red', dir:'right')
s2 = SnakeSquare.new(x:0,y:20,size:20,color:'red', dir:'right')
snakes << SnakeController.new([s])
snakes << SnakeController.new([s2])
tail = snakes.pop
snakes.unshift(tail)
expect(snakes[0]).to eq tail
end
end
end
RSpec.describe SnakeController, "#nextMoveWithTick" do
context "snakes next movement with timer" do
it "can the snake make a move with timer?" do
snakes = []
s = SnakeSquare.new(x:0,y:0,size:20,color:'red', dir:'right')
s2 = SnakeSquare.new(x:0,y:20,size:20,color:'red', dir:'right')
snakes << SnakeController.new([s])
snakes << SnakeController.new([s2])
tick = 5
new_square = if tick % 300 == 0
snakes.last.dup
end
if new_square
snakes << new_square
new_square.add
end
size = snakes.size
expect(snakes[size]).to eq new_square
end
end
end
|
# encoding: UTF-8
require 'spec_helper'
describe "courses/_sections_pane" do
before do
stub_template 'courses/_sections_table' => "Sections table"
end
it "display a pane with the sections of a course" do
course = mock_model Course, number: 321, duration: Durations::FULL_YEAR, credits: 5.0, full_name: "Fractals 101"
course.stub(:sections).and_return course
course.stub(:current).and_return [1,2,3]
course.stub(:doc_of_kind).and_return mock_model(TextDocument, content: "Some description")
assign(:course, course)
render partial: "courses/sections_pane", locals: {course: course}
expect(rendered).to have_selector('div#sections_pane')
expect(rendered).to have_content('Course 321')
expect(rendered).to have_content("Some description")
expect(rendered).to have_content("In the #{academic_year_string(Settings.academic_year)} academic year there are 3 sections of Fractals 101.")
end
end
|
module TwitterCli
class RegisterProcessor < Processor
attr_accessor :user_interface
def initialize(conn)
super(conn)
@rejected_values = ["Another user exists with same name pls go for some other username!"]
end
def execute
name = get_name
user_register = UserRegistration.new(@conn, name, get_password)
result = user_register.process
unless @rejected_values.include? result
@user_interface ||= UserInterface.new(name)
puts "Dear " + name + " Please tweet or follow users your stream is currently empty\n"
puts user_interface.help
puts result
@user_interface.run
else
result
end
end
private
def get_name
puts "Pls enter the name which you wish to register with ?"
gets.chomp
end
def get_password
puts "Pls enter the password for your account?\n"
STDIN.noecho(&:gets).chomp
end
end
end
|
module RSpec
module Mocks
module AnyInstance
# @private
# The `AnyInstance::Recorder` is responsible for redefining the klass's
# instance method in order to add any stubs/expectations the first time
# the method is called. It's not capable of updating a stub on an instance
# that's already been previously stubbed (either directly, or via
# `any_instance`).
#
# This proxy sits in front of the recorder and delegates both to it
# and to the `RSpec::Mocks::Proxy` for each already mocked or stubbed
# instance of the class, in order to propagates changes to the instances.
#
# Note that unlike `RSpec::Mocks::Proxy`, this proxy class is stateless
# and is not persisted in `RSpec::Mocks.space`.
#
# Proxying for the message expectation fluent interface (typically chained
# off of the return value of one of these methods) is provided by the
# `FluentInterfaceProxy` class below.
class Proxy
def initialize(recorder, target_proxies)
@recorder = recorder
@target_proxies = target_proxies
end
def klass
@recorder.klass
end
def stub(method_name_or_method_map, &block)
if Hash === method_name_or_method_map
method_name_or_method_map.each do |method_name, return_value|
stub(method_name).and_return(return_value)
end
else
perform_proxying(__method__, [method_name_or_method_map], block) do |proxy|
proxy.add_stub(method_name_or_method_map, &block)
end
end
end
def unstub(method_name)
perform_proxying(__method__, [method_name], nil) do |proxy|
proxy.remove_stub_if_present(method_name)
end
end
def stub_chain(*chain, &block)
perform_proxying(__method__, chain, block) do |proxy|
Mocks::StubChain.stub_chain_on(proxy.object, *chain, &block)
end
end
def expect_chain(*chain, &block)
perform_proxying(__method__, chain, block) do |proxy|
Mocks::ExpectChain.expect_chain_on(proxy.object, *chain, &block)
end
end
def should_receive(method_name, &block)
perform_proxying(__method__, [method_name], block) do |proxy|
# Yeah, this is a bit odd...but if we used `add_message_expectation`
# then it would act like `expect_every_instance_of(klass).to receive`.
# The any_instance recorder takes care of validating that an instance
# received the message.
proxy.add_stub(method_name, &block)
end
end
def should_not_receive(method_name, &block)
perform_proxying(__method__, [method_name], block) do |proxy|
proxy.add_message_expectation(method_name, &block).never
end
end
private
def perform_proxying(method_name, args, block, &target_proxy_block)
recorder_value = @recorder.__send__(method_name, *args, &block)
proxy_values = @target_proxies.map(&target_proxy_block)
FluentInterfaceProxy.new([recorder_value] + proxy_values)
end
end
unless defined?(BasicObject)
class BasicObject
# Remove all methods except those expected to be defined on BasicObject
(instance_methods.map(&:to_sym) - [:__send__, :"!", :instance_eval, :==, :instance_exec, :"!=", :equal?, :__id__, :__binding__, :object_id]).each do |method|
undef_method method
end
end
end
# @private
# Delegates messages to each of the given targets in order to
# provide the fluent interface that is available off of message
# expectations when dealing with `any_instance`.
#
# `targets` will typically contain 1 of the `AnyInstance::Recorder`
# return values and N `MessageExpectation` instances (one per instance
# of the `any_instance` klass).
class FluentInterfaceProxy < BasicObject
def initialize(targets)
@targets = targets
end
if ::RUBY_VERSION.to_f > 1.8
def respond_to_missing?(method_name, include_private=false)
super || @targets.first.respond_to?(method_name, include_private)
end
else
def respond_to?(method_name, include_private=false)
super || @targets.first.respond_to?(method_name, include_private)
end
end
def method_missing(*args, &block)
return_values = @targets.map { |t| t.__send__(*args, &block) }
FluentInterfaceProxy.new(return_values)
end
end
end
end
end
|
module Api
module Endpoints
class Movies < Grape::API
namespace :movies do
desc 'Get movie.',
summary: 'Movies by day',
detail: 'Returns movies that are being shown given one week day.',
is_array: true,
success: Entities::Movie
params do
requires :day, type: String, values: Constants::DAYS
end
get ':day' do
movies = MoviesController.new.movies_by_day(params[:day])
present :movies, movies, with: Entities::Movie
end
desc 'Create a Movie',
summary: 'Create a movie',
detail: 'Allows to create movies in the system and associate them to the days a week in which they are being shown'
params do
requires :name, type: String
optional :description, type: String
optional :url, type: String
requires :days, type: Array[String], values: Constants::DAYS
end
post do
begin
MoviesController.new.create(declared(params))
rescue StandardError => e
status 400
e
end
end
end
end
end
end |
class RemoveOrderProductFromProduct < ActiveRecord::Migration[5.0]
def change
remove_reference :orders, :order_product
end
end
|
module Merb
module GlobalHelpers
def format_datetime(datetime)
datetime.respond_to?(:strftime) ? datetime.strftime("%d.%m.%Y %H:%M") : ""
end
def human_size(size)
return "0 B" if size == 0
size = Float(size)
suffix = %w(B KB MB GB TB)
max_exp = suffix.size - 1
exp = (Math.log(size) / Math.log(1024)).to_i
exp = max_exp if exp > max_exp
size /= 1024 ** exp
"#{"%.2f" % size} #{suffix[exp]}"
end
def link_to_image(image)
link_to tag(:div,
image_tag(image.url(:thumbnail)) +
tag(:span,
image.filename + " " +
human_size(image.size)
)
), image.url, :title => image.filename, :class => "img", :rel => "photos"
end
def textilize(text)
RedCloth.new(text || "").to_html
end
def datetime_picker(object, field, opts = {})
name = "#{object.class.to_s.snake_case}[#{field}]"
sel = object.send(field) || DateTime.now
tag(:span,
select(:name => "#{name}[day]", :class => "day", :selected => sel.day.to_s, :collection => (1..31).map{|e|e.to_s}) +
select(:name => "#{name}[month]", :class => "month", :selected => sel.month.to_s.rjust(2, "0"), :collection => (1..12).map{|e|e.to_s.rjust(2, "0")}) +
select(:name => "#{name}[year]", :class => "year", :selected => sel.year.to_s, :collection => (2007..2015).map{|e|e.to_s}) +
select(:name => "#{name}[hour]", :class => "hour", :selected => sel.hour.to_s.rjust(2, "0"), :collection => (0..23).map{|e|e.to_s.rjust(2, "0")}) +
select(:name => "#{name}[min]", :class => "min", :selected => sel.min.to_s, :collection => (0..11).map{|e|(e*5).to_s.rjust(2, "0")}),
:class => "datetime"
)
end
end
end
|
class CreateUserInvites < ActiveRecord::Migration
def change
create_table :user_invites do |t|
t.integer :inviter_id
t.string :type
t.string :message
t.boolean :accepted
t.boolean :pending
t.integer :user_id
t.integer :campaign_id
t.timestamps
end
end
end
|
class Api::CommentsController < ApplicationController
def index
@comments = Book.find_by_url(params[:url]).comments
if @comments
render 'api/comments/index'
else
render json: ["Could not find matching "], status: 422
end
end
def create
@book = Book.find_by_url(book_url[:url])
@comment = Comment.new(comment_params)
@comment.book_id = @book.id
if @comment.save
render 'api/comments/show'
elsif @book.nil?
render json: ["Could not find matching book"], status: 422
else
render json: @comment.errors.full_messages, status: 422
end
end
def update
@comment = Comment.find(params[:id])
if @comment.update(body: params[:body])
render 'api/comments/show'
else
render json: @comment.errors.full_messages, status: 422
end
end
def destroy
@comment = Comment.find(params[:id])
if @comment.delete
render 'api/comments/show'
else
render json: @comment.errors.full_messages, status: 422
end
end
def comment_params
params.require(:comment).permit(:body, :time, :pos_x, :pos_y)
end
def updated_params
params.require(:comment).permit(:body)
end
def book_url
params.require(:comment).permit(:url)
end
end
|
require 'spec_helper'
## Input:
# Data: subject code, sleep period #, labtime, sleep stage
# Options: min bout length == X, epoch length(if not from database data)
# The input can come from scored_epoch events as well. In that case, only the subject code need be supplied
## Output:
# 1. Sleep bouts
# 2. Wake bouts
# 3. Rem bouts
# 4. NREM bouts
#
# Each line: subject_code start_labtime bout_length censored next_state
describe Tools::BoutMaker do
before do
@data_location = "/usr/local/htdocs/access/spec/data/bout_maker_data"
@subject_code = "2844GX"
@query_results = YAML.load(File.read("/usr/local/htdocs/access/spec/data/bout_maker_data/sql_output.robj"))
@input_data = @query_results.map{|epoch| [@subject_code, 1, epoch["labtime"], epoch["scored_stage"]]}
@full_input_data = YAML.load(File.read("/usr/local/htdocs/access/spec/data/bout_maker_data/full_input_data.robj"))
@simple_input = YAML.load(File.read("/usr/local/htdocs/access/spec/data/bout_maker_data/simple_input_2.robj"))
@min_length = 3
@epoch_length = 0.5
end
it "Validates input data" do
@query_results.length.should == 1477
@input_data.length.should == 1477
end
describe "Simple Input" do
# Output for simple data:
let(:sleep_desired_output) { [["2844GX", 1, 2013.064, 2.5, 0, 5], ["2844GX", 1, 2013.131, 4.5, 0, 5], ["2844GX", 1, 2013.239, 6.5, 1, "."], ["2844GX", 1, 2013.423, 2.0, 1, "."], ["2844GX", 2, 2013.564, 2.0, 0, 5], ["2844GX", 2, 2013.631, 7.5, 1, "."]] }
let(:wake_desired_output) { [["2844GX", 1, 2013.106, 1.5, 0, 1], ["2844GX", 1, 2013.206, 2, 0, 6], ["2844GX", 1, 2013.381, 2.5, 0, 1], ["2844GX", 2, 2013.598, 2.0, 0, 1]] }
let(:rem_desired_output) { [["2844GX", 1, 2013.181, 1.5, 0, 5], ["2844GX", 1, 2013.239, 3, 0, 1], ["2844GX", 2, 2013.564, 2.0, 0, 5], ["2844GX", 2, 2013.723, 2.0, 1, "."]] }
let(:nrem_desired_output) { [["2844GX", 1, 2013.064, 2.5, 0, 5], ["2844GX", 1, 2013.131, 3, 0, 6], ["2844GX", 1, 2013.289, 3.5, 1, "."], ["2844GX", 1, 2013.423, 2.0, 1, "."], ["2844GX", 2, 2013.631, 5.5, 0, 6]] }
it "should return desired output for simple input" do
[[:sleep_bouts, sleep_desired_output], [:wake_bouts, wake_desired_output], [:rem_bouts, rem_desired_output], [:nrem_bouts, nrem_desired_output]].each do |method, desired_output|
bm = Tools::BoutMaker.new(@simple_input, @min_length, @epoch_length)
bouts = bm.send(method)
expect(bouts.length).to eq(desired_output.length), "#{method}: #{bouts.length}\n#{bouts}"
bouts = bouts.map {|x| [x[0], x[1], x[2].round(3), x[3], x[4], x[5]]}
bouts.each_with_index do |b, i|
b.should == desired_output[i]
end
bouts.should == desired_output
end
end
it "should return non-numeric next states" do
[[:sleep_bouts, sleep_desired_output], [:wake_bouts, wake_desired_output], [:rem_bouts, rem_desired_output], [:nrem_bouts, nrem_desired_output]].each do |method, desired_output|
bm = Tools::BoutMaker.new(@simple_input, @min_length, @epoch_length, :legacy_category)
bouts = bm.send(method)
expect(bouts.length).to eq(desired_output.length), "#{method}: #{bouts.length}\n#{bouts}"
next_states = bouts.map{|x| x[5]}.uniq.to_set
expect(next_states).to be_proper_subset(["Sleep", "Wake", "NREM", "REM", "."].to_set), "#{next_states.to_a}"
end
end
it "should work for bouts of min length == 2" do
pending
end
end
describe "Full Dataset" do
it "should run" do
bm = Tools::BoutMaker.new(@input_data, @min_length, @epoch_length)
[:sleep_bouts, :wake_bouts, :rem_bouts, :nrem_bouts].each do |method|
r = bm.send(method)
r.length.should > 0
end
end
it "should create files that match the previous program's output" do
bm = Tools::BoutMaker.new(@full_input_data, 2, 0.5, :legacy_category)
[:sleep, :wake, :rem, :nrem].each do |method|
r = bm.send(method.to_s+"_bouts")
my_file_path = Tools::BoutMaker.to_file(@subject_code, method, 2, 0.5, r, @data_location)
#my_file = File.open(my_file_path)
test_file = File.open(File.join(@data_location, "#{method.to_s}_test.csv"))
my_file_length = IO.popen("wc -l #{my_file_path}").readline.split(" ")[0].to_i
test_file_length = IO.popen("wc -l #{test_file.path}").readline.split(" ")[0].to_i
expect(my_file_length).to eq(test_file_length)
end
end
end
end |
require 'rltk/cg/llvm'
require 'rltk/cg/module'
require 'rltk/cg/execution_engine'
require 'rltk/cg/contractor'
# tells LLVM we are using x86 arch
RLTK::CG::LLVM.init(:X86)
# include supporting library
RLTK::CG::Support.load_library('./stdlib.so')
module JS
class Contractor < RLTK::CG::Contractor
attr_reader :module
def initialize
super
# ir objects
@module = RLTK::CG::Module.new('JS JIT')
@st = Hash.new
@func = Hash.new
# execution engine
@engine = RLTK::CG::JITCompiler.new(@module)
# pass to
@module.fpm.add(:InstCombine, :Reassociate, :GVN, :CFGSimplify, :PromoteMemToReg)
# define supporting library
@func["ptD"] = @module.functions.add("ptD",
RLTK::CG::NativeIntType,
Array.new(1,
RLTK::CG::DoubleType))
@func["nl"] = @module.functions.add("nl",
RLTK::CG::NativeIntType,
[])
# create main func
@func["main"] = @module.functions.add("main",
RLTK::CG::NativeIntType,
[])
@st["test"] = @module.globals.add(RLTK::CG::PointerType.new(RLTK::CG::NativeIntType),"test")
@st["test"].linkage = :weak_any
end
def finalize()
#build(@func["main"].blocks.append()) do
#ret (visit Number.new(0))
#end
@func["main"].tap { @func["main"].verify }
end
def add(ast)
build(@func["main"].blocks.append("entry")) do
# initialize all global variables
ast.map { |node| visit node }
ret (RLTK::CG::NativeInt.new(0))
end
end
def execute()
optimize(@func["main"])
@engine.run_function(@func["main"])
end
def optimize(fun)
@module.fpm.run(fun)
fun
end
def dump()
@func.each do |key, value|
value.dump()
end
@st.each do |key, value|
puts value.inspect
end
@st["test"].dump()
end
def dumpo()
@func.each do |key, value|
optimize(value).dump()
end
end
on Assign do |node|
right = visit node.right
loc =
if @st.has_key?(node.name)
@st[node.name]
else
@st[node.name] = alloca RLTK::CG::DoubleType, node.name
end
store right, loc
nil
end
on Binary do |node|
left = visit node.left
right = visit node.right
case node
when Add then fadd(left, right, 'addtmp')
when Sub then fsub(left, right, 'subtmp')
when Mul then fmul(left, right, 'multmp')
when Div then fdiv(left, right, 'divtmp')
end
end
on Write do |node|
visit Call.new(node.lineno, "ptD", node.arg_names)
end
on Call do |node|
callee = @module.functions[node.name]
if not callee
raise 'Unknown function referenced.'
end
if callee.params.size != node.args.length
raise "Function #{node.name} expected #{callee.params.size} argument(s) but was called with #{node.args.length}."
end
args = node.args.map { |arg| visit arg }
call callee, *args.push('calltmp')
end
on Variable do |node|
if @st.key?(node.name)
self.load @st[node.name], node.name
else
raise "Uninitialized variable '#{node.name}'."
end
end
on Number do |node|
RLTK::CG::Double.new(node.value.to_f)
end
on Function do |node|
puts node.inspect
# Reset the symbol table.
@st.clear
# Translate the function's prototype.
fun = visit node.proto
# Create a new basic block to insert into, allocate space for
# the arguments, store their values, translate the expression,
# and set its value as the return value.
build(fun.blocks.append('entry')) do
fun.params.each do |param|
@st[param.name] = alloca RLTK::CG::DoubleType, param.name
store param, @st[param.name]
end
ret (visit node.body)
end
# Verify the function and return it.
fun.tap { fun.verify }
end
on Prototype do |node|
if fun = @module.functions[node.name]
if fun.blocks.size != 0
raise "Redefinition of function #{node.name}."
elsif fun.params.size != node.arg_names.length
raise "Redefinition of function #{node.name} with different number of arguments."
end
else
fun = @module.functions.add(node.name, RLTK::CG::DoubleType, Array.new(node.arg_names.length, RLTK::CG::DoubleType))
end
# Name each of the function paramaters.
fun.tap do
node.arg_names.each_with_index do |name, i|
fun.params[i].name = name
end
end
end
def printst
puts @st.inspect
end
end
end
|
class AddRepresentativeToPolicyCalculations < ActiveRecord::Migration
def change
add_reference :policy_calculations, :representative, index: true
add_foreign_key :policy_calculations, :representatives
end
end
|
class CreateInsumos < ActiveRecord::Migration[5.0]
def change
create_table :insumos do |t|
t.integer :codigo
t.string :descricao
t.string :codigo_seinfra
t.references :unidade, foreign_key: true
t.timestamps
end
end
end
|
class CreatePeopleData < ActiveRecord::Migration
def change
create_table :people_data do |t|
t.hstore :values
t.references :person
t.timestamps
end
add_index :people_data, :person_id
end
end
|
class UsersController < ApplicationController
before_action :allready_logged, only: :new
def new
@user=User.new
end
def create
@user = User.new(user_params)
if @user.save
flash[:notice] = "Murlock successfully created"
redirect_to @user
else
render 'new'
end
end
def show
@user = us
end
def edit
@user = User.find(current_user[:id])
end
def update
@user = User.find(current_user[:id])
@user.update_attribute(:avatar, params[:user][:avatar])
redirect_to :back
end
def crop
end
private
def us
if params[:id]
return User.find(params[:id])
else
return User.find(current_user[:id])
end
end
def user_params
params[:user][:rank] = "pollywog" if !params[:user][:rank]
params[:user][:location] = "other" if !params[:user][:location]
params.require(:user).permit(:name, :email, :password, :password_confirmation, :rank, :location)
end
def allready_logged
if session[:user]||session[:visitor]
flash[:alert] = "Why??? why are uou doing this to me???"
redirect_to root_url
end
end
end
|
require 'spec_helper'
describe PrivateMessenger, '#invitation' do
it 'sends the correct invitation' do
event_owner = create(:user)
invitee = create(:user)
message = :invitation
event = create(:event, owner: event_owner)
invitation = build(:invitation, event: event, invitee: invitee)
PrivateMessenger.new(
recipient: invitee,
message: message,
sender: event_owner,
message_object: invitation
).deliver
FakeYammer.messages_endpoint_hits.should == 1
FakeYammer.message.should include('vote')
FakeYammer.message.should include(event_owner.name)
end
end
describe PrivateMessenger, '#reminder' do
it 'sends the correct reminder' do
event_owner = create(:user)
invitee = create(:user)
message = :reminder
event = create(:event, owner: event_owner)
invitation = build(:invitation, event: event, invitee: invitee)
PrivateMessenger.new(
recipient: invitee,
message: message,
sender: event_owner,
message_object: invitation
).deliver
FakeYammer.messages_endpoint_hits.should == 1
FakeYammer.message.should include('Reminder')
FakeYammer.message.should include(event_owner.name)
end
end
describe PrivateMessenger, '#group_invitation' do
it 'sends a group invitation' do
event_owner = create(:user)
group = create(:group)
message = :group_invitation
event = create(:event, owner: event_owner)
invitation = build(:invitation, event: event, invitee: group)
PrivateMessenger.new(
recipient: group,
message: message,
sender: event_owner,
message_object: invitation
).deliver
FakeYammer.messages_endpoint_hits.should == 1
FakeYammer.message.should include('I want your input')
FakeYammer.message.should include(group.name)
end
end
describe PrivateMessenger, '#group_reminder' do
it 'sends a group reminder' do
event_owner = create(:user)
group = create(:group)
message = :group_reminder
event = create(:event, owner: event_owner)
invitation = build(:invitation, event: event, invitee: group)
PrivateMessenger.new(
recipient: group,
message: message,
sender: event_owner,
message_object: invitation
).deliver
FakeYammer.messages_endpoint_hits.should == 1
FakeYammer.message.should include('Reminder')
FakeYammer.message.should include(event_owner.name)
end
end
|
class EventsController < ApplicationController
layout 'admin'
# TOOD probably want to make this more restrictive
def checkAccess
end
def edit_remotely
@event = Event.find(params[:id])
render :update do |page|
page.replace_html("event_#{@event.id}",
:partial => "events/event_edit",
:object => @event)
end
end
def update_remotely
@event = Event.find(params[:id])
respond_to do |format|
if @event.update_attributes(params[:event])
#flash[:notice] = 'Event was successfully updated.'
format.html { redirect_back }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @event.errors, :status => :unprocessable_entity }
end
end
end
# GET /events
# GET /events.xml
def index
if hasAccess(3)
@events = Event.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @events }
end
else
deny_access
end
end
# GET /events/1
# GET /events/1.xml
def show
@event = Event.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @event }
end
end
# GET /events/new
# GET /events/new.xml
def new
@event = Event.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @event }
end
end
# GET /events/1/edit
def edit
@event = Event.find(params[:id])
render :layout => 'WardAreaBook'
end
def create_new_family_event
@event = Event.new(params[:event])
@event.author = session[:user_id]
respond_to do |format|
if @event.save
#Advance the next milestone if:
# the event is a memberMilestone
# user has a teaching record
# this event is the current milestone
if @template.memberMilestones.include?([@event.category,@event.category]) and
@event.family.teaching_record and
@event.category == @event.family.teaching_record.membership_milestone
nextMileStone = @template.getNextMileStone(@event.family)
@event.family.teaching_record.membership_milestone = nextMileStone[0]
@event.family.teaching_record.save!
end
#flash[:notice] = 'Event was successfully created.'
format.html { redirect_to(:controller => 'families',
:action => 'show', :id => @event.family_id)}
else
format.html { render :action => "new" }
format.xml { render :xml => @event.errors, :status => :unprocessable_entity }
end
end
end
# POST /events
# POST /events.xml
def create
@event = Event.new(params[:event])
@event.author = session[:user_id]
respond_to do |format|
if @event.save
#flash[:notice] = 'Event was successfully created.'
format.html { redirect_to(@event) }
format.xml { render :xml => @event, :status => :created, :location => @event }
else
format.html { render :action => "new" }
format.xml { render :xml => @event.errors, :status => :unprocessable_entity }
end
end
end
# PUT /events/1
# PUT /events/1.xml
def update
event = Event.find(params[:id])
if event.author == session[:user_id] or event.person_id == session[:user_id] or hasAccess(2)
event.update_attributes(params[:event])
end
if params[:redirect] == "list"
redirect_to events_path
else
redirect_to event.family
end
end
#TODO Hack! There's got to be a more approprate way to do this.
def remove
destroy
end
# DELETE /events/1
# DELETE /events/1.xml
def destroy
#flash[:notice] = 'Event successfully deleted.'
@event = Event.find(params[:id])
@event.destroy
respond_to do |format|
format.html { redirect_to events_path }
format.xml { head :ok }
end
end
end
|
class Rsvp < ApplicationRecord
self.table_name= 'rsvp'
belongs_to :user
has_many :rsvp_guests, inverse_of: :rsvp, dependent: :destroy
accepts_nested_attributes_for :rsvp_guests, allow_destroy: true, reject_if: proc { |a| a['name'].blank? }
end
|
require_relative 'util/i18n'
module Errors
class BaseError < StandardError
attr_writer :line_num
def initialize(error_message = '')
super error_message
end
end
# Dynamically define custom error classes (using anonymous class objects).
# send is used to bypass visibility on define_method, and definition with proc
# is used to keep a reference to message (as opposed to a block passed to the
# class initialisation which loses context).
# See: config/i18n/en/tokenizer_errors.yaml
# See: config/i18n/en/interpreter_errors.yaml
def self.register_custom_errors(owner)
file = owner.name.downcase.sub '::', '_'
Util::I18n.messages(file).each do |error, message|
owner.const_set error, Class.new(owner::BaseError)
owner.const_get(error).send :define_method, :initialize, (proc { |*args| super format(message, *args) })
end
end
end
|
class ChangeColumnNameArticles < ActiveRecord::Migration
def change
rename_column :articles, :format, :article_format
end
end
|
class IngredientsController < ApplicationController
# GET /ingredients
# GET /ingredients.json
def index
@ingredients = Ingredient.all.sort_by { |e| e.name }
respond_to do |format|
format.html # index.html.erb
format.json { render json: @ingredients }
end
end
# GET /ingredients/1
# GET /ingredients/1.json
def show
@ingredient = Ingredient.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @ingredient }
end
end
# GET /ingredients/new
# GET /ingredients/new.json
def new
@ingredients = Ingredient.all.sort_by { |e| e.name }
respond_to do |format|
format.html # new.html.erb
format.json { render json: @ingredient }
end
end
# GET /ingredients/1/edit
def edit
@ingredient = Ingredient.find(params[:id])
end
# POST /ingredients
# POST /ingredients.json
def create
@ingredient_cart = params[:ingredients_list].split(",").collect {|a| a.strip}
Ingredient.add_cart(@ingredient_cart)
redirect_to ingredients_path
end
# PUT /ingredients/1
# PUT /ingredients/1.json
def update
@ingredient = Ingredient.find(params[:id])
respond_to do |format|
if @ingredient.update_attributes(params[:ingredient])
format.html { redirect_to @ingredient, notice: 'Ingredient was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @ingredient.errors, status: :unprocessable_entity }
end
end
end
# DELETE /ingredients/1
# DELETE /ingredients/1.json
def destroy
@garbage = params[:disposal_list].split("<br>")
Ingredient.dispose_garbage(@garbage)
redirect_to ingredients_path
end
end
|
require 'rails_helper'
describe ExerciseTask do
let(:company) { create(:company) }
let(:user) { create(:user, company: company) }
let(:track) { create(:track, company: company.reload) }
let(:exercise_task) { build(:exercise_task, track: track, reviewer: user) }
describe 'association' do
it { should belong_to(:reviewer).class_name(User) }
it { should have_attached_file(:sample_solution) }
end
describe 'validations' do
it { should validate_presence_of(:reviewer) }
it { should validate_attachment_content_type(:sample_solution).allowing('application/zip') }
end
describe '#reviewer_name' do
it { expect(exercise_task.reviewer_name).to eq(user.name) }
end
end |
module ActionView
module Helpers
class FormBuilder
def genre_select(method, priority_or_options = {}, options = {}, html_options = {})
if Hash === priority_or_options
html_options = options
options = priority_or_options
else
options[:priority_countries] = priority_or_options
end
@template.genre_select(@object_name, method, objectify_options(options), @default_options.merge(html_options))
end
end
module FormOptionsHelper
def genre_select(object, method, options = {}, html_options = {})
GenreSelect.new(object, method, self, options.delete(:object)).render(options, html_options)
end
end
class GenreSelect < InstanceTag
include ::GenreSelect::TagHelper
def render(options, html_options)
@options = options
@html_options = html_options
if self.respond_to?(:select_content_tag)
select_content_tag(genre_option_tags, @options, @html_options)
else
html_options = @html_options.stringify_keys
add_default_name_and_id(html_options)
content_tag(:select, add_options(genre_option_tags, options, value(object)), html_options)
end
end
end
end
end
|
module Wolves
class Png
PNG_HEADER = "\x89PNG\r\n\x1A\n"
PNG_TXT = ['Title',
'Author',
'Description',
'Copyright',
'Creation Time',
'Software',
'Disclaimer',
'Warning',
'Source',
'Comment']
# Wolves::Png accepts a File pointing to a PNG image.
def initialize(file)
@file = file
@file.seek 0
if @file.read(8) != PNG_HEADER
raise ArgumentError, 'Not a PNG file!'
end
# Simple way to read the PNG file.
@chunks = {}
while !@file.eof?
length, type = *@file.read(8).unpack('NA*')
data = @file.read length
crc = @file.read(4).unpack('N').first
if Zlib::crc32(type + data) != crc
raise RuntimeError, "CRC checksum error on #{type}"
end
@chunks[type] ||= []
@chunks[type] << data
end
end
# Writes PNG data to file.
def png(file)
file.write PNG_HEADER
# Make sure IEND is actually at the end (Ruby 1.9).
iend = @chunks.delete 'IEND'
@chunks['IEND'] = iend
@chunks.each do |type, data|
data.each do |data_part|
file.write [data_part.length, type].pack('NA*')
file.write data_part
file.write [Zlib::crc32(type + data_part)].pack('N')
end
end
end
# Set the payload.
def payload=(pl)
@chunks['tEXt'] ||= []
@chunks['tEXt'] << PNG_TXT.sample + "\0" + pl.raw
end
# Fetch the payload.
def payload
@chunks['tEXt'].each do |t|
raw = t[(t.index("\0") + 1)..(t.length)]
if Payload.headercheck(raw)
pl = Payload.new
pl.raw = raw
return pl
end
end
nil
end
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
aws_credentials_path = File.dirname(__FILE__) + '/../aws.credentials'
aws_credentials = File.read(aws_credentials_path)
load_aws = <<SCRIPT
aws_credentials='#{aws_credentials}'
mkdir -p ~/.aws
echo "$aws_credentials" > /home/ubuntu/.aws/credentials
SCRIPT
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/xenial64"
# Create a forwarded port mapping which allows access to a specific port
# within the machine from a port on the host machine and only allow access
# via 127.0.0.1 to disable public access
# config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"
# Share an additional folder to the guest VM. The first argument is
# the path on the host to the actual folder. The second argument is
# the path on the guest to mount the folder. And the optional third
# argument is a set of non-required options.
config.vm.synced_folder "codelabs", "/home/ubuntu/codelabs"
config.vm.synced_folder "keys", "/home/ubuntu/keys", mount_options: ["dmode=755,fmode=400"]
config.vm.synced_folder "final-project", "/home/ubuntu/final-project"
# Provider-specific configuration so you can fine-tune various
# backing providers for Vagrant. These expose provider-specific options.
# Example for VirtualBox:
#
# config.vm.provider "virtualbox" do |vb|
# # Display the VirtualBox GUI when booting the machine
# vb.gui = true
#
# # Customize the amount of memory on the VM:
# vb.memory = "1024"
# end
#
# View the documentation for the provider you are using for more
# information on available options.
# Install git and zsh prerequisites
config.vm.provision :shell, inline: "apt-get update"
config.vm.provision :shell, inline: "apt-get -y install git zsh make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev tree jq"
# Clone Oh My Zsh from the git repo.
config.vm.provision :shell, privileged: false,
inline: "rm -rf ~/.oh-my-zsh && git clone git://github.com/robbyrussell/oh-my-zsh.git ~/.oh-my-zsh"
# Configure ~/.zshrc.
config.vm.provision :shell, privileged: false, inline: <<-SHELL
cat > ~/.zshrc <<'EOL'
export ZSH=$HOME/.oh-my-zsh
ZSH_THEME="agnoster"
COMPLETION_WAITING_DOTS="true"
plugins=(git python pip zsh-syntax-highlighting)
source $ZSH/oh-my-zsh.sh
PROMPT_COMMAND='prompt'
export PROJECT_HOME=$HOME
EOL
SHELL
# Change the ubuntu user's shell to use zsh.
config.vm.provision :shell, inline: "chsh -s /bin/zsh ubuntu"
# Install zsh-syntax-highlighting
config.vm.provision :shell, privileged: false, inline: <<-SHELL
git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
SHELL
# Install pyenv
config.vm.provision :shell, privileged: false, inline: <<-SHELL
# Install pyenv
# see: https://github.com/pyenv/pyenv
curl -sL https://raw.githubusercontent.com/pyenv/pyenv-installer/master/bin/pyenv-installer | bash
cat >> ~/.zshrc <<'EOL'
export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init -)"
EOL
SHELL
# Install Python and pip packages.
config.vm.provision :shell, privileged: false, inline: <<-SHELL
export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init -)"
# Use pyenv to install Python 3.6.2
pyenv --version
pyenv install 3.6.2
pyenv global 3.6.2
pip install flake8 autopep8 awscli boto3
SHELL
# Add AWS environment variables to ~/.zshrc.
config.vm.provision "aws_env", type: "shell", privileged: false, :inline => load_aws
# Configure the default AWS region.
config.vm.provision "aws_region", type: "shell", privileged: false, inline: <<-SHELL
mkdir -p ~/.aws
cat > ~/.aws/config <<'EOL'
[default]
region=us-east-1
EOL
SHELL
# Enable AWS CLI auto-completion.
config.vm.provision "aws_completion", type: "shell", inline: <<-SHELL
wget --quiet https://raw.githubusercontent.com/aws/aws-cli/develop/bin/aws_zsh_completer.sh -P /usr/local/bin
cat >> /home/ubuntu/.zshrc <<EOL
source /usr/local/bin/aws_zsh_completer.sh
EOL
SHELL
end
|
module ActiveRecord::IdRegions
module Migration
def create_table(table_name, options = {})
options[:id] = :bigserial if options[:id].nil?
value = anonymous_class_with_id_regions.rails_sequence_start
super
return if options[:id] == false
set_pk_sequence!(table_name, value) unless value == 0
end
def anonymous_class_with_id_regions
ActiveRecord::IdRegions::Migration.anonymous_class_with_id_regions
end
def self.anonymous_class_with_id_regions
@class_with_id_regions ||= Class.new(ActiveRecord::Base).include(ActiveRecord::IdRegions)
end
end
end
|
class Trainer
attr_accessor :locations
attr_reader :name
@@all = []
###### Instance methods ######
#Initialize a trainer with a name and an array of locations
def initialize(name)
@name = name
@@all << self
end
#Return an array of all the trainer's contracts with locations
def contracts()
Contract.all().select() { | contract | contract.trainer == self }
end
#Return an array of all the trainer's locations
def locations()
self.contracts().map() { | contract | contract.location }
end
#Create a contract with a new location
def join_location(location)
if self.locations().include?(location)
return "#{self.name} already work from #{location.name}"
else
Contract.new(self, location)
end
end
#Return an array of clients for this trainer
def clients()
Client.all().select() { | client | client.trainer == self }
end
###### Class methods ######
#Return all trainers
def self.all()
@@all
end
#Return the trainer with the most clients
def self.most_clients()
self.all().max_by { | trainer | trainer.clients().length() }
end
end |
class Removetempfromproperties < ActiveRecord::Migration
def change
remove_column :properties, :buildingsinfotemp, :string
end
end
|
# Exercise A
stops = [ "Croy", "Cumbernauld", "Falkirk High", "Linlithgow", "Livingston", "Haymarket"]
#1 Add "Edinburgh Waverley" to the end of the array
stops.push("Edinburgh Waverley")
#2 Add "Glasgow Queen St" to the start of the array
stops.unshift("Glasgow Queen Street")
#3 Add "Polmont" at the appropriate point (between "Falkirk High" and "Linlithgow")
stops.insert(4, "Polmont")
#4 Work out the index position of "Linlithgow"
stop = 0
for station in stops
if station == "Linlithgow"
p "Found Linlithgow at index position #{stop}"
end
stop += 1
end
#5 Remove "Livingston" from the array using its name
stops.delete("Livingston")
#6 Delete "Cumbernauld" from the array by index
stops.delete_at(2)
#7 How many stops there are in the array?
p "There are #{stops.length} stops in the array."
#8 How many ways can we return "Falkirk High" from the array?
p stops[2]
p stops[-5]
#9 Reverse the positions of the stops in the array
stops.reverse!()
#10 Print out all the stops using a for loop
for station_name in stops
puts station_name
end
puts "" #added for spacing
puts ""
# Exercise B
users = {
"Jonathan" => {
:twitter => "jonnyt",
:favourite_numbers => [12, 42, 75, 12, 5],
:home_town => "Stirling",
:pets => {
"fluffy" => :cat,
"fido" => :dog,
"spike" => :dog
}
},
"Erik" => {
:twitter => "eriksf",
:favourite_numbers => [8, 12, 24],
:home_town => "Linlithgow",
:pets => {
"nemo" => :fish,
"kevin" => :fish,
"spike" => :dog,
"rupert" => :parrot
}
},
"Avril" => {
:twitter => "bridgpally",
:favourite_numbers => [12, 14, 85, 88],
:home_town => "Dunbar",
:pets => {
"colin" => :snake
}
},
}
#1 Get Jonathan's Twitter handle (i.e. the string "jonnyt")
p users["Jonathan"][:twitter]
#2 Get Erik's hometown
p users["Erik"][:home_town]
#3 Get the array of Erik's favourite numbers
p users["Erik"][:favourite_numbers]
#4 Get the type of Avril's pet Colin
p users["Avril"][:pets]["colin"]
#5 Get the smallest of Erik's favourite numbers
sorted_array = users["Erik"][:favourite_numbers].sort
p "Erik's lowest favourite number is #{sorted_array[0]}"
#6 Add the number 7 to Erik's favourite numbers
users["Erik"][:favourite_numbers].push(7)
p users["Erik"][:favourite_numbers]
#7 Change Erik's hometown to Edinburgh
users["Erik"][:home_town] = "Edinburgh"
p users["Erik"][:home_town]
#8 Add a pet dog to Erik called "Fluffy"
users["Erik"][:pets]["fluffy"] = :dog
p users["Erik"][:pets]
#9 Add yourself to the users hash
users["Graeme"] = {:home_town => "Linlithgow",:pets=>{"buster" => :dog, "charlie" => :dog}}
p users ["Graeme"]
puts "" #added for spacing
puts ""
# Exercise C
united_kingdom = [
{
name: "Scotland",
population: 5295000,
capital: "Edinburgh"
}, {
name: "Wales",
population: 3063000,
capital: "Swansea"
}, {
name: "England",
population: 53010000,
capital: "London"
}
]
#1 Change the capital of Wales from "Swansea" to "Cardiff".
united_kingdom[1][:capital] = "Cardiff"
p united_kingdom[1][:capital]
#2 Create a Hash for Northern Ireland and add it to the united_kingdom array (The capital is Belfast, and the population is 1,811,000).
united_kingdom.push({:name => "Northern Ireland",:population => 1811000, :capital => "Belfast"})
p united_kingdom[3]
#3 Use a loop to print the names of all the countries in the UK.
country = 0
while country < united_kingdom.length
p united_kingdom[country][:name]
country += 1
end
#4 Use a loop to find the total population of the UK.
country = 0
total_population = 0
while country < united_kingdom.length
total_population += united_kingdom[country][:population]
country += 1
end
p "Total Population of UK is #{total_population}"
|
class School < ActiveRecord::Base
has_many :ratings
has_many :features
has_many :badges
end
|
class Area < ApplicationRecord
belongs_to :state
has_many :clinicas
geocoded_by :nombre
after_validation :geocode
def display_name
" #{self.nombre}"
end
end |
class ConversationMessage < ApplicationRecord
belongs_to :author, :class_name => 'User'
belongs_to :conversation
belongs_to :author, :class_name => 'User'
after_commit { PipelineService.publish(self) }
end
|
class Admin::PropertyContactsController < ApplicationController
before_filter :authenticate_admin
before_filter :current_admin
layout 'admin'
def create
parms = {}
parms[:person_id] = params[:person_id]
parms[:property_id] = params[:property_id]
parms[:person_attr_type_id] = params[:type_id]
contact = PropertyContact.new(parms)
if contact.save
flash[:notice] = "Contact was added"
redirect_to admin_property_path(params[:property_id])
else
flash[:alert] = "#{contact.errors.full_messages.to_sentence}"
redirect_to admin_property_path(params[:property_id])
end
end
def destroy
property_contact = PropertyContact.find(params[:id])
if property_contact.destroy
flash[:notice] = "Contact was deleted"
redirect_to admin_property_path(params[:property_id])
else
flash[:notice] = "Failed to delete contact"
redirect_to admin_property_path(params[:property_id])
end
end
end
|
class EpmSavedQueries < EasyPageModule
def category_name
@category_name ||= 'others'
end
def get_show_data(settings, user, page_context = {})
public, personal = Hash.new, Hash.new
queries = EasyQuery.registered_subclasses.keys.select{ |query_class| !settings['queries'] || settings['queries'].include?(query_class.name.underscore) }
queries.each do |query_class|
personal[query_class] = query_class.private_queries(user) if settings['saved_personal_queries']
public[query_class] = query_class.public_queries(user) if settings['saved_public_queries'] && user.easy_user_type == User::EASY_USER_TYPE_INTERNAL
end
return {:public => public, :personal => personal, :selected => queries }
end
def get_edit_data(settings, user, page_context={})
queries = EasyQuery.registered_subclasses.keys.collect{|q| q.name.underscore }
return {:queries => queries}
end
end
|
# Exercise 10: What Was That?
# https://learnrubythehardway.org/book/ex10.html
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
blackslash_cat = "I'm \\ a \\ cat."
# Single quotes ' only takes \' as scape sequence
fat_cat = '''
I\'ll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
'''
fat_cat2 = """
I'll do a list:
\t* Cat food
\t* 4\" long bar
\t* Fishies
\t* Catnip\n\t* Grass
"""
puts tabby_cat
puts persian_cat
puts blackslash_cat
puts fat_cat
puts fat_cat2
puts "Done and beeps in some devices \a"
puts "chaR\bracter befO\bore backspace shouldnn\b't appear"
puts "The formfeed character \finserts a page or section break"
puts "The linefeed character \ninserts a return and start from the down line"
puts "THE CARRIAGE RETURN make sense of this line by inserting a return and going to beggining of line \rThe carriage return "
puts "Let's insert \va vertical tab"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.