text stringlengths 10 2.61M |
|---|
class Todo < ActiveRecord::Base
acts_as_list
belongs_to :user
validates :minutes, :task, presence: true
def self.assign_times(startpos)
todo=Todo.where("position > #{startpos}").order("starttime asc").first
if todo.starttime != nil
starting_time = todo.starttime
else
starting_time = Time.zone.now.beginning_of_minute
starting_time_minutes = starting_time.min % 5
case starting_time_minutes
when 0
starting_time += 5.minutes
when 1
starting_time += 4.minutes
when 2
starting_time += 3.minutes
when 3
starting_time += 7.minutes
else
starting_time += 6.minutes
end
end
Todo.where("position > #{startpos}").order("position asc").each do |todo|
if todo.position == 1
ending_time = starting_time + todo.minutes.minutes
todo.update_attributes(:starttime => starting_time)
todo.update_attributes(:endtime => ending_time)
else
last_position = todo.position - 1
last_position_endtime = Todo.find_by_position(last_position).endtime
starting_time = last_position_endtime
ending_time = starting_time + todo.minutes.minutes
todo.update_attributes(:starttime => starting_time)
todo.update_attributes(:endtime => ending_time)
end
end
end
def self.clear_times(startpos)
Todo.where("position > #{startpos}").order("position asc").each do |todo|
todo.update_attributes(:starttime => nil)
todo.update_attributes(:endtime => nil)
todo.update_attributes(:completedtime => nil)
todo.update_attributes(:complete => nil)
end
end
end |
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# username :string not null
# password_digest :string not null
# session_token :string not null
# created_at :datetime not null
# updated_at :datetime not null
#
require 'rails_helper'
RSpec.describe User, type: :model do
subject(:user) { FactoryGirl.build(:user, username: "someusername", password: "password") }
describe 'validations' do
it { should validate_presence_of(:username) }
it { should validate_presence_of(:password_digest) }
it { should validate_presence_of(:session_token) }
it { should validate_length_of(:password).is_at_least(6) }
end
describe 'associations'
describe '::find_by_credentials' do
before { user.save! }
it 'should return user if credentials exists' do
expect(User.find_by_credentials("someusername", "password")).to eq(user)
end
it 'should return nil if credentials does not exist' do
expect(User.find_by_credentials("wrong_someusername", "wrong_password")).to be nil
end
end
describe '#reset_session_token' do
it 'reset the user session token' do
old_session_token = user.session_token
user.reset_session_token!
expect(user.session_token).not_to eq(old_session_token)
end
end
describe '#is_password?' do
context 'if correct password' do
it 'it returns true' do
expect(user.is_password?("password")).to be true
end
end
context 'if incorrect password'do
it 'it returns false' do
expect(user.is_password?("bad_password")).to be false
end
end
end
end
|
# Write methods to implement the multiply, subtract, and divide operations for
# integers. The results of all these are integers. Use only the add operator
def multiply(num1, num2)
result = 0
if num1 > num2
num2.times do
result += num1
end
else
num1.times do
result += num2
end
end
result
end
def negative(num)
if num > 0
"-#{num}".to_f
elsif num < 0
"#{num}"[1..-1].to_f
end
end
def subtract(num1, num2)
num1 + negative(num2)
end
def divide(num1, num2)
result = 0
until num1 < num2
num1 = subtract(num1, num2)
result +=1
end
[result, num1]
end
|
require 'test/unit'
require 'record_roo'
class Product
attr_accessor :key, :name, :price, :category
def initialize fake
end
end
class RecordTest < Test::Unit::TestCase
include RecordRoo
def setup
config_path = File.expand_path("../data", __FILE__)
@filepath = "#{config_path}/products"
@csv_datasource = RecordRoo::DataSource.new "#{@filepath}.csv"
@xlsx_datasource = RecordRoo::DataSource.new "#{@filepath}.xlsx"
@xls_datasource = RecordRoo::DataSource.new "#{@filepath}.xls"
@model = Product
@attributes = [:key, :name, :price, :category]
end
def test_csv_file_parsing
collection = @csv_datasource.parse
assert_instance_of Array, collection
assert_instance_of Array, collection.first
end
def test_xlsx_file_parsing
collection = @xlsx_datasource.parse
assert_instance_of Array, collection
assert_instance_of Array, collection.first
end
def test_xls_file_parsing
collection = @xls_datasource.parse
assert_instance_of Array, collection
assert_instance_of Array, collection.first
end
def test_csv_model_generator
collection = @csv_datasource.model_generator({model: @model, attributes: @attributes})
assert !collection.empty?
assert_instance_of @model, collection.first
end
def test_xlsx_model_generator
collection = @xlsx_datasource.model_generator({model: @model, attributes: @attributes})
assert !collection.empty?
assert_instance_of @model, collection.first
end
def test_xls_model_generator
collection = @xls_datasource.model_generator({model: @model, attributes: @attributes})
assert !collection.empty?
assert_instance_of @model, collection.first
end
end
|
require 'rails_helper'
require './spec/helpers/account'
describe 'User Accounts' do
context 'account creation' do
it 'can create an account' do
visit '/users/sign_up'
fill_in 'user_email', with: 'foo@bar.co.uk'
fill_in 'user_password', with: '123456'
fill_in 'user_password_confirmation', with: '123456'
click_button 'Sign up'
expect(page).to have_content 'Hailo, foo@bar.co.uk'
end
end
context 'authentication' do
context 'clicking on the log out button' do
it 'logs the user out of the site' do
create_an_account
click_link 'Log out'
expect(page).to have_content 'Signed out successfully.'
end
end
context 'clicking on the log in button' do
it 'takes the user to the log in page' do
visit '/'
click_link 'Log in'
expect(page).to have_content 'Log in'
end
end
end
end
|
describe Darklite::Utils do
let(:first_second) do
Time.local(2015, 9, 1, 0, 0, 1)
end
let(:last_second) do
Time.local(2015, 9, 1, 23, 59, 59)
end
let(:sunrise) do
Time.local(2015, 9, 1, 6, 40, 0)
end
let(:sunset) do
Time.local(2015, 9, 1, 19, 39, 0)
end
describe '#convert_to_seconds' do
it 'returns time in seconds' do
expect(described_class.convert_to_seconds(first_second)).to eq(1)
expect(described_class.convert_to_seconds(last_second)).to eq(86_399)
end
end
describe '#estimate_color_temperature' do
it 'is NIGHTTIME_CT from midnight until sunrise' do
expect_color_estimate(first_second, sunrise, sunset, 500)
expect_color_estimate(sunrise, sunrise, sunset, 500)
end
it 'moves to DAYTIME_CT at sunrise' do
expect_color_estimate(sunrise + 1, sunrise, sunset, 499)
expect_color_estimate(sunrise + 600, sunrise, sunset, 153)
end
it 'stays at DAYTIME_CT from after sunrise to before sunset' do
expect_color_estimate(sunrise + 601, sunrise, sunset, 153)
expect_color_estimate(sunset - 1800, sunrise, sunset, 153)
end
it 'moves to EVENING_CT around sunset' do
expect_color_estimate(sunset - 1799, sunrise, sunset, 153)
expect_color_estimate(sunset - 1000, sunrise, sunset, 180)
expect_color_estimate(sunset + 2400, sunrise, sunset, 294)
end
it 'moves to NIGHTTIME_CT after sunset' do
expect_color_estimate(sunset + 2401, sunrise, sunset, 294)
expect_color_estimate(sunset + 5000, sunrise, sunset, 406)
expect_color_estimate(sunset + 7199, sunrise, sunset, 500)
end
it 'is NIGHTTIME_CT after sunset until midnight' do
expect_color_estimate(sunset + 7200, sunrise, sunset, 500)
expect_color_estimate(last_second, sunrise, sunset, 500)
end
end
end
|
class Tree
attr_accessor :children, :value
def initialize(v,parent=nil)
@value = v
@children = []
@parent = lambda { parent }
end
def addChild(v)
newTree = Tree.new(v,self)
end
def parent
@parent.call()
end
def parent=(other)
@parent = lambda {other}
end
end
def List
attr_accessor :head, :tail
def initialize(head=nil)
@head = head
@tail = nil
end
def insert_front(val)
list = List.new(@head)
list.tail = @tail
@head = val
end
end
|
require_relative "my_stack.rb"
class MyStackQueue
def initialize
@push_stack = MyStack.new
@pop_stack = MyStack.new
end
#stack1 [3,2,1] <- top of the stack front of the queue
#stack2 [4,5] <- top of the stack end of the queue
#enequeue
#stack1 [3,2,1,0]
#stack2 [4,5]
#dequeue
#stack1 [3,2,1,0]
#stack2 [4]
#queue [1,2,3,4,5]
def enqueue(ele)
@push_stack.push(ele)
end
def dequeue
@pop_stack.push(@push_stack.pop) until @push_stack.empty?
@pop_stack.pop
end
def size
@pop_stack.count + @push_stack.count
end
def empty?
@pop_stack.empty? && @push_stack.empty?
end
end
test = MyStackQueue.new
test.enqueue(1)
test.enqueue(2)
test.enqueue(3)
p test.dequeue |
module Refinery
module Albums
class Album < Refinery::Core::BaseModel
self.table_name = 'refinery_albums'
attr_accessible :title, :date, :photo_id, :summary, :description, :purchase_link, :position
acts_as_indexed :fields => [:title, :summary, :description, :purchase_link]
validates :title, :presence => true, :uniqueness => true
belongs_to :photo, :class_name => '::Refinery::Image'
end
end
end
|
class Article < ApplicationRecord
has_many :comments, dependent: :destroy
has_many :users, through: :comments
#allows us to delete associated comments along with deleted articles
validates :title, presence: true, length: { minimum: 5 }
validates :text, presence: true, length: {minimum: 2}
#article has many comments
scope :most_recent, -> { order(id: :desc)}
end
|
class StickersController < ApplicationController
def index
@stickers = Sticker.order(:order)
end
end
|
require 'rails_helper.rb'
require_relative '../../db/migrate/20180628172800_add_dimensions_to_attachments.rb'
describe AddDimensionsToAttachments do
let(:rr) { create :reporting_relationship, active: false }
after do
ActiveRecord::Migrator.migrate Rails.root.join('db', 'migrate'), @current_migration
Message.reset_column_information
end
describe '#up' do
before do
@current_migration = ActiveRecord::Migrator.current_version
ActiveRecord::Migrator.migrate Rails.root.join('db', 'migrate'), 20180627210514
Attachment.reset_column_information
end
subject do
ActiveRecord::Migrator.migrate Rails.root.join('db', 'migrate'), 20180628172800
Attachment.reset_column_information
end
it 'Adds dimensions to images' do
message = Message.create!(
reporting_relationship_id: rr.id,
original_reporting_relationship_id: rr.id,
read: false,
inbound: true,
send_at: Time.zone.now,
type: 'TextMessage',
number_from: rr.client.phone_number,
number_to: rr.user.department.phone_number
)
attachment = Attachment.create!(
message: message,
media: Rack::Test::UploadedFile.new(Rails.root.join('spec', 'fixtures', 'fluffy_cat.jpg'), 'image/png')
)
subject
attachment.reload
expect(attachment.dimensions).to eq([3024, 3024])
end
end
end
|
class BakerAndTaylor < BookStore
def initialize(value)
@base_url = "http://www.baker-taylor.com/gs-searchresults.cfm"
@options = {"search" => value}
@results = ".gsc-table-result .gsc-webResult"
@item = "table .gs-title a"
end
end |
class Game < ApplicationRecord
belongs_to :user
def final_score
(self.end_time - self.start_time)
end
end
|
# -*- coding: utf-8 -*-
class UserAvatarAdpater
def initialize(user, raw_file)
@raw_file = raw_file
user_id_str = user.id.to_s
@temp_file_entity = FileEntity.create :attach => raw_file
# @temp_file_dir = File.join(TEMP_FILE_BASE_DIR, user_id_str)
# @temp_file_name = File.join(@temp_file_dir, 'avatar_tmp')
@temp_file_url = "/auth/setting/temp_avatar?entity_id=#{@temp_file_entity.id}"
end
# 获取临时文件图片的宽高hash
def temp_image_size
temp_file = File.new(@temp_file_entity.attach.path)
image = Magick::Image::read(temp_file).first
return {:height=>image.rows, :width=>image.columns}
end
def file_entity
@temp_file_entity
end
def temp_image_url
@temp_file_url
end
# -------------------------------------
def self.crop_logo(user, x1, y1, width, height, file_entity_id)
# user_id_str = user.id.to_s
# temp_file_dir = File.join(TEMP_FILE_BASE_DIR, user_id_str)
# temp_file_name = File.join(temp_file_dir, 'avatar_tmp')
file_entity = FileEntity.find(file_entity_id)
temp_file = File.new(file_entity.attach.path)
# 读取临时文件,裁切,转换格式
img = Magick::Image::read(temp_file).first
img.crop!(x1.to_i, y1.to_i, width.to_i, height.to_i, true)
img.format = 'PNG'
# 写第二个临时文件,裁切好的PNG文件
croped_file = Tempfile.new(["user-#{user.id}", 'png'])
img.write croped_file.path
# 赋值给user.logo (保存到云)
user.update_attributes(:logo=>croped_file)
# 移除临时文件
croped_file.close
croped_file.unlink
file_entity.destroy
end
end
|
class CreateResults < ActiveRecord::Migration
def self.up
create_table :results do |t|
t.integer :score
t.integer :correct
t.integer :wrong
t.references :question, index: true, foreign_key: true
t.timestamps null: false
end
end
def self.down
drop_table :results
end
end |
Rails.application.routes.draw do
resources :tweets
root 'static_pages#home'
match 'help', to: 'static_pages#help', via: 'get'
resources :users
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 bin/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)
require 'faker'
Trainer.destroy_all
Pokemon.destroy_all
10.times do
name = Faker::Name.name
location = Faker::Games::Pokemon.location
trainer = Trainer.create(name: name, location: location)
5.times do
pokemon_name = Faker::Games::Pokemon.name
pokemon_move = Faker::Games::Pokemon.move
pokemon_level = rand(1..99)
trainer.pokemons.create(name: pokemon_name, move: pokemon_move, level: pokemon_level )
end
end
puts "seeded #{Trainer.all.length} trainers and #{Pokemon.all.length} pokemon."
|
module SequelSpec
module Matchers
module Validation
class ValidateNotNullMatcher < ValidateMatcher
def description
desc = "validate that #{@attribute.inspect} is not null"
desc << " with option(s) #{hash_to_nice_string @options}" unless @options.empty?
desc
end
def validation_type
:validates_not_null
end
end
def validate_not_null(attribute)
ValidateNotNullMatcher.new(attribute)
end
end
end
end
|
require "test_helper"
describe Review do
let(:review) { Review.new }
let(:review1) {reviews(:review1)}
it "rating must be present" do
review1.valid?.must_equal true
review1.rating = nil
review1.valid?.must_equal false
review1.save
review1.errors.keys.must_include :rating
end
it "rating must be an integer" do
review1.valid?.must_equal true
review1.rating = 2.3
review1.valid?.must_equal false
review1.rating = "string"
review1.valid?.must_equal false
end
it "rating must be <= 1 and >= 5" do
review1.valid?.must_equal true
review1.rating = -1
review1.valid?.must_equal false
review1.rating = 6
review1.valid?.must_equal false
end
it "has a product" do
review1.valid?.must_equal true
review1.product.must_be_kind_of Product
end
it "must have a product" do
review1.valid?.must_equal true
review1.product = nil
review1.valid?.must_equal false
end
it "title must be present" do
review1.valid?.must_equal true
review1.title = nil
review1.valid?.must_equal false
review1.save
review1.errors.keys.must_include :title
end
it "title should be at least 2 characters long" do
review1.valid?.must_equal true
review1.title = "a"
review1.valid?.must_equal false
review1.save
review1.errors.keys.must_include :title
end
it "title should be at shorter than 100 characters " do
review1.valid?.must_equal true
review1.title = "a" * 101
review1.valid?.must_equal false
review1.save
review1.errors.keys.must_include :title
end
it "review_text must be present" do
review1.valid?.must_equal true
review1.review_text = nil
review1.valid?.must_equal false
review1.save
review1.errors.keys.must_include :review_text
end
it "review_text should be at least 2 characters long" do
review1.valid?.must_equal true
review1.review_text = "t"
review1.valid?.must_equal false
review1.save
review1.errors.keys.must_include :review_text
end
it "review_text should be at shorter than 700 characters " do
review1.valid?.must_equal true
review1.review_text = "n" * 701
review1.valid?.must_equal false
review1.save
review1.errors.keys.must_include :review_text
end
end
|
require 'rails_helper'
describe Room do
it { should belong_to(:home) }
it { should have_many(:temperatures) }
it { should validate_presence_of :name }
it { should validate_presence_of :temp_setting }
end
|
puts "Please write word or multiple words:"
words = gets.chomp
puts "There are #{words.delete(" ").length} characters in '#{words}'"
|
class Device < ActiveRecord::Base
belongs_to :member
belongs_to :division
has_many :proofs
def last_proof
self.proofs.last
end
def ave_de(date_filter)
Device.device_average_de(self, date_filter)
end
def quantities(date_filter)
Device.device_sticker_quantities(date_filter, self)
end
class << self
#put class methods here
def device_average_de(device, date_filter)
if date_filter.patch =~ /^All$/i
# this returns the AVE proof dE
device_average_de_all_patches(device, date_filter)
else
# this returns the average Patch dE
device_average_de_one_patch(device, date_filter)
end
end
def device_sticker_quantities(date_filter, device=nil)
sticker_count = 0
my_query = "SELECT SUM(proofs.sticker_count) as value
FROM proofs, devices
WHERE devices.id = proofs.device_id
AND devices.member_id = #{date_filter.member_id}
AND proofs.proofdate BETWEEN '#{date_filter.get_start_date}' AND '#{date_filter.get_end_date}' "
# this allows us to roll through each device in the chart
if device
my_query += "AND devices.id = #{device.id} "
else
my_query += "AND devices.id = #{date_filter.device.id} " if date_filter.device
end
my_query += "AND proofs.pass = 1 " if date_filter.pass =~ /#{date_filter.member_pref('pass_label')}/i
my_query += "AND proofs.pass = 0 " if date_filter.pass =~ /#{date_filter.member_pref('fail_label')}/i
my_query += "AND proofs.profile_name = '#{date_filter.profile}' " unless date_filter.profile =~ /^All$/i
my_query += "AND proofs.customer = '#{date_filter.customer}' " unless date_filter.customer =~ /^All$/i
my_query += "AND proofs.operator = '#{date_filter.operator}' " unless date_filter.operator =~ /^All$/i
my_query += "AND devices.location = '#{date_filter.location}' " unless date_filter.location =~ /^All$/i
my_query += "AND devices.series = '#{date_filter.series}' " unless date_filter.series =~ /^All$/i
my_query += "GROUP BY devices.id "
# fail my_query.inspect
my_values = find_by_sql [my_query]
if my_values.first
my_values.each do |stickers|
sticker_count += stickers.value.to_i
end
end
sticker_count
end
def device_measurements(date_filter, *conditions) # count of proofs
sticker_count = 0
# Device
if date_filter.device
device = date_filter.device
elsif conditions[0] && conditions[0][:device]
device = conditions[0][:device]
else
device = nil
end
# pass
if conditions[0] && conditions[0][:pass]
pass = conditions[0][:pass]
else
pass = date_filter.pass
end
# location
if not date_filter.location =~ /^All$/i
location = date_filter.location
elsif conditions[0] && conditions[0][:location]
location = conditions[0][:location]
else
location = nil
end
# series
if not date_filter.series =~ /^All$/i
series = date_filter.series
elsif conditions[0] && conditions[0][:series]
series = conditions[0][:series]
else
series = nil
end
# profile
if not date_filter.profile =~ /^All$/i
profile = date_filter.profile
elsif conditions[0] && conditions[0][:profile]
profile = conditions[0][:profile]
else
profile = nil
end
# operator
if not date_filter.operator =~ /^All$/i
operator = date_filter.operator
elsif conditions[0] && conditions[0][:operator]
operator = conditions[0][:operator]
else
operator = nil
end
# customer
if not date_filter.customer =~ /^All$/i
customer = date_filter.customer
elsif conditions[0] && conditions[0][:customer]
customer = conditions[0][:customer]
else
customer = nil
end
my_query = "SELECT COUNT(proofs.id) as value
FROM proofs, devices
WHERE devices.id = proofs.device_id
AND devices.member_id = #{date_filter.member_id}
AND proofs.proofdate BETWEEN '#{date_filter.get_start_date}' AND '#{date_filter.get_end_date}' "
my_query += "AND devices.id = #{device.id} " if device
my_query += "AND devices.series = '#{series}' " if series
my_query += "AND devices.location = '#{location}' " if location
my_query += "AND proofs.pass = 1 " if pass =~ /^Pass$/i
my_query += "AND proofs.pass = 0 " if pass =~ /^Fail$/i
my_query += "AND proofs.profile_name = '#{profile}' " if profile
my_query += "AND proofs.customer = '#{customer}' " if customer
my_query += "AND proofs.operator = '#{operator}' " if operator
my_query += "GROUP BY devices.id "
my_values = find_by_sql [my_query]
my_values = find_by_sql [my_query]
if my_values.first
my_values.each do |stickers|
sticker_count += stickers.value.to_i
end
end
sticker_count
end
def device_proofs_size(date_filter, device=nil)
proof_size = 0
my_query = "SELECT SUM(proofs.proofsize) as value
FROM proofs, devices
WHERE devices.id = proofs.device_id
AND devices.member_id = #{date_filter.member_id}
AND proofs.proofdate BETWEEN '#{date_filter.get_start_date}' AND '#{date_filter.get_end_date}' "
# this allows us to roll through each device in the chart
if device
my_query += "AND devices.id = #{device.id} "
else
my_query += "AND devices.id = #{date_filter.device.id} " if date_filter.device
end
my_query += "AND proofs.pass = 1 " if date_filter.pass =~ /#{date_filter.member_pref('pass_label')}/i
my_query += "AND proofs.pass = 0 " if date_filter.pass =~ /#{date_filter.member_pref('fail_label')}/i
my_query += "AND proofs.profile_name = '#{date_filter.profile}' " unless date_filter.profile =~ /^All$/i
my_query += "AND proofs.customer = '#{date_filter.customer}' " unless date_filter.customer =~ /^All$/i
my_query += "AND proofs.operator = '#{date_filter.operator}' " unless date_filter.operator =~ /^All$/i
my_query += "AND devices.location = '#{date_filter.location}' " unless date_filter.location =~ /^All$/i
my_query += "AND devices.series = '#{date_filter.series}' " unless date_filter.series =~ /^All$/i
my_query += "GROUP BY devices.id "
# fail my_query.inspect
my_values = find_by_sql [my_query]
if my_values.first
my_values.each do |inches|
proof_size += inches.value.to_i
end
end
proof_size
end
def get_device_or_nil(id)
if id == '' then
return nil
else
find(id)
end
end
private
def device_average_de_all_patches(device, date_filter)
# because this is by device it does not need member_id
from = "FROM proofs, devices"
from << ", patches " unless date_filter.patch =~ /^All$/i
my_query = "SELECT FORMAT(AVG(proofs.dE2000),2) as value
FROM proofs, devices
WHERE devices.id = #{device.id}
AND devices.id = proofs.device_id
AND proofs.proofdate BETWEEN '#{date_filter.get_start_date}' AND '#{date_filter.get_end_date}' "
my_query += "AND proofs.pass = 1 " if date_filter.pass =~ /#{date_filter.member_pref('pass_label')}/i
my_query += "AND proofs.pass = 0 " if date_filter.pass =~ /#{date_filter.member_pref('fail_label')}/i
my_query += "AND proofs.profile_name = '#{date_filter.profile}' " unless date_filter.profile =~ /^All$/i
my_query += "AND proofs.customer = '#{date_filter.customer}' " unless date_filter.customer =~ /^All$/i
my_query += "AND proofs.operator = '#{date_filter.operator}' " unless date_filter.operator =~ /^All$/i
my_query += "GROUP BY devices.id "
my_values = find_by_sql [my_query]
if my_values.first
my_values.first.value
else
0.0
end
end
def device_average_de_one_patch(device, date_filter)
# because this is by device it does not need member_id
# patch detail is hard coded into this query
my_query = "SELECT FORMAT(AVG(patches.dE2000),2) as value
FROM proofs, devices, patches
WHERE devices.id = #{device.id}
AND devices.id = proofs.device_id
AND proofs.id = patches.proof_id
AND patches.patch_name = '#{date_filter.patch}'
AND proofs.proofdate BETWEEN '#{date_filter.get_start_date}' AND '#{date_filter.get_end_date}' "
my_query += "AND proofs.pass = 1 " if date_filter.pass =~ /#{date_filter.member_pref('pass_label')}/i
my_query += "AND proofs.pass = 0 " if date_filter.pass =~ /#{date_filter.member_pref('fail_label')}/i
my_query += "AND proofs.profile_name = '#{date_filter.profile}' " unless date_filter.profile =~ /^All$/i
my_query += "AND proofs.customer = '#{date_filter.customer}' " unless date_filter.customer =~ /^All$/i
my_query += "AND proofs.operator = '#{date_filter.operator}' " unless date_filter.operator =~ /^All$/i
my_query += "GROUP BY devices.id "
my_values = find_by_sql [my_query]
if my_values.first
my_values.first.value
else
0.0
end
end
end
end
|
# Problem 321: Swapping Counters
# http://projecteuler.net/problem=321
# A horizontal row comprising of 2n + 1 squares has n red counters placed at one end and n blue counters at the other end, being separated by a single empty square in the centre. For example, when n = 3.
#
# http://projecteuler.net/project/images/p_321_swapping_counters_1.gif
#
# A counter can move from one square to the next (slide) or can jump over another counter (hop) as long as the square next to that counter is unoccupied.
#
# http://projecteuler.net/project/images/p_321_swapping_counters_2.gif
#
# Let M(n) represent the minimum number of moves/actions to completely reverse the positions of the coloured counters; that is, move all the red counters to the right and all the blue counters to the left.
# It can be verified M(3) = 15, which also happens to be a triangle number.
#
# If we create a sequence based on the values of n for which M(n) is a triangle number then the first five terms would be:
# 1, 3, 10, 22, and 63, and their sum would be 99.
#
# Find the sum of the first forty terms of this sequence.
|
class MessageConsumer
include Hutch::Consumer
KEY = 'test.message'
consume KEY
queue_name 'message_consumer'
def process(message)
puts message.payload
end
end
|
class Searchers::UserSearcher
def search(users_relation, query)
users = perform_search(users_relation, query, false)
# If the result set does not contain any results, we need to loosen up our requirements
if users.count == 0
users = perform_search(users_relation, query, true)
end
users
end
def perform_search(users_relation, query, relaxed)
if relaxed
operator = " OR "
else
operator = " AND "
end
query_content = ""
if query.split.count > 1
count = 0
query.split.each do |str|
if count > 0
query_content += operator
end
real_str = str.gsub(/\s+/, "")
real_str_lower = real_str.downcase
query_content += "(LEVENSHTEIN(users.first,'#{real_str}') < 3 OR LEVENSHTEIN(last,'#{real_str}') < 3) OR (lower(users.first) LIKE '%#{real_str_lower}%' OR lower(users.last) LIKE '%#{real_str_lower}%')"
count += 1
end
else
real_query = query.gsub(/\s+/, "")
real_query_lower = real_query.downcase
query_content = "(LEVENSHTEIN(users.first,'#{real_query}') < 3 OR LEVENSHTEIN(last,'#{real_query}') < 3) OR (lower(users.first) LIKE '%#{real_query_lower}%' OR lower(users.last) LIKE '%#{real_query_lower}%')"
end
users_relation.where(query_content)
end
end |
class User < ActiveRecord::Base
has_secure_password
has_many :products, foreign_key: "user_id", dependent: :destroy
validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }
validates :email, uniqueness: { case_sensitive: false }
validates :username, length: { in: 2..15 }
validates :password, length: { in: 2..25 }, presence: true
validates_confirmation_of :password_confirmation
end
|
class Ultrasonic < AbstractReport
has_one :report, as: :specific, dependent: :destroy
has_many :ut_defects, dependent: :destroy
has_many :ut_probes, dependent: :destroy
attr_accessible :equipment,
:sensitivity,
:couplant,
:correction,
:report_attributes,
:ut_defects_attributes,
:calibration_date,
:ut_probes_attributes,
:cable,
:cal_block
accepts_nested_attributes_for :report
accepts_nested_attributes_for :ut_defects, allow_destroy: true
accepts_nested_attributes_for :ut_probes, allow_destroy: true
delegate :uid, to: :report
# after_initialize do |report|
# report.calibration_date ||= Date.today
# end
after_save do |ut|
ut.report.set_uid("UT") unless ut.report.nil?
ut.drop_pdf_path
end
def reject?
result = self.ut_defects.map(&:result).map(&:downcase).include?("reject")
end
def pathname
"ultrasonics"
end
def title
"Ultrasonic".upcase
end
def pdf_path
self.report.pdf_path
end
def deep_dup
ut = Ultrasonic.new
ut = self.dup
self.ut_defects.each do |defect|
ut.ut_defects << defect.dup
end
self.ut_probes.each do |probe|
ut.ut_probes << probe.dup
end
ut
end
end
|
require 'spec_helper'
# Helper method that converts string to the dumped representation
# @param value [String] original string
# @return [String] dump representation
def string_to_dump(value)
parsed_value = Liquid::Template.parse(value)
Base64.strict_encode64(Marshal.dump(parsed_value))
end
RSpec.describe Liquidize::Model do
describe 'include' do
shared_examples 'both' do
it 'adds class methods' do
expect(klass).to respond_to(:liquidize)
end
end
context 'with ActiveRecord' do
let(:klass) { Page }
it_behaves_like 'both'
end
context 'with plain Ruby' do
let(:klass) { NonActiveRecordPage }
it_behaves_like 'both'
end
end
describe '.liquidize' do
shared_examples 'both' do
it 'defines new instance methods' do
expect(page).to respond_to(:liquid_body_template)
expect(page).to respond_to(:parse_liquid_body!)
expect(page).to respond_to(:render_body)
end
end
context 'with ActiveRecord' do
let(:page) { Page.new }
it_behaves_like 'both'
end
context 'with plain Ruby' do
let(:page) { NonActiveRecordPage.new }
it_behaves_like 'both'
end
end
describe '#render_*' do
shared_examples 'both' do
it 'renders valid template' do
page.body = 'Hello, {{username}}!'
expect(page.render_body(username: 'Alex')).to eq('Hello, Alex!')
end
end
context 'with ActiveRecord' do
let(:page) { Page.new }
it_behaves_like 'both'
end
context 'with plain Ruby' do
let(:page) { NonActiveRecordPage.new }
it_behaves_like 'both'
end
end
describe 'setter' do
let(:valid_body) { 'Hi, {{username}}' }
let(:invalid_body) { 'Hi, {{username' }
let(:syntax_error_message) { "Liquid syntax error: Variable '{{' was not properly terminated with regexp: /\\}\\}/" }
shared_examples 'both' do
it 'still works as default setter' do
expect { page.body = valid_body }.to change(page, :body).from(nil).to(valid_body)
end
it 'parses new value' do
expect(page).to receive(:parse_liquid_body!)
page.body = valid_body
end
it 'does not set @*_syntax_error instance variable with valid body' do
page.instance_variable_set(:@body_syntax_error, nil) # prevent warning
expect { page.body = valid_body }.not_to(change { page.instance_variable_get(:@body_syntax_error) })
end
it 'sets @*_syntax_error instance variable with invalid body' do
page.instance_variable_set(:@body_syntax_error, nil) # prevent warning
expect { page.body = invalid_body }.to change { page.instance_variable_get(:@body_syntax_error) }.from(nil).to(syntax_error_message)
end
it 'resets syntax error when valid value is passed' do
page.instance_variable_set(:@body_syntax_error, nil) # prevent warning
expect { page.body = invalid_body }.to change { page.instance_variable_get(:@body_syntax_error) }.from(nil).to(syntax_error_message)
expect { page.body = valid_body }.to change { page.instance_variable_get(:@body_syntax_error) }.from(syntax_error_message).to(nil)
end
end
context 'with ActiveRecord' do
let(:page) { Page.new }
it_behaves_like 'both'
it 'sets liquid_body attribute' do
expect { page.body = valid_body }.to change(page, :liquid_body).from(nil).to(string_to_dump(valid_body))
end
it 'syntaxically correct values does not make record invalid' do
page.body = valid_body
expect(page).to be_valid
end
it 'value with syntax error makes record invalid' do
page.body = invalid_body
expect(page).not_to be_valid
expect(page.errors.messages).to eq(body: [syntax_error_message])
end
it 'does not parse body for the second time if it was already parsed and saved' do
page = Page.create(body: valid_body)
page_from_db = Page.find(page.id)
expect(page_from_db).not_to receive(:parse_liquid_body!)
render = page_from_db.render_body(username: 'Alex')
expect(render).to eq('Hi, Alex')
end
end
context 'with plain Ruby' do
let(:page) { NonActiveRecordPage.new }
it_behaves_like 'both'
end
end
end
|
class Movie < ApplicationRecord
AMOUNT_OF_MOVIES = 4
validates :name, presence: true
belongs_to :category
scope :different_movies, -> (movie) {
where("id <> ?", movie.id).limit(AMOUNT_OF_MOVIES)
}
scope :sorted, -> { order(name: :asc) }
end
|
class Publish::PaymentsController < PublishController
belongs_to :publisher
private
def collection
@payments = Payment.find(:all, :conditions => { :owner_id => current_publisher.id, :owner_type => 'Publisher' }).map do |a|
a if a.is_test_deposit? == false
end.compact
end
end
|
feature "Messages stream" do
scenario "Messages stream is public and can be seen by guests" do
sign_up
sign_in
fill_in :body, with: "This is a test"
click_button "Send"
click_button "Sign Out"
click_link "Conversation"
expect(page).to have_content "This is a test"
end
end |
class RefactorStatusOfFunnelsAndCandidates < ActiveRecord::Migration
def self.up
add_column :candidates, :in_funnel, :boolean, :default => false
add_column :funnels, :result, :text, :size => 32
add_column :funnels, :is_active, :boolean, :default => true
add_index :funnels, :is_active
add_index :candidates, :in_funnel
end
def self.down
remove_column :candidates, :in_funnel
remove_column :funnels, :result
remove_column :funnels, :is_active
remove_index :funnels, :is_active
remove_index :candidates, :in_funnel
end
end
|
class AuthenticationController < ApplicationController
def create
found_user = User.find_by_linkedin_id(params['linkedin_id'])
if found_user == nil
@user = User.new(:linkedin_id => params['linkedin_id'],
:email => params['linkedin_id'] + "@email.com",
:password => "password")
@user.first_name = params["first_name"]
@user.last_name = params["last_name"]
@user.reset_authentication_token
if @user.save!
sign_in @user
user_json = ActiveSupport::JSON.decode(params['user'])
default_identity = create_default_identity(user_json['identity'][0]) unless params['user'] == nil
@user.update_attribute(:default_identity_id, default_identity.id)
render :json => current_user
else
render :status => :bad_request, :text => ""
end
else
sign_in found_user
render :json => current_user
end
end
private
def create_default_identity(identity_data)
new_identity = current_user.identities.new
new_identity.identity_name = "Default Identity"
new_identity.first_name = identity_data['first_name']
new_identity.last_name = identity_data['last_name']
new_identity.twitter = identity_data['twitter']
new_identity.company_name = identity_data['current_position']['company_name'] ||= ""
new_identity.title = identity_data['current_position']['title'] ||= ""
new_identity.industry = identity_data['current_position']['industry'] ||= ""
new_identity.save
new_identity
end
end
|
class CreateMaterialAssignments < ActiveRecord::Migration
def up
create_table :material_assignments do |t|
t.integer :task_id, :null => false
t.integer :material_id, :null => false
t.integer :assignment_id, :null => false
t.integer :qty_sent, :null => false
t.integer :qty_used
t.timestamps
end
end
def down
drop_table :material_assignments
end
end
|
describe DockingStation do
let(:bike) { double(Bike.new) }
context 'Upon creation' do
it 'is empty' do
expect(subject.bikes).to eq []
end
it 'has capacity of 4' do
expect(subject.capacity).to eq 4
end
end
context 'can receive' do
it 'a working bike' do
subject.add_bike(bike)
expect(subject.bikes).to eq [bike]
end
it 'a broken bike' do
allow(bike).to receive(:working) { false }
allow(bike).to receive(:break) { true }
bike.break
subject.add_bike(bike)
expect(bike.working).to be_falsey
end
end
context 'cannot receive a bike' do
it 'when capacity has been reached' do
4.times { subject.add_bike(bike) }
expect { subject.add_bike(bike) }.to raise_error 'DockingStation is full'
end
end
context 'Member of the public accesses the station and it' do
before(:each) do
allow(bike).to receive(:working) { true }
end
it 'releases a working bike' do
subject.add_bike(bike)
subject.release_bike
expect(bike.working).to be_truthy
end
it 'releases one working bike at a time' do
4.times { subject.add_bike(Bike.new) }
subject.release_bike
expect(subject.bikes.length).to eq 3
end
it 'does not release the broken bike' do
subject.add_bike(bike)
bike2 = Bike.new
bike2.break
subject.add_bike(bike2)
bike = subject.release_bike
expect(bike.working).to be_truthy
end
end
context 'The station reports itself empty' do
it 'when there are no bikes available' do
expect { subject.release_bike }.to raise_error 'DockingStation is empty'
end
it 'when there are no working bikes available' do
allow(bike).to receive(:working) { false }
allow(bike).to receive(:break) { true }
bike.break
subject.add_bike(bike)
expect { subject.release_bike }.to raise_error 'No bikes available'
end
end
end |
require 'pry'
BEST_SCORE = 21
TOTAL_WINS = 5
@ranks = %w[2 3 4 5 6 7 8 9 10 Jack Queen King Ace]
@suits = %w[Hearts Spades Diamonds Clubs]
@cards = []
@ranks.each do |rank|
@suits.each do |suit|
@cards << [rank, suit]
end
end
def prompt(msg)
puts "=> #{msg}"
end
def total_value(cards)
values = cards.map { |card| card[0] }
sum = 0
values.each do |value|
sum += if value == 'Ace'
11
elsif value.to_i.zero?
10
else
value.to_i
end
end
values.select { |value| value == 'Ace' }.count.times do
sum -= 10 if sum > BEST_SCORE
end
sum
end
def blackjack?(value)
value == BEST_SCORE
end
def busted?(value)
value > BEST_SCORE
end
def cards_written_out(cards)
if cards.flatten.count == 2
cards.join(' of ')
else
cards.map { |card| card.join(' of ') }.to_s.gsub(/["\[\]]/, '')
end
end
def dealers_cards_and_value
prompt "Dealers cards: #{cards_written_out(@dealers_cards)}"
prompt "Dealers cards value: #{dealers_hand_value}"
end
def players_cards_and_value
prompt "Players cards: #{cards_written_out(@players_cards)}"
prompt "Players cards value: #{players_hand_value}"
end
def shuffle_and_deal
@cards.shuffle!
@players_cards = @cards.shift(2)
@dealers_cards = @cards.shift(2)
end
def dealers_hand_value
total_value(@dealers_cards)
end
def players_hand_value
total_value(@players_cards)
end
def detect_result
if players_hand_value > BEST_SCORE
:player_busted
elsif dealers_hand_value > BEST_SCORE
:dealer_busted
elsif dealers_hand_value < players_hand_value
:player
elsif dealers_hand_value > players_hand_value
:dealer
else
:tie
end
end
def player_won?
detect_result == :dealer_busted ||
detect_result == :player
end
def dealer_won?
detect_result == :player_busted ||
detect_result == :dealer
end
def tie?
detect_result == :tie
end
def display_result(dealer_cards, player_cards)
result = detect_result
case result
when :player_busted
prompt "You busted! Dealer wins!"
when :dealer_busted
prompt "Dealer bust! You win!"
when :player
prompt "You win!"
when :dealer
prompt "Dealer wins!"
when :tie
prompt "It's a tie!"
end
end
def footer(player_score, dealer_score)
puts "-----------"
puts "Players score: #{player_score}"
puts "Dealers score: #{dealer_score}"
puts 'First one to 5 wins the match'
puts "-----------"
end
def hit_or_stay_header
prompt "Dealers first card: #{cards_written_out(@dealers_cards[0])}"
puts ""
players_cards_and_value
end
def hit_or_stay_loop
loop do
system 'clear'
hit_or_stay_header
break if blackjack?(players_hand_value)
sleep(1)
prompt 'Hit or Stay?'
@answer = gets.chomp
break if ['hit', 'stay'].include?(@answer) ||
busted?(players_hand_value)
prompt 'That is not a valid answer'
sleep(1)
end
end
def players_turn
loop do
hit_or_stay_loop
if @answer.casecmp?('Hit')
prompt 'You chose to hit'
@players_cards << @cards.shift
else
prompt 'You chose to stay'
end
sleep(1)
system('clear')
hit_or_stay_header
break if blackjack?(players_hand_value) ||
busted?(players_hand_value) ||
@answer == 'stay'
end
end
def dealers_turn
loop do
system 'clear'
players_cards_and_value
puts ""
dealers_cards_and_value
puts ""
sleep(1)
break unless dealers_hand_value < players_hand_value
@dealers_cards << @cards.shift
prompt 'Dealer hits'
sleep(1)
end
end
def new_game_pause
puts 'New game starting'
sleep(1)
puts '.'
sleep(1)
puts '.'
sleep(1)
puts '.'
sleep(1)
end
def adding_score(score)
score += 1
end
player_score = 0
dealer_score = 0
system('clear')
prompt "Welcome to 21!"
sleep(1)
loop do
loop do
shuffle_and_deal
players_turn
dealers_turn unless busted?(players_hand_value) ||
blackjack?(players_hand_value)
display_result(@dealer_cards, @players_cards)
if player_won?
player_score = adding_score(player_score)
elsif dealer_won?
dealer_score = adding_score(dealer_score)
end
binding.pry
footer(player_score, dealer_score)
break if player_score == TOTAL_WINS || dealer_score == TOTAL_WINS
new_game_pause
end
loop do
if player_score == TOTAL_WINS
prompt "Player won the match!"
else
prompt "Dealer won the match!"
end
prompt "Would you like to play again? (Y or N)"
@play_answer = gets.chomp
break if @play_answer.downcase == 'n' || @play_answer.downcase == 'y'
prompt "That's not a valid answer"
end
break if @play_answer.downcase == 'n'
end
prompt "Thanks for playing 21!"
|
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
require 'fileutils'
require 'open-uri'
module TwitterCldr
module Resources
class SegmentDictionariesImporter < Importer
URL_TEMPLATE = 'https://raw.githubusercontent.com/unicode-org/icu/%{tag}/%{path}'
DICTIONARY_FILES = [
'icu4c/source/data/brkitr/dictionaries/burmesedict.txt',
'icu4c/source/data/brkitr/dictionaries/cjdict.txt',
'icu4c/source/data/brkitr/dictionaries/khmerdict.txt',
'icu4c/source/data/brkitr/dictionaries/laodict.txt',
'icu4c/source/data/brkitr/dictionaries/thaidict.txt'
]
output_path File.join(*%w(shared segments dictionaries))
requirement :dependency, TwitterCldr::Resources::property_importer_classes
ruby_engine :mri
def execute
FileUtils.mkdir_p(output_path)
DICTIONARY_FILES.each do |test_file|
import_dictionary_file(test_file)
end
end
private
def import_dictionary_file(dictionary_file)
source_url = url_for(dictionary_file)
source = URI.open(source_url).read
lines = source.split("\n")
trie = TwitterCldr::Utils::Trie.new
space_regexp = TwitterCldr::Shared::UnicodeRegex.compile('\A[[:Z:][:C:]]+').to_regexp
lines.each do |line|
line.sub!(space_regexp, '')
next if line.start_with?('#')
characters, frequency = line.split("\t")
frequency = frequency ? frequency.to_i : 0
trie.add(characters.unpack('U*'), frequency)
end
output_path = output_path_for(dictionary_file)
File.write(output_path, Marshal.dump(trie))
end
def url_for(dictionary_file)
URL_TEMPLATE % {
tag: tag,
path: dictionary_file
}
end
def tag
@tag ||= "release-#{Versions.icu_version.gsub('.', '-')}"
end
def output_path_for(dictionary_file)
file = File.basename(dictionary_file).chomp(File.extname(dictionary_file))
File.join(output_path, "#{file}.dump")
end
def output_path
params.fetch(:output_path)
end
end
end
end
|
Rails.application.routes.draw do
resources :articles
devise_for :users
mount TranslationCenter::Engine => "/translation_center"
root to: "articles#index"
end
|
require_relative "../test_helper"
require_relative "../../lib/recommended_links/indexer"
require 'rummageable'
module RecommendedLinks
class IndexerTest < Test::Unit::TestCase
test "Indexing a recommended link adds it to the search index" do
recommended_link = RecommendedLink.new(
"Care homes",
"Find a care home and other residential housing on the NHS Choices website",
"http://www.nhs.uk/CarersDirect/guide/practicalsupport/Pages/Carehomes.aspx",
["care homes", "old people's homes", "nursing homes", "sheltered housing"],
"recommended-link", "Business"
)
stub_index = stub("Rummageable::Index")
Rummageable::Index.expects(:new).returns(stub_index)
stub_index.expects(:add_batch).with([{
"title" => recommended_link.title,
"description" => recommended_link.description,
"format" => recommended_link.format,
"link" => recommended_link.url,
"indexable_content" => recommended_link.match_phrases.join(", "),
}])
Indexer.new.index([recommended_link])
end
test "Indexing multiple recommended links adds them all using rummager" do
recommended_links = [
RecommendedLink.new("First","","",[]),
RecommendedLink.new("Second","","",[])
]
stub_index = stub("Rummageable::Index")
Rummageable::Index.expects(:new).returns(stub_index)
stub_index.expects(:add_batch).with(recommended_links.map { |l| l.to_index })
Indexer.new.index(recommended_links)
end
test "Can remove links" do
deleted = [DeletedLink.new("http://delete.me/1"), DeletedLink.new("http://delete.me/2")]
s = sequence('deletion')
stub_index = stub("Rummageable::Index")
Rummageable::Index.expects(:new).with('http://rummager.dev.gov.uk', '/mainstream').returns(stub_index)
stub_index.expects(:delete).with("http://delete.me/1").in_sequence(s)
stub_index.expects(:delete).with("http://delete.me/2").in_sequence(s)
Indexer.new.remove(deleted)
end
test "Can add links to different indexes" do
recommended_link = RecommendedLink.new(
"Care homes",
"Find a care home and other residential housing on the NHS Choices website",
"http://www.nhs.uk/CarersDirect/guide/practicalsupport/Pages/Carehomes.aspx",
["care homes", "old people's homes", "nursing homes", "sheltered housing"],
"recommended-link", "test-index"
)
stub_index = stub("Rummageable::Index")
Rummageable::Index.expects(:new).with('http://rummager.dev.gov.uk', '/test-index').returns(stub_index)
stub_index.expects(:add_batch).with([{
"title" => recommended_link.title,
"description" => recommended_link.description,
"format" => recommended_link.format,
"link" => recommended_link.url,
"indexable_content" => recommended_link.match_phrases.join(", "),
}])
Indexer.new.index([recommended_link])
end
test "Can remove links from different indexes" do
deleted_link = DeletedLink.new(
"http://example.com/delete-me",
"test-index"
)
stub_index = stub("Rummageable::Index")
Rummageable::Index.expects(:new).with('http://rummager.dev.gov.uk', '/test-index').returns(stub_index)
stub_index.expects(:delete).with("http://example.com/delete-me")
Indexer.new.remove([deleted_link])
end
end
end
|
class FontNotoSansTelugu < Formula
head "https://noto-website-2.storage.googleapis.com/pkgs/NotoSansTelugu-unhinted.zip", verified: "noto-website-2.storage.googleapis.com/"
desc "Noto Sans Telugu"
homepage "https://www.google.com/get/noto/#sans-telu"
def install
(share/"fonts").install "NotoSansTelugu-Regular.ttf"
(share/"fonts").install "NotoSansTelugu-Bold.ttf"
end
test do
end
end
|
FactoryGirl.define do
factory :user do
first_name 'Earving'
last_name 'Winkleson'
sequence(:email) { |n| "earving#{n}@winkleson.com" }
password 'MyTest1234'
end
end
|
class AddStationToBillInfos < ActiveRecord::Migration[5.0]
def change
add_reference :bill_infos, :station, foreign_key: true
end
end
|
require "spec_helper"
describe "AttrArgsShorthand" do
let!(:test_object_level_1) { TestObjectLevel.new(arg1: 'test1', arg2: 'test2') }
let!(:test_object_level_2) { TestObjectLevel.new(arg3: 'test3', arg4: 'test4') }
let!(:test_class_level_1) { TestClassLevel.new(arg1: 'test1', arg2: 'test2') }
let!(:test_class_level_2) { TestClassLevel.new(arg3: 'test3', arg4: 'test4') }
it "sets variables" do
expect(test_object_level_1.instance_variable_get(:@arg1)).to eq 'test1'
end
it "reads variables through methods" do
expect(test_object_level_1.arg1).to eq "test1"
expect(test_object_level_1.arg2).to eq "test2"
expect(test_object_level_2.arg3).to eq "test3"
expect(test_object_level_2.arg4).to eq "special4"
end
it "doesnt define methods on other objects" do
expect { test_object_level_1.arg3 }.to raise_error(NoMethodError)
end
it "sets writer methods" do
test_object_level_1.arg1 = "test11"
expect(test_object_level_1.arg1).to eq "test11"
expect(test_object_level_1.instance_variable_get(:@arg1)).to eq "test11"
expect { test_object_level_2.arg1 = "test11" }.to raise_error(NoMethodError)
end
it "doesnt overwrite defined methods" do
expect(test_object_level_1.arg4).to eq "special4"
test_object_level_1.arg4 = "wee4"
expect(test_object_level_1.arg4).to eq "special4"
expect(test_object_level_1.instance_variable_get(:@arg4)).to eq "something4"
end
end
|
class ParamParser
attr_reader :parsed_url
def initialize(url_param)
@parsed_url = url_param.split(' ')
end
def path
parsed_url[0]
end
def email
parsed_url[2]
end
def mailable?
parsed_url[1] == '\cc:'
end
end
|
# config valid only for current version of Capistrano
lock "3.14.1"
set :application, "personal-website"
set :scm, :middleman
namespace :deploy do
task :create_symlinks do
on roles(:all) do
info "Deleting old symbolic links"
execute "find /home/public -type l -delete"
info "Creating symbolic links to public directory"
# Nearly Free Speech requires that symbolic links be relative
execute "cd /home/public"
execute "ln -s ../protected/releases/#{File.basename(release_path)}/* /home/public"
end
end
end
after :deploy, "deploy:create_symlinks"
|
module PUBG
class Telemetry
class Location
attr_reader :x, :y, :z
def initialize(args)
@x = args["X"]
@y = args["Y"]
@z = args["Z"]
end
end
end
end |
# == Schema Information
#
# Table name: rounds
#
# id :integer not null, primary key
# tournament_id :integer not null
# active :boolean default(TRUE)
# created_at :datetime not null
# updated_at :datetime not null
# round_number :integer not null
#
class Round < ApplicationRecord
validates :tournament_id, presence: true
has_many :matches
def self.current_round(tournament_id)
Round.where(tournament_id: tournament_id).count
end
def conclude_round
if Match.where(round_id: id, active: true).count > 0
return false
end
Round.transaction do
self.update_attributes(active: false)
Match.where(round_id: self.id).each do |mat|
mat.conclude_match
end
end
end
end
|
class AddFraseCuandoSiguenToBots < ActiveRecord::Migration
def change
add_column :bots, :frase_cuando_siguen, :string
end
end
|
# text interface for transport manipulation
module Terminal
class TextCommandor
attr_reader :commands, :stations, :routes, :trains, :carriages
def initialize(storage)
@commands = []
@storage = storage
end
def add_menu_item(name, type, options = {})
@commands << command_dispatcher(type).new(name, type, options)
end
def execute(menu_item_index)
command = menu_item_by_index(menu_item_index)
result = command.run
@storage.add_new_item(result) if command.type == :create && result
end
def print_menu
puts "Enter command index or type 'stop' to exit"
@commands.each.with_index(1) do |command, ind|
puts "#{ind}. #{command.name}"
end
end
def load_menu
add_menu_item('Station create',
:create,
types: [Transport::Station],
attrs: [{ title: 'name', select_type: :text }])
add_menu_item('Train create',
:create,
types: [Transport::CargoTrain, Transport::PassengerTrain],
attrs: [{ title: 'number', select_type: :text }])
add_menu_item('Route create',
:create,
types: [Transport::Route],
attrs: [{ title: 'first_station',
select_type: :select,
select_arr: @storage.stations },
{ title: 'last_station',
select_type: :select,
select_arr: @storage.stations }])
add_menu_item('Carriage create',
:create,
types: [Transport::CargoCarriage, Transport::PassengerCarriage],
attrs: [{ title: 'number', select_type: :text }])
add_menu_item('Add station to route',
:call,
objects: @storage.routes,
method: :add_transitional_station,
arg: @storage.stations)
add_menu_item('Remove station from route',
:call,
objects: @storage.routes,
method: :remove_transitional_station,
arg: @storage.stations)
add_menu_item('Set route for the train',
:call,
objects: @storage.trains,
method: :add_route,
arg: @storage.routes)
add_menu_item('Add carriage for the train',
:call,
objects: @storage.trains,
method: :add_carriage,
arg: @storage.carriages)
add_menu_item('Check carriage list',
:call,
objects: @storage.trains,
method: :carriages)
add_menu_item('Remove carriage from the train',
:call,
objects: @storage.trains,
method: :remove_carriage,
arg: @storage.carriages)
add_menu_item('Move the train forward',
:call,
objects: @storage.trains,
method: :go_to_next_station)
add_menu_item('Move the train backward',
:call,
objects: @storage.trains,
method: :go_to_previous_station)
add_menu_item('Check train current station',
:call,
objects: @storage.trains,
method: :current_station)
add_menu_item('Check station list',
:list,
objects: @storage.stations)
add_menu_item('Check trains on the station',
:call,
objects: @storage.stations,
method: :trains)
add_menu_item('Check trans stations of the route',
:call,
objects: @storage.routes,
method: :transitional_stations)
end
private
def command_dispatcher(type)
{
create: CreateCommand,
call: CallCommand,
list: ListCommand
}.fetch(type, BaseCommand)
end
def menu_item_by_index(menu_item_index)
@commands[menu_item_index - 1]
end
end
end
|
require 'redmine'
Redmine::Plugin.register :selectbox_autocompleter do
name 'Selectbox Autocompleter plugin'
author 'heriet'
description 'This plugin generate Autocomplete box for Select box'
version '1.2.1'
url 'https://github.com/heriet/redmine-selectbox-autocompleter'
author_url 'http://heriet.info'
settings(:default => {
'target_list' => [
'issue_assigned_to_id',
'values_assigned_to_id_1',
'values_author_id_1',
'wiki_page_parent_id',
'project_quick_jump_box'
].join("\r\n"),
'autocomplete_type' => 'select2',
}, :partial => 'selectbox_autocompleter/settings')
end
ActionDispatch::Callbacks.to_prepare do
require File.expand_path('../app/helpers/selectbox_autocompleter_helper', __FILE__)
ActionView::Base.send :include, SelectboxAutocompleterHelper
end
require_dependency 'selectbox_autocompleter/hooks'
|
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def show_qtiest?( params )
condition_1_qtiest?(params) or
condition_2_qtiest?(params) or
condition_3_qtiest?(params)
end
def show_mycute?( params )
params[:controller] == "uploaded_items"
end
def show_cuteProfile?( params )
params[:controller] == "users" and params[:action] =="show"
end
def error_for(object, method = nil, options={})
if method
err = instance_variable_get("@#{object}").errors.on(method).to_sentence rescue instance_variable_get("@#{object}").errors.on(method)
else
err = @errors["#{object}"] rescue nil
end
options.merge!(:class=>'fieldWithErrors', :id=>"#{[object,method].compact.join('_')}-error", :style=>(err ? "#{options[:style]}" : "#{options[:style]};display: none;"))
content_tag("p",err || "", options )
end
def in_the_steps?(params)
(params[:controller] == "steps") or
(params[:controller]=="posts")
end
def in_the_profile?(params)
(params[:controller] == 'users' and params[:action]=="edit" )
end
private
def condition_1_qtiest?(params)
params[:controller] == "items" and params[:action] == "show_random"
end
def condition_2_qtiest?(params)
params[:controller] == "users" and params[:action] == "join_us"
end
def condition_3_qtiest?(params)
params[:controller] == "users" and params[:action] == "join_uploader_or_invite_friends"
end
end
|
class Like < ActiveRecord::Base
belongs_to :user
belongs_to :pin
validates :user_id, presence: true
validates :pin_id, presence: true
validates_uniqueness_of :user_id, :scope => :pin_id
end
|
class AddSelfAssignableToShifts < ActiveRecord::Migration
def change
add_column :shifts, :self_assignable, :boolean
add_column :shifts, :requestable , :boolean
end
end
|
# prereqs: iterators, hashes, conditional logic
# Given a hash with numeric values, return the key for the smallest value
def key_for_min_value(name_hash)
min_value = 10000
#set default super high so all values would be less
# would be better to set default to first value but could not find a way to do this without using the .values method
name_hash.each do |key, value|
if value < min_value
min_value = value
end
end
name_hash.index(min_value)
end
|
class CollegeActivity < ApplicationRecord
belongs_to :college
belongs_to :activity
end
|
# frozen_string_literal: true
# Loads data from KKTIX group to database
class SaveOrganization
extend Dry::Monads::Either::Mixin
extend Dry::Container::Mixin
register :check_if_org_exist, lambda { |org_json|
puts org_json
if (org = Organization.find(slug: org_json['slug'])).nil?
Right(org: Organization.create, updated_data: org_json)
else
Right(org: org, updated_data: org_json)
end
}
register :update_org, lambda { |input|
Right(update_org(input[:org], input[:updated_data]))
}
def self.call(org)
Dry.Transaction(container: self) do
step :check_if_org_exist
step :update_org
end.call(org)
end
private_class_method
def self.update_org(org, updated_json)
org.update(slug: updated_json['slug'], name: updated_json['name'], uri: updated_json['uri'])
org.save
end
end
|
# frozen_string_literal: true
require 'rails_helper'
describe Documents::AttachmentsController do
let(:owner) { create(:user, :with_sessions, :with_documents) }
let(:guest) { create(:user, :with_sessions) }
let(:stranger) { create(:user, :with_sessions) }
let(:owner_token) { owner.sessions.active.first.token }
let(:document) { owner.documents.first }
let!(:attachment) do
document
.attachments
.create(original_file: Base64.encode64(File.read(Rails.root.join('spec', 'files', 'tux.png'))),
filename: 'tux.png')
end
let(:guest_token) { guest.sessions.active.first.token }
let(:stranger_token) { stranger.sessions.active.first.token }
before do
guest.guest_shares.create(document_id: document.id)
end
describe '#show' do
context 'when user is attachment owner' do
subject(:req) { -> { get :show, id: document.id, attachment_id: attachment.id } }
specify do
request.env['HTTP_AUTHORIZATION'] = owner_token
req.call
expect(JSON.parse(response.body).symbolize_keys).to match(Document::AttachmentSerializer.new(attachment).attributes)
end
end
context 'when user is attachment guest' do
subject(:req) { -> { get :show, id: document.id, attachment_id: attachment.id } }
specify do
request.env['HTTP_AUTHORIZATION'] = guest_token
req.call
expect(JSON.parse(response.body).symbolize_keys).to match(Document::AttachmentSerializer.new(attachment).attributes)
end
end
context 'when user has not right to see attachment' do
subject(:req) { -> { get :show, id: document.id, attachment_id: attachment.id } }
specify do
request.env['HTTP_AUTHORIZATION'] = stranger_token
req.call
expect(response.code).to eq '404'
end
end
end
describe '#destroy' do
context 'when user is attachment owner' do
subject(:req) { -> { delete :destroy, id: document.id, attachment_id: attachment.id } }
specify do
request.env['HTTP_AUTHORIZATION'] = owner_token
req.call
expect(response.code).to eq '200'
end
specify do
request.env['HTTP_AUTHORIZATION'] = owner_token
expect { req.call }.to change { document.reload.attachments.count }.by(-1)
end
end
context 'when user is attachment guest' do
subject(:req) { -> { delete :destroy, id: document.id, attachment_id: attachment.id } }
specify do
request.env['HTTP_AUTHORIZATION'] = guest_token
req.call
expect(response.code).to eq '404'
end
specify do
request.env['HTTP_AUTHORIZATION'] = guest_token
expect { req.call }.not_to change { document.reload.attachments.count }
end
end
context 'when user has not right to take any action on attachment' do
subject(:req) { -> { delete :destroy, id: document.id, attachment_id: attachment.id } }
specify do
request.env['HTTP_AUTHORIZATION'] = stranger_token
req.call
expect(response.code).to eq '404'
end
specify do
request.env['HTTP_AUTHORIZATION'] = stranger_token
expect { req.call }.not_to change { document.reload.attachments.count }
end
end
end
end
|
#!/usr/bin/env ruby
case ARGV[0]
when "start"
STDOUT.puts "called start"
when "stop"
STDOUT.puts "called stop"
when "restart"
STDOUT.puts "called restart"
else
STDOUT.puts "Unknown"
end
|
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def application_name
'KBs ADL Hydra Head'
end
end
|
module DaisyUtils
EXPECTED_DTD_FILES = ['dtbook-2005-2.dtd', 'dtbook-2005-3.dtd']
def valid_daisy_zip?(file)
DaisyUtils.valid_daisy_zip?(file)
end
def self.valid_daisy_zip?(file)
Zip::Archive.open(file) do |zipfile|
zipfile.each do |entry|
if EXPECTED_DTD_FILES.include? entry.name
return true
end
end
end
return false
end
def self.extract_book_uid(doc)
xpath_uid = "//xmlns:meta[@name='dtb:uid']"
matches = doc.xpath(doc, xpath_uid)
if matches.size != 1
raise MissingBookUIDException.new
end
node = matches.first
return node.attributes['content'].content.gsub(/[^a-zA-Z0-9\-\_]/, '-')
end
def self.extract_book_title(doc)
xpath_title = "//xmlns:meta[@name='dc:Title']"
matches = doc.xpath(doc, xpath_title)
if matches.size != 1
return ""
end
node = matches.first
return node.attributes['content'].content
end
def caller_info
return "#{request.remote_addr}"
end
def self.get_contents_xml_name(book_directory)
return Dir.glob(File.join(book_directory, '*.xml'))[0]
end
def extract_images_prod_notes_for_daisy doc
images = doc.xpath("//xmlns:img")
prodnotes = doc.xpath("//xmlns:imggroup//xmlns:prodnote")
captions = doc.xpath("//xmlns:imggroup//xmlns:caption")
@num_images = images.size()
limit = 249
@prodnotes_hash = Hash.new()
prodnotes.each do |node|
# MQ: Why are we even querying the DB for a matching DynamicImage?
# And why doesn't it care about the book the image belongs to?
dynamic_image = DynamicImage.where(:xml_id => node['imgref']).first
if (dynamic_image)
@prodnotes_hash[dynamic_image] = node.inner_text
else
@prodnotes_hash[node['imgref']] = node.inner_text
end
break if @prodnotes_hash.size > limit
end
@captions_hash = Hash.new()
captions.each do |node|
@captions_hash[node['imgref']] = node.inner_text
break if @captions_hash.size > limit
end
@alt_text_hash = Hash.new()
images.each do |node|
alt_text = node['alt']
id = node['id']
if alt_text.size > 1
@alt_text_hash[id] = alt_text
end
break if @alt_text_hash.size > limit
end
end
end |
# == Schema Information
#
# Table name: media
#
# id :string primary key
# app :string(100)
# context :string(100)
# locale :string(10)
# tags :string
# content_type :string(100)
# url :string
# name :string(100)
# lock_version :integer default(0), not null
# created_by :string
# created_at :datetime not null
# updated_at :datetime not null
# bytesize :integer default(0), not null
# updated_by :string
# delete_at :datetime
# email :string
# file_name :string default(""), not null
# usage :string default(""), not null
#
# Indexes
#
# index_media_on_app_and_locale (app,locale)
# index_media_on_delete_at (delete_at)
# index_media_on_file_name (file_name)
# index_media_on_id (id) UNIQUE
# media_main_index (app,context,name,locale,content_type) UNIQUE
#
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :medium do
app "app"
context "context"
locale "sv-SE"
tags "foo,bar,baz"
content_type "text/plain"
file_name "cartmans_mom.txt"
bytesize { rand(100000) }
name { "name#{rand(10000)}" }
lock_version 0
created_by "https://api.example.com/v1/api_users/a-b-c-d-e"
updated_by "https://api.example.com/v1/api_users/1-2-3-4-5"
delete_at { 1.month.from_now }
email "someone@example.com"
usage ""
end
end
|
module Ipizza
module Provider
class << self
def get(provider_name)
case provider_name.to_s.downcase
when 'lhv'
Ipizza::Provider::Lhv.new
when 'swedbank', 'hp'
Ipizza::Provider::Swedbank.new
when 'eyp', 'seb'
Ipizza::Provider::Seb.new
when 'sampo', 'sampopank', 'danske'
Ipizza::Provider::Sampo.new
when 'krep', 'krediidipank'
Ipizza::Provider::Krediidipank.new
when 'luminor', 'testluminor'
Ipizza::Provider::Luminor.new
end
end
end
end
end
|
require "test_helper"
describe SessionsController do
it "logs in an existing merchant and redirect to root_path" do
@merchant = merchants(:sappy1)
start_count = Merchant.count
login(@merchant, :github)
Merchant.count.must_equal start_count
must_redirect_to merchant_path(@merchant.id)
session[:merchant_id].must_equal @merchant.id
end
it "must have a username" do
@merchant = merchants(:sappy1)
login(@merchant, :github)
@merchant.username.must_equal "sappy1"
end
it "logs in a new user" do
@merchant = Merchant.new(oauth_provider: "github", oauth_uid: 9999, username: "toolazytomakeone", email: "toolazytomakeone@gmail.com")
proc {login(@merchant, :github)}.must_change 'Merchant.count', +1
merchant = Merchant.find_by(username: "toolazytomakeone")
must_redirect_to merchant_path(merchant.id)
session[:merchant_id].must_equal Merchant.find_by(username: "toolazytomakeone").id
end
it "clears the session and redirects back to the root path when a merchant logs out" do
@merchant = merchants(:sappy1)
login(@merchant, :github)
post logout_path
session[:merchant_id].must_equal nil
must_redirect_to root_path
end
it "notifies ther merchant after it logs out" do
@merchant = merchants(:sappy1)
login(@merchant, :github)
post logout_path
flash[:status].must_equal :success
flash[:result_text].must_equal "You successfully logged out."
end
end
|
class AddDebitAccountAndCreditAccountToTransactions < ActiveRecord::Migration
def change
add_reference :transactions, :debit, polymorphic: true, index: true
add_reference :transactions, :credit, polymorphic: true, index: true
end
end
|
Fabricator(:author) do
feed { |author| Fabricate(:feed, :author => author) }
username "user"
email { sequence(:email) { |i| "user_#{i}@example.com" } }
website "http://example.com"
domain "http://foo.example.com"
name "Something"
bio "Hi, I do stuff."
end
|
# encoding: UTF-8
# Copyright 2017 Max Trense
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Mahuta
module Visitor
def self.included(type)
type.extend ClassMethods
end
def initialize(options = {})
@options = options
end
def traverse(tree, depth = 0)
__traverse_subtree(tree, depth)
self
end
##
# Calls enter(node, depth) for the given node. If the enter method does not
# return :stop, this method recursively traverses the subtree under the
# current node. Calls leave(node, depth) after processing enter() and
# possibly the subtree.
private def __traverse_subtree(node, depth)
unless enter(node, depth) == :stop
node.children.each do |child|
__traverse_subtree(child, depth + 1)
end
end
leave(node, depth)
end
##
# Tries to call a method "enter_<node_type>" with arguments of
# [node, [depth]] if that exists. This method might return :stop, in which
# case the visitor will not traverse the subtree of this node.
def enter(node, depth)
method_name = "enter_#{node.node_type}"
if respond_to?(method_name)
send method_name, *[node, depth][0...method(method_name).arity]
end
end
##
# Tries to call a method "leave_<node_type>" with arguments of
# [node, [depth]] if that exists.
def leave(node, depth)
method_name = "leave_#{node.node_type}"
if respond_to?(method_name)
send method_name, *[node, depth][0...method(method_name).arity] # TODO Write a test for that!!!
end
end
module ClassMethods
def traverse(tree, depth = 0)
new.traverse(tree, depth)
end
end
end
end
|
module UsersHelper
def log_in(user)
session[:user_id] = user.id
cookies.signed[:user_id] = user.id
end
def logged_in_user
unless logged_in?
redirect_to root_path
end
end
def correct_user
@user = User.find(params[:id])
redirect_to(edit_user_path(@user)) unless @user == current_user
end
def current_user?(user)
user == current_user
end
def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
end
end
def logged_in?
!session[:user_id].nil?
end
def log_out
current_user
session.delete(:user_id)
@current_user = nil
end
def new_user_setting
@user = User.create(name: "ゲスト")
@user.name = "ゲスト#{@user.id}"
@user.save
end
end
|
class AddComputingMinutesToExecutions < ActiveRecord::Migration
def change
add_column :executions, :computing_minutes, :integer
end
end
|
class AddRequiredFieldsToOngs < ActiveRecord::Migration
def change
change_column :ongs, :name, :string, :null => false
change_column :ongs, :description, :text, :null => false
change_column :ongs, :address, :text, :null => false
end
end
|
# For this challenge you will be capitalizing certain characters in a string.
puts "Enter a sentence: "
str = gets.chomp
arr = str.split
arr.each do |s|
s.capitalize!
end
str = arr.join(" ")
puts str |
Pod::Spec.new do |s|
s.name = "ETExtension" # 库名称
s.version = "1.0.0" # 库版本
s.summary = "自动解析XML节点的值并转换成对象。" # 简介
s.description = <<-DESC
仿MJExtension写的,自动解析XML数据。还有很多功能没有实现,只是为了方便自己。
DESC
s.homepage = "https://github.com/LarkNan/ETExtension" # 该库的主页地址
s.license = { :type => "MIT", :file => "LICENSE" } # 协议
s.author = { "申铭" => "569818710@qq.com" } # 作者
s.platform = :ios, "8.0" # 最低适配的版本
s.source = { :git => "https://github.com/LarkNan/ETExtension.git", :tag => "#{s.version}" } # 源代码的具体地址以及版本
s.source_files = "ETExtensionExample/ETExtension/*.{h,m}" # 提供给别人的文件
s.requires_arc = true # 是否是ARC
s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2"}
s.dependency "KissXML", "5.1.2" # 库所依赖的第三方
end
|
class MoveDiagnosisFieldsToPatientCase < ActiveRecord::Migration
def up
add_column :patient_cases, :disease_id, :integer
add_column :patient_cases, :severity, :integer, :default => 0
add_column :patient_cases, :revision, :boolean, :default => false
add_column :patient_cases, :body_part_id, :integer
add_index :patient_cases, :disease_id
add_index :patient_cases, :revision
add_index :patient_cases, :body_part_id
end
def down
remove_column :patient_cases, :disease_id
remove_column :patient_cases, :severity
remove_column :patient_cases, :revision
remove_column :patient_cases, :body_part_id
end
end |
include RSpec
require_relative 'screen'
RSpec.describe Screen, type: Class do
let(:screen) { Screen.new(10, 10) }
describe "#insert" do
it "inserts a pixel at the proper x, y coordinates" do
p = Pixel.new(255, 255, 255, 1, 1)
screen.insert(p, 1, 1)
expect(screen.at(1, 1)).to eq p
end
it "retains color information upon insertion" do
p = Pixel.new(255, 255, 255, 1, 1)
screen.insert(p, 1, 1)
p1 = screen.at(1, 1)
expect(p1.red).to eq p.red
expect(p1.green).to eq p.green
expect(p1.blue).to eq p.blue
end
end
describe "#at" do
it "returns the pixel at a specific location" do
screen.insert(p, 1, 2)
p1 = screen.at(1, 2)
expect(p).to eq p1
end
it "handles invalid x, y values gracefully" do
p = screen.at(-1, -1)
expect(p).to eq nil
end
end
end
|
class EventsController < ApplicationController
def new
@event = Event.new
end
def create
@event = current_user.created_events.build(event_params)
if @event.save
flash.now[:success] = 'Event created!'
render :show
else
render :new
end
end
def show
@event = Event.find(params[:id])
@attendees = @event.attendees.paginate(page: params[:page]).order(created_at: :desc)
end
def index
@events = Event.paginate(page: params[:page]).order(created_at: :desc)
end
private
def event_params
params.require(:event).permit(:title, :description, :date, :location)
end
end
|
class CreateCampaigns < ActiveRecord::Migration
def change
create_table :campaigns do |t|
t.text :name
t.text :digest
t.integer :source_id
end
create_table :events do |t|
t.text :name
t.integer :campaign_id
end
add_foreign_key :campaigns, :sources
add_foreign_key :events, :campaigns
end
end
|
module Ui
class ConsoleStyle
def self.print_play_move(mark, move)
print_msg "play #{mark} #{move}"
end
def self.print_play_move_usage
print_msg 'usage: play $mark $move'
end
def self.print_board(board)
msg = "*===*\n"
board_string = board.to_s
(0...board_string.length).step(3) { |i| msg << "|" << board_string[i] << board_string[i+1] << board_string[i+2] << "|\n" }
msg << "*===*\n"
print_msg msg
end
def self.quit
print_msg 'quit'
end
def self.print_help
print_msg 'Type list_commands to view a list of implmented commands'
end
def self.print_list_commands
print_msg 'display_board, help, list_commands, new_game, play, quit, select'
end
def self.print_select_player
print_msg '*Select Player 1 (1) or Player 2 (2)*'
end
def self.ask_enter_move
print_msg '*Enter Move (0-8)*'
end
def self.print_winner(winner)
print_msg winner.nil? ? "Draw." : "#{winner} has won."
end
def self.print_msg(msg)
puts msg
return msg
end
end
end
|
module Exceptions
class InvalidBrigadeProjectError < StandardError; end
end |
# required plugins: vagrant-hostmanager and vagrant-persistent-storage
vagrant_root = File.dirname(File.expand_path(__FILE__))
Vagrant.configure("2") do |config|
config.vm.box = "ceph-base"
config.ssh.forward_agent = true
config.ssh.insert_key = false
config.ssh.compression = false
# config.hostmanager.enabled = true
(1..3).each do |i|
config.vm.define "ceph-#{i}" do |server|
server.ssh.username = 'root'
server.vm.hostname = "ceph-#{i}"
server.vm.network :private_network, ip: "172.21.12.#{i+11}"
server.vm.provider "virtualbox" do |vb|
vb.cpus = 2
end
server.vm.provision :shell, :inline => <<-EOF
set -x
pvs /dev/sdb || (pvcreate /dev/sdb && vgcreate pvs /dev/sdb)
EOF
server.persistent_storage.enabled = true
server.persistent_storage.size = 100 * 1000 #100 GB
server.persistent_storage.partition = false
server.persistent_storage.use_lvm = false
server.persistent_storage.location = File.join(vagrant_root, ".disks/ceph-#{i}.vdi")
end
end
config.vm.define "client" do |client|
client.ssh.username = 'root'
client.vm.hostname = "client"
client.vm.network :private_network, ip: "172.21.12.11"
end
config.vm.define "admin" do |admin|
admin.vm.hostname = "admin"
admin.vm.network :private_network, ip: "172.21.12.10"
admin.vm.provision :shell, :inline => "yum install -y pssh jq"
admin.vm.provision :shell, :privileged => false, :inline => <<-EOF
set -x
ssh-keyscan admin client ceph-{1..3} >> ~/.ssh/known_hosts 2> /dev/null
echo ceph-{1..3} | tr ' ' '\n' > ~/nodes-ceph
echo admin client ceph-{1..3} | tr ' ' '\n' > ~/nodes-all
EOF
end
end
# vim:ft=ruby:tabstop=2:softtabstop=2:shiftwidth=2
|
class AddTimestampToRssreader < ActiveRecord::Migration
def change
add_column "rssreader", "created_at", :datetime
add_column "rssreader", "updated_at", :datetime
end
end
|
Pod::Spec.new do |s|
s.name = 'UMessage'
s.version = '1.1.0'
s.summary = 'UMeng Push SDK'
s.homepage = 'http://dev.umeng.com/message/ios/sdk-download'
s.ios.deployment_target = '4.3'
s.source = { :git => "https://github.com/amoblin/easyPods.git", :branch => "master" }
s.source_files = "UMessage/UMessage.h"
s.preserve_paths = "UMessage/libUMessage_Sdk_1.1.0.a"
s.libraries = 'UMessage_Sdk_1.1.0', 'z'
s.requires_arc = false
s.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '"$(PODS_ROOT)/UMessage/UMessage"' }
end
|
# Design a game
# HangMan - word guessing game
# PSEUDO CODE
# Create a class WordGame
# getter/setter methods?
# state/attributes (word, guess count, game over)
# behaviours (update and display feedback, end the game)
# USER INTERFACE
# prompt user for a word - player one
# initialize instance
# turn word into one letter strings - get that word and store it
# create empty array to hold guessed letters
# display " _ " for each letter guessed
# until guess count equals length of the word
# if letter is in secret word
# guess count goes up unless letter is already in guessed letters - guessed letters go into array unless its already been guessed
# check position of the letter in the secret word
# otherwise ...
# if guessed letter is not in the secret word
# shovel that guessed letter into the array of guessed letters
# guess count goes up
# otherwise
# guess count stays the same
# display feedback/current state on the screen
# display guess count
# determine if game is over
# if it is display a winning or tauntin message
# WE HAVE TO KEEP TRACK OF THIS
# secret_word
# guess_count (integer - )
# updated_guess (as long as the secret word and will replace letter with underscores)
# wrong_letters (array)
# Through that we'll know when to end the game
# ACTIONS
# ex check_cup
# new instance of the class to initialize the game after they give you the word - se
# endter a word
# new game equals ________ secret word
# thanks for entering
# while you are guessing keep going until the word is completed
#puts -----------------------------------------
# FAILED ATTEMPT 1 aka RESEARCH
# class WordGame
# attr_reader :word, :updated_word
# def initialize(word)
# @word = word
# @found_letters = []
# @wrong_letters = []
# @updated_word = ''
# end
# def check_letter(guessed_letter)
# @word.chars.each do |letter|
# if letter === guessed_letter
# # update the @updated_word and show the user that new updated word
# @found_letters << guessed_letter
# update_word_based_on_guess
# else
# @wrong_letters << guessed_letter
# end
# end
# end
# return the @updated_word with the letters filled in
# def update_word_based_on_guess
# puts "thats right there is a #{letter} in #{@word}"
# found_letters = []
# @word.chars.map do |letter|
# if letter === guessed_letter
# found_letters << guessed_letter
# else
# end
# end
# end
# creates a set of blanks for every letter in the secret word
# def create_blank_word(secret_word)
# secret_word.split("").each do |letter|
# @updated_word << '_ '
# end
# return @updated_word
# end
# end
# puts "Player One: enter a secret word"
# secret_word = gets.chomp
# # instantiate a new instance of the game
# game = WordGame.new(secret_word)
# # create the blank word by calling create_blank_word on the instance of the game
# game.create_blank_word(secret_word)
# puts "alright, we have the secret word, the other player now has #{secret_word.length} tries to guess the word by entering a letter"
# puts "here is the word so far: #{game.updated_word}"
# puts "please guess a letter"
# number_of_guesses = 0
# guess = gets.chomp
# while number_of_guesses < secret_word.length - 1
# # check the letter that was guessed
# game.check_letter(guess)
# puts "this is the updated word: #{game.updated_word}"
# number_of_guesses += 1
# puts "please guess a new letter"
# guess = gets.chomp
# end
# puts "you're out of the loop"
# FINAL GAME
class WordGame
def initialize(starting_sentence)
@starting_sentence = starting_sentence
@sentence_array = @starting_sentence.split("").map(&:downcase)
@accurate_count = @sentence_array - [" "]
@final_sentence = @starting_sentence.gsub(/[a-zA-Z]/, "_").split("")
@guess_count = 0
end
def play_game
while @guess_count < @accurate_count.count
puts "Player two: you have #{@accurate_count.count - @guess_count} guesses. Dont fuck it up! start guessing each letter now: "
guess = gets.downcase.chomp
if @sentence_array.include?(guess)
letter_index = @sentence_array.find_index(guess)
@sentence_array[letter_index] = ""
@final_sentence[letter_index] = guess
puts "Correct! The sentence is now: #{@final_sentence.join}"
else
puts "Sorry loser, better luck next time"
end
@guess_count += 1
end
end
end
#DRIVER CODE
puts "Lets play a sick game. Player one; enter a secret word: "
secret_word = gets.downcase.chomp
game = WordGame.new(secret_word)
game.play_game |
# frozen_string_literal: true
module NvGpuControl
module Util
# Augments {#`} to log commands and handle error cases
module Shell
# Raised on a shell error
class Error < RuntimeError
# @return [Process::Status] the process status
attr_reader :status
# @return [Array<String>] arguments
attr_reader :args
# @return [String] Output of the Command
attr_reader :result
def initialize(status, args, result)
@status = status
@args = args
@result = (result || "")
super("Shell command failed with status #{status.exitstatus}. Arguments: #{args} Result: #{result}")
end
end
def `(command)
shell_command(command) do
[ Kernel.`(command), $? ] # `] # - Hack to avoid confusing poor Vim
end
end
def command?(name)
Kernel.system('which', name, [:out, :err] => File::NULL)
$?.success?
end
private
def shell_command(args, &block)
logger.debug "Shell command: #{args.inspect}"
result, status = block.call(args)
# rubocop:disable Style/NumericPredicate
return result if status == 0 || status.success?
raise Shell::Error.new(status, args, result)
end
end
end
end
|
class CustomersController < ApplicationController
# Want a reference to the currently logged in user before we run the edit/update process
# getting this via the session[:user_id]
before_filter :current_customer, :only => [ :edit, :show, :update]
def new
@customer = Customer.new
end
def create
@customer = Customer.new(params[:customer])
if @customer.save
# Tell the CustomerMailer to send a welcome Email after save
CustomerMailer.welcome_email(@customer).deliver
redirect_to page_home_path, :notice => "Account Created"
else
#TODO Need to re-think what and where notice is displayed
redirect_to customers_new_path, :notice => "Registration Failed"
end
end
def edit
@customer = Customer.find_by_id(@current_customer)
end
def update
# Find customer object using edit form parameters
@customer = Customer.find_by_id(params[:id])
# Update the customer
if @customer.update_attributes(params[:customer])
#TODO if successful, redirect to the show action
redirect_to(:action => 'show', :id =>@customer.id)
#redirect_to page_home_path, :notice => "Account Updated"
else
# if update fails, re-display the form so customer can fix problem
render('edit')
end
end
def show
@customer = Customer.find_by_id(@current_customer)
@first_name = @customer.first_name
@last_name = @customer.last_name
@name = "#{@first_name} #{@last_name} "
end
def delete
end
end
|
require File.expand_path 'app/views/page/container.rb', Rails.root
require File.expand_path 'app/views/welcome/index/content.rb', Rails.root
# Class encapsulating all page-specific view code for `welcome/index`.
class Views::Welcome::Index < Views::BasePage
needs :posts
include Widgets::Page
include Widgets::Welcome::Index
private
def page_content
widget Container do
widget Content, posts: posts
end
end
def header_text
'Welcome to Fortstrap!'
end
end # class Views::Welcome::Index
|
#! env ruby
def toWinPath(wslPath)
cmd = "wslpath -w '#{wslPath}'"
return `#{cmd}`.strip
end
# This utility decompiles every pex file in the target_dir
# and places the result file in the same directory.
require('optparse')
require('pathname')
require('fileutils')
options = {}
optParser = OptionParser.new do |opts|
opts.banner = "Usage: decompile-pex [options] target_dir"
# opts.on("-w", "--watch", "Watch built directory") do
# options[:watch] = true
# end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
end
optParser.parse!
targetDir = ARGV.pop
if not targetDir then
puts optParser
exit
end
targetDirPath = Pathname.new(targetDir)
if !targetDirPath.exist? or !targetDirPath.directory? then
puts "Cannot locate target directory: " + targetDirPath;
exit 1
end
decompiler = ENV['PEX_DECOMPILER']
if !File.exists?(decompiler) then
puts "Cannot locate decompiler from $PEX_DECOMPILER";
exit 1
end
Dir.chdir targetDirPath
Pathname.glob("#{targetDirPath}/**/*.pex").each do |f|
next if f.directory?
cmd = "\"#{decompiler}\" -p \"#{toWinPath(targetDirPath)}\" \"#{toWinPath(f)}\""
puts `#{cmd}`
end
|
module Admin
class TimelinesController < BaseController
load_and_authorize_resource :project
load_and_authorize_resource through: :project, shallow: true
def create
if @timeline.save
redirect_back fallback_location: [:admin, @project]
else
errors_to_flash(@project)
render 'new'
end
end
def update
if @timeline.update_attributes(update_params)
redirect_to [:admin, @timeline.project, :timelines]
else
errors_to_flash(@project)
render 'new'
end
end
def destroy
@timeline = Timeline.find(params[:id])
@timeline.destroy
redirect_to :back
end
def remove_image
@timeline.remove_image!
@timeline.save
redirect_to :back
end
private
def create_params
params.require(:timeline).permit(:actor, :image, :image_cache, :body, :project_id, :congressman_id, :timeline_date)
end
def update_params
params.require(:timeline).permit(:actor, :image, :image_cache, :body, :project_id, :congressman_id, :timeline_date)
end
end
end
|
# == Schema Information
#
# Table name: players
#
# id :integer not null, primary key
# summonerid :string
# created_at :datetime not null
# updated_at :datetime not null
# name :string
# tier :string
# topchampionid :string
#
FactoryGirl.define do
factory :player do
summonerid "39777270"
name "Batman"
tier "Challenger"
topchampionid "1"
end
end
|
# TO BE REMOVED
module Inventory
class ItemSerializer
include FastJsonapi::ObjectSerializer
attributes :name, :quantity, :uom
end
end
|
class Map::ApplicationController < ActionController::Base
include Passwordless::ControllerHelpers
include Geokit::Geocoders
layout 'map/application'
before_action :setup_client!
before_action :setup_config!
def show
render 'map/show'
end
def embed
# response.headers["Expires"] = 1.day.from_now.httpdate
# expires_in 1.day, public: true, must_revalidate: true
render 'map/embed'
end
private
def setup_client!
@client = Client.find_by_public_key(params[:key])
return if !params[:key].present?
raise ActionController::RoutingError.new('Not Found') if @client.nil?
headers['X-FRAME-OPTIONS'] = "ALLOW-FROM #{@client.domain}"
headers['Access-Control-Allow-Origin'] = "https://#{@client.domain}"
headers['Access-Control-Allow-Methods'] = 'GET'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
end
def setup_config!
I18n.locale = params[:locale]&.to_sym || :en
@config = {
token: ENV['MAPBOX_ACCESSTOKEN'],
endpoint: api_graphql_url,
locale: I18n.locale,
search: !(params[:path] =~ /region|country/),
}
location = params[:country].present? ? Country.find_by_country_code(params[:country]) : @client&.location
@config[:bounds] = location.client_bounds if location.present? && location.bounds.present?
@config[:center] = coordinates unless @config[:bounds].present?
@config[:country] = location.country_code if location&.respond_to?(:country_code)
@config.merge!(@client.config).merge!({
location_type: @client.location_type&.downcase,
location_id: @client.location_id
}) if @client.present?
end
def coordinates
@coordinates ||= begin
if params[:latitude].present? && params[:longitude].present?
[ params[:latitude], params[:longitude] ]
else
location = IpGeocoder.geocode(request.remote_ip)
location.success ? [ location.lat, location.lng ] : [ 51.505, -0.09 ] # Default to london for now
end
end
end
def current_user
@current_user ||= authenticate_by_session(Manager)
end
end
|
class EventVenue < ApplicationRecord
validates :name, :address, presence: true
validates :capacity, numericality: {greater_than_or_equal_to: 10, only_integer: true}
has_many :events
end
|
class AddDetailsToReview < ActiveRecord::Migration[5.1]
def change
add_column :reviews, :name, :string
add_column :reviews, :email, :string
add_column :reviews, :review, :string
add_column :reviews, :approved, :boolean
end
end
|
module Bs::SerializerHelper
def serialize_objects(*objects)
final_hash = {}
objects.each do |data|
serialize_options = {}
object = nil
if data.is_a?(Hash)
serialize_options = data[:options]
object = data[:data]
else
object = data
end
final_hash.merge!(serialize_object(object, serialize_options))
end
final_hash
end
def serialize_object(object, options)
serializer = ActiveModelSerializers::SerializableResource.new(
object, options
)
obj_hash = serializer.serializable_hash
# Manually remove the "bs/", AMS seems to ignore use_relative_model_naming
obj_hash.keys.each do |key|
if key.to_s.starts_with?('bs/')
obj_hash[key.to_s.sub('bs/', '').to_sym] = obj_hash.delete(key)
end
end
obj_hash
end
end
|
# frozen_string_literal: true
class Post < ApplicationRecord
belongs_to :user
belongs_to :framework
validates :title, presence: true, uniqueness: true
validates :body, presence: true
end
|
class UsersController < ApplicationController
before_action :authenticate_user!
before_action :only_current_user, except: [:index, :dashboard]
before_action :set_user, only: [:show, :edit, :destroy]
# before_action :correct_user, only: [:edit, :update, :destroy]
def index
# @user = User.find(params[:id])
@users = User.search(params[:search])
end
def new
@user = User.new
end
def search
@user = User.search(params[:parameter])
end
def dashboard
@user = current_user
end
def create
@user = User.new( params[:id] )
if @user.save
flash[:success] = "Profile created!"
redirect_to user_path( params[:user_id] )
else
render action: :new
end
end
def follow
@user = User.find_by_username(params[:id])
current_user.follow!(@user) # => This assumes you have a variable current_user who is authenticated
end
def edit
# @user = User.find(params[:id])
end
def show
@user = User.find(params[:id])
# @user = User.find_by_first_name params[:first_name]
@meal = @user.meal
@profile = @user.profile
@specialty = @user.specialty
@feedback = @user.feedback
@meal_feedback = @user.meal_feedback
# @update = current_user.update
# @conversation = @user.conversation
@activities = PublicActivity::Activity.order("created_at desc").where(owner_id: current_user.friend_ids, owner_type: "User")
end
def update
@user = User.find(params[:id])
if @user.update(user_params)
flash[:success] = "Your account was updated successfully"
redirect_to user_path
end
end
def my_friends
@friendships = current_user.friends
end
def search
@users = User.search(params[:search_param])
if @users
@users = current_user.except_current_user(@users)
render partial: 'friends/lookup'
else
render status: :not_found, nothing: true
end
end
def add_friend
@friend = User.new(params[:friend])
current_user.friendships.build(friend_id: @friend.id)
if current_user.save
redirect_to my_friends_path, notice: "Friend was successfully added."
else
redirect_to my_friends_path, flash[:error] = "There was an error with adding user as friend."
end
end
def destroy
@user = User.find(params[:id])
@user.destroy
redirect_to root_path
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:first_name, :last_name, :phone, :contact_email, :address, :town, :interests, :description, :avatar, :url)
end
def correct_user
@user = current_user
redirect_to root_path, notice: "Not authorized to access this page" if @user.nil?
end
def only_current_user
@user = User.find(params[:id])
redirect_to(root_url) unless @user == current_user
end
end |
require 'sinatra/jbuilder'
module JsonHelper
def render_json(*args)
content_type "application/json"
jbuilder *args
end
def not_found
content_type "application/json"
halt 404
end
end
|
# encoding: utf-8
#
# © Copyright 2013 Hewlett-Packard Development Company, L.P.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
require 'hpcloud/lb_virtualips'
module HP
module Cloud
class CLI < Thor
desc 'lb:virtualips name_or_id', "List the virtual IPs for the specified load balancer."
long_desc <<-DESC
Lists the virtual IPs for the specified load balancer.
Examples:
hpcloud lb:virtualips loader # List the virtual IPs for 'loader'
DESC
CLI.add_report_options
CLI.add_common_options
define_method "lb:virtualips" do |name_or_id|
columns = [ "id", "address", "ipVersion", "type" ]
cli_command(options) {
lb = Lbs.new.get(name_or_id)
ray = LbVirtualIps.new(lb.id).get_array
if ray.empty?
@log.display "There are no virtual IPs for the given load balancer."
else
Tableizer.new(options, columns, ray).print
end
}
end
end
end
end
|
require 'samanage'
@token = ARGV[0]
@datacenter = ARGV[1]
@samanage = Samanage::Api.new(token: @token, datacenter: @datacenter)
@samanage.users.each do |user|
user_needs_to_be_activated = !user['last_login'] && !user['disabled']
if user_needs_to_be_activated
begin
puts "Sending Activation to #{user['email']}"
@samanage.send_activation_email(email: user['email'])
rescue Samanage::Error, Samanage::InvalidRequest => e
puts "[#{e}] #{e.status_code} - #{e.response}"
end
end
end
|
class Company < ApplicationRecord
has_many :purchased_stocks
has_many :articles
has_many :watchlists
end
|
require 'spec_helper'
describe "UserPages" do
subject { page }
describe "register page" do
before { visit register_path }
it { should have_title('Register') }
it { should have_selector('h1', text: 'Register') }
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.