text stringlengths 10 2.61M |
|---|
class OVOST::Click
attr_reader :link_id, :click_id, :time
def initialize(click_id, link_id)
@click_id = click_id
@link_id = link_id
@time = Time.now
end
end
|
class Animal < ActiveRecord::Base
validates :name, :presence => true
validates_uniqueness_of :name
has_many :sightings, :dependent => :destroy
has_many :regions, through: :sightings
end
|
class GuitarAttachment < ActiveRecord::Base
mount_uploader :image, GuitarImageUploader
belongs_to :guitar
validates :image, presence: true
end
|
# frozen_string_literal: true
require 'test_helper'
module Vedeu
module Cursors
describe Repository do
let(:described) { Vedeu::Cursors::Repository }
describe '.cursor' do
before { Vedeu::Models::Focus.reset }
subject { Vedeu.cursor }
context 'when there are cursors are... |
class Category < ActiveRecord::Base
STATUS_TAGS = %w(打开 关闭 优先 推荐)
HashEx = ActiveSupport::HashWithIndifferentAccess
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
include ESModel
include ContentManagement::Model
class_attribute :default_templates
acts_as_tree :cache_depth => tru... |
class RenameUserFriends < ActiveRecord::Migration
def change
rename_column :users, :fb_friend_ids, :fb_friends
end
end
|
class DiveBarsController < ApplicationController
before_action :authorized
def index
@dive_bars = DiveBar.search(params[:q])
end
def show
@dive_bar = DiveBar.find(params[:id])
@favorite = (current_user.favorites.find_by(dive_bar_id: @dive_bar.id))
end
private
... |
class Api::V1::PaymentSerializer
include FastJsonapi::ObjectSerializer
attributes :holder_name, :card_type, :number, :token, :status, :expiry_month, :expiry_year
end
|
class Cave
attr_reader :stop_point
attr_accessor :grid
def initialize(file)
@stop_point = 0
@grid = []
File.readlines(file).each { |line|
if !!(line[0] =~ /[0-9]/)
@stop_point = line.to_i
elsif not line.strip.empty?
@grid << Array( line.strip.split('') )
end
}
end
def down_count_char(cha... |
class AddAddressToLocations < ActiveRecord::Migration[5.1]
def change
add_column :locations, :address, :text
add_column :locations, :lat, :decimal, precision: 15, scale: 10
add_column :locations, :lng, :decimal, precision: 15, scale: 10
end
end
|
class DropConfigWelcomeIndex < ActiveRecord::Migration[4.2]
def up
drop_table :config_welcome_indices
end
def down
create_table :config_welcome_indices do |t|
t.string :name, null: false
t.string :panel_partial, null: false
t.boolean :enable_show, default: false
t.timestamps null:... |
class Dealing < ApplicationRecord
belongs_to :item
belongs_to :buyer, class_name: "User", foreign_key: 'buyer_id'
end
|
module InvoiceAnalyst
def average_invoices_per_merchant
invoice_count = @engine.invoice_list.count
merchant_count = @engine.merchant_list.count
((invoice_count.to_f / merchant_count.to_f)).round(2)
end
def sum_of_square_differences_invoice_count(engine, mean)
merchants = @engine.merchant_list
... |
class Cryptsy
include Exchange
def update
@currency_pairs = []
@market_id = {}
@depth = {}
@data = JSON.load(open("http://pubapi.cryptsy.com/api.php?method=orderdata"))
@data["return"].values.map do |market|
pair = [market["primarycode"], market["secondarycode"]]
@market_id[pair] = ... |
require 'helper'
require 'qless/threaded_worker/processor'
describe Qless::ThreadedWorker::Processor do
TestException = Class.new(StandardError)
before do
$invokes = 0
@boss = Object.new
@processor = Qless::ThreadedWorker::Processor.new(@boss)
Celluloid.logger = nil
#Sidekiq.redis = REDIS
... |
require "fog/core/model"
module Fog
module Compute
class Brkt
class CspImage < Fog::Model
# @!group Attributes
identity :id
attribute :provider
attribute :csp_image_id
attribute :csp_settings
attribute :state
attribute :image_definition
# @!e... |
module SessionsHelper
def sign_in(user)
cookies.permanent[:remember_token] = user.remember_token
self.current_user = user
case self.current_user.role
when 'student'
current_student = Student.find_by_user_id(user.id)
when 'institution_attendant'
current... |
require 'test_helper'
class PaysafeTest < Minitest::Test
def test_that_it_has_a_version_number
refute_nil ::Paysafe::VERSION
end
end
|
class User < ApplicationRecord
has_many :task_lists, dependent: :destroy
has_many :tasks, through: :task_lists
has_and_belongs_to_many :favorites_task_lists, class_name: "TaskList"
devise :database_authenticatable, :registerable, :rememberable, :trackable, :validatable
def add_favorite! task_list_id
tas... |
# frozen_string_literal: true
# Author: Usman Ahmad
require 'date'
require_relative 'calendar'
require_relative 'clioper'
# A Command Line Interface for the 'Calendar' class
class CalendarCLI
TEXT_VALIDATION_LAMBDA = ->(text) { text =~ /^\w+(\s\w+)*$/ }
def initialize(calendar)
@calendar = calendar
end
... |
require './lib/user'
describe User do
let!(:user) {User.create(email: 'test@test.com', password: 'Secret123')}
it "Doesn't sign in if user doesn't exist" do
expect(User.authenticate('dave@dave.com', user.password)).to be_nil
end
it "Doesn't sign in if password is incorrect" do
expect(User.authenticate(... |
class ProductsController < ApplicationController
before_action :load_product_category, only: [:show]
def index
@pharmacies_sale = Discount.where("status = 'Показать'").order(:tail)
@product_categories = ProductCategory.where("status = 'Показать'")
@products = Product.where("status = 'Показать'")
@p... |
require 'rails_helper'
describe 'User can edit a category' do
scenario 'a user clicks edit on category index page' do
category = Category.create!(name: 'Legal')
visit categories_path
click_link "Edit"
expect(current_path).to eq(edit_category_path(category))
fill_in "category[name]", with: "Fi... |
#!/usr/bin/ruby
require 'open3'
def partial_print(pos)
if pos == 0
print "H"
elsif pos == 1
print "e"
elsif pos == 2
print "l"
elsif pos == 3
print "l"
elsif pos == 4
print "o"
elsif pos == 5
print " "
elsif pos == 6
print "W"
els... |
require "rails_helper"
RSpec.describe ReviewComment, type: :mailer do
describe "comment" do
let(:comment) { FactoryGirl.create(:comment) }
let(:mail) { ReviewComment.comment(comment) }
let(:review) { comment.review }
let(:recipient) { review.user }
let(:url) { site_path(review.site) }
it "re... |
require_relative '../models/user_model'
require 'faker'
FactoryBot.define do
factory :user, class: UserModel do
nome_usuario { Faker::Internet.username(specifier: 8) }
senha { Faker::Internet.password(min_length: 8) }
end
end
|
#!/usr/bin/env ruby
require "bundler/setup"
require "cassowary"
variables = {}
class SexpSolver
include Cassowary
attr_reader :variables
def initialize(variables)
@variables = variables
end
def parse_and_solve(str)
sexp = str.strip
whitespace = " \n\r\t"
atom_end = whitespace + "()"
c... |
class ToursController < ApplicationController
before_action :load_tour, only: :show
def index
@tours = Tour.newest.paginate(page: params[:page],
per_page: Settings.paginate.tours)
end
def search
@tours_search = Tour.search(params[:title]).newest.paginate(
page: params[:page], per_page: Set... |
require( 'minitest/autorun' )
require( 'minitest/rg' )
require_relative( '../guest' )
require_relative( '../room' )
class TestGuest < MiniTest::Test
def setup
@guest = Guest.new("Borna", 20)
@room = Room.new("Autumn", 10, 10, "Crawling")
@room2 = Room.new("Summer", 30, 10, "Bye,bye,bye")
end
def t... |
class UpdateColumnNameInSpeeches < ActiveRecord::Migration
def change
rename_column :speeches, :type, :speech_type
end
end
|
class Company < ApplicationRecord
has_many :event
has_many :entrant
end
|
require "application_system_test_case"
class ClientPoliciesTest < ApplicationSystemTestCase
setup do
@client_policy = client_policies(:one)
end
test "visiting the index" do
visit client_policies_url
assert_selector "h1", text: "Client Policies"
end
test "creating a Client policy" do
visit c... |
# Copyright (c) 2009-2011 VMware, Inc.
$:.unshift(File.dirname(__FILE__))
require 'spec_helper'
require 'rack/test'
require 'eventmachine'
describe 'Serialization data server -- web server' do
include Rack::Test::Methods
before :all do
@opts = load_config
@opts[:serialization_base_dir] = "/tmp/spec_test_s... |
class MiTransactionsController < ApplicationController
def download_transaction_pdf
if params.include? "start_date" and params.include? "end_date" and !params["start_date"][0].blank? and !params["end_date"][0].blank?
start_date = Time.parse(params[:start_date]).strftime('%y-%m-%d 00:00:00')
end_... |
Rails.application.config.after_initialize do
# check configuration
if AppConfig.has_key?(:user_defined_in_basic)
AppConfig[:user_defined_in_basic].each do |keys, fields|
if fields.respond_to?(:each)
fields.each do |field|
unless JSONModel(:user_defined).schema['properties'].include?(fie... |
class Paper < ApplicationRecord
# This file breaks the SOLID principles. How would you refactor?
def to_pdf
HtmlToPdf.generate(
to_html,
file_name: pdf_name,
margins: {top: '100px', left: '50px', right: '50px', bottom: '100px'},
tags: %w[paper]
)
end
def to_html
"<h1>#{titl... |
require 'spec_helper'
describe MicroService::Node do
it 'has a version number' do
expect(MicroService::Node::VERSION).not_to be nil
end
describe "#initialize_secret" do
it 'should always have a secret' do
expect(MicroService::Node.new.secret).not_to be nil
expect(MicroService::Node.create.secret).not_to ... |
def invalid
puts "Invalid input. Please enter a positive number."
puts ""
end
# take in loan amount, APR, and duration from user
amount = 0
loop do
puts "What is your total loan amount?"
print "Dollars: "
amount = gets.chomp.to_i
break if amount > 0
invalid
end
puts ""
apr = 0
loop do
puts "What is th... |
class ProgressesController < ApplicationController
before_action :load_project
def new
@progress = Progress.new
end
def create
@progress = @project.progresses.build(progress_params)
if @progress.save
redirect_to project_url(@project), notice: 'Progress report created'
... |
# frozen_string_literal: true
module ImplementableConcern
extend ActiveSupport::Concern
included do
before_action :raise_method_not_implemented_error, unless: -> { method_implemented? }
end
private
def method_implemented?
self.class::IMPLEMENT_METHODS.include?(action_name)
end
def raise_metho... |
class SessionsController < ApplicationController
def new
@user = User.new
end
def create
@user = User.find_by(email: params[:user][:email])
if @user && login_valid?(@user)
session[:user_id] = @user.id
redirect_to photos_path
else
flash[:error] = "You stupid fuck you can't even ... |
Knowyourbackyard::Application.routes.draw do
resources :logos, except: [:index, :show]
resources :images
resources :advertisers
resources :socials, only: [:new, :create, :edit, :update, :destroy]
resources :videomaker_submissions
resources :video_submissions
resources :resolvedreviewdisputes, except: [:ed... |
require "pry"
def game_hash
teams = {
:home => {
:team_name => "Brooklyn Nets",
:colors => ["Black", "White"],
:players => {
"Alan Anderson" => {
:number => 0,
:shoe => 16,
:points => 22,
:rebounds => 12,
:assists => 12,
:steals => 3,
:bloc... |
class Style < ApplicationRecord
include RatingAverage
has_many :beers
has_many :ratings, through: :beers
def self.top(length)
Style.all.sort_by{ |b| -(b.average_rating || 0) }.first(length)
end
end
|
if %w[development test].include?(Rails.env)
require 'rubocop/rake_task'
RuboCop::RakeTask.new
frozen_cops = [
'Style/FrozenStringLiteralComment',
'Layout/EmptyLineAfterMagicComment',
'Layout/EmptyLines'
]
RuboCop::RakeTask.new('rubocop:frozen') do |c|
c.options = ['--auto-correct', "--only=#... |
class CandidatesController < ApplicationController
before_action :require_user_logged_in
def create
@enterprise = Enterprise.find(params[:enterprise_id])
current_user.register(@enterprise)
flash[:success] = '企業を候補企業として登録しました'
redirect_to controller: :enterprises, action: :index
end
def upd... |
class Store < ActiveRecord::Base
has_many :employees
validates :name, presence: true
validates :name, length: { minimum: 3 }
validates :annual_revenue, numericality: { greater_than_or_equal_to: 0 }
validate :must_carry_men_or_womens_apparel
def must_carry_men_or_womens_apparel
if (!mens_apparel && !wom... |
class Deck < ActiveRecord::Base
belongs_to :pod
belongs_to :plaver, class_name: Player # Por algúna mistica, pluraliza mal "Players", por eso tengo que setear el class_name a mano u.u
has_many :match_1, foreign_key: :deck_1, class_name: Match
has_many :match_2, foreign_key: :deck_2, class_name: Match
def m... |
# Put module's plugins on LOAD_PATH.
dir = File.expand_path('../../', File.dirname(__FILE__))
$LOAD_PATH.unshift File.join(dir, 'lib')
require_relative '../../../../spec_helper'
require 'facter'
describe 'fqdn_metrics' do
before :each do
Facter.clear
end
{
"host.example.com" =>... |
#!/usr/bin/env ruby
# encoding: utf-8
lib = File.expand_path(File.dirname(__FILE__) + '/lib')
$: << lib
require 'rubygems'
require 'rake/clean'
require "#{lib}/glyph.rb"
task :default => :spec
# RSpec
begin
require "rspec/core/rake_task"
RSpec::Core::RakeTask.new(:spec) do |t|
t.pattern = 'spec/**/*_spec.rb'
t... |
#!/usr/bin/env ruby
# (c) Copyright 2016 Thoughtgang <http://www.thoughtgang.org>
# Utility for listing Plan R plugins
require 'plan-r/application/cli'
require 'plan-r/application/plugin_mgr'
class App < PlanR::CliApplication
def self.disable_db?; true; end
#def self.disable_jruby?; true; end
def self.disable_v... |
# frozen_string_literal: true
# @api private
# Rack applications used to intercept HTTP requests and apply a set of
# validators on them.
class WebTrap::Shared::RackApp
# Instantiate a new Rack application with the provided set of validators.
#
# @param validators [Array]
# Set of validators used on the inte... |
class AddPicIdAndOrganizationIdToDeals < ActiveRecord::Migration[5.1]
def change
add_column :deals, :pic_id, :integer
add_column :deals, :organization_id, :integer
end
end
|
require 'open-uri'
class GamesController < ApplicationController
def new
@letters = []
alphabet = ('A'..'Z').to_a
10.times do
@letters << alphabet.sample
end
end
def score
word = params[:word].upcase
letters = params[:letters].split
score = 0
buildable = true
# Condit... |
module API::V1
class DrugsController < ApplicationController
def index
# cleanse the query parameter value
q = params[:q] || ""
# perform the search
@drugs = Drug.typeahead_search(q)
end
def show
# find the drug
drug = Drug.canonical.find_by_product_ndc(params[:id])
... |
require "rails_helper"
describe UserMailer do
let(:user) { create(:user) }
let(:question) { create(:question) }
let(:mail) { UserMailer.subscription_question(user, question) }
it "renders the headers" do
expect(mail.subject).to eq "На вопрос, который вы подписались ответили"
expect(mail.to).to eq [use... |
class ProductsController < ApplicationController
helper_method :sort_column, :sort_direction
before_action :find_product, only: :show
def index
@products = Product.order(sort_column + " " + sort_direction).classify_published(params)
@product_categories = ProductCategory.all
end
def show
@evaluat... |
class AddMenuToRestaurants < ActiveRecord::Migration[5.2]
def change
add_column :restaurants, :menu, :string, default: ""
add_column :restaurants, :admin_approved, :boolean, default: false
end
end
|
class Dog < ApplicationRecord
# Geocoder
geocoded_by :address
after_validation :geocode, if: :will_save_change_to_address?
belongs_to :user
has_many :bookings, dependent: :destroy
has_many :reviews, through: :bookings
has_many_attached :photos
DOG_CATEGORY = %w(walk sport flirt companion hunt holiday e... |
require 'rails_helper'
feature 'Admin can see users list', %q{
As a Lunches Admin, I can browse registered users.
} do
given(:admin) { create(:admin) }
given(:user) { create(:user) }
given!(:users) { create_list(:generate_user, 10) }
scenario 'admin try view users list' do
sign_in(admin)
visit adm... |
class ConversationsController < ApplicationController
before_action :load_profile
before_action :load_conversations
def index
end
def show
@conversation = @conversations.find(params[:id])
end
def create
@conversation = @conversations.create
@conversation.profiles << Profile.find(params[... |
class Plan < ActiveRecord::Base
belongs_to :project
has_many :builds, :dependent => :destroy
has_many :running_builds, :class_name => 'Build', :conditions => { :status => 'running' }
has_many :pending_builds, :class_name => 'Build', :conditions => { :status => 'pending' }
has_many :weather_relevant_builds,... |
require "rspec"
require_relative "../../lib/fast-filter"
# Tests require Redis running at localhost:6379
RSpec.describe FastFilter::Operation do
let(:bloom_filter) { FastFilter::Operation.new(engine: 'bloom', namespace: 'bloom') }
let(:bitmap_filter) { FastFilter::Operation.new(engine: 'bitmap', namespace: 'bitma... |
require 'text'
module ActiveRecord #:nodoc:
module Acts #:nodoc:
module Suggest#:nodoc:
def self.included(base) #:nodoc:
base.extend ClassMethods
end
module ClassMethods #:nodoc:
def acts_as_suggest
extend ActiveRecord::Acts::Suggest::SingletonMethods
... |
require 'sinatra/reloader'
require './idea'
class IdeaBoxApp < Sinatra::Base
configure :development do
register Sinatra::Reloader
end
get '/' do
erb :index, locals: {ideas: Idea.all}
end
not_found do
erb :error
end
post '/' do
idea = Idea.new(params['idea_title'], params... |
#!/usr/bin/env ruby
$:.unshift File.join(File.dirname(__FILE__), *%w[.. lib])
require 'optparse'
require 'proxymachine'
begin
options = {:host => "0.0.0.0", :port => 5432}
opts = OptionParser.new do |opts|
opts.banner = <<-EOF
Usage:
proxymachine -c <config file> [-h <host>] [-p <port>]
Options:
EO... |
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
protected
# 入力フォームからアカウント名情報をDBに保存するために追加
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :indutry_type, :foundation_date, :capital, :emp... |
class AddAttachmentImghandToColor < ActiveRecord::Migration
def self.up
add_column :colors, :imghand_file_name, :string
add_column :colors, :imghand_content_type, :string
add_column :colors, :imghand_file_size, :integer
add_column :colors, :imghand_updated_at, :datetime
end
def self.down
remo... |
class Borrower < ActiveRecord::Base
attr_accessible :name, :loans_attributes
has_many :loans
validates_presence_of :name
accepts_nested_attributes_for :loans
end
|
class Game < ApplicationRecord
belongs_to :company
belongs_to :user
belongs_to :team
belongs_to :rating_list, required: false
has_one :catchword_list, dependent: :destroy
has_one :objection_list, dependent: :destroy
has_many :game_turns, dependent: :destroy
has_many :game_ratings, dependent: :destroy
... |
# frozen_string_literal: true
# Define a block where default logging is suppressed.
#
# Messages for actions within this block will be logged at `info` level instead
# of `notice`, so they will not be seen normally but will still be present
# when `verbose` logging is requested.
#
# > **Note:** Not available in apply ... |
require "faker"
# From stackoverflow adding color to strings.
class String
def black; "\033[30m#{self}\033[0m" end
def red; "\033[31m#{self}\033[0m" end
def green; "\033[32m#{self}\033[0m" end
def brown; "\033[33m#{self}\033[0m" end
def blue; "\033[34m#{self}\0... |
require "rails_helper"
module Clockface
RSpec.describe TasksController, type: :controller do
routes { Clockface::Engine.routes }
describe "GET #index" do
it "assigns the ordered list of all tasks" do
task1 = create(:task)
task2 = create(:task)
get :index
expect(respon... |
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe RsyncController do
describe "routing" do
it "should route /rsync/new to rsync#new" do
{ :get => "/rsync/new" }.should route_to(:controller => 'rsync',
:action => 'new')
end
... |
class AddIsStaticAndStaticSymbolToCubicleLabel < ActiveRecord::Migration
def self.up
add_column :cubicle_labels, :is_static, :boolean, :default => false
add_column :cubicle_labels, :static_symbol, :string
end
def self.down
remove_column :cubicle_labels, :static_symbol
remove_column :cubicle_label... |
class CreateCoverflows < ActiveRecord::Migration
def self.up
create_table :coverflows do |t|
t.integer :cflow_id
t.string :cflow_type
t.timestamps
end
end
def self.down
drop_table :coverflows
end
end
|
class AddIndexToRoads < ActiveRecord::Migration
change_table :roads do |t|
t.index :start_point, :spatial => true
t.index :end_point, :spatial => true
end
end
|
require 'rails_helper'
describe Form, type: :model do
subject(:form) { FactoryGirl.create :form }
it { is_expected.to be_audited }
end
|
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :role do
name 'Admin User'
end
factory :normal_user, :class => Role do
name 'Normal User'
end
end
|
class RetailersController < ApplicationController
before_action :authenticate_user!, :only => [:new, :create, :edit, :update, :destroy]
def index
if params[:category].present?
@retailers = Retailer.joins(:categories).where("categories.name = ?", params[:category]).order(:name)
@retailer_type = params[:catego... |
require_relative 'company'
require_relative 'instance_counter'
class Wagon
include Company
include InstanceCounter
attr_reader :wagon_type
WAGON_TYPE_FORMAT = /^\Aпассажирский\z|\Aгрузовой\z$/i
def initialize
# validate!
register_instance
end
protected
def validate!
raise ArgumentError if ... |
class GradesController < ApplicationController
before_action :teacher_logged_in, only: [:update]
def update
@grade=Grade.find_by_id(params[:id])
if @grade.update_attributes!(:grade => params[:grade][:grade])
flash={:success => "#{@grade.user.name} #{@grade.course.name}的成绩已成功修改为 #{@grade.grade}"}
... |
# Look at Ruby's merge method. Notice that it has two versions.
# What is the difference between merge and merge!? Write a program
# that uses both and illustrate the differences.
puts 'exercise with merge:'
first_hash = {first: "hash_1"}
second_hash = {second: "hash_2"}
puts first_hash.merge(second_hash)
puts first... |
class ChangeNameForSanitize < ActiveRecord::Migration[5.1]
def change
rename_column :urls, :sanitaized_url, :sanitized_url
end
end
|
# frozen_string_literal: true
class EtsPdf::Parser < SimpleClosure
def initialize(path)
@path = path
end
def call
File.readlines(@path).collect { |line| ParsedLine.new(line) }
end
end
|
#encoding: utf-8
class CreateShare < ActiveRecord::Migration
def change
create_table :shares do |t|
t.integer :share_user_id
t.integer :click_user_id
t.integer :share_time
t.datetime :created_at
end
end
end
|
class People
def initialize(connection)
@connection = connection
end
def add(person)
@connection.execute(
'INSERT INTO people (name, job, gender, age) VALUES (?, ?, ?, ?)',
person.name,
person.job,
person.gender,
person.age
... |
# frozen_string_literal: true
class Hour < ApplicationRecord
belongs_to :project
belongs_to :rate
has_one :client, through: :project
has_one :user, through: :client
validates :project, :rate, :date, :total_hours, :description, presence: true
scope :orderd, -> { order(:date) }
attr_accessor :repeat_dat... |
# frozen_string_literal: true
module Sandbox
module Actions
module Articles
class Index < Action
include Deps[repo: 'repositories.articles']
def handle(_req, res)
res.status = 200
relation = repo.articles_with_authors
res.body = serialize(relation)
end... |
require_relative './sem'
require 'minitest'
require 'set'
require 'optparse'
class ExerciseContext < Minitest::Test
def initialize(name)
@name = name
@events = []
@count = 0
@events_mutex = Mutex.new
@threads = []
@number_of_concurrent_threads = java.util.concurrent.atomic.AtomicInteger.new(0... |
require 'test_helper'
class GameTest < ActiveSupport::TestCase
test "should not save game without a gamer" do
game = games(:missing_gamer_game)
assert_not game.save
end
test "should not save empty game" do
game = Game.new
assert_not game.save
end
test "should not save game without required... |
# 2017-04-13
# David Lin
# Leetcode 513
# Method: BFS
# Definition for a binary tree node.
# class TreeNode
# attr_accessor :val, :left, :right
# def initialize(val)
# @val = val
# @left, @right = nil, nil
# end
# end
# @param {TreeNode} root
# @return {Integer}
def find_bottom_left_value... |
VAGRANTFILE_API_VERSION = "2"
# Basado en https://github.com/FriendsOfCake/vagrant-ansible
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "trusty64"
config.vm.box_url = "http://cloud-images.ubuntu.com/vagrant/trusty/current/trusty-server-cloudimg-amd64-vagrant-disk1.box"
config.vm.networ... |
class RenameAmenityColumn < ActiveRecord::Migration[5.1]
def change
rename_column :amenities, :type, :amenity_type
end
end
|
require_relative '../lib/toggl2redmine'
ActiveResource::Base.logger = Logger.new(STDERR)
class Sync < Struct.new(:toggl_key, :redmine_key, :day)
def perform
set_keys
toggl_times.each do |ttime|
next if ttime.running?
new_time = Toggl2redmine::Redmine::TimeEntry.from_toggl(ttime)
old_time... |
require 'rails_helper'
# Needed to use login objects through Devise
include Warden::Test::Helpers
Warden.test_mode!
def login_admin
login_as create(:admin_user), scope: :admin_user
end
feature 'Stats' do
before do
login_admin
end
scenario 'shows the total of votes and total per contestant', js: true do
... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.box = "trusty-amd64"
config.vm.box_url = "http://cloud-images.ubuntu.com/vagrant/trusty/current/trusty-server-cloudimg-amd64-vagrant-disk1.box"
config.vm.network :private_networ... |
class Piano < ApplicationRecord
has_many :piano_purchases
end
|
#!/usr/bin/env ruby
def sum_even_fibonacci(limit) #sum even Fibonacci numbers under limit
sum = 2
last = 2
before_last = 1
while (last + before_last) <= limit
current = last + before_last
if (current%2 == 0)
sum = sum + current
puts current
end
before_last = last
last = curren... |
# encoding: UTF-8
require 'spec_helper'
describe Delayed::JobGroups::Plugin do
before(:all) do
@old_max_attempts = Delayed::Worker.max_attempts
Delayed::Worker.max_attempts = 2
end
after(:all) do
Delayed::Worker.max_attempts = @old_max_attempts
end
before(:each) do
CompletionJob.invoked =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.