text stringlengths 10 2.61M |
|---|
feature 'Signing up for Makers BnB' do
scenario 'users should be able to create an account' do
visit('/sign_up')
fill_in('name', with: 'Test User')
fill_in('email', with: 'test@email.com')
fill_in('password', with: 'password')
click_on('Submit')
expect(current_path).to eq('/view_all_spaces')
end
end
|
require 'selenium/webdriver'
Capybara.register_driver :chrome do |app|
Capybara::Selenium::Driver.new(app, browser: :chrome)
end
Capybara.register_driver :headless_chrome do |app|
capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
chromeOptions: { args: %w[headless disable-gpu] }
)
Capybara::Selenium::Driver.new app,
browser: :chrome,
desired_capabilities: capabilities
end
Capybara.javascript_driver = :headless_chrome
DEFAULT_HOST = ENV.fetch('DEFAULT_HOST', 'lvh.me').freeze
DEFAULT_PORT = ENV.fetch('DEFAULT_PORT', '9887').to_i.freeze
RSpec.configure do |_config|
Capybara.default_host = "http://#{DEFAULT_HOST}"
Capybara.server_port = DEFAULT_PORT
Capybara.app_host = "http://#{DEFAULT_HOST}:#{Capybara.server_port}"
def switch_to_subdomain(subdomain)
Capybara.app_host = if subdomain.blank? || subdomain == :none
"http://#{DEFAULT_HOST}:#{DEFAULT_PORT}"
else
"http://#{subdomain}.#{DEFAULT_HOST}:#{DEFAULT_PORT}"
end
end
end
|
# frozen_string_literal: true
shared_examples 'invalid access when not logged in' do |path|
before { get path }
it { should redirect_to(root_path) }
it 'alertが存在すること' do
expect(flash[:alert]).to be_present
end
end
|
module Podflow
class View
attr_reader :name, :template
def initialize(data = {})
@name = data['name'] || 'MyView'
@template = data['template'] || 'MyTemplateFile'
end
def render(series, episode, tmplt = PodUtils.local_template_string(template))
"\n#{name}\n--\n#{ERB.new(tmplt).result(binding)}\n--"
end
end
end
|
Spree::Order.class_eval do
has_many :boleto_docs
def payable_via_boleto?
!!self.class.boleto_payment_method
end
def self.boleto_payment_method
Spree::PaymentMethod.where(type: "Spree::PaymentMethod::BoletoMethod").first
end
end
|
# frozen_string_literal: true
require 'sinclair'
module Simulation
class BatchOptions < Sinclair::Options
skip_validation
with_options :resimulate
with_options :data_file, :repetitions
with_options :min_population, :max_population, :population_points
with_options :min_infection, :max_infection, :infection_points
with_options :min_mutation, :max_mutation, :mutation_points
with_options :min_activation, :max_activation, :activation_points
with_options :population, :infection, :mutation, :activation
end
end
|
class User
def to_s
HTMLUserPrinter.new(user).print
end
end
# With DIP
class User
def to_s(user_printer)
user_printer.print
end
end
|
class Score < ActiveRecord::Base
belongs_to :player
belongs_to :game
before_create :add_score
after_create :check_for_game_end
before_destroy :delete_score
scope :for_player, ->(player) { where(player: player) }
scope :for_player_and_game, ->(player,game) { where(player: player, game: game) }
##
# Adds a score record, properly incrementing points and scores on appropriate tables
#
def add_score
transaction do
self.player.points = self.player.points + 1
if self.player.save
self.player.team.score = self.player.team.score + 1
self.player.team.save
end
self.player.inc_score_stats
end
end
##
# Removes a score record, properly decrementing points and scores on appropriate tables
#
def delete_score
transaction do
self.player.points = self.player.points - 1
if self.player.save
self.player.team.score = self.player.team.score - 1
self.player.team.save
end
self.player.dec_score_stats
end
end
##
# checks for game end
#
def check_for_game_end
if self.player.team.score >= 5
self.player.game.finish
end
end
end
|
class CreateDiscordServers < ActiveRecord::Migration[6.0]
def up
create_table :discord_servers do |t|
t.bigint :discord_id, null: false
t.bigint :registration_channel_id
t.bigint :verified_role_id
t.timestamps
end
add_index :discord_servers, :discord_id, unique: true
end
def down
drop_table :discord_servers
end
end
|
require_relative '_helper'
require 'dbp/book_compiler/tex_to_markdown/exit_environment'
require 'strscan'
module DBP::BookCompiler::TexToMarkdown
describe ExitEnvironment do
subject { ExitEnvironment.new }
let(:input) { '{environment}remaining text' }
let(:translator) do
Object.new.tap do |allowing|
def allowing.finish_command;
end
end
end
let(:reader) { StringScanner.new(input) }
let(:writer) { StringIO.new }
it 'identifies itself as end' do
_(subject.name).must_equal 'end'
end
it 'consumes the argument' do
subject.execute(translator, reader, writer)
_(reader.rest).must_equal 'remaining text'
end
it 'writes and end div tag' do
subject.execute(translator, reader, writer)
_(writer.string).must_equal '</div>'
end
describe 'tells translator to' do
let(:translator) { MiniTest::Mock.new }
after { translator.verify }
it 'finish the command that the \end interrupted' do
translator.expect :finish_command, nil
subject.execute(translator, reader, writer)
end
end
end
end
|
class AnswersController < ApplicationController
include Voted
before_action :authenticate_user!
before_action :load_question, only: [ :create, :award ]
before_action :load_answer, except: [ :create ]
after_action :publish_answer, only: [ :create ]
respond_to :js, only: [ :create, :destroy ]
authorize_resource
def create
@answer = @question.answers.create(answer_params)
@answer.user = current_user
if @answer.save
respond_with @answer
else
render 'error'
end
end
def award
@answer.make_best
end
def update
@question = @answer.question
@answer.update(answer_params)
end
def destroy
respond_with @answer.destroy
end
private
def load_question
@question = Question.find(params[:question_id])
end
def load_answer
@answer = Answer.find(params[:id])
end
def answer_params
params.require(:answer).permit(:body, attachments_attributes: [:file])
end
def publish_answer
return if @answer.errors.any?
renderer = ApplicationController.renderer.new
renderer.instance_variable_set(:@env, { "HTTP_HOST"=>"localhost:3000",
"HTTPS"=>"off",
"REQUEST_METHOD"=>"GET",
"SCRIPT_NAME"=>"",
"warden" => warden })
ActionCable.server.broadcast( "answers_#{@question.id}", {
answer: @answer.to_json,
attachments: @answer.attachments.to_json
})
end
end |
require 'spec_helper'
module Alf
module Lang
describe ObjectOriented, 'to_rash' do
include ObjectOriented.new(supplier_names_relation)
subject{
to_rash(options).each_line.map do |line|
::Kernel.eval(line)
end
}
before do
expect(subject).to be_kind_of(Array)
subject.each{|t| expect(t).to be_a(Hash)}
end
after do
expect(Relation(subject)).to eq(_self_operand)
end
context 'when an ordering is specified' do
let(:ordering){ [[:name, :desc]] }
let(:options){ {:sort => ordering} }
it 'respects it' do
expected = supplier_names.sort.reverse
expect(subject.map{|t| t[:name]}).to eq(expected)
end
end
end
end
end
|
require 'rails_helper'
feature "admin can log in and update profile" do
scenario "admin updates profile" do
#ADMIN LOGS IN
business = Business.create(name: "wash", email: "wash@wash.com", hash_password: "password")
admin = Admin.create(name: "Admin", business: business, email: "admin@admin.com", password: "password")
visit new_admin_session_path
within(".container") do
fill_in("Email", with: 'admin@admin.com')
fill_in("Password", with: 'password')
end
click_on('Log in')
expect(page).to have_current_path root_path
#ADMIN CLICKS EDIT PROFILE
click_on('Edit profile')
expect(page).to have_content 'Edit Admin'
fill_in("Name", with: 'Admin Edit')
fill_in("Email", with: 'admin1@admin.com')
click_on('Update')
click_on('Edit profile')
find_field('Name').value == "Admin Edit"
find_field('Email').value == "admin1@admin.com"
end
end
|
require 'rails_helper'
describe "the signin process" do
before :each do
visit '/users/sign_in'
user = create(:user)
end
it "signs a user in who users the right password" do
fill_in 'Email', :with => 'katharinechen.ny@gmail.com'
fill_in 'Password', :with => '123456789'
click_button "Log in"
expect(page).to have_content "Signed in successfully"
end
it "gives a user an error who uses the wrong password" do
fill_in 'Email', :with => 'katharinechen.ny@gmail.com'
fill_in 'Password', :with => 'wrongpassword'
click_button "Log in"
expect(page).to have_content "Invalid email or password"
end
end
|
FactoryGirl.define do
factory :user_profile do
user_id 1
addrStreet1 { Faker::Address.street_address }
addrStreet2 { Faker::Address.secondary_address }
addrCity { Faker::Address.city }
addrState { Faker::Address.state_abbr }
addrZip { Faker::Address.zip_code }
phone { Faker::PhoneNumber.cell_phone }
end
end
|
class OmniReport < Prawn::Document
def initialize(hash, layout, size)
font_families.update(
"Ubuntu" => {
:normal => "#{Rails.root}/app/assets/fonts/Ubuntu-Regular.ttf",
:italic => "#{Rails.root}/app/assets/fonts/Ubuntu-Italic.ttf",
:bold => "#{Rails.root}/app/assets/fonts/Ubuntu-Bold.ttf",
:bold_italic => "#{Rails.root}/app/assets/fonts/Ubuntu-BoldItalic.ttf"
}
)
super(page_size: size, page_layout: layout, left_margin: 15, right_margin: 15, top_margin: 15, bottom_margin: 15)
font("Ubuntu")
repeat(:all, :dynamic => true) do
header(hash[:header])
end
body(hash[:body])
if self.page_count > 1
repeat(:all, :dynamic => true) do
footer
end
end
end
def header(array) # [0=>titolo, 1=>Amministratore, 2=>Immobile, 3=>Esercizio]
bounding_box([bounds.left, bounds.top], width: bounds.width, height: 45) do
text array[:admin], size:6
move_down(2)
table [[array[:title]]], row_colors: ["bae8dc"], width: bounds.width, cell_style: {size: 12, border_width: 1,
borders: [:top, :bottom],
align: :center,
border_color: "00aa8f"}
move_down(2)
text array[:building], size:6
move_up(6)
text array[:year], size:6, align: :right
end
end
def body(hash)
bounding_box([bounds.left, bounds.top-45], width: bounds.width) do
hash.each do |k, v|
header_count = v[:table].first.count
table v[:rules][:key_as_title] == true ? v[:table].unshift([{content:k, colspan:header_count}]) : v[:table], width: bounds.width, row_colors: (v[:rules][:row_striped] == true ? ["F0F0F0", "FFFFFF"] : "FFFFFF"), cell_style: {size: 5, border_width: 0.1, borders: [:bottom], border_lines: [:dotted], align: :left} do
v[:rules][:right_bordered_columns].each do |col|
column(col-1).borders = [:bottom, :right]
column(col-1).border_lines = [:dotted]
column(col-1).border_width = 0.1
end
if v[:rules][:key_as_title] == true
row(0).align = :center
row(0).font_style = :bold
row(0).size=7
row(0).borders = [:bottom]
row(0).border_lines = [:solid]
row(0).border_with = 1
v[:rules][:right_align_columns].each do |col|
column(col-1).align = :right
end
row(1).font_style = :bold
row(1).borders = [:bottom]
row(1).border_lines = [:solid]
row(1).border_width = 1
self.header = v[:rules][:header_rows] + 1
else
row(0).font_style = :bold
row(0).borders = [:bottom]
row(0).border_lines = [:solid]
row(0).border_width = 1
self.header = true
end
v[:rules][:footer_rows].times do |footer|
row(-(footer+1)).font_style = :bold
row(-(footer+1)).borders = [:top]
row(-(footer+1)).border_lines = [:solid]
row(-(footer+1)).border_width = 1
row(-(footer+1)).background_color= "FFFFFF"
end
end
move_down(10)
end
end
end
def footer
bounding_box([bounds.right-10, bounds.bottom], width: 10, height: 6) do
text "#{self.page_number}/#{self.page_count}", align: :right, size:6
end
end
end |
require 'rails_helper'
RSpec.describe "comments/index", type: :view do
login_user
before(:each) do
assign(:comments, [
FactoryBot.create(:comment),
FactoryBot.create(:comment)
])
end
it "renders a list of comments" do
render
end
end
|
class API::V1::UsersController < API::V1::BaseApiController
skip_before_action :api_key_authorize!, only: [:create]
def create
user = User.new(raw_user_params)
if User.exists?(email: user.email)
render_error_as_json(409, 'Conflict', "User with email '#{user.email}' is already registered")
else
if user.save
render json: user, serializer: UserSerializer, status: 201
end
end
end
def index
render json: User.all, each_serializer: UserSerializer
end
def show
render json: User.find(params[:user_id]), serializer: UserSerializer
end
def show_conversations
render json: User.find(params[:user_id]), serializer: UserWithConversationsSerializer
end
private
def raw_user_params
params.require(:user).require(:email)
params.require(:user).require(:password)
params.require(:user).require(:name)
params.require(:user).permit(:email, :password, :name)
end
end
|
class UserAccountsController < ApplicationController
before_filter :authorize_user_account, only: [:show]
def show
@user_account = UserAccount.find(params[:id])
@incidents = Incident.where(user_account_id: @user_account.id).find_each
@admin_account = AdminAccount.find(@user_account.admin_account_id)
@reports = @admin_account.reports.all
@user_reports = @user_account.user_reports.all
end
def new
@admin_account = AdminAccount.find(params[:admin_account_id])
@user_account = @admin_account.user_accounts.build
end
def create
@admin_account = AdminAccount.find(params[:admin_account_id])
@user_account = @admin_account.user_accounts.build(user_account_params)
if @user_account.save
flash[:success] = "Account created"
redirect_to @user_account
else
render 'new'
end
end
private
def user_account_params
params.require(:user_account).permit(:name, :admin_account_id, :job_title, :dob)
end
def authorize_user_account
@user_account = UserAccount.find(params[:id])
unless admin_signed_in? && @user_account.admin_account_id == current_admin.id
redirect_to root_path
end
end
end
|
# coding: utf-8
require 'spec_helper'
describe Post do
before(:each) do
@post = Post.new :title => "Title", :content => "Content"
end
it "is valid with valid attributes" do
@post.should be_valid
end
it "is not valid without a title" do
@post.title = nil
@post.should_not be_valid
end
it "is not valid without content" do
@post.content = nil
@post.should_not be_valid
end
end
# == Schema Information
#
# Table name: posts
#
# id :integer primary key
# title :string(255)
# content :text
# created_at :timestamp
# updated_at :timestamp
# personal :boolean default(FALSE)
# cached_slug :string(255)
# published :boolean default(FALSE), not null
#
|
module Pawnee
module SshConnection
# Reconnects to the remote server (using net/ssh).
# This is useful since often things in linux don't take effect
# until the user creates a new login shell (adding a user to
# a group for example)
def reconnect!
host = self.destination_connection.host
options = self.destination_connection.options
user = options[:user]
# Close the existing connection
self.destination_connection.close
# Reconnect
new_connection = Net::SSH.start(host, user, options)
# Copy the instance variables to the old conection so we can keep using
# the same session without reassigning references
self.destination_connection.instance_variables.each do |variable_name|
value = new_connection.instance_variable_get(variable_name)
self.destination_connection.instance_variable_set(variable_name, value)
end
end
end
end |
#!/usr/bin/ruby
require './ssutil_modules/misc'
require './ssutil_modules/projucer_project'
args = SSUtil.parse_args()
if args.should_do_update()
ProjucerProject.update_projects()
p "Projects updated"
args.done_update()
end
if args.should_quit
abort()
end
base_jucer = ProjucerProject.get_current_dir_project()
version = base_jucer.get_version()
`rm -r ../release`
`mkdir -p ../release/MacOSX/AU`
`mkdir -p ../release/MacOSX/VST3`
# assuming projucer alias is set to point the projucer executable
jucer_projects = Dir.glob('../*/*.jucer')
jucer_projects.each do |p|
puts "Resaving #{p}"
`zsh -ic 'projucer --resave #{p}'`
end
projects = Dir.glob('../*/Builds/MacOSX/*.xcodeproj')
if projects.empty?
puts "There are no xcode projects. Please run projucer on each project once to generate the xcode projects"
return
end
projects.each do |f|
if f.include?('SpectralGateBuild') || f.include?('Base.xcodeproj') || f.include?('Playground')
next
end
project_name = File.basename(f, '.xcodeproj')
build_dir = File.dirname(f) + "/build/Release"
puts "Cleaning project #{project_name}..."
SSUtil::perform_and_print "xcodebuild clean -project '#{f}\' -scheme '#{project_name} - All' -configuration Release"
puts "Building project #{project_name}..."
SSUtil::perform_and_print "xcodebuild build -project '#{f}' -scheme '#{project_name} - All' -configuration Release"
`cp -r "#{build_dir}/#{project_name}.component" "../release/MacOSX/AU/#{project_name}.component"`
`cp -r "#{build_dir}/#{project_name}.vst3" "../release/MacOSX/VST3/#{project_name}.vst3"`
end
`pandoc ../CHANGES.md -f markdown -t html -s -o PACKAGE_README.html`
`cp SpectralSuitePackager.pkgproj.template SpectralSuitePackager.pkgproj`
`sed -i '' 's/{VERSION}/#{version}/g' SpectralSuitePackager.pkgproj`
`packagesbuild SpectralSuitePackager.pkgproj`
|
require 'rails_helper'
RSpec.describe Item, :type => :model do
let(:category) { FactoryGirl.build(:category) }
let(:item) { FactoryGirl.build(:item) }
let(:item2) { FactoryGirl.build(:item2) }
before(:each) do
category.save!(validate: false)
item.categories << category
item.save!
item2.categories << category
item2.save!
end
it 'is valid' do
expect(item).to be_valid
end
it 'is invalid without a title' do
item.title = nil
expect(item).to be_invalid
end
it 'is invalid without a description' do
item.description = nil
expect(item).to be_invalid
end
it 'is invalid without a price' do
item.price = nil
expect(item).to be_invalid
end
it 'belongs to at least one category' do
item.categories = []
expect(item).to be_invalid
end
it 'should connect to categories' do
expect(item.categories.first.name).to eq('food')
end
it 'is not valid if title is an empty' do
item.title = ""
expect(item).to be_invalid
end
it 'is not valid if description is empty' do
item.description = ""
expect(item).to be_invalid
end
it 'must have a unique title within supplier shop' do
item2.title = item.title
item2.supplier_id = item.supplier_id
expect(item2).to be_invalid
item2.title = 'straps'
expect(item2).to be_valid
end
it 'is invalid if the price is less than zero' do
item.price = -1.00
expect(item).to be_invalid
end
it 'is invalid if price is anything other than a decimal numeric value' do
item.price = "alkdj"
expect(item).to be_invalid
end
it 'has a default photo if empty' do
item.photo = nil
expect(item.photo.options.has_key?(:default_url)).to be true
expect(item.photo.options.has_value?('/images/missing_large.png')).to be true
end
end
|
# Tongtech.com, Inc.
require File.expand_path("../../spec_helper", __FILE__)
describe Bosh::CloudStackCloud::Cloud do
before(:each) do
@registry = mock_registry
end
it "detaches an CloudStack volume from a server" do
server = double("server", :id => "i-test", :name => "i-test")
volume = double("volume", :id => "v-foobar")
volume_attachments = double("body", :body => {"volumeAttachments" =>
[{"volumeId" => "v-foobar"},
{"volumeId" => "v-barfoo"}]})
cloud = mock_cloud do |cloudstack|
cloudstack.servers.should_receive(:get).
with("i-test").and_return(server)
cloudstack.volumes.should_receive(:get).
with("v-foobar").and_return(volume)
cloudstack.should_receive(:get_server_volumes).
and_return(volume_attachments)
end
volume.should_receive(:detach).with(server.id, "v-foobar").and_return(true)
cloud.should_receive(:wait_resource).with(volume, :available)
old_settings = {
"foo" => "bar",
"disks" => {
"persistent" => {
"v-foobar" => "/dev/vdc",
"v-barfoo" => "/dev/vdd"
}
}
}
new_settings = {
"foo" => "bar",
"disks" => {
"persistent" => {
"v-barfoo" => "/dev/vdd"
}
}
}
@registry.should_receive(:read_settings).
with("i-test").and_return(old_settings)
@registry.should_receive(:update_settings).
with("i-test", new_settings)
cloud.detach_disk("i-test", "v-foobar")
end
it "raises an error when volume is not attached to a server" do
server = double("server", :id => "i-test", :name => "i-test")
volume = double("volume", :id => "v-barfoo")
volume_attachments = double("body",
:body => {"volumeAttachments" =>
[{"volumeId" => "v-foobar"}]})
cloud = mock_cloud do |cloudstack|
cloudstack.servers.should_receive(:get).
with("i-test").and_return(server)
cloudstack.volumes.should_receive(:get).
with("v-barfoo").and_return(volume)
cloudstack.should_receive(:get_server_volumes).
and_return(volume_attachments)
end
expect {
cloud.detach_disk("i-test", "v-barfoo")
}.to raise_error(Bosh::Clouds::CloudError, /is not attached to server/)
end
end
|
class Images < Application
before :ensure_authenticated
before :ensure_lecture_author
def index
@images = @lecture.images.ordered
display @images, :layout => false
end
def create(file)
Image.create(:lecture => @lecture, :filedata => file)
"1" # flash upload requirement
end
def update_positions(positions)
positions.each_with_index do |id, index|
@lecture.images.get(id).update(:position => index)
end
""
end
def destroy(id)
@image = Image.get(id) || (raise NotFound)
if @image.destroy
""
else
raise InternalServerError
end
end
protected
def ensure_lecture_author
@lecture = Lecture.get(params[:lecture_id]) || (raise NotFound)
raise Unauthorized unless @lecture.author?(session.user)
end
end # Images
|
class MessagesController < ApplicationController
before_action :require_user_logged_in
before_action :correct_user, only: [:edit, :update, :destroy]
def index
@messages = Message.all
end
def new
@message = Message.new
end
def create
@message = current_user.messages.build(message_params)
if @message.save
flash[:success] = '投稿しました。'
redirect_to root_url
else
@messages = current_user.messages.order(id: :desc).page(params[:page])
flash.now[:danger] = '投稿に失敗しました。'
render 'toppages/index'
end
end
def edit
@message = Message.find(params[:id])
end
def update
@message = Message.find(params[:id])
if @message.update(message_params)
flash[:success] = 'Message は正常に更新されました'
redirect_to mypage_users_path
else
flash.now[:danger] = 'Message は更新されませんでした'
render :edit
end
end
def destroy
@message.destroy
flash[:success] = '削除しました。'
redirect_back(fallback_location: root_path)
end
end
private
def message_params
params.require(:message).permit(:title, :content)
end
def correct_user
@message = current_user.messages.find_by(id: params[:id])
unless @message
redirect_to root_url
end
end |
class CreateSantasTableForLists < ActiveRecord::Migration
def change
create_table :santas do |t|
t.string :email, null: false
t.string :name, null: false
t.integer :list_id, index: true, null: false
t.timestamps index: true, null: false
end
end
end
|
require 'spec_helper'
describe HalfAndHalf do
after(:each) do
HalfAndHalf.instance_variable_set(:@experiments, [])
end
describe '#experiment' do
it 'should create and add an experiment' do
experiment = HalfAndHalf.experiment(:ab)
experiment.should be_a(HalfAndHalf::Experiment)
HalfAndHalf.experiments.should include(experiment)
end
end
describe '#get_experiment' do
it 'should return experiment with name' do
experiment = HalfAndHalf.experiment(:ab)
HalfAndHalf.get_experiment(:ab).should == experiment
end
end
describe '#track_event' do
it 'should track event in Redis' do
experiment = HalfAndHalf.experiment :ab do |e|
e.control 'control a'
e.treatment 'treatment b'
end
trial = experiment.create_trial
HalfAndHalf.track_event(:clicked, token: trial.token)
Redis.current.bitcount('halfandhalf.ab.control.clicked').should == 1
end
end
describe 'integration' do
it 'should run sample experiment from readme' do
experiment = HalfAndHalf.experiment :message_subject do |e|
e.control ->(recipient) { "Hi!" }
e.treatment ->(recipient) { "Hi, #{recipient.name}!" },
name: :with_recipient_name
e.events :delivered, :opened, :clicked
end
trials = 2000.times.map do
trial = experiment.create_trial
HalfAndHalf.track_event(:delivered, token: trial.token)
trial
end
control_trials = trials.select do |trial|
trial.variant == experiment.control
end
treatment_trials = trials.select do |trial|
trial.variant == experiment.treatment
end
400.times do |i|
HalfAndHalf.track_event(:opened, token: control_trials[i].token)
end
40.times do |i|
HalfAndHalf.track_event(:clicked, token: control_trials[i].token)
end
500.times do |i|
HalfAndHalf.track_event(:opened, token: treatment_trials[i].token)
end
50.times do |i|
HalfAndHalf.track_event(:clicked, token: treatment_trials[i].token)
end
treatment_opened = experiment.treatment.get_event(:opened)
treatment_opened.conversion_rate.should == 0.5
treatment_opened.should be_significant
treatment_clicked = experiment.treatment.get_event(:clicked)
treatment_clicked.conversion_rate.should == 0.05
treatment_clicked.should_not be_significant
end
end
end |
#!/usr/bin/env ruby
require "set"
require "pry"
class SnowmanState
attr_reader :data, :mx, :my
def initialize(data, mx, my)
@data = data
@mx = mx
@my = my
end
def [](x,y)
return " " if x < 0 or y < 0
(@data[y] || [])[x] || " "
end
def move_to(nx, ny, px, py)
# When moving there are 3 relevant points
# [mx, my] monster
# [nx, ny] next
# [px, py] push-to
next_tile = self[nx, ny]
push_tile = self[px, py]
case next_tile
when ".", "s"
SnowmanState.new(@data, nx, ny)
when "1"
case push_tile
when "."
updating(nx, ny, [nx,ny,"."], [px,py,"1"])
when "s"
updating(nx, ny, [nx,ny,"."], [px,py,"2"])
when "2"
updating(nx, ny, [nx,ny,"."], [px,py,"3"])
when "4"
updating(nx, ny, [nx,ny,"."], [px,py,"5"])
when "6"
updating(nx, ny, [nx,ny,"."], [px,py,"7"])
else
nil
end
when "2"
case push_tile
when "."
updating(nx, ny, [nx,ny,"."], [px,py,"2"])
when "s"
updating(nx, ny, [nx,ny,"."], [px,py,"4"])
when "4"
updating(nx, ny, [nx,ny,"."], [px,py,"6"])
else
nil
end
when "4"
case push_tile
when "."
updating(nx, ny, [nx,ny,"."], [px,py,"4"])
when "s"
updating(nx, ny, [nx,ny,"."], [px,py,"4"])
else
nil
end
when "3"
case push_tile
when "."
updating(mx, my, [nx,ny,"2"], [px,py,"1"])
when "s"
updating(mx, my, [nx,ny,"2"], [px,py,"2"])
else
nil
end
when "5"
case push_tile
when "."
updating(mx, my, [nx,ny,"4"], [px,py,"1"])
when "s"
updating(mx, my, [nx,ny,"4"], [px,py,"2"])
else
nil
end
when "6"
case push_tile
when "."
updating(mx, my, [nx,ny,"4"], [px,py,"2"])
when "s"
updating(mx, my, [nx,ny,"4"], [px,py,"4"])
else
nil
end
# 7 is win already, and can't be pushed
else
nil
end
end
private def updating(nmx, nmy, *list)
new_data = @data.map(&:dup)
list.each do |x,y,v|
new_data[y][x] = v
end
SnowmanState.new(
new_data.map(&:-@),
nmx,
nmy
)
end
def right
move_to(@mx+1, @my, @mx+2, @my)
end
def left
move_to(@mx-1, @my, @mx-2, @my)
end
def up
move_to(@mx, @my-1, @mx, @my-2)
end
def down
move_to(@mx, @my+1, @mx, @my+2)
end
def win?
!(@data.join =~ /[1-6]/)
end
def loss?
b1 = 0
b2 = 0
b4 = 0
@data.join.each_char do |c|
case c
when "1"
b1 += 1
when "2"
b2 += 1
when "3"
b1 += 1
b2 += 1
when "4"
b4 += 1
when "5"
b1 += 1
b4 += 1
when "6"
b2 += 1
b4 += 1
# ignore 7s, they don't matter
end
end
balls = b1 + b2 + b4
raise unless balls % 3 == 0
snowmen = balls / 3
return true if b4 > snowmen
return true if b4 + b2 > snowmen * 2
false
end
def moves
[
["left", left],
["right", right],
["up", up],
["down", down],
].select{|a,b| b}
end
def hash
[@data, @mx, @my].hash
end
def ==(other)
[@data, @mx, @my] == [other.data, other.mx, other.my]
end
def eql?(other)
self == other
end
# Make it print better
def to_s
result = @data.map(&:dup)
if result[my][mx] == "s"
result[my][mx] = "M"
elsif result[my][mx] == "."
result[my][mx] = "m"
else
raise "Bad monster location"
end
result.join("\n") + "\n\n"
end
class << self
def from_file(path)
data = Pathname(path).readlines.map(&:chomp)
mx, my = find_monster(data)
raise unless mx and my
new(
data.map(&:-@),
mx,
my
)
end
# m - monster
# M - monster on snow
def find_monster(data)
data.each_with_index do |row, y|
row.chars.each_with_index do |char, x|
if char == "m"
row[x] = "."
return x, y
elsif char == "M"
row[x] = "s"
return x, y
end
end
end
raise "Cannot find monster"
end
end
end
class SnowmanSolver
def initialize(path)
initial_state = SnowmanState.from_file(path)
@states = {initial_state => ["start", nil]}
@queue = [initial_state]
end
def call
until @queue.empty?
next_state = @queue.shift
if @states.size % 10000 == 0
puts "Q #{@queue.size} S #{@states.size / 1000}"
# puts next_state
end
if next_state.win?
answer = []
cur_state = next_state
while cur_state
dir, cur_state = @states[cur_state]
answer << dir
end
puts "FINAL Q #{@queue.size} S #{@states.size}"
puts answer.reverse
return
end
next_state.moves.each do |dir, state|
next if @states[state]
next if state.loss?
@states[state] = [dir, next_state]
@queue.push state
end
end
puts "There is no way to win this level"
end
def manual
state = @queue.shift
%W[
right right
up down
left left left left
up down
up left up up right
].each do |dir|
state = state.send(dir)
end
while true
puts state
puts "Next? "
dir = STDIN.readline.chomp
if state.respond_to?(dir)
next_state = state.send(dir)
state = next_state if next_state
end
end
end
end
unless ARGV.size == 1
STDERR.puts "#{$0} puzzle.txt"
exit 1
end
SnowmanSolver.new(ARGV[0]).call
# SnowmanSolver.new(ARGV[0]).manual
|
require "rails_helper"
RSpec.describe Api::V3::FacilityTransformer do
describe ".to_response" do
let(:facility) { FactoryBot.build(:facility) }
it "sets the sync_region_id to the facility group id" do
transformed_facility = Api::V3::FacilityTransformer.to_response(facility)
expect(transformed_facility[:sync_region_id]).to eq facility.facility_group_id
end
end
end
|
class ChangeColumnTypeOnCustomItems < ActiveRecord::Migration
def up
change_column :custom_items, :value_name, :text
change_column :appointment_items, :value_name, :text
end
def down
change_column :custom_items, :value_name, :string
change_column :appointment_items, :value_name, :text
end
end
|
xml.instruct!
xml.DOCS do
@articles.each do |article|
next if article.name.nil? or article.text.nil? or article.publish_date.nil?
xml.ARTC do
xml.HDRA do
xml.SRCM "DenikReferendum.cz"
xml.DATI article.publish_date.to_formatted_s(:cz_date)
xml.TITA article.name
xml.LNKW detail_article_url(pretty_id(article))
xml.LANG "cz"
xml.CLMN article.section.name unless article.section.nil?
xml.CREA article.author.full_name unless article.author.nil?
end
xml.TXTA do
xml.cdata! article.text
end
end
end
end
|
class CatalogController < ApplicationController
skip_before_action :authorize
include CurrentMember
before_action :set_member
def index
@activities = Activity.order(:name)
end
end
|
class EventsControllerTest < ApplicationControllerTest
test "The events of owner can be deleted" do
event_owner = FactoryBot.create(:user)
event = FactoryBot.create(:event, owner: event_owner)
sign_in_as(event_owner)
assert_difference('Event.count', -1) do
delete event_path(event)
end
end
test "The events of other owners cannot be deleted" do
event_owner = FactoryBot.create(:user)
event = FactoryBot.create(:event, owner: event_owner)
sing_in_user = FactoryBot.create(:user)
sign_in_as(sing_in_user)
assert_difference('Event.count', 0) do
assert_raise(ActiveRecord::RecordNotFound) do
delete event_path(event)
end
end
end
end
|
class FormBuilder < ActionView::Helpers::FormBuilder
include ActionView::Helpers::TagHelper
include ActionView::Context
def errors?(method)
return unless @object.respond_to?(:errors)
@object.errors[method].present?
end
def errors_for(method)
return unless errors?(method)
content = []
key = "activerecord.attributes.#{@object.class.name.underscore}.#{method}"
content << I18n.t(key, default: method.to_s.humanize)
content << @object.errors.messages[method].join(", ")
content_tag :div, class: "invalid-feedback d-block" do
content.join(" ")
end
end
end
|
require 'swine/core'
require 'devise'
require 'devise-encryptable'
require 'cancan'
Devise.secret_key = SecureRandom.hex(50)
module Swine
module Auth
mattr_accessor :default_secret_key
def self.config(&block)
yield(Swine::Auth::Config)
end
end
end
Swine::Auth.default_secret_key = Devise.secret_key
require 'swine/auth/engine'
|
# encoding: utf-8
class BCIBank < Bank
attr_accessor :user, :password, :account_number
attr_reader :session
URL = "https://www.bci.cl/cl/bci/aplicaciones/seguridad/autenticacion/loginPersonas.jsf"
LOGIN_FORM_NAME = "frm"
BROWSER = "Mac FireFox"
START_URL = "https://www.bci.cl/cuentaswls/ControladorCuentas?opcion=CTACTECARTOLA&objeto="
def initialize(account = {})
@user = account[:user]
@password = account[:password]
@account_number = account[:number]
@session = new_session
end
def url
URL
end
def balance
# We make sure we are on the first page
session.get("#{START_URL}#{self.account_number}")
# The balance is in the 7 table, second td
string_balance = session.page.root.css("table")[6].css("td")[1].text
# Remove de $ simbol and the dots
convert_money_to_integer(string_balance)
end
def transactions
transactions = []
# We go to the transactions page
session.get("#{START_URL}#{self.account_number}")
# Tables that hold the transactions, we select the tr's
table_rows = session.page.root.css("table")[10].css("tr.blanco, tr.suave")
table_rows.each do |row|
values = row.css("td").map { |td| clean_string(td) }
total = values[3].size > 0 ? values[3] : values[4]
transaccion_info = {
:date => Date.parse(values[0]),
:description => values[1],
:serial => values[2],
:total => convert_money_to_integer(total)
}
transactions << Transaction.new(transaccion_info)
end
transactions
end
def new_session
agent = Mechanize.new
agent.user_agent_alias=BROWSER
agent.get(URL)
form = agent.page.form(LOGIN_FORM_NAME)
form["frm"]="frm"
form["frm:canal"]="110"
form["frm:clave"]= self.password
form["frm:clave_aux"]=""
form["frm:dvCliente"] = self.user[-1] #digito verificador rut
form["frm:grupo"] = ""
form["frm:j_idt12"] ="Ingresar"
# Rut only numbers without verification
form["frm:rutCliente"]= self.user[0..-2].gsub(/[\--.]/,'')
form["frm:rut_aux"] = ""
form["frm:servicioInicial"]="SuperCartola"
form["frm:touch"] = "#{(Time.now.to_f*1000).to_i}"
form["frm:transaccion"] = ""
form.submit
agent
end
private
def clean_string(html_object)
# We have to remove the special   character, which is not a \s+
nbsp = Nokogiri::HTML(" ").text
# This is the text of the html element
text_of_html_el = html_object.children.text
text_of_html_el.strip.gsub(nbsp,'').gsub(/\n/,'')
end
def convert_money_to_integer(money)
int = money.gsub(/[\$.]/,'').gsub(/\s+/,'')
int.to_i
end
end |
# A class that, given a word, computes the scrabble
# score for that word.
class Scrabble
def initialize(letters)
@letters = letters
@letter_val_hsh = letter_values
end
def self.score(letters)
Scrabble.new(letters).score
end
def score
return 0 if @letters.nil?
return 0 if @letters.empty?
return 0 if @letters.match?(/\t\n/)
@letters.upcase!
@letters.chars.each_with_object([]) do |letter, ary|
ary << @letter_val_hsh[letter]
end.sum
end
end
def letter_values
{
'A' => 1, 'B' => 3,
'C' => 3, 'D' => 2,
'E' => 1, 'F' => 4,
'G' => 2, 'H' => 4,
'I' => 1, 'J' => 8,
'K' => 5, 'L' => 1,
'M' => 3, 'N' => 1,
'O' => 1, 'P' => 3,
'Q' => 10, 'R' => 1,
'S' => 1, 'T' => 1,
'U' => 1, 'V' => 4,
'W' => 4, 'X' => 8,
'Y' => 4, 'Z' => 10
}
end
|
require '../lib/rublicious.rb'
describe Rublicious::Client do
before do
@feeds = Rublicious::Client.new
@response = [{'a' => 1, 'b' => 2}, {'b' => {'c' => {'d' => 10}}}]
@resp_hash = {
'rss' => 'items',
'links' => ['www.google.com', 'www.google.com.br', 'a string'],
'category' => {'a' => 1},
'array' => [{'arr:item' => 2}]
}
end
it "should have a default handler that add methods based on the response hash keys" do
@feeds.default_handler @response
@response.first.respond_to?('a').should be_true
@response.first.respond_to?('c').should be_false
@response[1].respond_to?('b').should be_true
@response[1].respond_to?('b_c').should be_true
@response[1].respond_to?('b_c_d').should be_true
@response[1].respond_to?('c_d').should be_false
@response[1].respond_to?('b_d').should be_false
@feeds.default_handler @resp_hash
@resp_hash.respond_to?('rss').should be_true
@resp_hash.respond_to?('category').should be_true
@resp_hash.respond_to?('category_a').should be_true
@resp_hash.respond_to?('array').should be_true
@resp_hash.array.first.respond_to?('arr_item').should be_true
end
it "should have metaprogrammed methods to get hash values" do
@feeds.default_handler @response
@response.first.respond_to?('a').should be_true
@response.first.a.should == 1
@response.first.b.should == 2
@response[1].b_c_d.should == 10
@feeds.default_handler @resp_hash
@resp_hash.rss.should == 'items'
@resp_hash.links.should include('a string')
@resp_hash.category.keys.should include('a')
@resp_hash.category.keys.should_not include('b')
@resp_hash.category_a.should == 1
@resp_hash.category_a.should == @resp_hash.category['a']
@resp_hash.array.first.arr_item.should == 2
end
end
|
class Anagram
attr_accessor :word
def initialize(word)
@word = word
end
def match(possible_matches)
matches = []
initial_word = @word.chars.to_a
possible_matches.each do |word|
character_array = word.chars.to_a
matches << word if initial_word.sort == character_array.sort
end
matches
end
end
|
# 1 ASCII Art
=begin
# Write a one-line program that created the following output 10 times,
# with the subsequent line indented 1 space to the right.
10.times {|number| puts (' ' * number) + "The Flintstones Rock!"}
# 2 This results in an error
puts "The value of 40 + 2 is " + (40 + 2)
# This error happens because an integer cannot be coerced into a string...
# It can be fixed by string concatentation or string interpolation
puts "The value of #{40} + #{2} is" + (40 + 2).to_s
# OR
puts "The value of 40 + 2 is" + " " + "#{40 + 2}"
# 3 Alan wrote this, meant to show all the factors of the input number:
def factors(number)
divisor = number
factors = []
begin
factors << number / divisor if number % divisor == 0
divisor -= 1
end until divisor == 0
factors
end
=end
# use a loop on the code above not begin/end/until
def factors(number)
divisor = number
factors = []
loop do
break if divisor <= 0
factors << number / divisor if number % divisor == 0
divisor -= 1
end
factors
end
p factors(1000)
# Bonus 1 the line number % divisor == 0, if the reaminder is 0 the numbers are
# divisible, and the divisor will be a factor of the number
# Bonus 2 like 37 in the method, is the return value, since method definitions return the last
# line in the method
# above could also be
def factors(number)
divisor = number
factors = []
while divisor > 0 do
factors << number / divisor if number % divisor == 0
divisor -= 1
end
factors
end
p factors(1000)
# 4 Implement a rolling buffer
def rolling_buffer1(buffer, max_buffer_size, new_element)
buffer << new_element
buffer.shift if buffer.size > max_buffer_size
buffer
end
def rolling_buffer2(input_array, max_buffer_size, new_element)
buffer = input_array + [new_element]
buffer.shift if buffer.size > max_buffer_size
buffer
end
# is there a difference between the two? other than the operators she
# chose to add an element to the buffer?
# Yes. RB2 does not alter the caller's input argument, RB1 does!
# 5 This code has the limit variable outside fo the scope of the emthod definition
# so it is not reached in teh while loop below.
=begin
limit = 15
def fib(first_num, second_num)
while first_num + second_num < limit
sum = first_num + second_num
first_num = second_num
second_num = sum
end
sum
end
result = fib(0, 1)
puts "result is #{result}"
=end
def fib(first_num, second_num, limit)
while first_num + second_num < limit
sum = first_num + second_num
first_num = second_num
second_num = sum
end
sum
end
result = fib(0, 1, 15)
puts "result is #{result}"
#6 Output of the code?
answer = 42
def mess_with_it(some_number)
some_number += 8
end
new_answer = mess_with_it(answer)
p answer - 8 # 34 answers variable is 42, so p 42 - 8
# 7 Munster Family
munsters = {
"Herman" => { "age" => 32, "gender" => "male" },
"Lily" => { "age" => 30, "gender" => "female" },
"Grandpa" => { "age" => 402, "gender" => "male" },
"Eddie" => { "age" => 10, "gender" => "male" },
"Marilyn" => { "age" => 23, "gender" => "female"}
}
def mess_with_demographics(demo_hash)
demo_hash.values.each do |family_member|
family_member["age"] += 42
family_member["gender"] = "other"
end
end
p mess_with_demographics(munsters)
# does the above emthod call ransack the data? Why or why not?
# yes, it removed all the names of all the family members, demo_hash could
# be reassigned which would retain the stored value of the munsters data,
# but since it doesn't the munsters original is modified
#8 What is the result of the call below? whatever hand was used in the tie as the result of the tie
def rps(fist1, fist2)
if fist1 == "rock"
(fist2 == "paper") ? "paper" : "rock"
elsif fist1 == "paper"
(fist2 == "scissors") ? "scissors" : "paper"
else
(fist2 == "rock") ? "rock" : "scissors"
end
end
puts rps(rps(rps("rock", "paper"), rps("rock", "scissors")), "rock")
# at each argument, you retunr a value, and in this case the final returns paper
# 9 consider the simple methods!
def foo(param = 'no')
"yes"
end
def bar(param = "no")
param == "no" ? "yes" : "no"
end
# what is the return value for:
bar(foo)
# fun brain puzzle, foo returns "yes" so bar("yes") leads to a false "no" leading to "no"
|
require 'tb'
require 'test/unit'
class TestTbLTSV < Test::Unit::TestCase
def parse_ltsv(ltsv)
Tb::LTSVReader.new(StringIO.new(ltsv)).to_a
end
def generate_ltsv(ary)
writer = Tb::LTSVWriter.new(out = '')
ary.each {|h| writer.put_hash h }
writer.finish
out
end
def test_escape_and_unescape
0x00.upto(0x7f) {|c|
s = [c].pack("C")
assert_equal(s, Tb.ltsv_unescape_string(Tb.ltsv_escape_key(s)))
assert_equal(s, Tb.ltsv_unescape_string(Tb.ltsv_escape_value(s)))
}
end
def test_parse
r = Tb::LTSVReader.new(StringIO.new("a:1\tb:2\na:3\tb:4\n"))
result = []
r.with_header {|header|
result << header
}.each {|obj|
result << obj
}
assert_equal([%w[a b], {"a"=>"1", "b"=>"2"}, {"a"=>"3", "b"=>"4"}], result)
end
def test_parse2
t = parse_ltsv("a:1\tb:2\n")
assert_equal(
[{"a"=>"1", "b"=>"2"}],
t)
end
def test_generate_ltsv
t = [{'a' => 'foo', 'b' => 'bar'}]
assert_equal("a:foo\tb:bar\n", generate_ltsv(t))
end
def test_generate_ltsv2
t = [{'a' => 'foo', 'b' => 'bar'},
{'a' => 'q', 'b' => 'w'}]
assert_equal("a:foo\tb:bar\na:q\tb:w\n", generate_ltsv(t))
end
end
|
# == Schema Information
#
# Table name: rules
#
# id :integer not null, primary key
# title :string(255)
# org_id :integer
# content :text
# url :string(255)
# is_published :boolean default(FALSE)
# created_at :datetime not null
# updated_at :datetime not null
#
class Rule < ActiveRecord::Base
attr_accessible :content, :org_id, :title, :url, :is_published
belongs_to :org
has_many :rule_tags
has_many :tags, :through => :rule_tags
has_many :rule_links
has_many :links, :through => :rule_links
validates_presence_of :title, :org_id
end
|
class RenameTableProfiles < ActiveRecord::Migration
def change
rename_table :profiles, :user_profiles
end
end
|
class AddVendorToUsuario < ActiveRecord::Migration
def change
add_column :usuarios, :vendor_id, :string
end
end
|
class Todo
include Mongoid::Document
field :title, type: String
field :due_date, type: DateTime
field :has_due_time, type: Boolean
field :description, type: String
validates :title, :due_date, :presence => true
# Checks if the due_date (and if existing due_time) is already past
def overdue?
due_date.past?
end
def datetime
if has_due_time
self.date + " " + self.time
else
self.date
end
end
def date
I18n.localize(due_date.to_date)
end
def time
I18n.localize(due_date, :format => :'time')
end
def description_with_size(size)
if description.length > size
description.first(size) + '...'
else
description.first(size)
end
end
end
|
class Reaction < ApplicationRecord
belongs_to :profile
after_initialize :set_defaults
validates :name, presence: { message: "The value must be provided" }
validates :cause, presence: { message: "The cause must be provided" }
validates :description, presence: { message: "The description must be provided" }
validates :start, presence: { message: "A date must be informed" }
def set_defaults
self.start = Time.now unless self.start
end
end
|
require 'rails_helper'
RSpec.describe 'the feed interface' do
it 'displays post' do
visit '/'
fill_in 'Description', with: 'Hello World!'
expect(page).to have_no_css('div#row_1')
click_button 'Post'
expect(page).to have_css('div#row_1')
expect(find('div#row_1')).to have_content('Hello World!')
expect(find('div#row_1')).to have_button('Delete Post')
expect(find('div#row_1')).to have_content('less than a minute ago')
end
it 'removes post' do
visit '/'
fill_in 'Description', with: 'Hello World!'
click_button 'Post'
expect(page).to have_css('div#row_1')
click_button 'Delete Post'
expect(page).to have_no_css('div#row_1')
end
it 'displays :success flash messages' do
visit '/'
fill_in 'Description', with: 'Hello World!'
expect(page).to have_no_content('Success!')
click_button 'Post'
expect(page).to have_content('Success!')
expect(page).to have_no_content('Successfully deleted post.')
click_button 'Delete Post'
expect(page).to have_content('Successfully deleted post.')
end
it 'diaplays empty post message flash message' do
visit '/'
expect(page).to have_no_content('Empty message not allowed.')
click_button 'Post'
expect(page).to have_content('Empty message not allowed.')
expect(page).to have_no_css('div#row_1')
fill_in 'Description', with: 'c'
click_button 'Post'
expect(page).to have_css('div#row_1')
end
it 'displays flash message when post message over 150 characters' do
max = 150
visit '/'
str = '0' * max
fill_in 'Description', with: str
click_button 'Post'
expect(page).to have_css('div#row_1')
str += '0'
fill_in 'Description', with: str
click_button 'Post'
expect(page).to have_content("#{max} characters is the maximum allowed.")
expect(page).to have_no_css('div#row_2')
end
end
|
class CreateResourceAudiences < ActiveRecord::Migration
def change
create_table :resource_audiences do |t|
t.references :resource, null: false
t.references :audience, null: false
t.timestamps
end
add_index :resource_audiences, :resource_id
add_index :resource_audiences, :audience_id
end
end
|
class TestTypeVersionsController < ApplicationController
before_action :set_test_type_version, only: [:show, :edit, :update, :destroy]
before_action :authorize_test_type_versions, only: [:new, :create, :index]
# GET /test_type_versions
def index
@page = params[:page]
@per_page = 10
@test_type_versions_filtered = params[:q].present? ? TestTypeVersion.by_name(params[:q]) : TestTypeVersion.all
@test_type_versions = @test_type_versions_filtered.paginate page: params[:page], per_page: @per_page
# Display the data collected according to a format
respond_to do |format|
format.html
format.json
#format.csv { send_data @test_type_versions.to_csv }
end
end
# GET /test_type_versions/1
def show
end
# GET /test_type_versions/new
def new
@test_type_version = TestTypeVersion.new
end
# GET /test_type_versions/1/edit
def edit
end
# POST /test_type_versions
def create
@test_type_version = TestTypeVersion.new(test_type_version_params)
if @test_type_version.save
redirect_to @test_type_version
else
render :new
end
end
# PATCH/PUT /test_type_versions/1
def update
if @test_type_version.update(test_type_version_params)
redirect_to @test_type_version
else
render :edit
end
end
# DELETE /test_type_versions/1
def destroy
if @test_type_version.destroy
redirect_to test_type_versions_url
else
render :show
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_test_type_version
@test_type_version = TestTypeVersion.find(params[:id])
authorize @test_type_version
end
# Authorization for class.
def authorize_test_type_versions
authorize TestTypeVersion
end
# Only allow a trusted parameter "white list" through.
def test_type_version_params
params.require(:test_type_version).permit(:name, :description, :data, :test_type_id)
end
end
|
class Admin::CommentsController < ApplicationController
before_filter :authenticate_admin_user!
# before_filter :load_video
# before_filter :authenticate_user!, except: [:index, :show]
# def create
# @comment = @video.comments.build(params[:comment])
# @comment.user = current_user
# if @comment.save
# redirect_to @video, notice: "Comment was created."
# else
# render :new
# end
# end
def index
@search = Comment.search(params[:q])
if params[:sort].present?
if params[:sort] == '3'
@comments = @search.result.where(:approved => nil)
@active = "pending"
else
@comments = @search.result.where(:approved => params[:sort])
if params[:sort] == '1'
@active = "approved"
else
@active = "unapproved"
end
end
else
@comments = @search.result
@active = "all"
end
end
def edit
@comment = Comment.find(params[:id])
end
def approve_comments
@comment = Comment.find(params[:id])
respond_to do |format|
if @comment.update_attributes(:approved => params[:approved])
format.html {redirect_to admin_comments_path, notice: "Comment is successfully updated."}
format.js {head :no_content }
format.json {}
else
format.html {render :edit}
format.js {head :no_content }
format.json {}
end
end
end
def update
@comment = Comment.find(params[:id])
respond_to do |format|
if @comment.update_attributes(params[:comment])
format.html {redirect_to admin_comments_path, notice: "Comment is successfully updated."}
format.js {head :no_content }
format.json {}
else
format.html {render :edit}
format.js {head :no_content }
format.json {}
end
end
end
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
redirect_to admin_comments_path, notice: "Comment is successfully destroyed."
end
# private
# def load_video
# @video = Video.find(params[:video_id])
# end
end
|
require 'pg'
require 'pg_hstore'
module Terrazine
# PG type map updater
class TypeMap
class << self
def update(pg_result, types)
# TODO! why it sometimes column_map?
t_m = pg_result.type_map
columns_map = t_m.is_a?(PG::TypeMapByColumn) ? t_m : t_m.build_column_map(pg_result)
coders = columns_map.coders.dup
types.each do |name, type|
coders[pg_result.fnumber(name.to_s)] = fetch_text_decoder type
end
pg_result.type_map = PG::TypeMapByColumn.new coders
end
def fetch_text_decoder(type)
# decoder inside decoder
# as example array of arrays with integers - type == [:array, :array, :integer]
if type.is_a?(Array)
decoder = new_text_decoder type.shift
assign_elements_type type, decoder
else
new_text_decoder type
end
end
def assign_elements_type(types, parent)
parent.elements_type = if types.count == 1
select_text_decoder(types.shift).new
else
type = types.shift
assign_elements_type(types, select_text_decoder(type))
end
parent
end
def new_text_decoder(type)
select_text_decoder(type).new
end
def select_text_decoder(type)
decoder = { array: PG::TextDecoder::Array,
float: PG::TextDecoder::Float,
boolaen: PG::TextDecoder::Boolean,
integer: PG::TextDecoder::Integer,
date: PG::TextDecoder::TimestampWithoutTimeZone,
hstore: Hstore,
json: PG::TextDecoder::JSON }[type]
raise "Undefined decoder #{type}" unless decoder
decoder
end
end
end
class Hstore < PG::SimpleDecoder
def decode(string, _tuple = nil, _field = nil)
PgHstore.load(string, true) if string.is_a? String
end
end
end
|
require_relative "../config/environment"
module Config
module RabbitMQ
CONF = {
host: ENV['RABBITMQ_IP'],
user: ENV['RABBITMQ_USER'],
password: ENV['RABBITMQ_PASS']
}
end
end |
class SessionsController < ApplicationController
def new
render :login
end
def create
employee = Employee.find_by(employee_id: params[:employee_id])
if employee && employee.authenticate(params[:password])
session[:user_id] = employee.id
redirect_to '/home'
else
@error = 'The employee number or password entered is incorrect.'
render :login
end
end
def destroy
session.clear
redirect_to home_path
end
end
|
class EmailListsAccountDefaultToAutomatic < ActiveRecord::Migration
def self.up
change_column :email_lists, :account, :string, :default => :automatic
end
def self.down
change_column :email_lists, :account, :string, :default => nil
end
end
|
#!/usr/bin/ruby
#
#
#
require 'csv';
bbe = `which bbe`.chomp
floatconv = 'fc'
floatconv_src = 'floatToBits.cpp'
date = `date +%s`
tmpfile = "tmp#{date}".chomp
logfile = "#{tmpfile}.log"
id_key="\\xba\\xda\\xba\\xab"
off_key="\\xda\\xda\\xda\\xad"
slope_key="\\xca\\xda\\xca\\xac"
await_input = 1
def usage
puts "Parameters: PIP_IMAGE TEMP_FILE START END"
puts " PIP_IMAGE - Binary output file from CCS"
puts " TEMP_FILE - CSV containing temperature data"
puts " START - First PIP ID"
puts " END - Last PIP ID"
end
def failedImage
puts "+------------------------+"
puts "| |"
puts "| FLASHING FAILURE |"
puts "| |"
puts "+------------------------+"
puts ""
puts "Press any key to try again"
puts "or [Ctrl]+C to quit."
readline
end
def replaceHex(filename, search, replace)
end
###################################
unless ARGV.length == 4
usage
exit 1
end
infile = ARGV[0]
temp_offset_file = ARGV[1]
start_idx = ARGV[2].to_i
end_idx = ARGV[3].to_i
tempData = Hash.new
CSV.foreach(temp_offset_file) do |row|
id,slope,offset = row
tempData[id] = slope, offset
end
puts "Using temporary file #{tmpfile}"
index = start_idx
until index > end_idx
new_id=sprintf("%08x",index)
if await_input == 1
puts "Please attach PIP #{index}"
puts "Press [ENTER] to continue or 's' to skip"
response = STDIN.readline.chomp
if response == 's'
index += 1
next
end
end
await_input = 1
id1=new_id[0,2]
id2=new_id[2,2]
id3=new_id[4,2]
id4=new_id[6,2]
bbecmd = "s/#{id_key}/\\x#{id4}\\x#{id3}\\x#{id2}\\x#{id1}/"
`#{bbe} -o #{tmpfile} -e "#{bbecmd}" #{infile}`
success=$?.success?
unless success
failedImage
next
end
slope,offset = tempData[index.to_s]
unless slope == nil
puts "Setting slope: #{slope}, and offset: #{offset}"
slope_long = `./fc #{slope}`
offset_long = `./fc #{offset}`
id1=slope_long[0,2]
id2=slope_long[2,2]
id3=slope_long[4,2]
id4=slope_long[6,2]
bbecmd = "s/#{slope_key}/\\x#{id4}\\x#{id3}\\x#{id2}\\x#{id1}/"
`#{bbe} -o #{tmpfile}.0 -e "#{bbecmd}" #{tmpfile}`
success = $?.success?
unless success
failedImage
next
end
id1=offset_long[0,2]
id2=offset_long[2,2]
id3=offset_long[4,2]
id4=offset_long[6,2]
bbecmd = "s/#{off_key}/\\x#{id4}\\x#{id3}\\x#{id2}\\x#{id1}/"
`#{bbe} -o #{tmpfile} -e "#{bbecmd}" #{tmpfile}.0`
success = $?.success?
unless success
failedImage
next
end
end # No slope/offset data available
puts "Flashing PIP #{index}"
output = `mspdebug rf2500 "prog #{tmpfile}" 2>&1`
success = $?.success?
unless success
if output.include? "usbutil: unable to find a device matching 0451:f432"
puts "USB device changed. Retrying flash"
await_input = 0
next
end
failedImage
next
end
puts "Verifying PIP #{index}"
`mspdebug rf2500 "verify #{tmpfile}" 2>&1`
success = $?.success?
unless success
failedImage
next
end
puts "#######################"
puts "# FLASHING SUCCESSFUL #"
puts "#######################"
puts ""
`rm #{tmpfile} #{tmpfile}.0`
index += 1
end
|
module ApplicationHelper
# helper_method :resource_name, :resource, :devise_mapping, :resource_class
def resource_name
:driver
end
def resource
@resource ||= Driver.new
end
def resource_class
Driver
end
def devise_mapping
@devise_mapping ||= Devise.mappings[:driver]
end
end
|
require 'test_helper'
class SongsControllerTest < ActionController::TestCase
setup do
@song = songs(:one)
end
test "should get index" do
get :index
assert_response :success
end
test "should create song" do
assert_difference('Song.count') do
post :create, params: { song: { album_art: @song.album_art, artist: @song.artist, audio_url: @song.audio_url, genre: @song.genre, title: @song.title } }
end
assert_response 201
end
test "should show song" do
get :show, params: { id: @song }
assert_response :success
end
test "should update song" do
patch :update, params: { id: @song, song: { album_art: @song.album_art, artist: @song.artist, audio_url: @song.audio_url, genre: @song.genre, title: @song.title } }
assert_response 200
end
test "should destroy song" do
assert_difference('Song.count', -1) do
delete :destroy, params: { id: @song }
end
assert_response 204
end
end
|
# -*- mode: ruby -*-
Vagrant::Config.run do |config|
config.vm.box = "centos"
hostname = "192.168.33.11"
config.vm.network :hostonly, hostname
config.vm.provision :chef_solo do |chef|
chef_root = File.expand_path('../chef-repo', __FILE__)
chef.cookbooks_path = ["#{chef_root}/cookbooks", "#{chef_root}/site-cookbooks"]
chef.data_bags_path = "#{chef_root}/data_bags"
if File.exists?("#{chef_root}/nodes/#{hostname}.json")
json_name = "#{hostname}.json"
else
json_name = "node.json"
end
json = JSON.parse(File.read("#{chef_root}/nodes/#{json_name}"))
json.delete("recipes").each do |r|
chef.add_recipe r
end
chef.json.merge!(json)
end
end
|
require 'rails_helper'
RSpec.describe Project, type: :model do
it { should belong_to(:kind).class_name('ProjectKind') }
it { should belong_to :user }
it { should have_many(:assignments) }
it { should validate_presence_of(:name) }
it { should validate_presence_of(:repo_url) }
end
# == Schema Information
#
# Table name: projects
#
# id :integer not null, primary key
# name :string
# repo_url :string
# desc :text
# kind_id :integer not null
# created_at :datetime not null
# updated_at :datetime not null
# user_id :integer
# ruby_version :string default("2"), not null
# database_adapter :string default("postgresql"), not null
# database_name :string default("rails"), not null
# database_username :string default("rails"), not null
# database_password :string default("rails"), not null
# secret :string default(""), not null
# type :string default("RailsProject"), not null
# port :integer default(80)
# db_admin_password :string default("")
#
|
str = "gizmo"
def first_anagram?(str)
str.chars.permutation.to_a.map(&:join)
end
p first_anagram?("gizmo")
def second_anagram?(str1,str2)
str2 = str2.chars
str1 = str1.chars.each do |char|
if !str2.index(char).nil?
str2[str2.index(char)] = ""
end
end
p str2
end
p second_anagram?("elvis", "lives")
p second_anagram?("gizmo", "sally")
def third_anagram?(str1, str2)
str1.chars.sort.join == str2.chars.sort.join
end
p third_anagram?("elvis", "lives")
p third_anagram?("gizmo", "sally")
def fourth_anagram?(str1, str2)
count1 = Hash.new(0)
count2 = Hash.new(0)
str1.chars.each {|el| count1[el] += 1}
str2.chars.each {|el| count2[el] += 1}
count1 == count2
end
p fourth_anagram?("elvis", "lives")
p fourth_anagram?("gizmo", "sally") |
require 'rails_helper'
RSpec.describe Application do
before { @application = FactoryGirl.build(:application) }
subject { @application }
it { should respond_to(:user_id) }
it { should respond_to(:gender) }
it { should respond_to(:birth_day) }
it { should respond_to(:birth_month) }
it { should respond_to(:birth_year) }
it { should respond_to(:race) }
it { should respond_to(:education) }
it { should respond_to(:university) }
it { should respond_to(:other_university) }
it { should respond_to(:travel_origin) }
it { should respond_to(:outside_north_america) }
it { should respond_to(:graduation_season) }
it { should respond_to(:graduation_season) }
it { should respond_to(:major) }
it { should respond_to(:hackathons) }
it { should respond_to(:github) }
it { should respond_to(:linkedin) }
it { should respond_to(:website) }
it { should respond_to(:devpost) }
it { should respond_to(:other_link) }
it { should respond_to(:statement) }
it { should be_valid }
it { should validate_presence_of(:user_id) }
it { should validate_presence_of(:birth_day) }
it { should validate_presence_of(:birth_month) }
it { should validate_presence_of(:birth_year) }
it { should validate_presence_of(:education) }
it { should validate_presence_of(:graduation_season) }
it { should validate_presence_of(:graduation_year) }
it { should validate_presence_of(:hackathons) }
end
|
# frozen_string_literal: true
RSpec.describe OpenApi::SchemaValidator do
describe 'VERSION' do
it 'has a version number' do
expect(OpenApi::SchemaValidator::VERSION).not_to be nil
end
end
describe '.validate!' do
context 'when json is valid' do
subject { described_class.validate!(petstore_json) }
let(:petstore_json) { JSON.parse(petstore_string) }
let(:petstore_string) { File.read('./spec/fixtures/petstore.json') }
it { is_expected.to be_truthy }
end
context 'when json is invalid' do
subject(:validate!) { described_class.validate!(invalid_json) }
let(:invalid_json) { JSON.parse(invalid_string) }
let(:invalid_string) { File.read('./spec/fixtures/invalid.json') }
it { expect { validate! }.to raise_error(JSON::Schema::ValidationError) }
end
end
end
|
# coding: utf-8
class QualityMaintenancesController < ApplicationController
before_filter :auth_required
respond_to :html, :xml, :json
def index
end
def search
@items = QualityMaintenance.order(:title).includes(:participants)
if !params[:q].blank?
@items = @items.where("(title LIKE :q) OR (program LIKE :q) OR (details LIKE :q)", {:q => "%#{params[:q]}%"})
end
if params[:filter].to_i > 0
@items = @items.where("(status = :s AND year(maintenance_date) = :y)", {:s => QualityMaintenance::ACTIVE, :y => params[:filter]})
end
respond_with do |format|
format.html do
render :layout => false
end
end
end
def new
@quality_maintenances = QualityMaintenance.new
render :layout => false
end
def create
raise "User watching must be equal to user logged in" if current_user.id != current_user_watching.id
params[:quality_maintenance][:user_id] = current_user.id
@quality_maintenances = QualityMaintenance.new(params[:quality_maintenance])
@quality_maintenances.status = QualityMaintenance::ACTIVE
@quality_maintenances.last_updated_by = current_user.id
flash = {}
if @quality_maintenances.save
flash[:notice] = "Mantenimiento creado satisfactoriamente."
# LOG
@quality_maintenances.activity_log.create(user_id: current_user.id,
message: "Creó el Mantenimiento\"#{@quality_maintenances.title}\" (ID: #{@quality_maintenances.id}).")
respond_with do |format|
format.html do
if request.xhr?
json = {}
json[:id] = @quality_maintenances.id
json[:title] = @quality_maintenances.title
json[:flash] = flash
render :json => json
else
render :inline => "Esta accion debe ser accesada via XHR"
end
end
end
else
flash[:error] = "No se pudo crear el mantenimiento."
respond_with do |format|
format.html do
if request.xhr?
json = {}
json[:flash] = flash
json[:model_name] = self.class.name.sub("Controller", "").singularize
json[:errors] = {}
json[:errors] = @quality_maintenances.errors
render :json => json, :status => :unprocessable_entity
else
redirect_to @quality_maintenances
end
end
end
end
end
def show
@quality_maintenances = QualityMaintenance.find(params[:id])
render :layout => false
end
def update
@quality_maintenances = QualityMaintenance.find(params[:id])
@quality_maintenances.last_updated_by = current_user.id
previous_status_class = @quality_maintenances.status_class
flash = {}
if @quality_maintenances.update_attributes(params[:quality_maintenance])
flash[:notice] = "Mantenimiento actualizado satisfactoriamente."
respond_with do |format|
format.html do
if request.xhr?
json = {}
json[:id] = @quality_maintenances.id
json[:title] = @quality_maintenances.title
json[:status_text] = @quality_maintenances.status_text
json[:status_class] = @quality_maintenances.status_class
json[:previous_status_class] = previous_status_class
json[:flash] = flash
render :json => json
else
render :inline => "Esta accion debe ser accesada via XHR"
end
end
end
else
flash[:error] = "No se pudo actualizar el mantenimiento."
respond_with do |format|
format.html do
if request.xhr?
json = {}
json[:flash] = flash
json[:model_name] = self.class.name.sub("Controller", "").singularize
json[:errors] = {}
json[:errors] = @quality_maintenances.errors
render :json => json, :status => :unprocessable_entity
else
redirect_to @quality_maintenances
end
end
end
end
end
end
|
class AddTeamIdToTeamProfiles < ActiveRecord::Migration[5.1]
def change
add_column :team_profiles, :team_id, :integer
add_index :team_profiles, :team_id
end
end
|
require 'rails_helper'
RSpec.describe PaymentsController, type: :controller do
describe '#index' do
it 'responds with a 200' do
get :index
expect(response).to have_http_status(:ok)
end
end
describe '#show' do
loan = Loan.create!(funded_amount: 100.0)
let(:payment) { loan.payments.create(amount: 10.0) }
it 'responds with a 200' do
get :show, params: { id: payment.id }
expect(response).to have_http_status(:ok)
end
end
context 'if the loan is not found' do
it 'responds with a 404' do
get :show, params: { id: 10000 }
expect(response).to have_http_status(:not_found)
end
end
describe '#create' do
loan = Loan.create!(funded_amount: 100.0)
it 'responds with a 200' do
post :create, params: { loan_id: loan.id, amount: 10.0 }
expect(response).to have_http_status(:ok)
end
it 'responds with a 422 if amount exceeds outstanding balance' do
post :create, params: { loan_id: loan.id, amount: 10000.0 }
expect(response).to have_http_status(422)
end
end
end
|
class Wiki
include Enumerable
def initialize
@pages = []
end
def each(&block)
@pages.each &block
end
def save!(page)
@pages << page
end
def delete(page_title)
@pages.delete_if do |page|
page.title == page_title
end
end
end
|
require 'spec_helper'
require 'yt/request'
describe Yt::Request do
subject(:request) { Yt::Request.new host: 'example.com' }
let(:response) { response_class.new nil, nil, nil }
let(:response_body) { }
describe '#run' do
context 'given a request that returns' do
before { allow(response).to receive(:body).and_return response_body }
before { expect(Net::HTTP).to receive(:start).once.and_return response }
context 'a success code 2XX' do
let(:response_class) { Net::HTTPOK }
it { expect{request.run}.not_to fail }
end
context 'an error code 5XX' do
let(:response_class) { Net::HTTPServerError }
let(:retry_response) { retry_response_class.new nil, nil, nil }
before { allow(retry_response).to receive(:body) }
before { expect(Net::HTTP).to receive(:start).at_least(:once).and_return retry_response }
context 'every time' do
let(:retry_response_class) { Net::HTTPServerError }
it { expect{request.run}.to fail }
end
context 'but returns a success code 2XX the second time' do
let(:retry_response_class) { Net::HTTPOK }
it { expect{request.run}.not_to fail }
end
end
context 'an error code 403 with a "quota exceeded message"' do
let(:response_class) { Net::HTTPForbidden }
let(:retry_response) { retry_response_class.new nil, nil, nil }
let(:response_body) { "{\n \"error\": {\n \"errors\": [\n {\n \"domain\": \"youtube.quota\",\n \"reason\": \"quotaExceeded\",\n \"message\": \"The request cannot be completed because you have exceeded your \\u003ca href=\\\"/youtube/v3/getting-started#quota\\\"\\u003equota\\u003c/a\\u003e.\"\n }\n ],\n \"code\": 403,\n \"message\": \"The request cannot be completed because you have exceeded your \\u003ca href=\\\"/youtube/v3/getting-started#quota\\\"\\u003equota\\u003c/a\\u003e.\"\n }\n}\n" }
before { allow(retry_response).to receive(:body) }
before { expect(Net::HTTP).to receive(:start).at_least(:once).and_return retry_response }
context 'every time' do
let(:retry_response_class) { Net::HTTPForbidden }
it { expect{request.run}.to fail }
end
context 'but returns a success code 2XX the second time' do
let(:retry_response_class) { Net::HTTPOK }
it { expect{request.run}.not_to fail }
end
end
context 'an error code 401' do
let(:response_class) { Net::HTTPUnauthorized }
it { expect{request.run}.to fail }
end
context 'any other non-2XX error code' do
let(:response_class) { Net::HTTPNotFound }
it { expect{request.run}.to fail }
end
end
# TODO: clean up the following tests, removing repetitions
context 'given a request that raises' do
before { expect(Net::HTTP).to receive(:start).once.and_raise http_error }
# NOTE: This test is just a reflection of YouTube irrational behavior of
# being unavailable once in a while, and therefore causing Net::HTTP to
# fail, although retrying after some seconds works.
context 'an OpenSSL::SSL::SSLError' do
let(:http_error) { OpenSSL::SSL::SSLError.new }
context 'every time' do
before { expect(Net::HTTP).to receive(:start).at_least(:once).and_raise http_error }
it { expect{request.run}.to fail }
end
context 'but works the second time' do
before { expect(Net::HTTP).to receive(:start).at_least(:once).and_return retry_response }
before { allow(retry_response).to receive(:body) }
let(:retry_response) { Net::HTTPOK.new nil, nil, nil }
it { expect{request.run}.not_to fail }
end
end
# NOTE: This test is just a reflection of YouTube irrational behavior of
# being unavailable once in a while, and therefore causing Net::HTTP to
# fail, although retrying after some seconds works.
context 'an Errno::ETIMEDOUT' do
let(:http_error) { Errno::ETIMEDOUT.new }
context 'every time' do
before { expect(Net::HTTP).to receive(:start).at_least(:once).and_raise http_error }
it { expect{request.run}.to fail }
end
context 'but works the second time' do
before { expect(Net::HTTP).to receive(:start).at_least(:once).and_return retry_response }
before { allow(retry_response).to receive(:body) }
let(:retry_response) { Net::HTTPOK.new nil, nil, nil }
it { expect{request.run}.not_to fail }
end
end
# NOTE: This test is just a reflection of YouTube irrational behavior of
# being unavailable once in a while, and therefore causing Net::HTTP to
# fail, although retrying after some seconds works.
context 'an Errno::ENETUNREACH' do
let(:http_error) { Errno::ENETUNREACH.new }
context 'every time' do
before { expect(Net::HTTP).to receive(:start).at_least(:once).and_raise http_error }
it { expect{request.run}.to fail }
end
context 'but works the second time' do
before { expect(Net::HTTP).to receive(:start).at_least(:once).and_return retry_response }
before { allow(retry_response).to receive(:body) }
let(:retry_response) { Net::HTTPOK.new nil, nil, nil }
it { expect{request.run}.not_to fail }
end
end
# NOTE: This test is just a reflection of YouTube irrational behavior of
# being unavailable once in a while, and therefore causing Net::HTTP to
# fail, although retrying after some seconds works.
context 'an Errno::EHOSTUNREACH' do
let(:http_error) { Errno::EHOSTUNREACH.new }
context 'every time' do
before { expect(Net::HTTP).to receive(:start).at_least(:once).and_raise http_error }
it { expect{request.run}.to fail }
end
context 'but works the second time' do
before { expect(Net::HTTP).to receive(:start).at_least(:once).and_return retry_response }
before { allow(retry_response).to receive(:body) }
let(:retry_response) { Net::HTTPOK.new nil, nil, nil }
it { expect{request.run}.not_to fail }
end
end
# NOTE: This test is just a reflection of YouTube irrational behavior of
# being unavailable once in a while, and therefore causing Net::HTTP to
# fail, although retrying after some seconds works.
context 'an OpenSSL::SSL::SSLErrorWaitReadable', ruby21: true do
let(:http_error) { OpenSSL::SSL::SSLErrorWaitReadable.new }
context 'every time' do
before { expect(Net::HTTP).to receive(:start).at_least(:once).and_raise http_error }
it { expect{request.run}.to fail }
end
context 'but works the second time' do
before { expect(Net::HTTP).to receive(:start).at_least(:once).and_return retry_response }
before { allow(retry_response).to receive(:body) }
let(:retry_response) { Net::HTTPOK.new nil, nil, nil }
it { expect{request.run}.not_to fail }
end
end
# NOTE: This test is just a reflection of YouTube irrational behavior of
# being unavailable once in a while, and therefore causing Net::HTTP to
# fail, although retrying after some seconds works.
context 'a SocketError', ruby21: true do
let(:http_error) { SocketError.new }
context 'every time' do
before { expect(Net::HTTP).to receive(:start).at_least(:once).and_raise http_error }
it { expect{request.run}.to fail }
end
context 'but works the second time' do
before { expect(Net::HTTP).to receive(:start).at_least(:once).and_return retry_response }
before { allow(retry_response).to receive(:body) }
let(:retry_response) { Net::HTTPOK.new nil, nil, nil }
it { expect{request.run}.not_to fail }
end
end
end
end
end
|
RSpec.describe Telegram::Bot::UpdatesController do
include_context 'telegram/bot/updates_controller'
let(:params) { {arg: 1, 'other_arg' => 2} }
let(:respond_type) { :photo }
let(:result) { double(:result) }
let(:payload_type) { :message }
let(:payload) { {message_id: double(:message_id), chat: chat} }
let(:chat) { {id: double(:chat_id)} }
shared_examples 'missing chat' do
context 'when chat is missing' do
let(:payload_type) { :some_type }
it { expect { subject }.to raise_error(/chat/) }
end
end
describe '#respond_with' do
subject { controller.respond_with respond_type, params }
include_examples 'missing chat'
it 'sets chat_id & reply_to_message_id' do
expect(bot).to receive("send_#{respond_type}").
with(params.merge(chat_id: chat[:id])) { result }
should eq result
end
end
describe '#reply_with' do
subject { controller.reply_with respond_type, params }
include_examples 'missing chat'
it 'sets chat_id & reply_to_message_id' do
expect(bot).to receive("send_#{respond_type}").with(params.merge(
chat_id: chat[:id],
reply_to_message_id: payload[:message_id],
)) { result }
should eq result
end
context 'when update is not set' do
let(:controller_args) { [bot, chat: deep_stringify(chat)] }
it 'sets chat_id' do
expect(bot).to receive("send_#{respond_type}").
with(params.merge(chat_id: chat[:id])) { result }
should eq result
end
end
end
describe '#edit_message' do
subject { controller.edit_message(type, params) }
let(:type) { :reply_markup }
it { expect { subject }.to raise_error(/Can not edit message without/) }
context 'when inline_message_id is present' do
let(:payload) { {inline_message_id: double(:message_id)} }
it 'sets inline_message_id' do
expect(bot).to receive("edit_message_#{type}").with(params.merge(
inline_message_id: payload[:inline_message_id],
)) { result }
should eq result
end
end
context 'when message is present' do
let(:payload) { {message: super().merge(chat: chat)} }
it 'sets chat_id & message_id' do
expect(bot).to receive("edit_message_#{type}").with(params.merge(
message_id: payload[:message][:message_id],
chat_id: payload[:message][:chat][:id],
)) { result }
should eq result
end
end
end
end
|
# encoding: utf-8
control "V-52205" do
title "The DBMS must support the requirement to back up audit data and records onto a different system or media than the system being audited on an organization-defined frequency."
desc "Protection of log data includes assuring log data is not accidentally lost or deleted. Backing up audit records to a different system or onto media separate from the system being audited on an organizational-defined frequency helps to assure, in the event of a catastrophic system failure, the audit records will be retained.false"
impact 0.5
tag "check": "Check with the database administrator, storage administrator or system administrator, as applicable at the site, to verify that Oracle is configured EITHER to perform backups of the audit data specifically, OR, with appropriate permissions granted, to permit a third-party tool to do so. Test the backup process. Test the restore process (using a non-production system as the target).
If Oracle is not so configured, this is a finding. If the test run of the backup and restore fails, this is a finding."
tag "fix": "Utilize DBMS features or other software that supports the ability to back up audit data and records onto a system or media different from the system being audited on an organization-defined frequency.
EITHER use Oracle features (such as Backup or Data Pump) to perform backups of the audit data specifically, OR grant appropriate permissions to permit a third-party tool to do so."
# Write Check Logic Here
end |
module Jobs
class MessageDeliveryJob < Struct.new(:delivery_id)
include ResourceMixIn
def perform
@delivery = Delivery.find(delivery_id)
@message = @delivery.message
deliver
end
def deliver
unless @delivery.delivered?
send_delivery
@delivery.delivered!
end
end
def send_delivery
resource(@delivery).post @delivery.to_xml, :content_type => :xml, :accept => :xml
end
end
end
|
class DataTable
private
def method_missing( method, *args )
method_name = method.to_s
case method_name
when /^(get_)?(first|last)_row$/
index = /first|last/.match( method_name )[0].eql?( 'first' ) ? 0 : -1
row( index )
when /^(get_)?row_\d+$/
index = /\d+/.match( method_name )[0]
row( index )
when /^(get_)?row_count$/
self.size
when /^del(ete)?_row_\d+$/
index = /\d+/.match( method_name )[0]
delete_row( index )
end
end
end
|
class LinkedListNode
attr_accessor :value, :next_node
def initialize(value, next_node=nil)
@value = value
@next_node = next_node
end
end
def print_values(list_node)
if list_node
print "#{list_node.value} --> "
print_values(list_node.next_node)
else
print "nil\n"
return
end
end
#-----------------------------------
# Turtle and Bunny
#
# turtle == firstNode
# bunny == firstNode
# if bunny == end
# return 'False, No loop found'
# bunny = bunny.next
# turtle = turtle.next
# if bunny == turtle
# return 'True, Loop found'
# need to show bunny is going faster than the turtle
# to prove there is a loop
#-----------------------------------
node1 = LinkedListNode.new(37)
node2 = LinkedListNode.new(99, node1)
node3 = LinkedListNode.new(12, node2)
node1.next_node = node3
print_values(node3)
|
class App < ApplicationRecord
include Level
has_many :tokens, dependent: :destroy
validates :name, presence: true, uniqueness: true, length: { maximum: 255 }
validates :level, presence: true
validates :redirect_uri, presence: true, uri: { query: false }, allow_nil: true
before_create do
self.client_id = UUIDTools::UUID.timestamp_create
self.client_secret = UUIDTools::UUID.random_create
end
after_save do
destroy_invalid_tokens if changed_attributes[:level]
end
# Fetch preset app by symbol
def self.[](sym)
params =
case sym
when :weixin then { name: 'weixin', level: 'standard' }
else return nil
end
App.find_by(params) || App.create(params)
end
private
def destroy_invalid_tokens
Token.where("level > #{App.levels[level]}", app: self).destroy_all
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
User.destroy_all
Company.destroy_all
u1 = User.create!(username: "alex", first_name: "Alex", last_name: "Chin", password: "password", password_confirmation: "password")
u2 = User.create!(username: "mike", first_name: "Mike", last_name: "Hayden", password: "password", password_confirmation: "password")
u3 = User.create!(username: "rane", first_name: "Rane", last_name: "Gowan", password: "password", password_confirmation: "password")
c1 = u1.companies.create!(ticker: "APPL", cost: 33000, revenue: 55000)
c2 = u2.companies.create!(ticker: "AIM", cost: 3000, revenue: 5000)
c3 = u1.companies.create!(ticker: "BARC.L", cost: 333000, revenue: 535000)
c4 = u3.companies.create!(ticker: "BP.L", cost: 33000, revenue: 550)
|
class Ability
include CanCan::Ability
def initialize(user)
# alias_action :create, :edit, :update, :destroy, :to => :crud
can :manage, Story, :user_id => user.id
can :read, Story
can :create, Comment
end
end |
class StocksController < ApplicationController
before_filter :authenticate_user!, except: [:index]
before_action :set_stock, only: [:show, :edit, :edit_ppsr, :update, :update_ppsr, :destroy]
# GET /stocks
# GET /stocks.json
def index
@stocks = Stock.all.reorder("serial_number DESC")
end
# GET /stocks/1
# GET /stocks/1.json
def show
@stock = Stock.find(params[:id])
@items = @stock.item
@stock_audits = @stock.stock_audit
end
def stock_location
@stocks = Stock.all
end
# GET /stocks/filter/Ordered
def status_filter
@stock_status = params[:stock_status]
@stocks = Stock.select { |stock| stock.status == @stock_status }
end
# GET /stocks/new
def new
@stock = Stock.new
if @stock.shipping_date != nil
@formatted_shipping_date = @stock.shipping_date.strftime('%d-%m-%Y')
end
end
# GET /stocks/1/edit
def edit
if @stock.shipping_date != nil
@formatted_shipping_date = @stock.shipping_date.strftime('%d-%m-%Y')
end
end
def edit_ppsr
@stock = Stock.find(params[:id])
if @stock.shipping_date != nil
@formatted_date = @stock.shipping_date.strftime('%d-%m-%Y')
end
end
def export
@stocks = Stock.select { |stock| stock.job_id != nil }
respond_to do |format|
format.html
format.csv { send_data @stocks.as_csv }
format.xls
end
end
# GET /stocks/import
def import
end
# POST /items/import
def import_file
begin
Stock.import(params[:file])
redirect_to root_url, notice: "Stock imported. Duplicates are Ignored."
rescue
redirect_to root_url, notice: "Invalid CSV file format."
end
end
# POST /stocks
# POST /stocks.json
def create
@job = Job.find_by job_number: stock_params[:job_number]
params[:stock].delete :job_number
@stock = Stock.new(stock_params)
@stock.accounts_signoff = 0
@stock.projects_signoff = 0
if @job != nil
@stock.job_id = @job.id
end
@stock_audit = StockAudit.new
@stock_audit.stock = @stock
@stock_audit.user = current_user
@stock_audit.audit_params = "#{stock_params}"
respond_to do |format|
if @stock.save
@stock_audit.comment = "has created the new stock item #{@stock.id}"
@stock_audit.save
format.html { redirect_to @stock, notice: 'Stock was successfully created.' }
format.json { render action: 'show', status: :created, location: @stock }
else
format.html { render action: 'new' }
format.json { render json: @stock.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /stocks/1
# PATCH/PUT /stocks/1.json
def update
@job = Job.find_by job_number: stock_params[:job_number]
if @job != nil
@job_user = @job.user
end
params[:stock].delete :job_number
if @job_user != nil
if @stock.status == stock_params[:status]
@status_updated = false
else
@project_manager = @job.user
@status_updated = true
end
end
@stock.update(stock_params)
if @job != nil
@stock.job_id = @job.id
else
@stock.job_id = nil
end
@stock_audit = StockAudit.new
@stock_audit.user = current_user
@stock_audit.stock = @stock
@stock_audit.comment = "updated stock"
@stock_audit.audit_params = "#{stock_params}"
respond_to do |format|
if @stock.save
@stock_audit.save
if @status_updated
if @project_manager != nil
UserMailer.status_update(@project_manager, @stock, current_user).deliver
else
UserMailer.jim_status_update(@stock, current_user).deliver
end
if @stock.status == "Production Complete"
UserMailer.production_notify_accounts(@stock, current_user).deliver
if @project_manager != nil
UserMailer.production_notify_pm(@stock, current_user).deliver
end
end
end
format.html { redirect_to @stock, notice: 'Stock was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @stock.errors, status: :unprocessable_entity }
end
end
end
def update_ppsr
@stock.update(stock_params)
@stock_audit = StockAudit.new
@stock_audit.user = current_user
@stock_audit.stock = @stock
@stock_audit.audit_params = "#{stock_params}"
@stock_audit.comment = "updated ppsr"
respond_to do |format|
if @stock.save
@stock_audit.save
format.html { redirect_to @stock, notice: 'Stock PPSR was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @stock.errors, status: :unprocessable_entity }
end
end
end
# DELETE /stocks/1
# DELETE /stocks/1.json
def destroy
@stock_audit = StockAudit.new
@stock_audit.user = current_user
@stock_audit.stock = @stock
@stock_audit.comment = "destroyed stock unit with an ID of #{@stock.id}"
@stock_audit.save
@stock.destroy
respond_to do |format|
format.html { redirect_to stocks_url }
format.json { head :no_content }
end
end
def bulk_edit_stock
@order = Order.find(params[:id])
@stock = @order.stock
end
def bulk_process_stock
end
def accounts_signoff
@stock = Stock.find(params[:id])
@stock.accounts_signoff = 1
@user_audit = StockAudit.new(stock_id: @stock.id, user_id: current_user.id, comment: "has signed off for accounts")
if @stock.save
@user_audit.save
if @stock.projects_signoff == 1
@stock.update(status: "Ready to Dispatch")
StockAudit.create(user_id: current_user.id, stock_id: @stock.id, comment: "triggered Ready to Dispatch from Accounts Signoff")
if @stock.job.user != nil
UserMailer.status_update(@stock.job.user, @stock, current_user).deliver
end
end
redirect_to @stock, notice: "Accounts Signoff Complete"
else
redirect_to @stock, alert: "something went wrong!"
end
end
def projects_signoff
@stock = Stock.find(params[:id])
@stock.projects_signoff = 1
@user_audit = StockAudit.new(stock_id: @stock.id, user_id: current_user.id, comment: "has signed off for projects")
if @stock.save
@user_audit.save
if @stock.accounts_signoff == 1
@stock.update(status: "Ready to Dispatch")
StockAudit.create(user_id: current_user.id, stock_id: @stock.id, comment: "triggered Ready to Dispatch from Project Signoff")
if @stock.job.user != nil
UserMailer.status_update(@stock.job.user, @stock, current_user).deliver
end
end
redirect_to @stock, notice: "Projects Signoff Complete"
else
redirect_to @stock, alert: "something went wrong!"
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_stock
@stock = Stock.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def stock_params
params.require(:stock).permit(:serial_number, :job_number, :engine_id, :alternator_id, :detail, :status, :status_detail, :gesan_number, :ppsr, :needs_ppsr, :supplier_name, :vin, :shipping_date, :accounts_signoff, :projects_signoff, :location, :ppsr_expiry)
end
end
|
require 'sinatra'
module Feminizeit
class Application < Sinatra::Base
configure do
set :root, File.dirname(__FILE__)
set :logger, $logger
set :public_folder, 'public'
set :raise_errors, false
set :show_exceptions, false
end
not_found do
erb :error
end
error 400..510 do
erb :error
end
get '/' do
erb :home
end
get '/search' do
erb :search
end
get '/about' do
erb :about
end
# get '/about' do
# erb :about
# end
get '/google/normal' do
require 'net/http'
html = Net::HTTP.get(URI google_shop_url(params[:q]))
google_shop_cleaner(html)
end
get '/google/feminizeit' do
require 'net/http'
html = Net::HTTP.get(URI google_shop_url(params[:q] + '%20women'))
html = hide_the_moneymaker_technology(html)
google_shop_cleaner(html)
end
def hide_the_moneymaker_technology(html)
html = html.gsub(/value="(.+?)women/, 'value="\\1')
html = html.gsub(/<b>(wome.+?)<\/b>/i, '')
html.gsub(/<b>(woma.+?)<\/b>/i, '')
end
def google_shop_url(query)
query = query.gsub(' ', '+')
"https://www.google.com/search?output=search&tbm=shop&q=#{query}&oq=#{query}&gs_l=products-cc.3..0l10.27221.28020.0.28134.6.5.1.0.0.0.316.537.4j3-1.5.0.msedr...0...1ac.1.64.products-cc..0.6.540.d3WzbVwsYws&gws_rd=ssl#tbm=shop&q=#{query}"
end
def google_shop_cleaner(html)
html = html.gsub('/images/', 'http://google.com/images/')
html = html.gsub('/xjs/', 'http://google.com/xjs/')
html = html.gsub(/\<div id=gbar.+?\<\/div\>/m, '')
html = html.gsub(/\<div id="_FQd".+?\<\/div\>/m, '')
html.gsub(/\<div id=guse.+?\<\/div\>/m, '')
end
end
end |
require_relative "bloopsaphone/bloops"
class Uncharted
def self.play
new.play
"play"
end
def initialize
@synth ||= Bloops.new
@instrument ||= @synth.sound Bloops::SQUARE
end
attr_reader :synth, :instrument
def play
synth.tune instrument, mary_had_a_little_lamb
synth.play
end
def mary_had_a_little_lamb
intro = "e4 d4 c4 d4 e4 e4 e4 4 d4 d4 d4 4 e4 g4 g4 4"
outro = "e4 d4 c4 d4 e4 e4 e4 c4 d4 d4 e4 d4 c4"
[intro, outro].join(" ")
end
end
|
FactoryBot.define do
factory :item do
text { 'アイウエオ' }
describe { 'かきくけこ' }
category_id { 2 }
status_id { 2 }
charge_id { 2 }
prefecture_id { 2 }
day_id { 2 }
price { 1000 }
association :user
after(:build) do |item|
item.image.attach(io: File.open('public/images/カエルの画像.png'), filename: 'カエルの画像.png')
end
end
end
|
class TimetablesController < ApplicationController
before_action :set_timetable, only: [:destroy]
require 'icalendar'
def create
@timetable = Timetable.new(timetable_params)
@timetable.user = current_user
respond_to do |format|
if @timetable.save
format.html { redirect_to @timetable, notice: 'Timetable was successfully created.' }
format.json { render :show, status: :created, location: @timetable }
else
format.html { render :new }
format.json { render json: @timetable.errors, status: :unprocessable_entity }
end
end
end
def destroy
@timetable.destroy
respond_to do |format|
format.html { redirect_to timetables_url, notice: 'Timetable was successfully destroyed.' }
format.json { head :no_content }
end
end
def ics_export
@timetables = Timetable.where(user: current_user, festival_id: params[:festival])
respond_to do |format|
format.html
format.ics do
cal = Icalendar::Calendar.new
filename = "Your festival calendar"
@timetables.each do |timetable|
timetable.events.each do |event|
performance = Icalendar::Event.new
performance.dtstart = event.concert.start_time
performance.dtend = event.concert.end_time
performance.summary = "#{event.timetable.festival.name} : #{event.concert.artist.name}"
performance.location = event.concert.stage
cal.add_event(performance)
end
end
cal.publish
render :text => cal.to_ical
# send_data cal.to_ical, type: 'text/calendar', disposition: 'attachment', filename: filename
end
end
end
def get_playlist
@festival = Festival.find(params[:festival])
@timetables = Timetable.where(user: current_user, festival_id: params[:festival])
# .where(user: current_user, festival_id: params[:festival])
spotify_user = RSpotify::User.new(current_user.hash_spotify)
playlist = spotify_user.create_playlist!("Ma playlist pour #{@festival.name}")
tracks = []
@timetables.each do |timetable|
timetable.events.each do |event|
if RSpotify::Artist.search(event.concert.artist.name).first
if RSpotify::Artist.search(event.concert.artist.name).first.top_tracks(:FR).first
track = RSpotify::Artist.search(event.concert.artist.name).first.top_tracks(:FR).first
tracks << track
end
end
end
end
playlist.add_tracks!(tracks)
redirect_to festival_path(@festival)
end
private
# Use callbacks to share common setup or constraints between actions.
def set_timetable
@timetable = Timetable.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def timetable_params
params.require(:timetable).permit(:timetable_id, :concert_id)
end
end
|
FactoryGirl.define do
factory :subject do
code
symbol
name 'Subject name'
unit 'unit'
user
transient do
norm_count 0
end
after(:create) do |subject, evaluator|
create_list(:norm, evaluator.norm_count, subject: subject)
end
end
end
|
require_relative "../onebus/my_crawler.rb"
require_relative "../onebus/my_data_parser.rb"
require 'json'
describe OneBus::DataParser do
before(:all) do
#test the boundary cases
@params1 = {
from: 69,
going_to: 64,
departure_at: DateTime.new(2014,4,2),
}
@source1=OneBus::Crawler.crawl(@params1)
@params2 = {
from: 00,
going_to: 00,
departure_at: DateTime.new(2014,5,8),
}
@source2=OneBus::Crawler.crawl(@params2)
#test the main functionality part
@params3 = {
from: 69,
going_to: 65,
departure_at: DateTime.new(2014,4,5),
}
@source3=OneBus::Crawler.crawl(@params3)
@source_hash3= JSON.parse(@source3)
end
it "should return uncatched throw" do
expect{OneBus::DataParser.giveResults(@source1,@params1[:from],@params1[:going_to])}.to raise_error
end
it "should return uncatched throw" do
expect{OneBus::DataParser.giveResults(@source2,@params2[:from],@params2[:going_to])}.to raise_error
end
it "should return proper cities names" do
source_city, destination_city = OneBus::DataParser.city(@source_hash3,@params3[:from],@params3[:going_to])
source_city.should eql "Düsseldorf"
destination_city.should eql "Magdeburg"
end
it "should return date time objects of departure date" do
source_station_date =
OneBus::DataParser.get_time_table(@source_hash3["payload"]["itemList"][0]["ConnectionSectionList"][0],
"DayFrom",
"TimeofdayFrom")
@params3[:departure_at].to_date.should eql source_station_date.to_date
end
end |
class ExportCustomersReportMailer < ActionMailer::Base
include ActionView::Helpers::TextHelper
include ActionView::Helpers::NumberHelper
default :from => "no-reply@zenmaid.com"
def customers_export_report(csv_file, user)
attachments["export.csv"] = csv_file
mail(to: ['arun@zenmaid.com', 'amar@zenmaid.com'], subject: "Customer export for #{user.id}, #{user.user_profile.company_name}")
end
end
|
class Tree_Node
attr_accessor :parent, :children, :value
def initialize(value, parent= [], children = [])
@value = value
@parent = parent
@children = children
end
def remove_child(child)
child.parent = nil
@children.delete(child) || nil
end
def dup
return Tree_Node.new(self.value) if self.children.empty?
new_tree = Tree_Node.new(self.value)
self.children.each do |child|
new_tree.add_child(child.dup)
end
new_tree
end
def sum
self.value + self.children.map(&:sum).inject(:+)
end
def add_child(child)
child.parent.remove_child(child) unless child.parent.empty?
child.parent = self
@children << child
child
end
def dfs(search_value)
return self if self.value == search_value
@children.each do |child|
val = child.dfs(search_value)
return val unless val.nil?
end
nil
end
def bfs (search_value)
queue = [self]
until queue.empty?
current_node = queue.shift
return current_node if search_value == current_node.value
queue += current_node.children
end
nil
end
end
class KnightPathFinder
attr_reader :new_tree
def initialize(start_position)
@start_position = start_position
@new_tree = Tree_Node.new(@start_position)
build_move_tree(@new_tree)
end
def find_path(end_position)
#use breadth-first search to recursively find the shortest path #and print it
get_path(@new_tree.bfs(end_position)).each do |step|
p step.value
end
end
def build_move_tree(node, generated_moves=[])
children = create_move(node)
return if children.nil?
children.each do |child_cords|
next if generated_moves.include?(child_cords)
generated_moves << child_cords
node.add_child(Tree_Node.new(child_cords))
end
node.children.each do |child|
build_move_tree(child, generated_moves)
end
nil
end
def get_path(end_node)
path = []
until end_node == []
path << end_node
end_node = end_node.parent
end
path.reverse
end
def create_move(position)
possible_moves = []
possible_move_coords = [
[1, 2], [2, 1], [-1, -2], [-2, -1],
[1, -2], [2, -1], [-1, 2], [-2, 1]
]
possible_move_coords.map do |coords|
x, y = coords
px, py, = position.value
possible_moves << [px+x, py+y] unless invalid_move?([px+x, py+y])
end
possible_moves
end
def invalid_move?(position)
position.any? {|cord| cord > 7 || cord < 0 }
end
end
# kp.find_path([7, 7])
# kp = KnightPathFinder.new([0,0])
root = Tree_Node.new(1)
root.add_child(Tree_Node.new(2)).add_child(Tree_Node.new(5))
root.add_child(Tree_Node.new(3)).add_child(Tree_Node.new(4))
root.sum
|
class ApplicationController < ActionController::Base
before_action :set_start_time
def set_start_time
@start_time = Time.now
end
end
|
class ProfilesController < ApplicationController
before_action :authenticate_user!, only: [:create, :edit, :update]
def create
end
def edit
@profile = found_profile
verify_edit(@profile)
end
def update
@profile = found_profile
new_profile = profile_params
if verify_update(@profile, new_profile)
@profile.update_attributes(new_profile)
redirect_to profile_path(id: @profile.id), notice: 'Your profile has been updated successfully!'
end
end
private
def found_profile
Profile.find_by_id(params[:id])
end
def profile_params
params.require(:profile).permit(:bio, :url, :stage_name, :image)
end
def owner?(profile, message = 'You are not the owner of this profile.')
return true if profile.user_id == current_user.id
redirect_to profile_path(profile), alert: message
false
end
def verify_edit(profile)
return true if profile && owner?(profile)
redirect_to profile_path, alert: 'Oops! Profile not found.' if profile.blank?
false
end
def verify_update(old_profile, new_profile, message = 'Oops! It looks like you forgot to enter a bio.')
if new_profile[:bio].blank?
redirect_to edit_profile_path, id: old_profile.id, alert: message
return false
end
return true if owner?(old_profile)
false
end
end
|
require 'rails_helper'
RSpec.describe Member, type: :model do
it {should validate_presence_of(:first_name)}
it {should validate_presence_of(:last_name)}
it {should validate_presence_of(:gender_code)}
it {should validate_presence_of(:member_type)}
it {should validate_presence_of(:member_source_type)}
it {should validate_presence_of(:account_status_type)}
it {should validate_presence_of(:user)}
it {should belong_to(:user)}
it {should belong_to(:member_type)}
it {should belong_to(:member_source_type)}
it {should belong_to(:account_status_type)}
it {should have_many(:member_contact)}
it {should have_many(:member_address)}
end
|
class Pulmonary::InhalerDevicesController < ApplicationController
before_action :authenticate_user!
before_action :set_inhaler_device, only: [ :edit, :update ]
load_and_authorize_resource
def index
@inhaler_devices = InhalerDevice.order(inhaler_device_type: :asc, active_ingredient_inn: :asc, active_ingredient_trade_name: :asc, medicine_dosage: :asc)
end
def show
redirect_to pulmonary_inhaler_devices_path
end
def new
@inhaler_device = InhalerDevice.new
end
def create
@inhaler_device = InhalerDevice.new(inhaler_device_params)
if @inhaler_device.save
flash[:success] = t('.new-inhaler-device-flash')
redirect_to pulmonary_inhaler_devices_path
else
render :new
end
end
def edit
end
def update
if @inhaler_device.update(inhaler_device_params)
flash[:success] = t('.edit-inhaler-device-flash')
redirect_to pulmonary_inhaler_devices_path
else
render :edit
end
end
private
def inhaler_device_params
params.require(:inhaler_device).permit(
:inhaler_device_type,
:active_ingredient_inn,
:active_ingredient_trade_name,
:medicine_dosage,
:active
)
end
def set_inhaler_device
@inhaler_device = InhalerDevice.find(params[:id])
end
end
|
class StorageTypesController < ApplicationController
before_filter :authenticate_user!
def index
@cloud = Cloud.find(params[:cloud_id])
@storage_types = StorageType.all
end
end |
class User < ActiveRecord::Base
rolify
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :ldap_authenticatable, :database_authenticatable , :rememberable, :trackable, :registerable, :validatable
has_many :widgets
has_many :user_role_mappings
has_and_belongs_to_many :providers
before_validation(on: :create) do
self.email ||= "#{self.login}@enova.com"
end
def update_roles
self.roles = []
if self.email.end_with?('@enova.com')
if not self.left_company?
ldap_groups_to_roles
user_to_roles
end
else
user_to_roles
end
end
def left_company?
employee_type = get_employee_type
(type, date) = employee_type.split('-', 2)
return type == "NLE" && date <= DateTime.now
end
def self.enova_users
self.where("email LIKE (?)", "%@enova.com")
end
def self.get_all_ldap_groups
ldap = User.get_ldap
results = ldap.search(
base: 'ou=groups,ou=corp,dc=enova,dc=com',
filter: Net::LDAP::Filter.eq('objectclass', 'group'),
attributes: %w[ distinguishedName ],
return_result:true
)
groups = []
results.each do |result|
groups << result.distinguishedname.first
end
return groups
end
private
def self.get_ldap
ldap_args = {}
ldap_args[:host] = 'adds.enova.com'
ldap_args[:base] = 'ou=users,ou=corp,dc=enova,dc=com'
ldap_args[:encryption] = :simple_tls
ldap_args[:port] = 636
auth = {}
auth[:username] = 'CN=Adpublic Nhu,OU=NHU,OU=Users,OU=CORP,DC=enova,DC=com'
auth[:password] = 'lJgOQYEDBNQjcJ_gD^btKCGLXmDUy'
auth[:method] = :simple
ldap_args[:auth] = auth
ldap = Net::LDAP.new(ldap_args)
end
def user_to_roles
UserRoleMapping.where(user: self).each do |mapping|
self.add_role(mapping.role)
end
end
def ldap_groups_to_roles
groups = get_ldap_groups
LdapRoleMapping.all.each do |mapping|
if groups.include?(mapping.ldap_group)
self.add_role(mapping.role)
end
end
end
def get_ldap_groups
ldap = User.get_ldap
ldap.search(
base: ldap.base,
filter: Net::LDAP::Filter.eq( "uid", self.login ),
attributes: %w[ memberOf ],
return_result:true
).first.memberof.to_a
end
def get_employee_type
ldap = User.get_ldap
ldap.search(
base: ldap.base,
filter: Net::LDAP::Filter.eq( "uid", self.login ),
attributes: %w[ employeeType ],
return_result:true
).first.employeeType.first
end
end
|
# frozen_string_literal: true
class RegistrationsController < Devise::RegistrationsController
include Roles
after_action :admin_approved, only: [:create]
private
def admin_approved
resource.update!(approved: true) if is_admin? current_user
end
end
|
class AddPublicToIndicators < ActiveRecord::Migration
def change
add_column :indicators, :public, :boolean
end
end
|
class ChangeTypeToLevelToAcademicData < ActiveRecord::Migration
def up
rename_column :academic_data, :type, :level
end
def down
rename_column :academic_data, :level, :type
end
end
|
# $Id$
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe Video do
include ContentSpecHelper
before(:each) do
@video = new_content(:type => :video)
end
it "should not be valid without required attributes" do
@video.should be_valid
@video.title = nil
@video.should_not be_valid
end
it "should be a video type" do
@video.stubs(:transcode).returns(true)
@video.type.should == "Video"
end
end
describe Video, "on create" do
include ContentSpecHelper
before(:each) do
@video = new_content(:type => :video)
end
it "should create object" do
lambda {
@video.save
}.should change(Content, :count).by(1)
end
it "should collect file metadata after file saved" do
@video.expects(:save_metadata).once
@video.save
end
it "should have a duration and bitrate after file saved" do
@video.save
@video.duration.should_not be_nil
end
it "should transcode if valid" do
@video.expects(:transcode).once
@video.save
end
it "should not save attachment" do
@video.stubs(:transcode).returns(true)
@video.save
attachment_processed?(@video).should be_false
end
end
describe Video, "on update" do
include ContentSpecHelper
before(:each) do
@video = create_content(:type => :video)
end
it "should never process metadata" do
@video.expects(:save_metadata).never
@video.update_attributes(:taken_at => Time.now)
end
it "should not process video on validation" do
@video.expects(:save_metadata).never
@video.valid?
end
end
|
class Word
include Mongoid::Document
include Mongoid::Timestamps
has_and_belongs_to_many :courses
field :name, type: String
field :pronounce, type: String
field :content, type: String
end
|
require "test_helper"
class EditingAnArticleAsAUserTest < Capybara::Rails::TestCase
before do
@user = :derek
log_in(@user)
end
def test_creating_an_article_adds_the_article_to_the_user_page
create_article
visit user_path(users(@user))
assert page.has_content? 'Star Wars'
end
def test_creating_an_article_adds_the_user_to_the_article_page
create_article
visit articles_path
page.find('tr', text: 'Star Wars').click_on 'Show'
assert page.has_content? "#{users(@user).email}"
end
def test_editing_an_article_adds_the_article_to_the_user_page
edit_article
visit user_path(users(@user))
assert page.has_content? 'Balboa'
end
def test_editing_an_article_adds_the_user_to_the_article_page
edit_article
visit article_path(articles(:balboa))
assert page.has_content? "#{users(@user).email}"
end
def test_editing_twice_does_not_add_the_article_twice
edit_article
edit_article
visit user_path(users(@user))
refute page.has_content? 'Balboa', count: 2
end
def test_editing_twice_does_not_add_the_user_twice
edit_article
edit_article
visit article_path(articles(:balboa))
refute page.has_content? "#{users(@user).email}", count: 2
end
private
def create_article
visit new_article_path
fill_in 'Title', with: 'Star Wars'
fill_in 'Body', with: 'Star Wars is an amazing series'
click_on 'Create Article'
end
def edit_article
visit edit_article_path(articles(:balboa))
fill_in 'Title', with: 'Balboa'
fill_in 'Body', with: 'Balboa is actually way better than Lindy Hop'
click_on 'Update Article'
end
end
|
class DeleteColumnFromFav < ActiveRecord::Migration
def change
remove_column :favs, :html
remove_column :favs, :javascript
remove_column :favs, :css
end
end
|
require 'colorize'
require './piece.rb'
class Horse < Piece
attr_accessor :number
def initialize(color, number)
super(color)
@number = number
end
def to_string
if color
"H#{number} ".white
else
"H#{number} ".black
end
end
def to_sym
if color
return "h#{number}w".to_sym
else
return "h#{number}b".to_sym
end
end
# returns an array of possible moves from position parameter (an array with 2 elements) (e.g. [0,0] means piece is at position 0,0)
def possible_moves(position, board, color)
out_array = []
x = position[0]
y = position[1]
add_to_move_array(x - 1, y - 2, board, color, out_array)
add_to_move_array(x - 2, y - 1, board, color, out_array)
add_to_move_array(x - 2, y + 1, board, color, out_array)
add_to_move_array(x - 1, y + 2, board, color, out_array)
add_to_move_array(x + 1, y + 2, board, color, out_array)
add_to_move_array(x + 2, y + 1, board, color, out_array)
add_to_move_array(x + 2, y - 1, board, color, out_array)
add_to_move_array(x + 1, y - 2, board, color, out_array)
out_array
end
private
def add_to_move_array(x, y, board, color, move_array)
if x > 7 || x < 0 || y > 7 || y < 0
false
elsif !board[x][y] || board[x][y].color != color
move_array.push([x, y])
true
else
false
end
end
end
|
class AddEntryIdToLike < ActiveRecord::Migration
def change
add_column :user_interactions, :entry_id, :integer
add_index :user_interactions, :entry_id
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.