text stringlengths 10 2.61M |
|---|
class AddResolvedCaptchToTail < ActiveRecord::Migration[5.1]
def change
add_column :tails, :resolved_captcha, :boolean, default: false
end
end
|
class Selection < ApplicationRecord
belongs_to :restaurant
end
|
# encoding: utf-8
describe Faceter::Functions, ".wrap" do
let(:arguments) { [:wrap, :foo, Selector.new(options)] }
let(:input) { { foo: :FOO, bar: :BAR, baz: :BAZ, qux: :QUX } }
it_behaves_like :transforming_immutable_data do
let(:options) { {} }
let(:output) { { foo: { foo: :FOO, bar: :BAR, baz: :BAZ, qux: :QUX } } }
end
it_behaves_like :transforming_immutable_data do
let(:options) { { except: [] } }
let(:output) { { foo: { foo: :FOO, bar: :BAR, baz: :BAZ, qux: :QUX } } }
end
it_behaves_like :transforming_immutable_data do
let(:options) { { except: :foo } }
let(:output) { { foo: { bar: :BAR, baz: :BAZ, qux: :QUX } } }
end
it_behaves_like :transforming_immutable_data do
let(:options) { { except: :bar } }
let(:output) { { bar: :BAR, foo: { foo: :FOO, baz: :BAZ, qux: :QUX } } }
end
it_behaves_like :transforming_immutable_data do
let(:options) { { except: [:foo, :bar] } }
let(:output) { { bar: :BAR, foo: { baz: :BAZ, qux: :QUX } } }
end
it_behaves_like :transforming_immutable_data do
let(:options) { { only: [] } }
let(:output) { { foo: {}, bar: :BAR, baz: :BAZ, qux: :QUX } }
end
it_behaves_like :transforming_immutable_data do
let(:options) { { only: :foo } }
let(:output) { { foo: { foo: :FOO }, bar: :BAR, baz: :BAZ, qux: :QUX } }
end
it_behaves_like :transforming_immutable_data do
let(:options) { { only: :bar } }
let(:output) { { foo: { bar: :BAR }, baz: :BAZ, qux: :QUX } }
end
it_behaves_like :transforming_immutable_data do
let(:options) { { only: [:foo, :bar] } }
let(:output) { { foo: { foo: :FOO, bar: :BAR }, baz: :BAZ, qux: :QUX } }
end
it_behaves_like :transforming_immutable_data do
let(:options) { { only: [:bar] } }
let(:input) { { foo: { foo: :FOO, bar: :FOO }, bar: :BAR, baz: :BAZ } }
let(:output) { { foo: { foo: :FOO, bar: :BAR }, baz: :BAZ } }
end
it_behaves_like :transforming_immutable_data do
let(:options) { { except: :foo } }
let(:input) { { foo: { foo: :FOO, bar: :FOO }, bar: :BAR, baz: :BAZ } }
let(:output) { { foo: { foo: :FOO, bar: :BAR, baz: :BAZ } } }
end
end # describe Faceter::Functions.wrap
|
class UserSerializer < ActiveModel::Serializer
attributes :id, :username, :bio
has_many :user_shows
has_many :shows, through: :user_shows
end |
require 'json'
require_relative '../lib/pul_solr'
set :application, 'pul_solr'
set :repo_url, 'https://github.com/pulibrary/pul_solr.git'
# Default branch is :main
# ask :branch, `git rev-parse --abbrev-ref HEAD`.chomp
set :branch, ENV['BRANCH'] || 'main'
# Default deploy_to directory is /var/www/my_app_name
set :deploy_to, '/solr/pul_solr'
set :filter, :roles => %w{main}
# Default value for :scm is :git
# set :scm, :git
# Default value for :format is :airbrussh.
# set :format, :airbrussh
# You can configure the Airbrussh format using :format_options.
# These are the defaults.
# set :format_options, command_output: true, log_file: 'log/capistrano.log', color: :auto, truncate: :auto
# Default value for :pty is false
# set :pty, true
# Default value for :linked_files is []
# set :linked_files, fetch(:linked_files, []).push('config/database.yml', 'config/secrets.yml')
# Default value for linked_dirs is []
# set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'public/system')
# Default value for default_env is {}
# set :default_env, { path: "/opt/ruby/bin:$PATH" }
# Default value for keep_releases is 5
# set :keep_releases, 5
def solr_url
ENV['SOLR_URL'] ||= 'http://localhost:8983/solr'
end
namespace :deploy do
desc "Generate the crontab tasks using Whenever"
after :published, :whenever do
on roles(:main) do
within release_path do
execute("cd #{release_path} && bundle exec whenever --set 'environment=#{fetch(:whenever_environment, "production")}&host=#{fetch(:whenever_host, "test-host")}' --update-crontab pul_solr")
end
end
end
desc "Update configsets and reload collections"
after :published, :restart do
on roles(:main), wait: 5 do
# on stand alone server just restart solr, no way to send information to zoo keeper since it does not exist
if fetch(:stand_alone, false)
on roles(:main) do
execute "sudo /usr/sbin/service solr restart"
end
# on solr cloud, reload the configsets and collections
else
config_map.each { |key, val| update_configset(config_dir: key, config_set: val) }
collections.each { |collection| reload_collection(collection) }
end
end
end
end
namespace :alias do
task :list do
on roles(:main) do
execute "curl '#{solr_url}/admin/collections?action=LISTALIASES'"
end
end
# Swaps the rebuild and production catalog aliases.
# Production and rebuild collections are set with env variables when running the task.
task :swap do
production = ENV['PRODUCTION']
rebuild = ENV['REBUILD']
production_alias = ENV['PRODUCTION_ALIAS'] || "catalog-alma-production"
rebuild_alias = ENV['REBUILD_ALIAS'] || "catalog-alma-production-rebuild"
if production && rebuild
on roles(:main) do
# Delete the rebuild alias
execute "curl '#{solr_url}/admin/collections?action=DELETEALIAS&name=#{rebuild_alias}'"
# Move the production alias
execute "curl '#{solr_url}/admin/collections?action=CREATEALIAS&name=#{production_alias}&collections=#{production}'"
# Create the rebuild alias
execute "curl '#{solr_url}/admin/collections?action=CREATEALIAS&name=#{rebuild_alias}&collections=#{rebuild}'"
end
else
puts "Please set the PRODUCTION and REBUILD environment variables. Optionally, set PRODUCTION_ALIAS and REBUILD_ALIAS as well. For example:"
# Set PRODUCTION the collection name that is going to be in production.
# Set REBUILD the collection name that is in production until the swap and moving forward is going to be in rebuild.
# To know the current collection names for PRODUCTION and REBUILD see Solr UI -> collections. The following is an example.
puts "PRODUCTION=catalog-alma-production2 REBUILD=catalog-alma-production3 cap production alias:swap"
puts "PRODUCTION=catalog-staging2 REBUILD=catalog-staging1 PRODUCTION_ALIAS=catalog-staging REBUILD_ALIAS=catalog-staging-rebuild cap production alias:swap"
end
end
end
namespace :configsets do
def list_configsets
execute "curl #{solr_url}/admin/configs?action=LIST&omitHeader=true"
end
def update_configset(config_dir:, config_set:)
execute "cd /opt/solr/bin && ./solr zk -upconfig -d #{File.join(release_path, "solr_configs", config_dir)} -n #{config_set} -z #{zk_host}"
end
def delete_configset(config_set)
execute "curl \"#{solr_url}/admin/configs?action=DELETE&name=#{config_set}&omitHeader=true\""
end
desc 'List all Configsets'
task :list do |task_name, args|
on roles(:main) do
list_configsets
end
end
desc 'Update or create a Configset'
task :update, :config_dir, :config_set do |task_name, args|
on roles(:main) do
update_configset(config_dir: args[:config_dir], config_set: args[:config_set])
end
end
desc 'Delete a Configset'
task :delete, :config_set do |task_name, args|
on roles(:main) do
delete_configset(args[:config_set])
end
end
end
namespace :collections do
def list_collections
execute "curl '#{solr_url}/admin/collections?action=LIST'"
end
def create_collection(collection, config_name, num_shards = 1, replication_factor = 1, shards_per_node = 1)
execute "curl '#{solr_url}/admin/collections?action=CREATE&name=#{collection}&collection.configName=#{config_name}&numShards=#{num_shards}&replicationFactor=#{replication_factor}&maxShardsPerNode=#{shards_per_node}'"
end
def reload_collection(collection)
execute "curl '#{solr_url}/admin/collections?action=RELOAD&name=#{collection}'"
end
def delete_collection(collection)
execute "curl '#{solr_url}/admin/collections?action=DELETE&name=#{collection}'"
end
desc 'List Collections'
task :list do
on roles(:main) do
list_collections
end
end
desc 'Reload a Collection'
task :reload, :collection do |task_name, args|
on roles(:main) do
reload_collection(args[:collection])
end
end
desc 'Create a Collection'
# usage example: bundle exec cap staging collections:create[dpul-staging,dpul,1,3,1]
task :create, :collection, :config_name, :num_shards, :replication_factor, :shards_per_node do |task_name, args|
on roles(:main) do
num_shards = args[:num_shards] || 1
replication_factor = args[:replication_factor] || 1
shards_per_node = args[:shards_per_node] || 1
create_collection(args[:collection], args[:config_name], num_shards, replication_factor, shards_per_node)
end
end
desc 'Delete a Collection'
task :delete, :collection do |task_name, args|
on roles(:main) do
delete_collection(args[:collection])
end
end
end
namespace :solr do
desc "Opens Solr Console"
task :console do
on roles(:main) do |host|
solr_host = host.hostname
user = "pulsys"
port = rand(9000..9999)
puts "Opening #{solr_host} Solr Console on port #{port} as user #{user}"
Net::SSH.start(solr_host, user) do |session|
session.forward.local(port, "localhost", 8983)
puts "Press Ctrl+C to end Console connection"
`open http://localhost:#{port}`
session.loop(0.1) { true }
end
end
end
end
|
require("rspec")
require("title_case")
describe("title_case") do
it("capitalizes first letter of inputted words except those blacklisted") do
title_case("sometimes a great notion").should(eq("Sometimes a Great Notion"))
end
it("still capitalizes blacklisted words if they are the first word in the title") do
title_case("a knight's tale").should(eq("A Knight's Tale"))
end
it("returns correctly capitalized title regardless of case used inside word") do
title_case("a kNiGHt's tAlE").should(eq("A Knight's Tale"))
end
end
|
class RemoveIndexItemsDefault < ActiveRecord::Migration
def change
change_column_default(:items, :lunch, nil)
change_column_default(:items, :combo, nil)
end
end
|
class RemoveColumnFromMeal < ActiveRecord::Migration[6.0]
def change
remove_reference :meals, :meal_plan, null: false, foreign_key: true
end
end
|
require 'spec_helper'
describe Api::V1::AlexPelanController do
describe 'GET #portfolio' do
before(:each) { get :portfolio, :format => :json }
it "populates the 3 projects" do
expect(json['alex_pelan'].count).to eq 3
end
it "contains the proper JSON keys for github projects" do
project_hash = json['alex_pelan'][0]
expect(project_hash).to have_key('description')
expect(project_hash).to have_key('language')
expect(project_hash).to have_key('name')
expect(project_hash).to have_key('extra_display_information')
expect(project_hash).to have_key('stargazers_count')
expect(project_hash).to have_key('watchers_count')
expect(project_hash).to have_key('repo_url')
expect(project_hash).to have_key('project_url')
end
end
describe 'GET #tweets' do
it "responds with the requested number of tweets" do
get :tweets, count: 10, :format => :json
# we have "include rts set to false, so it filters those out rather than giving me a different tweet in its place
# pretty silly imo
expect(json['alex_pelan'].count).to be_between(0,10)
end
it "contains the proper JSON keys for tweets" do
get :tweets, :format => :json
first_tweet = json['alex_pelan'][0]
expect(first_tweet).to have_key("text")
expect(first_tweet).to have_key("user")
expect(first_tweet).to have_key("id")
end
end
describe 'GET #currently_reading' do
before(:each) {get :currently_reading, :format => :json}
# of course, this can manually be screwed up by me :)
it "responds with only one book" do
expect(json["books"].count).to eq 1
end
it "contains the proper JSON keys for goodreads books" do
first_book = json["books"][0]["book"]
expect(first_book).to have_key("description")
expect(first_book).to have_key("title")
expect(first_book).to have_key("image_url")
end
end
describe 'GET #recently_played' do
before(:each) {get :recently_played, count: 10, :format => :json}
it "responds with the requested number of songs" do
expect(json["alex_pelan"].count).to be_between(10,11) #more annoying inconsistency from APIs - if currently listening, it returns the current track as well as the 10 previous
end
it "contains the proper JSON keys for songs" do
first_song = json["alex_pelan"][0]
expect(first_song).to have_key("artist")
expect(first_song).to have_key("name")
expect(first_song).to have_key("album")
end
end
describe 'GET #recently_drank' do
before(:each) {get :recently_drank, count: 50, :format => :json}
it "responds with the requested number of beers" do
expect(json["checkins"]["count"]).to eq 50
end
it "contains the proper JSON keys for beers" do
first_checkin = json["checkins"]["items"][0]
expect(first_checkin).to have_key("beer")
expect(first_checkin).to have_key("brewery")
end
end
end
|
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
# log_in user
# redirect_to user
# flash[:success] = 'Logged in successfully.'
if params[:remember_me] == "1"
flash[:success] = '1'
cookies.permanent[:auth_token] = user.auth_token
redirect_to user
else
flash[:success] = '0'
cookies[:auth_token] = user.auth_token
redirect_to user
end
else
flash.now[:success] = 'Username/password is wrong.'
render 'new'
end
end
def destroy
# @current_user = nil
# cookies[:auth_token] = nil
# reset_session
logout
redirect_to root_path
end
end
|
class TagsController < ApplicationController
before_action :retrieve_user
before_action :find_task
def create
unless params[:name].blank?
tag = Tag.where(name: params[:name]).first ||
Tag.create(name: params[:name])
@task.tags << tag unless @task.tags.where(id: tag.id).first
end
redirect_to user_task_path(@user, @task)
end
def destroy
if tag = Tag.where(name: params[:name]).first
@task.tags.delete(tag)
end
redirect_to user_task_path(@user, @task)
end
def find_task
@task = @user.tasks.find(params[:task_id])
end
def retrieve_user
unless @user = User.where(id: params[:user_id]).first and
(@login_user.adm? or @login_user.id == @user.id)
redirect_to user_path(@login_user)
end
end
end
|
require "rulp"
Rulp::log_level = Logger::UNKNOWN
Rulp::print_solver_outputs = false
class IntegerLinearProgram
def initialize(students, sections, fte_per_section = 0.25, students_per_ta = 30)
@students = students
@sections = sections
@fte_per_section = fte_per_section
@students_per_ta = students_per_ta
@problem = Rulp::Max(objective)
enrollment_contraint
fte_contraint
skill_contraint
experience_contraint
end
def solve
# @problem.solve
@problem.cbc
end
def results
results = []
@students.each do |student|
@sections.each do |section|
if VAR_b(student.id, section.id).value
results << { student_id: student.id, section_id: section.id }
end
end
end
results
end
def print_results
@students.each do |student|
puts student.name
@sections.each do |section|
if VAR_b(student.id, section.id).value
puts "\t #{section.course.label}"
end
end
puts
end
end
private
def objective
variables = []
@students.each do |student|
@sections.each do |section|
student_score = student.preferences.where(course_id: section.course_id).first.try(:value)
student_score ||= 1
# FIXME
instructor_score = student.preferences.where(course_id: section.course_id).first.try(:value)
instructor_score ||= 1
variables << (student_score * instructor_score * VAR_b(student.id, section.id))
end
end
variables.sum
end
def enrollment_contraint
@sections.each do |section|
variables = @students.map { |student| VAR_b(student.id, section.id) }
constraint = (variables.sum <= (section.current_enrollment / @students_per_ta))
@problem[ constraint ]
end
end
def fte_contraint
@students.each do |student|
variables = @sections.map { |section| VAR_b(student.id, section.id) }
constraint = (variables.sum <= (student.fte / @fte_per_section))
@problem[ constraint ]
end
end
def skill_contraint
# FIXME
end
def experience_contraint
# FIXME
end
end
|
class AddWantsToDrink < ActiveRecord::Migration
def change
add_column :drinks, :wants, :boolean, :default => false
end
end
|
class Category < ApplicationRecord
has_and_belongs_to_many :escort_profiles
end
|
module DialogB
START_OF_RECORD = '$$'
LINE_CONTINUATION = ' '
def self.find_records_in_stream(io, options = {})
options[:before_continuation] ||= ''
record = []
io.each do |line|
line.chomp!
type, data = split_line(line, options)
if type == START_OF_RECORD # Start of record (yield and reset collector)
yield options[:as_hash] ? record_to_h(record) : record unless record.empty?
record = []
elsif type == LINE_CONTINUATION
record.last[1] << options[:before_continuation] << data unless data.nil?
else
record << [type, data] unless data.nil?
end
end
yield options[:as_hash] ? record_to_h(record) : record # last record
end
protected
def self.split_line(line, options = {})
options = {:strip_data => true}.merge(options)
type = line[0..1]
data = line[3, line.length - 3]
data.strip! if !data.nil? and options[:strip_data]
[ type, data ]
end
def self.record_to_h(record)
h = {}
record.each do |type, data|
if h[type].nil?
h[type] = data
elsif h[type].is_a? Array
h[type] << data
else
h[type] = [h[type], data]
end
end
h
end
end
|
require "pry"
require_relative "./concerns/findable.rb"
class Genre
attr_accessor :name, :songs
extend Concerns::Findable
@@all = []
def initialize(name)
self.name = name
self.songs = []
end
def self.all
@@all
end
def self.destroy_all
self.all.clear
end
def save
self.class.all << self
end
def self.create(name)
new_instance = self.new(name)
new_instance.save
new_instance
end
def artists
collection = []
songs.each {|song| collection << song.artist if !collection.include?(song.artist)}
collection
end
end
|
require_dependency YourPlatform::Engine.root.join('app/models/user').to_s
class User
def title
name + " " + corporations.map(&:token).join(" ")
end
end
|
class User < ActiveRecord::Base
has_many :phones
has_many :subscriptions
has_many :subscription_configurations, through: :subscriptions
def self.fetch_by_phone_number(number)
self.joins(:phones).where(['number = ?', number]).first
end
end
|
require 'test_helper'
class SubchaptersControllerTest < ActionController::TestCase
setup do
@subchapter = subchapters(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:subchapters)
end
test "should get new" do
get :new
assert_response :success
end
test "should create subchapter" do
assert_difference('Subchapter.count') do
post :create, subchapter: { chapter_id: @subchapter.chapter_id, en_description: @subchapter.en_description, es_description: @subchapter.es_description }
end
assert_redirected_to subchapter_path(assigns(:subchapter))
end
test "should show subchapter" do
get :show, id: @subchapter
assert_response :success
end
test "should get edit" do
get :edit, id: @subchapter
assert_response :success
end
test "should update subchapter" do
patch :update, id: @subchapter, subchapter: { chapter_id: @subchapter.chapter_id, en_description: @subchapter.en_description, es_description: @subchapter.es_description }
assert_redirected_to subchapter_path(assigns(:subchapter))
end
test "should destroy subchapter" do
assert_difference('Subchapter.count', -1) do
delete :destroy, id: @subchapter
end
assert_redirected_to subchapters_path
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'tapbot/version'
Gem::Specification.new do |spec|
spec.name = "tapbot"
spec.version = Tapbot::VERSION
spec.authors = ["David Ramirez"]
spec.email = ["david@davidrv.com"]
spec.summary = "Tapbot api gem"
spec.description = "Tapbot api gem"
spec.homepage = "https://tapbot.readme.io/"
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
# delete this section to allow pushing this gem to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "https://rubygems.org"
else
raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
end
spec.files = Dir["README.md","Gemfile","Rakefile", "spec/*", "lib/**/*"]
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.10"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency 'webmock', '~> 1.6'
spec.add_development_dependency "rspec"
spec.add_runtime_dependency 'httparty', '~> 0.13.7'
spec.add_runtime_dependency 'hashie', '~> 3.4', '>= 3.4.2'
end
|
class Api::EntriesController < ApplicationController
before_action :authenticate_user
def index
@entries = current_user.entries.order(:created_at)
@entries.where(word_count: 0).delete_all
Entry.create(user: current_user) if @entries.empty?
# TODO: time zone
@entries << Entry.create(user: current_user) if @entries.last.created_at.to_date < Date.today
@entries = Entry.set_lock(@entries)
render json: @entries.as_json(only: [:id, :created_at, :preview, :word_count, :goal, :locked]), status: 200
end
def show
@entry = current_user.entries
@entry = @entry.find(params[:id])
if @entry && !@entry.locked
render json: @entry
else
render json: {error: 'You are not authorized to access this entry.'}, status: 401
end
end
def update
# @entries = []
@entry = Entry.find(params[:id])
# if @entry.created_at.to_date == Date.today
@entry.update(entry_params)
@entries = Entry.set_lock(@entry.user.entries)
@entries << @entry
render json: @entries.as_json(only: [:id, :created_at, :preview, :word_count, :goal, :locked]), status: 200
# else
# render json: @entry.as_json(only: [:id, :created_at, :preview, :word_count, :goal, :locked]), status: 401
# end
end
protected
def entry_params
params.require(:entry).permit(:content)
end
end
|
class AddTransidToOrders < ActiveRecord::Migration
def change
add_column :orders, :transid, :string, default: '', null: false
end
end
|
class CreateExpReservations < ActiveRecord::Migration[5.0]
def change
create_table :exp_reservations do |t|
t.integer "user_id"
t.integer "experience_id"
t.date "data_entrada"
t.date "data_saida"
end
end
end
|
class Ability
include CanCan::Ability
def initialize(admin)
admin ||= Admin.new
is_super_admin = admin.is_super_admin?
if is_super_admin
[:new, :create, :reset_password, :change_password, :view_activities].each do |action|
can action, Admin
end
else
[:new, :create, :manage].each { |action| can action, User }
end
end
end
|
Fabricator(:calorie) do
protein { Random.rand(200) }
fat { 10 + Random.rand(200) }
carbs { 10 + Random.rand(200) }
date_of_entry { Faker::Date.between(20.days.ago, Date.today) }
end
|
# Este módulo se ha creado para la asignatura de
# Lenguajes y Paradigmas de la Programación impartida
# en la Universidad de la Laguna como práctica,
# haciendo uso del lenguaje de programación Ruby.
#
# Author:: Javier Esteban Pérez Rivas (mailto:alu0100946499@ull.edu.es)
# Copyright:: Creative Commons
# License:: Distributes under the same terms as Ruby
module DLL
# Esta clase permite crear una lista
# doblemente enlazada.
# Se ha incluido el mixin Enumerable.
class DLL
include Enumerable
Node = Struct.new(:value, :next, :prev)
attr_reader :head, :tail
# La lista se crea vacía por defecto.
def initialize()
@head, @tail = nil, nil
end
# Devuelve true si la lista está vacía, false en otro caso.
def empty()
return true if (@head == nil && @tail == nil)
false
end
# Muestra los elementos de la lista como si fuese un string.
def to_s()
out = ""
aux = @tail
while (aux != nil) do
if(aux[:next] == nil)
out << "#{aux[:value]}"
else
out << "#{aux[:value]}, "
end
aux = aux.next
end
out
end
# Inserta los elementos por el principio de la lista.
def insert_head(*objects)
objects.each{ |x|
if(self.empty)
aux = Node.new(x, nil, @head)
@tail = aux
@head = aux
else
aux = Node.new(x, nil, @head)
@head[:next] = aux
@head = aux
end
}
end
# Inserta los elementos por el final de la lista.
def insert_tail(*objects)
objects.each{ |x|
if(self.empty)
aux = Node.new(x, @tail, nil)
@tail = aux
@head = aux
else
aux = Node.new(x, @tail, nil)
@tail[:prev] = aux
@tail = aux
end
}
end
# Elimina el elemento al que apunta head.
def erase_head()
aux = @head[:prev]
aux[:next] = nil
@head = aux
end
#Elimina el elemento al que apunta tail.
def erase_tail()
aux = @tail[:next]
aux[:prev] = nil
@tail = aux
end
# Se incluye el metodo del mixin Enumerable
# Se define como la iteración entre los valores de los nodos.
def each # :yields: value
aux = @tail
while (aux != nil) do
yield aux[:value]
aux = aux.next
end
end
end
end
|
=begin
dfefine a method that utilizes a specific alphabet that does not include vowels
An array made up of string objects is passed in as the argument
I need to return a new transformed array object witout vowels
pass in the argment to a block using the .map method
iterate over the variable for the string, using the string method .delete with string object (aeiouAEIOU) as the argument
def remove_vowels(array)
array.map do |word|
word.delete('aeiouAEIOU')
end
end
puts remove_vowels(%w(abcdefghijklmnopqrstuvwxyz)) == %w(bcdfghjklmnpqrstvwxyz)
puts remove_vowels(%w(green YELLOW black white)) == %w(grn YLLW blck wht)
puts remove_vowels(%w(ABC AEIOU XYZ)) == ['BC', '', 'XYZ']
Write a method that calculates and returns the index of the first Fibonacci
number that has the number of digits specified as an argument. (The first Fibonacci number has index 1.)
the input is the number, which refers to the nuber of digits
the output is the index value of the first number in the series that hits that number of digits(input)
Write the sequence that is the fibonnaci that is going to push the value into a
new array within the method definition
Assume the argument is always greater than or equal to 2
First nuber has an index of 1
[counter + 1].lengthof the argument, is the size of the array
loop structure do
add the value of the previous number[index] to the new number [index[]]
How to write the fibonnaci sequence
beginning with the number 1, add that number to the previous number, then next
So the next index value will be the sum of the previous index and the one previous to that
can be number[index] = number[index-1] + number[index-2]
conditional if index = 1
number = 1
else index == 2
number = 2
else
number[index] = number[index-1] + number[index-2]
index = counter
index is the reurn
push the index value into the array_count
the coutner stops when the argument is equal to the number of digits in the index #'s return value
break if (return value of index) == array_count.length
outcome will be the size of the whole array
def find_fibonacci_index_by_length(digits)
array_count = []
first_number = 1
second_number = 1
index = 0
loop do
case index # sorts the fibonnaci into array_count
when 0
array_count << first_number
when 1
array_count << second_number
else
array_count << array_count[index - 1] + array_count[index - 2]
end
break if array_count[index].to_s.size == digits
end
index + 1
end
puts find_fibonacci_index_by_length(2) == 7 # 1 1 2 3 5 8 13
puts find_fibonacci_index_by_length(3) == 12 # 1 1 2 3 5 8 13 21 34 55 89 144
# LAUNCHSCHOOL SOLUTOON
def find_fibonacci_index_by_length(number_digits)
first = 1 #1st number of fibb
second = 1 #2nd number in fibb
index = 2
loop do
index += 1
fibonacci = first + second #3rd number of fibb is 2,
break if fibonacci.to_s.size >= number_digits # refers to variable, not an array like mine..ok
first = second # reassign the frist variable to the second
second = fibonacci # reassign the secnd now to the variable first+second
end
index # return value of the method call
end
puts find_fibonacci_index_by_length(2) == 7 # 1 1 2 3 5 8 13
puts find_fibonacci_index_by_length(3) == 12 # 1 1 2 3 5 8 13 21 34 55 89 144
puts find_fibonacci_index_by_length(10) == 45
puts find_fibonacci_index_by_length(100) == 476
puts find_fibonacci_index_by_length(1000) == 4782
puts find_fibonacci_index_by_length(10000) == 47847
Reversed Arrays PArt 1
Write a method that takes an array as an argument and reveres its element in place,MEANING,
mutate the array passed into the method, return value should be teh same as the Array object
not alloawed to use Array.reverse
we have an array object that swaps places with objects on the elft and right sides of the array
initiate a variable LEFT_INDEX = 0
initiate a variable RIGHT_INDEX = -1
this allows us to refer to the objects on either sidde of the array object
initiate a while loop for interation, when the left index value is less than the array.size/2
(since we are swapping 2 values at a time)
in order to swap 2 values at a time, we have to reassign left_index and right_index values contained in the array with right_index and left_index
end the while
return the array
def reverse!(array)
left_index = 0
right_index = -1
while left_index < array.size / 2
array[left_index], array[right_index] = array[right_index], array[left_index]
end
array
end
puts reverse!([3, 2, 5, 6, 8, 3]) == [3, 8, 6, 5, 2, 3]
Reverse Part 2
Write a method that takes an array and returns a new array witht he elemtns fo the rogiinal list in reverse order
Do not modify the original list
definte the method reverse
initialize a new array object
initialize an index value for the items in the original array
initialize a loop that allows iteration through the index vae
iterate over the array object in reverse order, beginning at index value -1
reassign the index throughh the index = index - 1
def reverse(list)
new_array = []
index = -1
loop do
new_array << list[index]
break if index * -1 == list.size
index -= 1
end
new_array
end
puts reverse([1,2,3,4]) == [4,3,2,1] # => true
puts reverse(%w(a b e d c)) == %w(c d e b a) # => true
puts reverse(['abc']) == ['abc'] # => true
puts reverse([]) == [] # => true
Write a methd that takes two Arrays as arguments and returns an ARray that contains all of the values
from the argument Arrays. There should be no duplicates in the New Array, even if there are in the original arrays
def merge(array1, array2)
array = []
array << array1
array << array2
array.flatten.uniq
end
puts merge([1, 3, 5], [3, 6, 9]) == [1, 3, 5, 6, 9]
Halvsies
Write a method that takes an array as an argument, returns 2 arrays, as a pair of nested arrays that
contain the first half and second half of the original aarary and the second half of the original
array, respectively. if the OG array contains an odd number of elements the middle should be ni the first
half of the array
each_with_index
if number is < arary.size / 2
that gets passed into the first half of the array
else
that index value gets passed in the second nested array
def halvsies(array)
first_half = []
second_half = []
whole_array = [first_half, second_half]
array.each_with_index do |num, idx|
if idx == array.size / 2 && array.size == idx * 2
second_half << num
elsif idx <= array.size / 2
first_half << num
else
second_half << num
end
end
whole_array
end
puts halvsies([1, 2, 3, 4]) == [[1, 2], [3, 4]] # idx is 0, 1, 2 3, array size is 4, 2 is half
puts halvsies([1, 5, 2, 4, 3]) == [[1, 5, 2], [4, 3]]
puts halvsies([5]) == [[5], []]
puts halvsies([]) == [[], []]
puts halvsies([1, 2, 3, 4, 5, 6, 7, 8]) == [[1, 2, 3, 4], [5, 6, 7, 8]] # 4 index value is 3, size is 8
Find the Duplicate
Give an unordered array and the information that exactly one value occurs twice (each other occurs once)
how would you determine which value occurs twice? Write a method to find the return value that is known in the array.
if the aray has a value taht is the same as another
first sort the array with a mutated method
array.sort!
then find the numbers and their index value
array.sort!.each_with_index
Now initialize the block with 2 local variables |number, idx|
return the NUMBER if that index value and the next index value are equal
def find_dup(array)
array.sort!.each_with_index do |number, idx|
return number if array[idx] == array[idx + 1]
end
end
puts find_dup([1, 5, 3, 1]) == 1
puts find_dup([18, 9, 36, 96, 31, 19, 54, 75, 42, 15,
38, 25, 97, 92, 46, 69, 91, 59, 53, 27,
14, 61, 90, 81, 8, 63, 95, 99, 30, 65,
78, 76, 48, 16, 93, 77, 52, 49, 37, 29,
89, 10, 84, 1, 47, 68, 12, 33, 86, 60,
41, 44, 83, 35, 94, 73, 98, 3, 64, 82,
55, 79, 80, 21, 39, 72, 13, 50, 6, 70,
85, 87, 51, 17, 66, 20, 28, 26, 2, 22,
40, 23, 71, 62, 73, 32, 43, 24, 4, 56,
7, 34, 57, 74, 45, 11, 88, 67, 5, 58]) == 73
DOES MY list include this
Write a method named include? that takes an Array and a search value as arguments
This method should return true if search value is in the array flase if otherwise.
No use of include? is allowed.
iterate over the array and compare the object to the value argument
Initialize the .each method for the array
if the array value == value
return true
else
false
def include?(array, value)
array.each do |num|
compare = num <=> value
if compare == 0 # I could have made tihs simpler by assigning an == to each other
return true
end
end # block is ocer
false # remember, the block returning true is all that matters, otherwise itwill be false,
# no need for an ELSE statement within the block, the method definition will return false
# if the block does not return true
end
puts include?([1,2,3,4,5], 3) == true
puts include?([1,2,3,4,5], 6) == false
puts include?([], 3) == false
puts include?([nil], nil) == true
puts include?([], nil) == false
def include?(array, value)
!!array.find_index(value) # !! returns a true/false value
end
puts include?([1,2,3,4,5], 3) == true
puts include?([1,2,3,4,5], 6) == false
puts include?([], 3) == false
puts include?([nil], nil) == true
puts include?([], nil) == false
Right Triangles
Write a method that tkaes a positive integer, n, as an argument and displays
a right triangle whose sides each have N stars, the hyptoeneuse of the triangle
should have one end at the lower left of the triangle anad the other at
the upper right
puts the # of lines and # of spaces
=end
def triangle(sides)
for stars in 1..sides
puts ('*'*stars).rjust(sides)
end
end
triangle(5)
triangle(9)
#top to right bottom
=begin
def triangle(sides)
stars = '*'
counter = 0
loop do
puts stars.center(1) * counter
break if counter == sides
counter += 1
end
end
triangle(5)
triangle(9)
=end |
require 'rails_helper'
describe "appointments", type: :feature do
before do
@hawkeye = Doctor.create({name: "Hawkeye Pierce", department: "Surgery"})
@homer = Patient.create({name: "Homer Simpson", age:38})
@appointment = Appointment.create({appointment_datetime: DateTime.new(2016, 03, 15, 18, 00, 0), patient: @homer, doctor: @hawkeye})
end
it "should display an appointment's doctor" do
visit appointment_path(@appointment)
expect(page).to have_link("Hawkeye Pierce", href: doctor_path(@hawkeye))
end
it "should display an appointment's patient" do
visit appointment_path(@appointment)
expect(page).to have_link("Homer Simpson", href: patient_path(@homer))
end
it 'should display an appointment\'s date and time' do
visit appointment_path(@appointment)
expect(page).to have_text('March 15, 2016')
expect(page).to have_text('18:00')
end
it "should not have an index page" do
expect {visit('/appointments')}.to raise_error(ActionController::RoutingError)
end
end
|
Admin.controllers :cartes do
get :index do
@cartes = Carte.all
render 'cartes/index'
end
get :new do
@carte = Carte.new
render 'cartes/new'
end
post :create do
@carte = Carte.new(params[:carte].slice("name", "image"))
params[:carte][:items].split(/\r?\n/).each do |i|
item_name,item_price = i.split('|')
if item_name.present? and item_price.present?
@carte.items.build(name: item_name, price: item_price)
end
end
if @carte.save
flash[:notice] = 'Carte was successfully created.'
redirect url(:cartes, :edit, :id => @carte.id)
else
render 'cartes/new'
end
end
get :edit, :with => :id do
@carte = Carte.find(params[:id])
render 'cartes/edit'
end
put :update, :with => :id do
@carte = Carte.find(params[:id])
if @carte.update_attributes(params[:carte].slice("name", "image"))
if params[:carte][:items].present?
@carte.items = params[:carte][:items].split(/\r?\n/).map do |i|
item_name,item_price = i.split('|')
if item_name.present? and item_price.present?
Item.new(name: item_name, price: item_price, carte_id: @carte.id)
end
end
else
@carte.items = []
end
flash[:notice] = 'Carte was successfully updated.'
redirect url(:cartes, :edit, :id => @carte.id)
else
render 'cartes/edit'
end
end
delete :destroy, :with => :id do
carte = Carte.find(params[:id])
if carte.destroy
flash[:notice] = 'Carte was successfully destroyed.'
else
flash[:error] = 'Unable to destroy Carte!'
end
redirect url(:cartes, :index)
end
end
|
module Helpers
def self.symbolize_keys(hash)
Hash[hash.map{ |k, v| [k.to_sym, v] }]
end
def self.parse_path_word(word)
# validate keyword
word =~ /(\w+)\.(\w+)/
word = $1
format = $2
[word, format]
end
def self.sanitize_word_list(word_list)
word_list.map { |w| w.to_s }
end
def self.sanitize_word(word)
word.to_s
end
end |
class G0120a
attr_reader :options, :name, :field_type, :node
def initialize
@name = "Bathing (Self-Performance) - how resident takes bath/shower, sponge bath, and transfers in/out of tub/shower . (G0120a)"
@field_type = DROPDOWN
@node = "G0120A"
@options = []
@options << FieldOption.new("^", "NA")
@options << FieldOption.new("0", "Independent - no help provided.")
@options << FieldOption.new("1", "Supervision - oversight help only.")
@options << FieldOption.new("2", "Physical help limited to transfer only.")
@options << FieldOption.new("3", "Physical help in part of bathing activity")
@options << FieldOption.new("4", "Total dependence")
@options << FieldOption.new("8", "Activity did not occur")
end
def set_values_for_type(klass)
return "0"
end
end |
class AppointmentsController < ApplicationController
before_action :find_appointment, only: [:show, :edit, :update, :destroy]
# before_action -> {authorized_for(@appointment)}
before_action :require_login
def index
@type = params[:value]
if params[:appointment_type_id]
@appointments = Appointment.where(user_id: current_user.id, appointment_type_id: @type)
else
@appointments = Appointment.where(user_id: current_user.id)
end
end
def general_appointment
@appointments = Appointment.where(user_id: current_user.id, appointment_type_id: 1)
end
def vaccination
# @appointment = Appointment.find(params[:id])
# authorized_for(@appointment)
@appointments = Appointment.where(user_id: current_user.id, appointment_type_id: 2)
end
def emergency
@appointments = Appointment.where(user_id: current_user.id, appointment_type_id: 3)
end
def show
authorized_for(@appointment)
@doctor = @appointment.doctor
@user = @appointment.user
end
def new
@appointment = Appointment.new
@appointment.user = current_user
authorized_for(@appointment)
@user = current_user
end
def create
@appointment = Appointment.new(appointment_params)
authorized_for(@appointment)
@user = current_user
if @appointment.valid?
@appointment.save(appointment_params)
redirect_to appointments_path
else
flash[:errors] = @appointment.errors.full_messages
render :new
end
end
def edit
authorized_for(@appointment)
@user = current_user
end
def update
authorized_for(@appointment)
@user = current_user
if @appointment.valid?
@appointment.update(appointment_params)
redirect_to appointment_path(@appointment)
else
flash[:errors] = @appointment.errors.full_messages
render :new
end
end
def destroy
authorized_for(@appointment)
@appointment.destroy
redirect_to appointments_path
end
private
def find_appointment
@appointment = Appointment.find(params[:id])
end
def appointment_params
params.require(:appointment).permit(:doctor_id, :user_id, :appointment_type_id, :note, :appointment_date)
end
def require_login
redirect_to sessions_new_path unless session.include?(:user_id)
end
end
|
require 'collins_client'
require 'lib/collins_integration'
describe "Asset Find" do
before :all do
@integration = CollinsIntegration.new('default.yaml')
@client = @integration.collinsClient
end
def checkQuery(params, expected_size)
params[:size] = 50
assets = @client.find params
assets.size.should eql expected_size
end
def checkOrder(params, tag_list)
params[:size] = 50
assets = @client.find params
assets.map{|x| x.tag}.should eql tag_list
end
#these are all pulled from prod using query logging
it "attribute=POOL;FIREHOSE&attribute=PRIMARY_ROLE;SERVICE&status=Allocated&type=SERVER_NODE&details=false&operation=and:2" do
p = {
"pool" => "FIREHOSE",
"primary_role" => "SERVICE",
"status" => "Allocated",
"type" => "SERVER_NODE",
"details" => "false",
"operation" => "and"
}
checkQuery p, 1
end
it "attribute=HOSTNAME;service-wentworth&details=false:1" do
p = {
"hostname" => "service-bustworth*"
}
checkQuery p,11
end
it "attribute=POOL;API_POOL&attribute=PRIMARY_ROLE;PROXY&status=Allocated&type=SERVER_NODE&details=false&operation=and:1" do
p = {
"pool" => "API_POOL",
"primary_role" => "PROXY",
"status" => "Allocated",
"type" => "SERVER_NODE",
"operation" => "and"
}
checkQuery p,1
end
it "attribute=HOSTNAME;%5EMAIL.*&attribute=POOL;MAILPARSER_POOL&attribute=PRIMARY_ROLE;TUMBLR_APP&status=Allocated&type=SERVER_NODE&details=false&operation=or:2" do
p = {
"hostname" => "dev-*",
"pool" => "DEVEL",
"status" => "Allocated",
"type" => "SERVER_NODE",
"operation" => "and"
}
checkQuery p,5
end
it "operation=and&ASSET_TAG=&status=Allocated&state=&type=SERVER_NODE" do
p = {
"status" => "allocated",
"type" => "SERVER_NODE",
"primary_role" => "TUMBLR_APP",
"operation" => "and"
}
checkQuery p,2
end
it "status=Allocated@primary_role=SERVICE" do
p = {
"primary_role" => "SERVICE",
"status" => "Allocated",
"operation" => "and"
}
checkQuery p, 14
end
it "status=Unallocated&type=&PRIMARY_ROLE=CACHE&POOL=MEMCACHE&MEMORY_SIZE_TOTAL=103079215104" do
p = {
"status" => "Unallocated",
"primary_role" => "CACHE",
"pool" => "MEMCACHE*",
"memory_size_total" => "103079215104",
"operation" => "and"
}
checkQuery p, 9
end
it "handles fuzzy hostname" do
p = {
"hostname" => "bustworth"
}
checkQuery p,11
end
it "handles regex" do
p = {
"pool" => "^MEMCACHE$"
}
checkQuery p,1
end
it "cql with other stuff" do
p = {
"pool" => "MEMCACHE",
"query" => "status = allocated or (hostname = *default* AND num_disks = 2)"
}
checkQuery p, 5
end
it "strips enclosing quotes" do
p = {
"pool" => "MEMCACHE",
"query" => "\"status = allocated or (hostname = *default* AND num_disks = 2)\" "
}
checkQuery p, 5
end
it "sorts the assets" do
p = {
"pool" => "MEMCACHE",
"query" => "\"status = allocated or (hostname = *default* AND num_disks = 2)\" ",
"sortField" => "tag",
"sort" => "ASC"
}
checkOrder p, ["001044", "001046", "001049", "001336", "001415"]
p = {
"pool" => "MEMCACHE",
"query" => "\"status = allocated or (hostname = *default* AND num_disks = 2)\" ",
"sortField" => "hostname",
"sort" => "ASC"
}
checkOrder p, ["001415", "001044", "001046", "001336", "001049"]
end
it "multi nots" do
p = {
"query" => "NOT hostname = *web* AND NOT status=allocated"
}
checkQuery p,50
end
end
|
class PublishersController < ApplicationController
def index
@publishers = Publisher.all
end
def show
end
def new
@publisher = Publisher.new
end
def edit
end
def create
@publisher = Publisher.new(publisher_params)
respond_to do |format|
if @publisher.save
format.html { redirect_to @publisher, notice: "Publisher was successfully created." }
format.json { render :show, status: :created, location: @publisher }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @publisher.errors, status: :unprocessable_entity }
end
end
end
def update
@publisher.update(publisher_params)
redirect_to @publisher
end
def destroy
@publisher.destroy
redirect_to publishers_path
end
def search
if params[:name].blank?
redirect_to request.referrer
else
@name = params[:name].downcase
@publishers = Publisher.where("lower(title) LIKE ?", "%#{@name}%")
end
end
private
def set_publisher
@publisher = Publisher.find(params[:id])
end
def publisher_params
params.require(:publisher).permit(:name)
end
end
|
#base class for common functionality
#implement the indicated methods in a subclass, the handlers in the
#class that will handle the response, and then call the class
#method handle_responses to take messages off the queue and handle them.
class MessageResponse::Base < Object
attr_accessor :payload
def initialize(raw_payload:)
self.payload = JSON.parse(raw_payload)
end
def status
self.payload['status']
end
def action
self.payload['action']
end
def error_message
self.payload['message']
end
def pass_through(field)
self.payload['pass_through'][field.to_s]
end
def parameter_field(field)
self.payload['parameters'][field.to_s]
end
def handler
klass = Kernel.const_get(self.pass_through(pass_through_class_key))
id = self.pass_through(pass_through_id_key)
klass.find(id)
end
def dispatch_result
case self.status
when 'success'
self.handler.send(success_method, self)
when 'failure'
self.handler.send(failure_method, self)
else
self.handler.send(unrecognized_method, self)
end
end
#redundant except for testing
def self.handle_responses
sqs = QueueManager.instance.sqs_client
response = sqs.receive_message(queue_url: self.incoming_queue, max_number_of_messages: 1)
return nil if response.data.messages.count.zero?
while response.data.messages.count.positive? do
raw_payload = response.data.messages[0].body
break unless raw_payload
self.handle_response(raw_payload: raw_payload)
sqs.delete_message({queue_url: self.incoming_queue, receipt_handle: response.data.messages[0].receipt_handle})
response = sqs.receive_message(queue_url: self.incoming_queue, max_number_of_messages: 1)
end
end
def self.handle_response(raw_payload:)
response = self.new(raw_payload: raw_payload)
response.dispatch_result
end
#The key in the pass through hash used to find the class of the
# object to handle the response
def pass_through_class_key
raise RuntimeError, 'Subclass Responsibility'
end
#The key in the pass through hash used to find the id of the
# object to handle the response
def pass_through_id_key
raise RuntimeError, 'Subclass Responsibility'
end
#AMQP queue from which to pull messages
def self.incoming_queue
raise RuntimeError, 'Subclass Responsibility'
end
#Name to use for listener logging
def self.listener_name
raise RuntimeError, 'Subclass Responsibility'
end
#method to call on handler object when message indicates success. Called
#with sole argument this response object
def success_method
raise RuntimeError, 'Subclass Responsibility'
end
#method to call on handler object when message indicates failure. Called
#with sole argument this response object
def failure_method
raise RuntimeError, 'Subclass Responsibility'
end
#method to call on handler object when message status is neither
# success nor failure (should not happen). Called
#with sole argument this response object
def unrecognized_method
raise RuntimeError, 'Subclass Responsibility'
end
end |
# Virus Predictor
# I worked on this challenge [with Ted Bogen].
# We spent [1.5] hours on this challenge.
# EXPLANATION OF require_relative
# Links this page to another file to pull information from it, require_relative is special because instead
# of requiring a file path to the linked file it looks for it in the same directory. This is especially handy
# for forked or shared files where the coders have different file paths.
#
#Constants such as STATE_DATA have a global scope - can be called from anywhere. Constants can't be overwritten.
class VirusPredictor
#initializes instance variables for state, population, and density - will be recognized in following methods
def initialize(state_of_origin, population_density, population)
@state = state_of_origin
@population = population
@population_density = population_density
end
#Returns below methods
def virus_effects
predicted_deaths(@population_density, @population, @state)
speed_of_spread(@population_density, @state)
end
# private #makes code below accessible only to you; won't show up if called outside class
#Conditional for number of deaths by population density
def predicted_deaths(population_density, population, state)
# predicted deaths is solely based on population density
if @population_density >= 200
number_of_deaths = (@population * 0.4).floor
counter_a = 200
counter_b = 0.4
while @population_density < 200
number_of_deaths = (@population * counter_b).floor
counter_a -= 50
counter_b -= 0.1
end
# elsif @population_density >= 150
# number_of_deaths = (@population * 0.3).floor
# elsif @population_density >= 100
# number_of_deaths = (@population * 0.2).floor
# elsif @population_density >= 50
# number_of_deaths = (@population * 0.1).floor
else
number_of_deaths = (@population * 0.05).floor
end
print "#{@state} will lose #{number_of_deaths} people in this outbreak"
end
#Increments by population density, with speed starting at 0
def speed_of_spread(population_density, state) #in months
# We are still perfecting our formula here. The speed is also affected
# by additional factors we haven't added into this functionality.
speed = 0.0
if @population_density >= 200
counter_a = 200
speed += 2.0
while @population_density < 200
speed -= 0.5
counter_a -= 50
end
# elsif @population_density >= 150
# speed += 1
# elsif @population_density >= 100
# speed += 1.5
# elsif @population_density >= 50
# speed += 2
else
speed += 2.5
end
puts " and will spread across the state in #{speed} months.\n\n"
end
end
#=======================================================================
# DRIVER CODE
# initialize VirusPredictor for each state
# alabama = VirusPredictor.new("Alabama", STATE_DATA["Alabama"][:population_density], STATE_DATA["Alabama"][:population])
# alabama.virus_effects
# jersey = VirusPredictor.new("New Jersey", STATE_DATA["New Jersey"][:population_density], STATE_DATA["New Jersey"][:population])
# jersey.virus_effects
# california = VirusPredictor.new("California", STATE_DATA["California"][:population_density], STATE_DATA["California"][:population])
# california.virus_effects
# alaska = VirusPredictor.new("Alaska", STATE_DATA["Alaska"][:population_density], STATE_DATA["Alaska"][:population])
# alaska.virus_effects
STATE_DATA.each do |state, value|
VirusPredictor.new(state, value[:population_density], value[:population]).virus_effects
end
#=======================================================================
# Reflection Section
# What are the differences between the two different hash syntaxes shown in the state_data file?
# -They have a different scope, STATE_DATA is a constant so it can't be overwritten and is visible everywhere.
# What does require_relative do? How is it different from require?
# -Links this page to another file to pull information from it, require_relative is special because instead
# of requiring a file path to the linked file it looks for it in the same directory. This is especially handy
# for forked or shared files where the coders have different file paths.
# What are some ways to iterate through a hash?
# - you can use a conditional loop like while or you can use each do.
# When refactoring virus_effects, what stood out to you about the variables, if anything?
# nothing stood out, uh-oh.
# What concept did you most solidify in this challenge?
# This challenge helped to solidify working with hashes, classes, and iterating. |
class CommandLineInterface
attr_accessor :user
PROMPT = TTY::Prompt.new
##############################################################################
##### HELPER METHODS #########################################################
##############################################################################
# create new CLI instance and call #welcome on this new run
def self.runner
new_run = self.new
new_run.welcome
end
# clear the terminal screen
def clear
puts `clear`
end
# blank screen & terminate program
def logout
self.clear
exit
end
# convert an array into a human-readable numbered list format
def list_array(arr)
arr.each_with_index do |item, index|
puts "#{index + 1}. #{item.name}"
end
end
###############################################################################
##### SESSION METHODS #########################################################
###############################################################################
########## LANDING PAGE ###############################
# start the program
# landing page with login options
# called by CLI.runner, in turn called by bin/run.rb
def welcome
# clear the screen and show logo, login option
self.clear
a = Artii::Base.new :font => 'doh'
puts a.asciify('FriendUp')
puts
# login options
PROMPT.select("Are you a new or returning user?") do |menu|
menu.choice "New User", -> {self.create_new_user}
menu.choice "Returning User\n", -> {self.login_page}
menu.choice "[] QUIT", -> {self.logout}
end
end
########## NEW USER ###############################
# new screen draw for creating new user name
def create_new_user
self.clear
input = PROMPT.ask("Please enter a desired user name: ")
if input.downcase == 'back'
self.welcome
elsif input.downcase == 'exit'
self.logout
elsif !(input =~ /\A[a-z\d][a-z\d_]*[a-z\d]\z/i)
# validate username
puts "Usernames can only have characters, numbers, or underscores."
sleep 0.7
self.create_new_user
elsif User.find_by(user_name: input)
# check if username is taken
puts "That user name already exists."
sleep 0.7
self.create_new_user
else
self.build_profile(input)
end
end
# if username is valid, create profile
def build_profile(username)
@user = User.new(user_name: username)
self.set_name
# call helper method to choose location from list of valid option
self.choose_location
# call helper method to add interests to this user
self.choose_interests
end
# assign name attribute with input
def set_name
self.clear
input = PROMPT.ask("Please enter your full name: ")
# validate user name only has single spaces and valid characters
if (input == input.split.join(" ") && !(input =~ /[^a-z\s'.-]/i))
self.user.name = input
else
puts "Please enter a valid name"
sleep 1
self.set_name
end
end
# provide list of valid locations to set location attribute
def choose_location
self.clear
# if user has location, put it in an array so only new locations are shown
locations = [
"Washington D.C.",
"New York City",
"Chicago",
"Los Angeles"
]
# subtract arrays to remove user location
current_location = []
current_location << self.user.location
locations = (locations - current_location)
# tack special options to end of menu
locations << ["[] BACK", "[] LOGOUT"]
input = PROMPT.select("Please choose your location", locations)
# check for special options, otherwise set location
if input == "[] BACK"
self.display_user_profile
elsif input == "[] LOGOUT"
self.logout
else
self.user.location = input
end
end
# let user add interests
def choose_interests
self.clear
# list all available interests the user hasn't added to their profile
possible_interests = (Interest.all - self.user.interests).map do |interest|
interest.name
end
if possible_interests == []
# check if user has already selected all interests
self.clear
puts "There are no additional interests to select. Returning you to your profile."
sleep 1
self.display_user_profile
else
# let user select multiple interests to add to their profile
selected_interests = PROMPT.multi_select("Please select one or more interests to add to your profile\n Press 'SPACE' to add and 'ENTER' to finish\n", possible_interests, echo:false, per_page:20)
# associate all chosen interests to user
selected_interests.each do |interest_name|
self.user.add_interest(Interest.find_by(name: interest_name))
end
self.user.save
self.display_user_profile
end
end
########## RETURNING USER ###############################
# handle returning users
def login_page
self.clear
input = PROMPT.ask("Welcome back, please enter your username: ")
if input.downcase == "back"
self.welcome
elsif input.downcase == 'exit'
self.logout
elsif User.find_by(user_name: input)
# valid input
@user = User.find_by(user_name: input)
self.display_user_profile
else
# if username not found, let them try again or go to new user creation
PROMPT.select("That username does not exist") do |menu|
menu.choice "Try Again", -> {self.login_page}
menu.choice "Create New User", -> {self.create_new_user}
end
end
end
########## MAIN PROFILE PAGE ###############################
# landing page for user profile
def display_user_profile
self.clear
# profile information
puts "username: #{self.user.user_name}"
puts
puts "Name: #{self.user.name}"
puts "Location: #{self.user.location}"
puts "Interests:"
self.list_array(self.user.interests)
puts
# menu options
PROMPT.select ("") do |menu|
menu.choice "View Events", -> {self.find_events}
menu.choice "View your RSVPs", -> {self.show_rsvps}
menu.choice "Edit Profile\n", -> {self.profile_edit}
menu.choice "[] LOGOUT", -> {self.logout}
end
end
########## EDITING PROFILE ###############################
# let user choose various profile information to edit
def profile_edit
self.clear
PROMPT.select("Choose your profile information to edit:") do |menu|
menu.choice "Name", -> {self.set_name}
menu.choice "Location", -> {self.choose_location}
menu.choice "Interests\n", -> {self.add_or_remove_interests}
menu.choice "[] BACK", -> {self.display_user_profile}
menu.choice "[] LOGOUT", -> {self.logout}
end
# destination methods would terminate program, so:
# save user and reload page once any edits are made
self.user.save
self.profile_edit
end
# forked choice for user
def add_or_remove_interests
self.clear
PROMPT.select("") do |menu|
menu.choice "Add new interests", -> {self.choose_interests}
menu.choice "Remove current interests\n", -> {self.remove_interests}
menu.choice "[] BACK", -> {self.profile_edit}
menu.choice "[] LOGOUT", -> {self.logout}
end
end
# user can remove interests they've added to profile
def remove_interests
self.clear
# make sure interests are there to be removed
if self.user.interests == []
puts "Please add some interests before you try to remove any."
sleep 1.5
self.add_or_remove_interests
else
current_interests = self.user.interests.map do |interest|
interest.name
end
# let user select multiple interests to remove
selected_interests = PROMPT.multi_select("Please select one or more interests you wish to remove from your profile\n Press 'SPACE' to select and 'ENTER' to finish\n", current_interests, echo:false, per_page:20)
# disassociate user from events
selected_interests.each do |interest_name|
self.user.remove_interest(Interest.find_by(name: interest_name))
end
# save user and return to option screen
self.user.save
self.add_or_remove_interests
end
end
########## FIND EVENTS ################
# show user a list of events in their area matching their interests
def find_events
self.clear
matched_events = self.user.matching_events
if self.user.location == nil
# make sure location is set
puts "Please set your location to see events in your area."
sleep 1.5
self.display_user_profile
elsif self.user.interests == []
# make sure interests are set
puts "Please choose some interests so we can show you matching events."
sleep 1.5
self.display_user_profile
elsif matched_events == []
# just in case there are no matching events
puts "No events found in your location matching your interests."
sleep 1.5
self.display_user_profile
else
# populate list of matching events
# define code to run for each event if selected
# tack navigation options onto bottom of list
choices = {}
matched_events.each do |event|
choices[event.name] = "self.display_event_details('#{event.name}', 'self.find_events')"
end
choices["[] BACK"] = 'self.display_user_profile'
choices["[] LOGOUT"] = 'self.logout'
# user selection returns as method call in string format; execute that call
eval(PROMPT.select("Choose an event to see more details:", choices, per_page:45))
end
end
# a more detailed view for a given event
def display_event_details(eventname, backpage)
self.clear
event = Event.find_by(name: eventname)
puts "Event Name: #{event.name}"
puts "Event Description: #{event.description}"
puts "Location: #{event.location}"
puts "Date/Time: #{event.event_datetime}"
puts "Attendees:"
self.list_array(event.users)
puts
# let user add or remove RSVP for event
PROMPT.select("") do |menu|
if self.user.events.include?(event)
menu.choice "Remove your RSVP for this event\n", -> {self.user.remove_event(event)}
else
menu.choice "RSVP for this event\n", -> {self.user.rsvp_to(event)}
end
menu.choice "[] BACK", -> {eval(backpage)}
menu.choice "[] LOGOUT", -> {self.logout}
end
# update object models and refresh this page on any RSVP change
self.user.save
self.user.reload
self.display_event_details(eventname, backpage)
end
# user can view events they've rsvp'd to
def show_rsvps
self.clear
user_events = (self.user.events)
if user_events == []
# make sure there are events to view
puts "You have no events! You should try adding some."
sleep 1.5
self.display_user_profile
else
# populate list of RSVP'd events
# define code to run for each event if selected
# navigation options on bottom of list
choices = {}
user_events.each do |event|
choices[event.name] = "self.display_event_details('#{event.name}', 'self.show_rsvps')"
end
choices["[] BACK"] = 'self.display_user_profile'
choices["[] LOGOUT"] = 'self.logout'
# selection returns method call as string; execute that call
eval(PROMPT.select("Choose an event to see more details", choices, per_page:45))
end
end
end |
module MachineContextInputMethods
def initialize( machine )
self[:machine] = machine
self[:conds] = []
end
def input
# self[:input] = eval_input( self[:input] ) || []
# feature:nodup - теперь надо в отдельный ключ сохранять, ибо иначе постоянное дублирование - плохо
# однако мы теперь [:input] оставляем нетронутым - тоже нюанс..
# self[:input_processed] ||= eval_input( self[:input] ) || []
# чето меня смущает это - вдруг потом будут этим ctx[:input] пользоваться и пойдет двойной рассчет
if !self[:input_processed_flag]
self[:input] = eval_input( self[:input] ) || []
self[:input_processed_flag]=1
end
self[:input]
end
def eval_input(rec)
if rec.is_a?(Proc)
rec.call
else
if rec.respond_to?(:dup) && !rec.nil? # feature:nodup
rec.dup
else
rec
end
end
end
# feature:nodup это фишка если input указывает на корневые данные - то их надо продублировать, ибо потом иначе rappend их портит
def r
self[:result]
end
def r=(value)
self[:result] = value
end
def stop=(value)
self[:stop] = value
end
def stop2=(value)
self[:stop2] = value
end
def rappend=(value)
if !self[:result].is_a?(Array)
self[:result] = [ self[:result] ]
end
self[:result].push( value )
end
# idea rappend, rprepend?
# короткие штуки
def machine
self[:machine]
end
def obj
self[:request]
end
end
module DasMachineContext
def initialize()
@context_stack = [ MachineContext.new(self) ] # 1 штучка пусть там живет как минимум
super
end
def compute( request, data, comment )
return compute_in_context( request ) if data.is_a?(MachineContext)
#raise "uuu" if data.is_a?(Hash)
ctx = MachineContext.new( self )
ctx[:input] = data
ctx[:parent] = @context_stack.last
@context_stack.push ctx
r = compute_in_context( request )
r = after_compute( r ) # эх, вот явное.. но нам это надо, чтобы сюда дефолт-метод воткнуть
@context_stack.pop
r
end
def after_compute(r)
r
end
def ctx
@context_stack.last
end
# фича state, пока сюда запихаем..
# смысл в том, что нам надо иметь некие знания..
def state
@state ||= {}
end
# но вообще надо уже уметь делать лукап в контекстах..
end
CombiningMachine. prepend DasMachineContext
MachineContext.prepend MachineContextInputMethods |
require "application_system_test_case"
class UsersConversationsTest < ApplicationSystemTestCase
setup do
@users_conversation = users_conversations(:one)
end
test "visiting the index" do
visit users_conversations_url
assert_selector "h1", text: "Users Conversations"
end
test "creating a Users conversation" do
visit users_conversations_url
click_on "New Users Conversation"
fill_in "Conversation", with: @users_conversation.conversation_id
fill_in "User", with: @users_conversation.user_id
click_on "Create Users conversation"
assert_text "Users conversation was successfully created"
click_on "Back"
end
test "updating a Users conversation" do
visit users_conversations_url
click_on "Edit", match: :first
fill_in "Conversation", with: @users_conversation.conversation_id
fill_in "User", with: @users_conversation.user_id
click_on "Update Users conversation"
assert_text "Users conversation was successfully updated"
click_on "Back"
end
test "destroying a Users conversation" do
visit users_conversations_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Users conversation was successfully destroyed"
end
end
|
require './heroes/powers'
class Storm
include Powers
attr_accessor :undercover
def initialize
@undercover = true
@secret_identity = "Ororo Munroe"
@description = "Storm"
end
def weak_to?(element)
case element
when :psychic_powers
false
when :krytonite
false
when :lightning
false
when :pasta
true
end
end
def possesions
[:x_men_uniform, :justice_league_membership_card]
end
end
|
class EventsController < ApplicationController
before_action :authenticate_user!, only:[:new, :edit, :manage]
def new
@event = Event.new
end
def create
@event = current_user.events.new(event_params)
if @event.save
redirect_to root_path, success:'イベント作成に成功しました'
else
flash.now[:danger] = 'イベント作成に失敗しました'
render :new
end
end
def index
@events = Event.all.order(:start_date, :start_time)
end
def show
@event = Event.find_by(id: params[:id])
@comment = Comment.new
end
def manage
@events = Event.where(user_id: current_user)
end
def edit
@event = Event.find_by(id: params[:id])
@user = @event.user
end
def update
@event = Event.find_by(id: params[:id])
if @event.update(event_params)
redirect_to events_manage_path
else
render :edit
end
end
def destroy
@event = Event.find_by(id: params[:id])
@event.destroy
redirect_to events_manage_path
end
private
def event_params
params.require(:event).permit(
:title, :start_date, :start_time, :end_date, :end_time, :venue, :address, :image, :description, :admission_fee
)
end
end
|
require "OTP"
class SpinlockQueue
class Node
attr_accessor :item, :successor
def initialize(item, successor)
self.item = item
self.successor = successor
end
end
attr_accessor :head, :tail
def initialize
@lock = OTP::Spinlock.new
dummy_node = Node.new(:dummy, nil)
self.head = dummy_node
self.tail = dummy_node
end
def push(item)
new_node = Node.new(item, nil)
@lock.lock
tail.successor = new_node
self.tail = new_node
@lock.unlock
true
end
def size
successor = head.successor
count = 0
while true
break if successor.nil?
current_node = successor
successor = current_node.successor
count += 1
end
count
end
end
|
class PeopleController < ApplicationController
before_action :authenticate_user!
before_action :set_person, only: [:show, :versions, :edit, :update, :destroy]
before_action :set_tmks, only: [:show, :destroy]
after_action :verify_authorized
after_action :set_last_page, only: [:edit, :new]
def index
@query = params[:query]
@order = params[:order]
@have_needs_review = Person.where(needs_review: true).any?
@people = Person.text_search(params[:query], params[:order]).page(params[:page]).per(15)
if params[:filter].present?
if params[:filter] == 'needs_review'
@people = @people.where(needs_review: true)
end
if params[:filter] == 'have_phone_number'
@people = @people.where('phone_numbers.number IS NOT NULL').references(:phone_numbers)
end
end
authorize @people
end
def show
@enrolls = @person.enrolls
# Ações do tipo HTTP PUT (ex: um update via form ao objeto @person)
# que são disparadas direto da página "show" devem retornar a própria página e não
# obedecer valores setados em last_page visto que pode redirecionar a uma página outra
# que não a que já estamos. Ou seja, se disparamos uma ação de "show" precisamos garantir
# que no retorne ela volte a "show"
# Um exemplo deste problema é a ação "Necessita revisão cadastral"
session[:last_page] = nil
end
def new
@person = Person.new
authorize @person
@person.phone_numbers.build
@person.addresses.build
end
def edit
if @person.addresses.empty?
@person.addresses.build
end
if @person.phone_numbers.empty?
@person.phone_numbers.build
end
end
def create
@person = Person.new secure_params
authorize @person
if @person.save
redirect_to person_path(@person)
else
render 'new'
end
end
def update
if @person.update(secure_params)
redirect_to session[:last_page] || person_path(@person)
else
render 'edit'
end
end
def destroy
@enrolls = @person.enrolls
if @person.safely_destroyable?
@person.destroy
redirect_to people_path(page: params[:page], query: params[:query], order: params[:order])
else
flash.now[:alert] = 'Esta pessoa esta relacionada a outros recursos do site portanto não pode ser deletada'
render 'show'
end
end
def versions
sql = "(item_type='Person' AND item_id=#{@person.id})"
sql += " OR (item_type='PhoneNumber' AND person_id=#{@person.id})"
sql += " OR (item_type='Address' AND person_id=#{@person.id})"
@versions = PaperTrail::Version.where(sql).order(created_at: :desc).page(params[:page]).per(10)
authorize @person
end
private
def set_tmks
@tmks = @person.tmks.order(contact_date: :desc)
end
def set_person
@person = Person.find params[:id]
authorize @person
end
def set_last_page
session[:last_page] = request.referrer || (@person.persisted? ? person_path(@person) : people_path)
end
def secure_params
params.require(:person).permit(:name, :email, :gender, :date_of_birth, :occupation, :nationality,
:marketing, :cpf, :rg, :scholarity, :relationship,
:needs_review, :needs_review_reason, :avatar, :avatar_delete,
addresses_attributes: [:id, :label, :line1, :zip, :city, :state,
:country, :_destroy],
phone_numbers_attributes: [:id, :label, :number, :phone_type,
:provider, :_destroy])
end
end
|
require_relative 'menumodule'
class SetTravelNotificationPage
include PageObject
include MenuPanel
include AccountsSubMenu
include ServicesSubMenu
include MyInfoSubMenu
include MessagesAlertsSubMenu
include PaymentsSubMenu
table(:heading, :id => 'tblMain')
button(:settravelnotificationbutton, :id => 'ctlWorkflow_btnView_SetTravelNoteGreen')
text_field(:startdate, :id => 'ctlWorkflow_txtTravelStartDate_TextBox' )
text_field(:enddate, :id => 'ctlWorkflow_txtTravelEndDate_TextBox' )
text_field(:destination, :id => 'ctlWorkflow_repContactPoints_ctl00_txtTravelDest' )
text_area(:message, :id =>'ctlWorkflow_txtMessage_txtContent')
checkbox(:iagree, :id =>'ctlWorkflow_Add_chkAgree')
button(:settravelnotificationbutton2, :id => 'ctlWorkflow_btnAdd_Next')
radio_button(:allcardholderstravelling, :id => 'ctlWorkflow_rdoCardHoldersTravelingYes')
div(:confirmmessage, :id =>'pnlMsgConfirmation')
def get_object(object)
self.send "#{object.downcase.gsub(' ','')}_element"
end
end |
require 'spec_helper'
module TextToNoise
describe Router do
it "reloads its configuration if it has changed"
describe ".parse" do
let( :mapping ) { double( NoiseMapping, :to => nil ) }
context "given a nil configuration" do
it "raises an ArgumentError" do
lambda {
Router.parse nil
}.should raise_error( ArgumentError )
end
end
context "given a blank configuration" do
it "raises an ArgumentError" do
lambda {
Router.parse " \t \n"
}.should raise_error( ArgumentError )
end
end
context "given a single line configuration" do
let( :config ) { "match( /brown/ ).to \"blue\"" }
it "creates a Mapping object for the given configuration line" do
NoiseMapping.should_receive( :new ).with( /brown/ ).and_return mapping
Router.parse config
end
it "configures the mapping" do
NoiseMapping.stub!( :new ).with( /brown/ ).and_return mapping
mapping.should_receive( :to ).with( "blue" )
Router.parse config
end
end
context "given a multiple line configuration" do
let( :config ) { 'match( /brown/ ).to "blue"; map( /green/ ).to "orange"' }
before { NoiseMapping.stub!( :new ).and_return mapping }
it "configures the second mapping in addition to the first" do
mapping.should_receive( :to ).with "blue"
mapping.should_receive( :to ).with "orange"
Router.parse config
end
it "stores the mappings" do
Router.parse( config ).should have( 2 ).mappings
end
end
context "given a hash-style configuration" do
let( :config ) { "match /brown/ => \"blue\"\n" }
it "configures the mapping" do
NoiseMapping.should_receive( :new ).with( /brown/ => "blue" ).and_return mapping
Router.parse config
end
end
end
describe "#sound_path" do
subject { described_class.new }
before { TextToNoise.player = double( TextToNoise::Player ) }
it "adds the argument to the player's sound paths" do
paths = []
TextToNoise.player.should_receive( :sound_dirs ).and_return paths
subject.sound_path "foo"
end
end
describe "#dispatch" do
let( :blue ) { /blue/ }
let( :green ) { /green/ }
let( :blue2 ) { /blu/ }
subject { Router.new.tap { |m| m.mappings = [blue, green, blue2] } }
it "iterates over its mappings comparing them to the input with #===" do
blue.should_receive( :=== ).with( anything )
green.should_receive( :=== ).with( anything )
subject.dispatch "orange"
end
it "calls #call on all mappings that matched" do
blue.should_receive :call
blue2.should_receive :call
green.should_not_receive :call
subject.dispatch( "blue" )
end
end
end
end
|
module ApplicationHelper
class HTMLwithPygments < Redcarpet::Render::HTML
def block_code(code, language)
Pygments.highlight(code, :lexer => language)
end
end
def markdown(text)
markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML.new(
:hard_wrap => true, :filter_html => true, :safe_links_only => true),
:no_intraemphasis => true, :fenced_code_blocks => true, :autolink => true)
return markdown.render(text).html_safe
end
end |
# frozen_string_literal: true
# == Schema Information
#
# Table name: lessons
#
# id :integer not null, primary key
# date :date not null
# deleted_at :datetime
# uid :uuid not null
# created_at :datetime not null
# updated_at :datetime not null
# group_id :integer not null
# subject_id :integer not null
#
# Indexes
#
# index_lessons_on_group_id (group_id)
# index_lessons_on_group_id_and_subject_id_and_date (group_id,subject_id,date) UNIQUE WHERE (deleted_at IS NULL)
# index_lessons_on_subject_id (subject_id)
# index_lessons_on_uid (uid) UNIQUE
# lesson_uuid_unique (uid) UNIQUE
#
# Foreign Keys
#
# lessons_group_id_fk (group_id => groups.id)
# lessons_subject_id_fk (subject_id => subjects.id)
#
FactoryBot.define do
factory :lesson do
sequence(:date) { |n| n.days.ago }
group { create :group }
subject { create :subject_with_skills }
transient do
student_grades { {} }
end
factory :lesson_with_grades do
after :create do |lesson, evaluator|
evaluator.student_grades.each do |student_id, skill_marks|
skill_marks.each do |skill_name, mark|
next unless mark
skill = Skill.find_by skill_name: skill_name
gd = GradeDescriptor.find_by skill: skill, mark: mark
create :grade, student_id: student_id, grade_descriptor: gd, lesson: lesson
end
end
end
end
end
end
|
class PasswordController < ApplicationController
def forgot
if params[:email].blank?
return render json: {error: 'Operação inválida'}, status: :404
end
user = User.find_by(email: params[:email])
if user.present?
user.save if user.generate_password_token
PasswordMailer.with(user: user, url: request.base_url).forgot.deliver_now
render json: {status: 'ok'}, status: 200
else
render json: {error: 'Email não encontrado. Por favor, faça um cadastro.'}, status: :404
end
end
def reset
token = params[:token]
if params[:token].blank?
return render json: {error: 'Operação invalida'}
end
user = User.find_by(validation_token: token)
if user.present? && user.is_token_valid?
if user.reset_password!(params[:password], params[:password_confirmation])
PasswordMailer.with(user: user).reset.deliver_now
render json: {status: 'ok'}, status: :ok
else
render json: {error: "Nao foi possivel trocar de senha, tente novamente mais tarde"}, status: :unprocessable_entity
end
else
render json: {error: 'Link não é valido ou expirou. Tente novamento com um novo link.'}, status: :404
end
end
end
|
class RemoveApiurlFromReferenceSource < ActiveRecord::Migration
def up
remove_column :reference_sources, :apiurl
end
def down
add_column :reference_sources, :apiurl, :string
end
end
|
require_relative "../lib/eventhub/base"
module EventHub
class Receiver < Processor2
def handle_message(message, args = {})
id = message.body["id"]
EventHub.logger.info("[#{id}] - Received")
file_name = "data/#{id}.json"
begin
File.delete(file_name)
EventHub.logger.info("[#{id}] - File has been deleted")
rescue => error
EventHub.logger.error("[#{id}] - Unable to delete File: #{error}")
end
nil
end
end
end
EventHub::Receiver.new.start
|
module Ricer::Plug::Params
class IntegerParam < Base
INT_MIN ||= -2123123123
INT_MAX ||= 2123123123
def default_options
{ min: INT_MIN, max: INT_MAX }
end
def min
(options[:min].to_i rescue INT_MIN) or INT_MIN
end
def max
(options[:max].to_i rescue INT_MAX) or INT_MAX
end
def convert_in!(input, message)
fail_type unless input.integer?
input = input.to_i
min, max = self.min, self.max
fail_int_between(min, max) unless input.between?(min, max)
input
end
def fail_int_between(min, max)
fail(:err_between, min: min, max: max)
end
def convert_out!(value, message)
value.to_s
end
end
end
|
class AddNumRetweetsToDataSet < ActiveRecord::Migration[5.2]
def change
add_column :data_sets, :num_retweets, :integer
end
end
|
class AddUpdatedByIdToTradeRestrictionTerms < ActiveRecord::Migration
def change
add_column :trade_restriction_terms, :updated_by_id, :integer
end
end
|
module V1
class Base < ApplicationAPI
version "v1", using: :path
helpers do
def success_response(message)
{
status: true,
message: message
}
end
def failure_response(message)
{
status: false,
message: message
}
end
def set_current_user(device_id)
@current_user ||= User.find_by(device_id: device_id)
end
def authorize!
if !@current_user
error!(failure_response("User not authorized"))
end
end
end
mount UserAPI
end
end |
require 'rails_helper'
RSpec.describe Trip do
it { should belong_to(:passenger) }
it { should belong_to(:flight) }
end
|
#shared the scope between all of the methods
lambda{
TABLE_X = 5
TABLE_Y = 5
STEP = 1
#4 directions used now
DIRECTIONS = ["NORTH", "EAST", "SOUTH", "WEST"]
NORTH, EAST, SOUTH, WEST = DIRECTIONS
RIGHT, LEFT, MOVE, PLACE = ["right", "left", "move", "place"]
is_robot_availabe = false
pos_x = 0
pos_y = 0
direction = nil
define_method :place do |*args|
is_robot_availabe = true
pos_x,pos_y,direction = args
direction = direction.to_s
# p direction
direction.chomp!#.strip!.upcase!
if not (0..TABLE_X).include?(pos_x) or not (0..TABLE_Y).include?(pos_y)
puts "Warning: The position of Robot at (#{pos_x}, #{pos_y}) is outside the table (5,5)."
is_robot_availabe = false
return
end
if not DIRECTIONS.include?(direction)
puts "Warning: #{direction} is invaid. Robot can only move towards the four directions: \n"\
"#{DIRECTIONS.inspect}."
is_robot_availabe = false
return
end
end
#place will put the toy robot on the table in position X,Y and facing one specific direction
define_method :left do
return if !is_robot_availabe
direction = DIRECTIONS[DIRECTIONS.index(direction) - 1]
end
define_method :right do
return if !is_robot_availabe
direction = DIRECTIONS[(DIRECTIONS.index(direction) + 1) % 4]
end
define_method :move do
return if !is_robot_availabe
case direction
when "NORTH"
if pos_y + STEP <= TABLE_Y
pos_y += STEP
return
end
when "EAST"
if pos_x + STEP <= TABLE_X
pos_x += STEP
return
end
when "SOUTH"
if pos_y - STEP >= 0
pos_y -= STEP
return
end
when "WEST"
if pos_x - STEP >= 0
pos_x -= STEP
return
end
end
puts "Warning: Robot cannot move towards #{direction} anymore. "
# return "MOVE" #for test
end
define_method :report do
return if !is_robot_availabe
puts "Report: The current location of Robot is #{pos_x}, #{pos_y} and facing towards #{direction}"
end
alias :PLACE :place
alias :LEFT :left
alias :RIGHT :right
alias :MOVE :move
define_method :east do
"EAST"
end
# end
}.call
# Dir.glob('input.rb') do |file|
# load file, true #will create a anonymous module for constants
# end
# if input.rb and File.exist? input.rb
# load input.rb, true
# end
#use eval:
eval(File.read('input.txt'))
# File.readlines("input.txt").each do |line|
# puts %Q{
# #{line.chomp} ==> #{eval(line)}
# }
# end
# env = Object.new
# File.open("input.txt", "r") do |file|
# while line = file.gets
# case line
# #format like: PLACE 1,2,EAST
# when /\A\s*PLACE\s*(\d+)\s*\,\s*(\d+)\s*\,\s*(\w+)\s*/i
# env.send "place", $1.to_i,$2.to_i,$3.upcase
#
# when /\A\s*(LEFT|RIGHT|MOVE|REPORT)\s*$/i
# env.send line.chomp.strip.downcase
# end
# end
# end
#
#
# rescue => e
# puts e.message
# puts "Error: Reading Input file failed, please add the input file. "
# end |
class AddColumnToTutor2 < ActiveRecord::Migration
def change
add_column :tutors, :welcome_message, :string
end
end
|
# Practice for how polymorphism works in Ruby
class Bird
def tweet(bird_type)
bird_type.tweet # calling its version of tweet here
end
end
class Cardinal < Bird #inherit from bird
def tweet
puts "Tweet"
end
end
class Parrot < Bird
def tweet
puts "Squawk"
end
end
generic_bird = Bird.new
# Below we see polymorphism
generic_bird.tweet(Cardinal.new)
generic_bird.tweet(Parrot.new)
|
class AddCurrentJobToUser < ActiveRecord::Migration[6.0]
def change
add_column :users, :current_job, :string
end
end
|
#Public: Takes an integer and muliplies it with itself and returning the result.
#
# number - The integer that will be multiplied with itself
#
# Examples
#
# square(5)
# # => 25
#
# Returns the squared integer
def square(number)
return number * number
end
|
require 'test_helper'
require "helpers/file_data"
class DiscrepancyCsvParserTest < ActiveSupport::TestCase
include FileData::CSV
test "converts csv into discrepancy data models" do
model = DiscrepancyCsvParser.parse(csv_data).first
assert model.is_a?(DiscrepancyData)
assert model.valid?
end
end
|
require 'state_machine'
class Notification
include Mongoid::Document
include Mongoid::Timestamps::Created
field :verb, type:String
field :count, type:Integer, default:0
# Relationships
belongs_to :receiver, :class_name => 'User', :inverse_of => :notifications_received
belongs_to :sender, :class_name => 'User', :inverse_of => :notifications_sent
belongs_to :notifiable, :polymorphic => true
scope :unread, where(has_been_read:"unread")
#validations
validates_presence_of :verb, :receiver, :notifiable
#state machine has been read message?
state_machine :has_been_read, :initial => :unread do
event :read_message do
transition :from => :unread, :to => :read
end
event :mark_unread do
transition :from => :read, :to => :unread
end
end
def notifiabled_obj
notifiable_type.constantize.find(notifiable_id)
end
end |
class VendingMachine
MONEY = [10, 50, 100, 500, 1000].freeze
def initialize(drink)
@insert_money = 0
@sales_amount = 0
@drinks = drink
end
def insert_money(money)
if MONEY.include?(money)
@insert_money += money
puts "現在の投入金額は#{@insert_money}円です。"
else
puts "このお金は使えません。"
end
end
def inset_money_info
puts "現在の投入金額は#{@insert_money}円です。"
end
def refund_money
puts "投入金額#{@insert_money}円を払い戻しいたします。"
puts "また来てね"
@insert_money = 0
end
def purchase
while true
puts "現在、購入できるのは以下の通りです。"
@drinks.drink.each_with_index do |drink, idx|
puts "No.#{idx+1} 名前:#{drink[:name]} 値段:#{drink[:price]} 在庫:#{drink[:stock]}本"
end
puts "どれを購入しますか?"
n = gets.to_i
if @insert_money >= @drinks.drink[n-1][:price] && @drinks.drink[n-1][:stock] > 0
puts "ガラン"
sleep(1)
puts "ゴロン"
sleep(1)
puts "ガラン!!!"
sleep(1)
puts "勇者は'#{@drinks.drink[n-1][:price]}円'と引き換えに'#{@drinks.drink[n-1][:name]}'を手にいれた!"
@drinks.drink[n-1][:stock] -= 1
@insert_money -= @drinks.drink[n-1][:price]
@sales_amount += @drinks.drink[n-1][:price]
puts "まだ買いますか?"
puts "Yse!(1) or No(2)"
n = gets.to_i
if n == 2
refund_money
break
else
true
end
elsif @insert_money < @drinks.drink[n-1][:price]
puts "投入金額が足りません。お金を入れてください。"
else
puts "Sold Out"
end
end
end
def sales_amount_info
puts "現在の総売り上げは#{@sales_amount}円です。"
end
end
class Drink
attr_reader :drink
def initialize
@drink = [{name: "コーラ", price: 120, stock: 5}]
end
def add(name, price)
@drink.push({name: name, price: price, stock: 5})
end
def info
@drink.each_with_index do |drink, idx|
puts "No.#{idx+1} 名前:#{drink[:name]} 値段:#{drink[:price]} 在庫:#{drink[:stock]}本"
end
end
end
# require './vend.rb'
# vm = VendingMachine.new(drink)
# drink = Drink.new
# drink.add("水", 100)
# drink.add("レッドブル", 200)
# drink.info
# 1000円投入する
# vm.insert_money (1000)
# 投入金額の確認
# vm.inset_money_info
# 売上金額の確認
# vm.sales_amount_info
# 投入金額の払い戻し
# vm.refund_money
# ドリンク購入
# vm.purchase
|
require "spec_helper"
feature "Job title assignments" do
scenario "Adding a new one" do
department = create(:department)
job_title = create(:job_title)
user = create(:user)
expect(user.job_title_assignments.count).to eq 0
visit edit_user_path(user, as: user)
select department.name, from: "Department"
select job_title.name, from: "Job title"
fill_in "Starts on", with: "1979-01-10"
fill_in "Ends on", with: "2009-12-14"
click_on "Update User"
expect(user.job_title_assignments.count).to eq 1
jta = user.job_title_assignments.first
expect(jta.department).to eq department
expect(jta.job_title).to eq job_title
expect(jta.starts_on).to eq Date.parse("1979-01-10")
expect(jta.ends_on).to eq Date.parse("2009-12-14")
end
scenario "Deleting", js: true do
user = create(:user)
create(:job_title_assignment, user: user)
expect(user.job_title_assignments.count).to eq 1
visit edit_user_path(user, as: user)
first(:link, "destroy").click
click_button "Update User"
expect(page).to have_selector "#flash_success", text: "User profile updated"
expect(user.job_title_assignments.count).to eq 0
end
scenario "Updating successfully" do
user = create(:user)
jta = create(:job_title_assignment, user: user)
new_department = create(:department)
visit edit_user_path(user, as: user)
select new_department.name, from: "user_job_title_assignments_attributes_0_department_id"
click_button "Update User"
expect(page).to have_selector "#flash_success", text: "User profile updated"
expect(jta.reload.department).to eq new_department
end
scenario "Updating with an overlapping date range" do
user = create(:user)
create(:job_title_assignment, user: user, starts_on: "2000-01-01", ends_on: "2000-12-31")
create(:job_title_assignment, user: user, starts_on: "2001-01-01", ends_on: "2001-12-31")
visit edit_user_path(user, as: user)
fill_in "user_job_title_assignments_attributes_0_starts_on", with: "2001-01-02"
fill_in "user_job_title_assignments_attributes_0_ends_on", with: "2002-01-01"
click_button "Update User"
expect(page).to have_selector "#flash_error", text: "User job title assignments have overlapping dates"
end
end
|
# == Schema Information
#
# Table name: responses
#
# id :bigint not null, primary key
# answer_choice_id :integer not null
# responder_id :integer not null
# created_at :datetime not null
# updated_at :datetime not null
#
class Response < ApplicationRecord
validates :responder_hasnt_answered
belongs_to :answer_choice,
primary_key: :id,
foreign_key: :answer_choice_id
belongs_to :respondent,
class_name: 'User',
primary_key: :id,
foreign_key: :responder_id
has_one :question,
through: :answer_choice,
source: :question
#def sibling_responses
# self.question.responses.where.not(id: self.id)
#end
def sibling_responses
ac = {answer_choice_id: self.answer_choice_id, id: self.id}
Response.find_by_sql([<<-SQL, ac])
SELECT
respones.*
FROM (
SELECT
questions.*
FROM
questions
JOIN answer_choices ON answer_choices.question_id = questions.id
WHERE
answer_choices.id = :answer_choice_id
) AS quest
JOIN
answer_choices ON answer_choices.question_id = questions.id
JOIN
responses ON responses.answer_choice_id = answer_choices.id
WHERE
(responses.id != :id)
SQL
end
def respondent_already_answered?
sibling_responses.exists?(responder_id: self.responder_id)
end
def poll_author_isnt_respondent
poll_author = self.answer_choice.question.poll.author_id
if poll_author == self.responder_id
errors[:responder_id] << 'responder cant be poll author'
end
end
private
def responder_hasnt_answered
if respondent_already_answered?
errors[:responder_id] << 'respondent already answered'
end
end
end
|
# write the migration code to create
# a shows table. The table should
# have name, network, day, and
# rating columns. name, network,
# and day have a datatype of string,
# and rating has a datatype of
# integer.
class CreateShows < ActiveRecord::Migration
def change
create_table :shows do |t|
t.string :name
t.string :network
t.string :day
t.integer :rating
end
end
end
|
require 'active_support/core_ext/numeric/time'
require 'deliveryboy/rails/active_record'
require 'deliveryboy/loggable'
require 'deliveryboy/plugins'
require 'email_address'
require 'email_history'
class Deliveryboy::Plugins::History
include Deliveryboy::Plugins # Deliveryboy::Maildir needs this to load plugins properly
include Deliveryboy::Loggable # to use "logger"
include Deliveryboy::Rails::ActiveRecord # establish connection
def initialize(config)
@config = config.reverse_merge({
:hard_bounce => 1.month,
:soft_bounce => 1.day,
:custom => {},
})
end
def find_or_create_email_addresses(list)
list.collect { |addr| EmailAddress.find_or_create_by_email(EmailAddress.base_email(addr)) }
end
def handle(mail, recipient)
time_now = Time.now
if mail.probably_bounced? && bounce = mail.bounced_message
histories = EmailHistory.where(:message_id => bounce.message_id).includes(:to)
bounce_type = (mail.bounced_hard? ? 'hard' : 'soft')
penalty = @config[:"#{bounce_type}_bounce"]
history_update = {
:bounce_at => time_now,
:bounce_reason => mail.diagnostic_code,
}
to_update = {
:penalized_message_id => mail.message_id,
:allow_to_since => penalty.since(time_now),
:"#{bounce_type}_bounce_at" => time_now,
}
logger.debug "[history] #{bounce_type} bounced (#{histories.collect(&:id).join(',')}) #{bounce.subject}"
EmailHistory.transaction do
histories.each do |history|
history.update_attributes(history_update)
if currently_more_severe = history.to.allow_to_since.to_i >= to_update[:allow_to_since].to_i
logger.debug "[history] SKIP #{bounce_type} bounced penalty #{history.to.email} (convicted)"
elsif custom = @config[:custom].find {|duration,emails| emails.include?(history.to.email) }
duration = custom.first.to_s.to_i
logger.debug "[history] CUSTOM #{bounce_type} bounced penalty (#{duration}) #{history.to.email} (customized)"
history.to.update_attributes(to_update.merge(
:allow_to_since => duration.since(time_now),
))
else
logger.debug "[history] #{bounce_type} bounced penalty #{history.to.email}"
history.to.update_attributes(to_update)
end
end
end
else
histories = []
EmailHistory.transaction do
find_or_create_email_addresses(mail.froms).each do |from_email|
find_or_create_email_addresses([recipient]).each do |to_email|
if to_email.allow_to_since && to_email.allow_to_since.to_i > time_now.to_i
logger.debug "[history] excluding #{to_email.email} until #{to_email.allow_to_since}"
return false
else
histories << EmailHistory.create!({:from => from_email, :to => to_email, :message_id => mail.message_id, :subject => mail.subject})
end
end
end
end
logger.debug "[history] recorded (#{histories.collect(&:id).join(',')}) From:#{mail.froms.join(',')} To:#{mail.destinations.join(',')} Subject:#{mail.subject}"
end
end
end |
class SpreadsheetsController < ApplicationController
def index
@title = "Spreadsheet Manager"
# Push this over to the model
hash = {}
Spreadsheet.gather_thine_spreadsheets.each do |f|
@last = ActiveRecord.const_get(f).last
hash.merge!(f.to_sym => @last)
end
@hash = hash
@current_jobs = Spreadsheet.all
end
def show
if @model = ActiveRecord.const_get(params[:id])
@title = "Spreadsheet | #{params[:id]}"
@column_names = @model.list_columns
@spreadsheet = @model.hashify
else
redirect_to :index, :notice => "This page does not exist"
end
rescue
redirect_to spreadsheets_path, :notice => "This page does not exist"
end
def new
@spreadsheet = Spreadsheet.new
end
def create
@spreadsheet = Spreadsheet.new(params[:spreadsheet])
if @spreadsheet.valid?
@spreadsheet.save
Delayed::Job.enqueue(CsvImportingJob.new(@spreadsheet.id))
redirect_to spreadsheets_path
else
render "new"
end
end
end
|
require 'rails_helper'
describe VideosController, type: :controller do
let(:user) { create(:user) }
let(:video) { create(:video) }
before do
session[:user_id] = user.id
end
describe 'show' do
it 'returns http success' do
get :show, id: video.id
expect(response).to be_success
expect(response).to have_http_status(200)
end
context 'when user have already seen the video' do
it 'creates @views with total views' do
VideoUser.create(video_id: video.id, user_id: user.id, views: 3)
get :show, id: video.id
expect(assigns(:views)).to eq(3)
end
end
context 'when user have not seen the video yet' do
it 'creates @views with 0' do
get :show, id: video.id
expect(assigns(:views)).to eq(0)
end
end
end
describe '#watch' do
it 'calls watch_video' do
expect_any_instance_of(User).to receive(:watch_video).with(video)
get :watch, id: video.id
expect(assigns(:views)).to_not be_nil
end
end
end
|
class Quip < ActiveRecord::Base
belongs_to :user
attr_accessible :image, :jackass_count, :message, :rating, :user_id
has_many :inappropriates
has_many :likes
has_many :feedbacks
validates :message, presence: true
validates_length_of :message, maximum: 141
validates :rating, presence: true
validates :user_id, presence: true
validates :image, presence: true
after_initialize :defaults
end
def defaults
self.image ||= 'none'
self.rating ||= 0
end
|
class LikesController < ApplicationController
def create
@like = Like.new(params[:like])
respond_to do |format|
if @like.save
format.html { redirect_to @like, notice: 'Like was successfully created.' }
format.json { render json: @like, status: :created, location: @like }
else
format.html { render action: "new" }
format.json { render json: @like.errors, status: :unprocessable_entity }
end
end
end
def destroy
@like = Like.find(params[:id])
@like.destroy
respond_to do |format|
format.html { redirect_to likes_url }
format.json { head :no_content }
end
end
end
|
# frozen_string_literal: true
require "rails/source_annotation_extractor"
desc "Enumerate all annotations (use notes:optimize, :fixme, :todo for focus)"
task :notes do
SourceAnnotationExtractor.enumerate "OPTIMIZE|FIXME|TODO", tag: true
end
namespace :notes do
["OPTIMIZE", "FIXME", "TODO"].each do |annotation|
# desc "Enumerate all #{annotation} annotations"
task annotation.downcase.intern do
SourceAnnotationExtractor.enumerate annotation
end
end
desc "Enumerate a custom annotation, specify with ANNOTATION=CUSTOM"
task :custom do
SourceAnnotationExtractor.enumerate ENV["ANNOTATION"]
end
end
|
# == Schema Information
#
# Table name: photos
#
# id :bigint(8) not null, primary key
# title :string not null
# description :string
# owner_id :integer not null
# created_at :datetime not null
# updated_at :datetime not null
#
class Photo < ApplicationRecord
validates :title, :owner_id, presence: true
validate :ensure_photo
belongs_to :user,
primary_key: :id,
foreign_key: :owner_id,
class_name: "User"
has_one_attached :image
has_many :photo_albums,
primary_key: :id,
foreign_key: :photo_id,
class_name: "PhotoAlbum"
has_many :albums,
through: :photo_albums,
source: :album
has_many :comments,
primary_key: :id,
foreign_key: :photo_id,
class_name: "Comment",
dependent: :destroy
has_many :tags,
primary_key: :id,
foreign_key: :photo_id,
class_name: "Tag",
dependent: :destroy
def ensure_photo
unless self.image.attached?
errors[:image] << "has to be attached"
end
end
end
|
class AccountingCategory < ActiveRecord::Base
belongs_to :accounting_category
has_and_belongs_to_many :devices
end
|
#!/usr/bin/env ruby
require 'shellwords'
# Will open all files with jshint errors in vim
class FixJshint
def get_error_list
output = %x[grunt jshint --no-color | grep '^Linting']
return output.split("\n")
end
def get_error_files
get_error_list.map do |line|
matches = line.match(/^Linting (.*) \.\.\.ERROR/)
File.expand_path(matches[1])
end
end
def run
puts "Running Jshint"
files = get_error_files
files.map! do |file|
file.shellescape
end
if files.length == 0
puts "No error found"
return
end
puts "Loading vim with #{files.length} files"
exec("vim -p #{files.join(' ')}")
end
end
FixJshint.new(*ARGV).run();
|
class Comment < ApplicationRecord
belongs_to :user
belongs_to :commentable, polymorphic: true
validates :review, presence: true, allow_blank: false
def comment_user(id)
User.find(id).username
end
def comment_status(status)
if status == 'A'
'Activated'
else
'Disabled'
end
end
end
|
module Jekyll
class Title < Liquid::Tag
def render(context)
site = context.registers[:site]
page = context.registers[:page]
config = site.config
page_title = page['title']
page_tag = page['tag']
title = config['title']
if page_title
title = "#{page_title} | #{title}"
elsif page_tag
title = "Tag: #{page_tag} | #{title}"
end
# Normalize apostrophe
title = title.gsub(/\"/, "\'")
# Special behaviour for `<em>xxx</em> yyy`
title = title.gsub(/\<em\>/, '').gsub(/\<\/em\>/, '')
title
end
end
end
Liquid::Template.register_tag('title', Jekyll::Title)
|
LauncherJournal::Application.routes.draw do
root to: 'entries#index'
resources :entries
resources :categories
end
|
class Budget < ActiveRecord::Base
belongs_to :budgetpost, :foreign_key => 'budget_id'
belongs_to :user, :foreign_key => 'user_id'
#validate :is_value_positive?
def value
if self.isexpense
return -self.dollarAmount
else
return self.dollarAmount
end
end
# DEPRECATED
def is_value_positive?
errors[:base] << "it's meaningless for a budget item's amount to be negative" if dollarAmount < 0
end
end |
# frozen_string_literal: true
require 'rails_helper'
require 'pundit/matchers'
RSpec.describe CompletionPolicy, type: :policy do
subject { described_class.new user, completion }
let(:completion) { Completion.new }
context 'when logged out' do
let(:user) { nil }
it { is_expected.to forbid_action :create }
it { is_expected.to forbid_action :destroy }
it { is_expected.to forbid_action :index }
it { is_expected.to forbid_action :update }
end
context 'when logged in' do
let(:user) { User.new }
it { is_expected.to permit_action :index }
context 'when the User is an admin' do
let(:user) { User.new admin: true }
it { is_expected.to permit_action :create }
it { is_expected.to permit_action :destroy }
it { is_expected.to permit_action :index }
it { is_expected.to permit_action :update }
end
end
end
|
require 'sinatra/base'
require 'mongoid'
require 'digest/sha1'
class Alarm
include Mongoid::Document
INTERVALS = %w( hourly daily monthly ).freeze
KEY_FORMAT = /[0-9a-f]{7}/
field :key, type: String
field :interval, type: String
field :last_call, type: DateTime
field :tag, type: String
field :threshold, type: Integer, default: 1
field :count, type: Integer, default: 0
validates :key, presence: true, uniqueness: true, format: { with: KEY_FORMAT }
validates :interval, presence: true, inclusion: { in: INTERVALS }
def name
tag.present? ? tag : key
end
def self.new_key
begin
key = Digest::SHA1.hexdigest(Time.current.to_s)[0..6]
end while self.where(key: key).exists?
key
end
end
class FalseAlarm < Sinatra::Base
configure do
Mongoid.load!(File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'mongoid.yml')))
end
configure :development do
require 'sinatra/reloader'
register Sinatra::Reloader
end
get '/new/:interval' do |interval|
alarm = Alarm.new(key: Alarm.new_key, interval: interval, tag: params[:tag])
alarm.threshold = params[:threshold] if params[:threshold].present?
alarm.save
status 404 and return alarm.errors.messages.to_json unless alarm.persisted?
alarm.key
end
get '/:key' do |key|
alarm = Alarm.where(key: key).first if key.match Alarm::KEY_FORMAT
alarm.inc(count: 1) if alarm.threshold
return status 404 unless alarm
alarm.last_call = Time.current
raise "failed to persist" unless alarm.save
"OK"
end
end
|
class ContactsController < ApplicationController
before_action :set_contact, only: [:show, :update, :destroy]
# GET /contacts
def index
@contacts = Contact.all
# ADICIONANDO NOVOS CONTATOS (quando tiver uma coleção):
# render json: @contacts.map { |contact| contact.attributes.merge({ author: "Maiqui" }) }
# QUANDO TIVER SÓ UM CONTATO:
# render json: @contacts.attributes.merge({ author: "Maiqui" })
# USANDO O METHODS:
# render json: @contacts, methods: :author
# SEM ROOT:
render json: @contacts
# [{
# "id": 1,
# "name": "Jarrett Upton",
# "email": "milton@kutch.net",
# "birthdate": "1991-09-07",
# "created_at": "2021-07-11T23:21:13.663Z",
# "updated_at": "2021-07-11T23:21:13.663Z",
# "kind_id": 1
# }]
# COM ROOT:
# render json: @contacts, root: true
# [{
# "contact": {
# "id": 1,
# "name": "Jarrett Upton",
# "email": "milton@kutch.net",
# "birthdate": "1991-09-07",
# "created_at": "2021-07-11T23:21:13.663Z",
# "updated_at": "2021-07-11T23:21:13.663Z",
# "kind_id": 1
# }
# }]
end
# GET /contacts/1
def show
render json: @contact
end
# POST /contacts
def create
@contact = Contact.new(contact_params)
if @contact.save
render json: @contact, status: :created, location: @contact
else
render json: @contact.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /contacts/1
def update
if @contact.update(contact_params)
render json: @contact
else
render json: @contact.errors, status: :unprocessable_entity
end
end
# DELETE /contacts/1
def destroy
@contact.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_contact
@contact = Contact.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def contact_params
params.require(:contact).permit(:name, :email, :birthdate, :kind_id)
end
end
|
class RemoveDefaultRailsTimpstampsFromInsOutsClicks < ActiveRecord::Migration[5.2]
def change
remove_column :ins, :created_at
remove_column :ins, :updated_at
remove_column :outs, :created_at
remove_column :outs, :updated_at
remove_column :clicks, :created_at
remove_column :clicks, :updated_at
end
end
|
module Travis::API::V3
class Queries::EnvVar < Query
params :id, :name, :value, :public, prefix: :env_var
def find(repository)
repository.env_vars.find(id)
end
def update(repository)
if env_var = find(repository)
env_var.update(env_var_params)
repository.save!
env_var
end
end
def delete(repository)
repository.env_vars.destroy(id)
end
end
end
|
# frozen_string_literal: true
# == Schema Information
#
# Table name: authors
#
# id :bigint(8) not null, primary key
# description :string
# name :string
# created_at :datetime not null
# updated_at :datetime not null
#
FactoryBot.define do
factory :author do
sequence(:name) {|n| "Name #{n}" }
sequence(:description) {|n| "Description #{n}" }
end
end
|
# frozen_string_literal: true
require 'prawn/core'
require 'prawn/format'
require "prawn/measurement_extensions"
require 'gruff'
require "open-uri"
module Pdf
module Finance
class InvoiceGenerator
include Pdf::Printer
# TODO: remove
include ActionView::Helpers::NumberHelper
include ThreeScale::MoneyHelper
include ::Finance::InvoicesHelper
def initialize(invoice_data)
@data = invoice_data
@coder = HTMLEntities.new
# TODO: accept as parameter
@style = Pdf::Styles::BlackAndWhite.new
@pdf = Prawn::Document.new(page_size: 'A4',
page_layout: :portrait)
@pdf.tags(@style.tags)
@pdf.font(@style.font)
end
# Generates PDF content and wraps it to envelope acceptable by Paperclip
def generate_as_attachment
InvoiceAttachment.new(@data, generate)
end
def generate
print_header
print_address_columns
move_down(5)
print_line_items
move_down(5)
print_line
move_down
print_total
move_down(2)
@pdf.text @data.invoice_footnote
move_down
@pdf.render
end
private
def print_header
two_columns do |column|
case column
when :left
@pdf.image(@data.logo, fit: [200,50], position: :left) if @data.logo?
when :right
print_address(@data.buyer)
end
end
move_down(14)
@pdf.text "Invoice for #{@data.name}", size: 20, align: :center
move_down(14)
subtitle('<b>Details</b>')
print_details
move_down(3)
end
def print_address_columns
# TODO: cleanup the constants
two_columns( [0.mm, @pdf.cursor], height: 50.mm) do |column|
case column
when :left then print_address( @data.provider, 'Issued by')
when :right then print_address( @data.buyer, 'For')
end
end
end
def print_address(person, name = nil)
subtitle("<b>#{name}</b>") if name
@pdf.table(person, @style.table_style.merge(width: TABLE_HALF_WIDTH))
end
def print_details
details = [['Invoice ID', @data.friendly_id],
['Issued on', @data.issued_on],
['Billing period start', @data.period_start],
['Billing period end', @data.period_end],
['Due on', @data.due_on]]
@pdf.table(details, @style.table_style)
end
def print_line_items
subtitle('<b>Line items</b>')
opts = { width: TABLE_FULL_WIDTH, headers: InvoiceReportData::LINE_ITEMS_HEADING }
@pdf.table(@data.line_items, @style.table_style.merge(opts))
move_down
@pdf.text(@data.vat_zero_text) if @data.vat_rate&.zero?
end
def print_total
@pdf.bounding_box([@pdf.bounds.right - 310, @pdf.cursor], width: 310) do
@pdf.text "<b>AMOUNT DUE: #{@coder.decode(rounded_price_tag(@data.cost))}</b>", size: 13, align: :right
end
end
end
end
end
|
# frozen_string_literal: true
class PersonalMessage < ApplicationRecord
belongs_to :conversation
belongs_to :user
has_attached_file :attachment
do_not_validate_attachment_file_type :attachment
validates :body, presence: true
after_create_commit do
conversation.touch
ConversationJob.perform_later(self)
end
end
|
class WelcomeController < ApplicationController
def index
if user_signed_in?
redirect_to lists_path, notice: "You're signed in, here are your lists! :D"
else
redirect_to new_user_session_path, notice: "Please sign in!"
end
end
end
|
# Class: Category
#
# Models our Product objects that live within categories and shelves.
#
# Attributes:
# @name - String: Primary Key related to the shelves table of db.
# @shelf_id - Integer: Denotes what shelf the object belongs to.
# @category_id - Integer: Denotes what category the object belongs to.
# @description - String: Describes the product
# @price - Integer: Price in pennies
# @quantity - Integer: How many of the product are on the shelf
# @id - Integer: Primary Key related to the products table of db.
#
# Public Methods:
# .requirements
class Product
include DatabaseMethods
attr_accessor :name, :quantity, :shelf_id, :category_id,
:description, :price, :quantity, :id
def initialize(options)
@name = options["name"]
@shelf_id = options["shelf_id"]
@category_id = options["category_id"]
@description = options["description"]
@price = options["price"]
@quantity = options["quantity"]
@id = options["id"]
end
# # Public: #list_location_of
# # Prompts database for the shelf name of the product.
# #
# # Returns:
# # String: Name of the shelf the product is on.
# #
# # State Changes:
# # None
#
# def list_location_of
# loc = DATABASE.execute("SELECT name FROM shelves WHERE id = #{@shelf_id}")
# loc[0]["name"]
# end
#
# # Public: #update_location_of
# # Changes the shelf_id to new_loc
# #
# # Paramteres:
# #
# #
# # Returns:
# # String: Name of the shelf the product is on.
# #
# # State Changes:
# # None
#
# def update_location_of(new_loc)
# @shelf_id = new_loc
# save
# end
#
# def assign_new_category(new_category)
# @category_id = new_category
# save
# end
#
# def buy_product(amount)
# @quantity += amount
# save
# end
#
# def sell_product(amount)
# check = quantity
# unless check - amount < 0
# @quantity -= amount
# save
# end
# end
#
# def update_price(amount)
# @price = amount
# save
# end
# Public: .requirements
# Class method that returns the instance methods of a Product item minus @id.
#
# Returns:
# Array
#
# State Changes:
# None
def self.requirements
requirements = ["name", "shelf_id", "category_id", "description", "price", "quantity"]
end
end |
module Abroaders
module Cell
# An alert-info that will be shown at the top of most pages when an
# onboarded account is logged in. It will tell them one of three things
# related to recommendations (or it might not render anything):
#
# 1. You have unresolved recommendations - please visit cards#index
# 1. You have an unresolved rec request (and we're working on it)
# 1. Please click here to request a recommendation.
#
# Each case is handled by a different subclass.
#
# @!method self.call(user, options = {})
# @param user [User] the currently logged-in user. May be an account,
# an admin, or nil.
#
# Cell will render an empty string if:
#
# 1. the user is an admin or nil
# 1. the user is a non-onboarded account
# 1. no subclasses of the cell can be found that have anything to
# display for the account
# 1. the current action is blacklisted. e.g. none of the subclasses
# should *ever* be shown on rec_reqs#new and #create. The
# CR::UnresolvedRecs subclass should not be shown on cards#index.
#
# Subclasses will raise an error if you try to initialize them
# with an account that can't be shown.
class RecommendationAlert < Abroaders::Cell::Base
include ::Cell::Builder
include Escaped
builds do |user|
if !(user.is_a?(Account) && user.onboarded?)
Empty
elsif user.unresolved_card_recommendations?
CardRecommendation::Cell::UnresolvedAlert
elsif user.unresolved_recommendation_requests?
RecommendationRequest::Cell::UnresolvedAlert
elsif RecommendationRequest::Policy.new(user).create?
RecommendationRequest::Cell::CallToAction
else
Empty
end
end
property :couples?
def show
return '' if request_excluded?
<<-HTML.strip
<div class="recommendation-alert alert alert-info">
<div class="recommendation-alert-header">#{header}</div>
<div class="recommendation-alert-body">
#{main_text}
</div>
<div class="recommendation-alert-actions">
#{actions}
</div>
</div>
HTML
end
BTN_CLASSES = 'btn btn-success'.freeze
private
def actions
''
end
# subclasses can override this, but they should probably call `super` and
# append to the result rather than overwriting it completely.
#
# format:
# {
# 'controller_name' => %w['array', 'of', 'action', 'names'],
# }
#
# all names must be strings, not symbols.
def excluded_actions
{
'errors' => '*',
'integrations/award_wallet' => %w[settings callback sync],
'recommendation_requests' => %w[new create],
}
end
def names_for(people)
owner_first = people.sort_by(&:type).reverse
escape!(owner_first.map(&:first_name).join(' and '))
end
def request_excluded?
return false if params.nil? # makes testing easier
excluded_actions.any? do |ctrlr, actions|
params['controller'] == ctrlr && (actions == '*' || actions.include?(params['action']))
end
end
end
end
end
|
# frozen_string_literal: true
class Simulation
def initialize(num_blobs)
@blobs = []
init_blobs(num_blobs)
end
def init_blobs(num_blobs)
num_blobs.times do
@blobs.push Blob.new
end
end
def tick
display
end
def display
line_width = 20
stats = [
['Total Blobs:', @blobs.length.to_s]
]
stats.each do |stat|
puts stat[0].ljust(line_width) + stat[1].rjust(line_width)
end
end
end
class Blob
def initialize; end
end
puts 'How many blobs shall we start with?'
num_blobs = gets.to_i
sim = Simulation.new(num_blobs)
puts 'Press Enter for new tick. Type in anything to stop program'
input = gets.chomp
while input.empty?
sim.tick
input = gets.chomp
end
|
class Post < ApplicationRecord
has_many :comments, dependent: :destroy
belongs_to :user
validates :title, :content, presence: true # length: { is: 5 }
# scope :by_user_comments, -> { where(id: User.first.comments.map(&:post_id).uniq).pluck('title') }
scope :by_user, -> { order(user_id: :asc) }
scope :ordered, -> { reorder(created_at: :desc)}
scope :posted_today, -> { where(created_at: Date.today.all_day) }
end
|
require 'rails_helper'
RSpec.describe Link, type: :model do
it { should belong_to :linkable }
it { should validate_presence_of :name }
it { should validate_presence_of :url }
it { should allow_value("http://foo.com").for(:url) }
it { should_not allow_value("somevalue").for(:url) }
#GIST filename: 'gist_for_test.txt', content: "It's a test gist."
let(:link_gist) { create(:link, :for_answer, url: 'https://gist.github.com/denio-rus/e1bdd70b70726a6d5d7fc57bd490a7a2') }
let(:link) { create(:link, :for_answer, url: 'http://yandex.ru') }
it 'returns hash with filenames and content from gist' do
expect(link_gist.gist_content).to eq [{:content=>"It's a test gist.", :filename=>:"gist_for_test.txt"}]
end
it 'returns true then link is gist on github' do
expect(link_gist).to be_gist
end
it 'returns false then link is not gist' do
expect(link).to_not be_gist
end
end
|
require 'spec_helper'
describe Mongoid::Scribe::DocumentsHelper do
let(:user) { FactoryGirl.create(:user, slug: "john-doe") }
let(:address) { FactoryGirl.create(:address) }
describe "#model_param" do
it "should format a model for use as a parameter" do
expect(helper.model_param(User)).to eq("user")
end
end
describe "#relation_label" do
context "the model has a slug" do
it "returns the slug" do
expect(helper.relation_label(user)).to eq(user.slug)
end
end
context "the model doesn't have a slug" do
it "returns the id" do
expect(helper.relation_label(address)).to eq(address.id)
end
end
end
end
|
#Create empty hash
interior_info = {}
#Ask designer for user information & put information into a hash
puts "What is the client's name?"
interior_info[:name] = gets.chomp
puts "How old are they?"
interior_info[:age] = gets.chomp.to_i
puts "How many kids do they have?"
interior_info[:kids] = gets.chomp.to_i
puts "What is their style preference?"
interior_info[:style] = gets.chomp
puts "What is their favorite color of blue?"
interior_info[:color] = gets.chomp
puts "Are they interested in a tiny home? (y/n)"
interior_info[:tiny] = gets.chomp
#Print hash back out onto screen
p interior_info
#Print Human Readable List
puts "Here is your info"
puts "Name = #{interior_info[:name]}"
puts "Age = #{interior_info[:age]}"
puts "Kids = #{interior_info[:kids]}"
puts "Style Preference = #{interior_info[:style]}"
puts "Favorite Blue = #{interior_info[:color]}"
puts "Tiny House? = #{interior_info[:tiny]}"
#Ask user if what value they would like to update, 'none' if none
puts "Do you need to edit an answer? If yes, type the name of the section. If no, type 'none'"
input = gets.chomp.downcase
#Check which answer they'd like to change
if input == "none"
puts "Thanks for the info!"
elsif input == "name"
print "What would you like to update it to? "
new_name = gets.chomp
interior_info[:name] = new_name
elsif input == "age"
print "What would you like to update it to? "
new_age = gets.chomp
interior_info[:age] = new_age
elsif input == "kids"
print "What would you like to update it to? "
new_kids = gets.chomp
interior_info[:kids] = new_kids
elsif input == "style"
print "What would you like to update it to? "
new_style = gets.chomp
interior_info[:style] = new_style
elsif input == "favorite blue"
print "What would you like to update it to? "
new_blue = gets.chomp
interior_info[:color] = new_blue
elsif input == "tiny house"
print "What would you like to update it to? "
new_tiny = gets.chomp
interior_info[:tiny] = new_tiny
end
#Print hash back out onto screen
p interior_info
#Print Human Readable List
puts "Here is your info"
puts "Name = #{interior_info[:name]}"
puts "Age = #{interior_info[:age]}"
puts "Kids = #{interior_info[:kids]}"
puts "Style Preference = #{interior_info[:style]}"
puts "Favorite Blue = #{interior_info[:color]}"
puts "Tiny House? = #{interior_info[:tiny]}"
|
Then(/^I should see the thank you message$/) do
wait_for_ajax
page.should have_content('Thank you')
end
And(/^the project should have a helper$/) do
@project.helpers.count.should eq(1)
end
When(/^I submit the help form$/) do
fill_in 'contact_enquiry_email', with: 'example@example.com'
fill_in 'contact_enquiry_message', with: 'message'
click_button 'Send'
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)
# Product ==> name: string, price: integer, image_url: string, description: string
# product = Product.new(name: "Sweet robot", price: 99, image_url: "some url", description: "the sweetest robot ever made")
# product.save
# product = Product.new(name: "Spatula", price: 5, image_url: "some url", description: "flip things over")
# product.save
|
class ProyectoTerminado < Material
has_many :storage_infos, foreign_key: :material_id
accepts_nested_attributes_for :storage_infos
class << self
def sti_name
"finished"
end
end
end |
xml.instruct! :xml, :version => '1.0'
xml.rss(:version => '2.0') do
xml.channel do
xml.title(@topic)
xml.link(url_for(:format => 'rss', :only_path => false))
xml.description()
xml.language('fr-fr')
@posts.each do |post|
xml.item do
xml.title(@topic)
xml.category()
xml.description(format_text(post.body))
xml.pubDate(post.created_at.strftime("%a, %d %b %Y %H:%M:%S %z"))
xml.link(forum_topic_url(@forum, @topic, :page => post.page))
xml.guid(forum_topic_url(@forum, @topic, :page => post.page))
end
end
end
end
|
class ChangeAffiliationEnumOnReview < ActiveRecord::Migration
# Refresh for :sample enum option.
def self.up
change_column :reviews, :affiliation, :enum, :limit => Review::AFFILIATION_ENUM_VALUES, :default => nil, :allow_nil => true
end
def self.down
change_column :reviews, :affiliation, :enum, :limit => Review::AFFILIATION_ENUM_VALUES, :default => nil, :allow_nil => true
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.